text:
package integration

import (
	"bufio"
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"regexp"
	"sort"
	"strconv"
	"sync"
	"testing"
	"time"

	"github.com/sorintlab/stolon/common"
	"github.com/sorintlab/stolon/pkg/cluster"
	pg "github.com/sorintlab/stolon/pkg/postgresql"
	"github.com/sorintlab/stolon/pkg/store"
	"github.com/sorintlab/stolon/pkg/util"

	_ "github.com/lib/pq"
	"github.com/satori/go.uuid"
	"github.com/sgotti/gexpect"
)

const (
	sleepInterval = 500 * time.Millisecond

	MinPort = 2048
	MaxPort = 16384
)

var (
	defaultPGParameters = cluster.PGParameters{"log_destination": "stderr", "logging_collector": "false"}
)

var curPort = MinPort
var portMutex = sync.Mutex{}

func pgParametersWithDefaults(p cluster.PGParameters) cluster.PGParameters {
	pd := cluster.PGParameters{}
	for k, v := range defaultPGParameters {
		pd[k] = v
	}
	for k, v := range p {
		pd[k] = v
	}
	return pd
}

type Querier interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
	ReplQuery(query string, args ...interface{}) (*sql.Rows, error)
}

func GetPGParameters(q Querier) (common.Parameters, error) {
	var pgParameters = common.Parameters{}
	rows, err := q.Query("select name, setting, source from pg_settings")
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var name, setting, source string
		if err = rows.Scan(&name, &setting, &source); err != nil {
			return nil, err
		}
		if source == "configuration file" {
			pgParameters[name] = setting
		}
	}
	return pgParameters, nil
}

func GetSystemData(q Querier) (*pg.SystemData, error) {
	rows, err := q.ReplQuery("IDENTIFY_SYSTEM")
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var sd pg.SystemData
		var xLogPosLsn string
		var unused *string
		if err = rows.Scan(&sd.SystemID, &sd.TimelineID, &xLogPosLsn, &unused); err != nil {
			return nil, err
		}
		sd.XLogPos, err = pg.PGLsnToInt(xLogPosLsn)
		if err != nil {
			return nil, err
		}
		return &sd, nil
	}
	return nil, fmt.Errorf("query returned 0 rows")
}

func GetXLogPos(q Querier) (uint64, error) {
	// get the current master XLogPos
	systemData, err := GetSystemData(q)
	if err != nil {
		return 0, err
	}
	return systemData.XLogPos, nil
}

// getReplicatinSlots return existing replication slots (also temporary
// replication slots on PostgreSQL > 10)
func getReplicationSlots(q Querier) ([]string, error) {
	replSlots := []string{}

	rows, err := q.Query("select slot_name from pg_replication_slots")
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	for rows.Next() {
		var slotName string
		if err := rows.Scan(&slotName); err != nil {
			return nil, err
		}
		replSlots = append(replSlots, slotName)
	}

	return replSlots, nil
}

func waitReplicationSlots(q Querier, replSlots []string, timeout time.Duration) error {
	sort.Sort(sort.StringSlice(replSlots))

	start := time.Now()
	curReplSlots := []string{}
	var err error
	for time.Now().Add(-timeout).Before(start) {
		curReplSlots, err := getReplicationSlots(q)
		if err != nil {
			goto end
		}
		sort.Sort(sort.StringSlice(curReplSlots))
		if reflect.DeepEqual(replSlots, curReplSlots) {
			return nil
		}
	end:
		time.Sleep(2 * time.Second)
	}
	return fmt.Errorf("timeout waiting for replSlots %v, got: %v, last err: %v", replSlots, curReplSlots, err)
}

func waitNotStolonReplicationSlots(q Querier, replSlots []string, timeout time.Duration) error {
	sort.Sort(sort.StringSlice(replSlots))

	start := time.Now()
	var curReplSlots []string
	var err error
	for time.Now().Add(-timeout).Before(start) {
		allReplSlots, err := getReplicationSlots(q)
		if err != nil {
			goto end
		}
		curReplSlots = []string{}
		for _, s := range allReplSlots {
			if !common.IsStolonName(s) {
				curReplSlots = append(curReplSlots, s)
			}
		}
		sort.Sort(sort.StringSlice(curReplSlots))
		if reflect.DeepEqual(replSlots, curReplSlots) {
			return nil
		}
	end:
		time.Sleep(2 * time.Second)
	}
	return fmt.Errorf("timeout waiting for replSlots %v, got: %v, last err: %v", replSlots, curReplSlots, err)
}

type Process struct {
	t    *testing.T
	uid  string
	name string
	args []string
	cmd  *gexpect.ExpectSubprocess
	bin  string
}

func (p *Process) start() error {
	if p.cmd != nil {
		panic(fmt.Errorf("%s: cmd not cleanly stopped", p.uid))
	}
	cmd := exec.Command(p.bin, p.args...)
	pr, pw, err := os.Pipe()
	if err != nil {
		return err
	}
	p.cmd = &gexpect.ExpectSubprocess{Cmd: cmd, Output: pw}
	if err := p.cmd.Start(); err != nil {
		return err
	}
	go func() {
		scanner := bufio.NewScanner(pr)
		for scanner.Scan() {
			p.t.Logf("[%s %s]: %s", p.name, p.uid, scanner.Text())
		}
	}()

	return nil
}

func (p *Process) Start() error {
	if err := p.start(); err != nil {
		return err
	}
	p.cmd.Continue()
	return nil
}

func (p *Process) StartExpect() error {
	return p.start()
}

func (p *Process) Signal(sig os.Signal) error {
	p.t.Logf("signalling %s %s with %s", p.name, p.uid, sig)
	if p.cmd == nil {
		panic(fmt.Errorf("p: %s, cmd is empty", p.uid))
	}
	return p.cmd.Cmd.Process.Signal(sig)
}

func (p *Process) Kill() {
	p.t.Logf("killing %s %s", p.name, p.uid)
	if p.cmd == nil {
		panic(fmt.Errorf("p: %s, cmd is empty", p.uid))
	}
	p.cmd.Cmd.Process.Signal(os.Kill)
	p.cmd.Wait()
	p.cmd = nil
}

func (p *Process) Stop() {
	p.t.Logf("stopping %s %s", p.name, p.uid)
	if p.cmd == nil {
		panic(fmt.Errorf("p: %s, cmd is empty", p.uid))
	}
	p.cmd.Continue()
	p.cmd.Cmd.Process.Signal(os.Interrupt)
	p.cmd.Wait()
	p.cmd = nil
}

func (p *Process) Wait(timeout time.Duration) error {
	timeoutCh := time.NewTimer(timeout).C
	endCh := make(chan error)
	go func() {
		err := p.cmd.Wait()
		endCh <- err
	}()
	select {
	case <-timeoutCh:
		return fmt.Errorf("timeout waiting on process")
	case <-endCh:
		return nil
	}
}

type TestKeeper struct {
	t *testing.T
	Process
	dataDir         string
	pgListenAddress string
	pgPort          string
	pgSUUsername    string
	pgSUPassword    string
	pgReplUsername  string
	pgReplPassword  string
	db              *sql.DB
	rdb             *sql.DB
}

func NewTestKeeperWithID(t *testing.T, dir, uid, clusterName, pgSUUsername, pgSUPassword, pgReplUsername, pgReplPassword string, storeBackend store.Backend, storeEndpoints string, a ...string) (*TestKeeper, error) {
	args := []string{}

	dataDir := filepath.Join(dir, fmt.Sprintf("st%s", uid))

	pgListenAddress, pgPort, err := getFreePort(true, false)
	if err != nil {
		return nil, err
	}

	args = append(args, fmt.Sprintf("--uid=%s", uid))
	args = append(args, fmt.Sprintf("--cluster-name=%s", clusterName))
	args = append(args, fmt.Sprintf("--pg-listen-address=%s", pgListenAddress))
	args = append(args, fmt.Sprintf("--pg-port=%s", pgPort))
	args = append(args, fmt.Sprintf("--data-dir=%s", dataDir))
	args = append(args, fmt.Sprintf("--store-backend=%s", storeBackend))
	args = append(args, fmt.Sprintf("--store-endpoints=%s", storeEndpoints))
	args = append(args, fmt.Sprintf("--pg-su-username=%s", pgSUUsername))
	if pgSUPassword != "" {
		args = append(args, fmt.Sprintf("--pg-su-password=%s", pgSUPassword))
	}
	args = append(args, fmt.Sprintf("--pg-repl-username=%s", pgReplUsername))
	args = append(args, fmt.Sprintf("--pg-repl-password=%s", pgReplPassword))
	if os.Getenv("DEBUG") != "" {
		args = append(args, "--debug")
	}
	args = append(args, a...)

	connParams := pg.ConnParams{
		"user":     pgSUUsername,
		"password": pgSUPassword,
		"host":     pgListenAddress,
		"port":     pgPort,
		"dbname":   "postgres",
		"sslmode":  "disable",
	}

	replConnParams := pg.ConnParams{
		"user":        pgReplUsername,
		"password":    pgReplPassword,
		"host":        pgListenAddress,
		"port":        pgPort,
		"dbname":      "postgres",
		"sslmode":     "disable",
		"replication": "1",
	}

	connString := connParams.ConnString()
	db, err := sql.Open("postgres", connString)
	if err != nil {
		return nil, err
	}

	replConnString := replConnParams.ConnString()
	rdb, err := sql.Open("postgres", replConnString)
	if err != nil {
		return nil, err
	}

	bin := os.Getenv("STKEEPER_BIN")
	if bin == "" {
		return nil, fmt.Errorf("missing STKEEPER_BIN env")
	}
	tk := &TestKeeper{
		t: t,
		Process: Process{
			t:    t,
			uid:  uid,
			name: "keeper",
			bin:  bin,
			args: args,
		},
		dataDir:         dataDir,
		pgListenAddress: pgListenAddress,
		pgPort:          pgPort,
		pgSUUsername:    pgSUUsername,
		pgSUPassword:    pgSUPassword,
		pgReplUsername:  pgReplUsername,
		pgReplPassword:  pgReplPassword,
		db:              db,
		rdb:             rdb,
	}
	return tk, nil
}

func NewTestKeeper(t *testing.T, dir, clusterName, pgSUUsername, pgSUPassword, pgReplUsername, pgReplPassword string, storeBackend store.Backend, storeEndpoints string, a ...string) (*TestKeeper, error) {
	u := uuid.NewV4()
	uid := fmt.Sprintf("%x", u[:4])

	return NewTestKeeperWithID(t, dir, uid, clusterName, pgSUUsername, pgSUPassword, pgReplUsername, pgReplPassword, storeBackend, storeEndpoints, a...)
}

func (tk *TestKeeper) PGDataVersion() (int, int, error) {
	fh, err := os.Open(filepath.Join(tk.dataDir, "postgres", "PG_VERSION"))
	if err != nil {
		return 0, 0, fmt.Errorf("failed to read PG_VERSION: %v", err)
	}
	defer fh.Close()

	scanner := bufio.NewScanner(fh)
	scanner.Split(bufio.ScanLines)

	scanner.Scan()

	version := scanner.Text()
	return pg.ParseVersion(version)
}

func (tk *TestKeeper) GetPrimaryConninfo() (pg.ConnParams, error) {
	regex := regexp.MustCompile(`\s*primary_conninfo\s*=\s*'(.*)'$`)

	fh, err := os.Open(filepath.Join(tk.dataDir, "postgres", "recovery.conf"))
	if os.IsNotExist(err) {
		return nil, nil
	}
	defer fh.Close()

	scanner := bufio.NewScanner(fh)
	scanner.Split(bufio.ScanLines)

	for scanner.Scan() {
		m := regex.FindStringSubmatch(scanner.Text())
		if len(m) == 2 {
			return pg.ParseConnString(m[1])
		}
	}
	return nil, nil
}

func (tk *TestKeeper) Exec(query string, args ...interface{}) (sql.Result, error) {
	res, err := tk.db.Exec(query, args...)
	if err != nil {
		return nil, err
	}

	return res, nil
}

func (tk *TestKeeper) Query(query string, args ...interface{}) (*sql.Rows, error) {
	res, err := tk.db.Query(query, args...)
	if err != nil {
		return nil, err
	}

	return res, nil
}

func (tk *TestKeeper) ReplQuery(query string, args ...interface{}) (*sql.Rows, error) {
	res, err := tk.rdb.Query(query, args...)
	if err != nil {
		return nil, err
	}

	return res, nil
}

func (tk *TestKeeper) SwitchWals(times int) error {
	maj, _, err := tk.PGDataVersion()
	if err != nil {
		return err
	}
	var switchLogFunc string
	if maj < 10 {
		switchLogFunc = "select pg_switch_xlog()"
	} else {
		switchLogFunc = "select pg_switch_wal()"
	}

	tk.Exec("DROP TABLE switchwal")
	if _, err := tk.Exec("CREATE TABLE switchwal(ID INT PRIMARY KEY NOT NULL)"); err != nil {
		return err
	}
	// if times > 1 we have to do some transactions or the wal won't switch
	for i := 0; i < times; i++ {
		if _, err := tk.Exec("INSERT INTO switchwal VALUES ($1)", i); err != nil {
			return err
		}
		if _, err := tk.db.Exec(switchLogFunc); err != nil {
			return err
		}
	}
	tk.Exec("DROP TABLE switchwal")
	return nil
}

func (tk *TestKeeper) CheckPoint() error {
	_, err := tk.Exec("CHECKPOINT")
	return err
}

func (tk *TestKeeper) WaitDBUp(timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		_, err := tk.Exec("select 1")
		if err == nil {
			return nil
		}
		tk.t.Logf("tk: %v, error: %v", tk.uid, err)
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func (tk *TestKeeper) WaitDBDown(timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		_, err := tk.Exec("select 1")
		if err != nil {
			return nil
		}
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func (tk *TestKeeper) GetPGProcess() (*os.Process, error) {
	fh, err := os.Open(filepath.Join(tk.dataDir, "postgres/postmaster.pid"))
	if err != nil {
		return nil, err
	}
	defer fh.Close()

	scanner := bufio.NewScanner(fh)
	scanner.Split(bufio.ScanLines)
	if !scanner.Scan() {
		return nil, fmt.Errorf("not enough lines in pid file")
	}
	pidStr := scanner.Text()
	pid, err := strconv.Atoi(string(pidStr))
	if err != nil {
		return nil, err
	}
	return os.FindProcess(pid)
}

func (tk *TestKeeper) SignalPG(sig os.Signal) error {
	p, err := tk.GetPGProcess()
	if err != nil {
		return err
	}
	return p.Signal(sig)
}

func (tk *TestKeeper) isInRecovery() (bool, error) {
	rows, err := tk.Query("SELECT pg_is_in_recovery from pg_is_in_recovery()")
	if err != nil {
		return false, err
	}
	defer rows.Close()
	for rows.Next() {
		var isInRecovery bool
		if err := rows.Scan(&isInRecovery); err != nil {
			return false, err
		}
		if isInRecovery {
			return true, nil
		}
		return false, nil
	}
	return false, fmt.Errorf("no rows returned")
}

func (tk *TestKeeper) WaitDBRole(r common.Role, ptk *TestKeeper, timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		time.Sleep(sleepInterval)
		// when the cluster is in standby mode also the master db is a standby
		// so we cannot just check if the keeper is in recovery but have to
		// check if the primary_conninfo points to the primary db or to the
		// cluster master
		if ptk == nil {
			ok, err := tk.isInRecovery()
			if err != nil {
				continue
			}
			if !ok && r == common.RoleMaster {
				return nil
			}
			if ok && r == common.RoleStandby {
				return nil
			}
		} else {
			ok, err := tk.isInRecovery()
			if err != nil {
				continue
			}
			if !ok {
				continue
			}
			// TODO(sgotti) get this information from the running instance instead than from
			// recovery.conf to be really sure it's applied
			conninfo, err := tk.GetPrimaryConninfo()
			if err != nil {
				continue
			}
			if conninfo["host"] == ptk.pgListenAddress && conninfo["port"] == ptk.pgPort {
				if r == common.RoleMaster {
					return nil
				}
			} else {
				if r == common.RoleStandby {
					return nil
				}
			}
		}
	}

	return fmt.Errorf("timeout")
}

func (tk *TestKeeper) GetPGParameters() (common.Parameters, error) {
	return GetPGParameters(tk)
}

type CheckFunc func(time.Duration) error

func waitChecks(timeout time.Duration, fns ...CheckFunc) error {
	end := make(chan error)
	fnc := len(fns)
	for _, fn := range fns {
		go func(fn CheckFunc, end chan error) {
			end <- fn(timeout)
		}(fn, end)
	}

	c := 0
	for c < fnc {
		err := <-end
		if err != nil {
			return err
		}
		c++
	}
	return nil
}

type TestSentinel struct {
	t *testing.T
	Process
}

func NewTestSentinel(t *testing.T, dir string, clusterName string, storeBackend store.Backend, storeEndpoints string, a ...string) (*TestSentinel, error) {
	u := uuid.NewV4()
	uid := fmt.Sprintf("%x", u[:4])

	args := []string{}
	args = append(args, fmt.Sprintf("--cluster-name=%s", clusterName))
	args = append(args, fmt.Sprintf("--store-backend=%s", storeBackend))
	args = append(args, fmt.Sprintf("--store-endpoints=%s", storeEndpoints))
	if os.Getenv("DEBUG") != "" {
		args = append(args, "--debug")
	}
	args = append(args, a...)

	bin := os.Getenv("STSENTINEL_BIN")
	if bin == "" {
		return nil, fmt.Errorf("missing STSENTINEL_BIN env")
	}
	ts := &TestSentinel{
		t: t,
		Process: Process{
			t:    t,
			uid:  uid,
			name: "sentinel",
			bin:  bin,
			args: args,
		},
	}
	return ts, nil
}

type TestProxy struct {
	t *testing.T
	Process
	listenAddress string
	port          string
	db            *sql.DB
	rdb           *sql.DB
}

func NewTestProxy(t *testing.T, dir string, clusterName, pgSUUsername, pgSUPassword, pgReplUsername, pgReplPassword string, storeBackend store.Backend, storeEndpoints string, a ...string) (*TestProxy, error) {
	u := uuid.NewV4()
	uid := fmt.Sprintf("%x", u[:4])

	listenAddress, port, err := getFreePort(true, false)
	if err != nil {
		return nil, err
	}

	args := []string{}
	args = append(args, fmt.Sprintf("--cluster-name=%s", clusterName))
	args = append(args, fmt.Sprintf("--listen-address=%s", listenAddress))
	args = append(args, fmt.Sprintf("--port=%s", port))
	args = append(args, fmt.Sprintf("--store-backend=%s", storeBackend))
	args = append(args, fmt.Sprintf("--store-endpoints=%s", storeEndpoints))
	if os.Getenv("DEBUG") != "" {
		args = append(args, "--debug")
	}
	args = append(args, a...)

	connParams := pg.ConnParams{
		"user":     pgSUUsername,
		"password": pgSUPassword,
		"host":     listenAddress,
		"port":     port,
		"dbname":   "postgres",
		"sslmode":  "disable",
	}

	replConnParams := pg.ConnParams{
		"user":        pgReplUsername,
		"password":    pgReplPassword,
		"host":        listenAddress,
		"port":        port,
		"dbname":      "postgres",
		"sslmode":     "disable",
		"replication": "1",
	}

	connString := connParams.ConnString()
	db, err := sql.Open("postgres", connString)
	if err != nil {
		return nil, err
	}

	replConnString := replConnParams.ConnString()
	rdb, err := sql.Open("postgres", replConnString)
	if err != nil {
		return nil, err
	}

	bin := os.Getenv("STPROXY_BIN")
	if bin == "" {
		return nil, fmt.Errorf("missing STPROXY_BIN env")
	}
	tp := &TestProxy{
		t: t,
		Process: Process{
			t:    t,
			uid:  uid,
			name: "proxy",
			bin:  bin,
			args: args,
		},
		listenAddress: listenAddress,
		port:          port,
		db:            db,
		rdb:           rdb,
	}
	return tp, nil
}

func (tp *TestProxy) WaitListening(timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		_, err := net.DialTimeout("tcp", net.JoinHostPort(tp.listenAddress, tp.port), timeout-time.Now().Sub(start))
		if err == nil {
			return nil
		}
		tp.t.Logf("tp: %v, error: %v", tp.uid, err)
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func (tp *TestProxy) CheckListening() bool {
	_, err := net.Dial("tcp", net.JoinHostPort(tp.listenAddress, tp.port))
	if err != nil {
		return false
	}
	return true
}
func (tp *TestProxy) WaitNotListening(timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		_, err := net.DialTimeout("tcp", net.JoinHostPort(tp.listenAddress, tp.port), timeout-time.Now().Sub(start))
		if err != nil {
			return nil
		}
		tp.t.Logf("tp: %v, error: %v", tp.uid, err)
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func (tp *TestProxy) Exec(query string, args ...interface{}) (sql.Result, error) {
	res, err := tp.db.Exec(query, args...)
	if err != nil {
		return nil, err
	}

	return res, nil
}

func (tp *TestProxy) Query(query string, args ...interface{}) (*sql.Rows, error) {
	res, err := tp.db.Query(query, args...)
	if err != nil {
		return nil, err
	}

	return res, nil
}

func (tp *TestProxy) ReplQuery(query string, args ...interface{}) (*sql.Rows, error) {
	res, err := tp.rdb.Query(query, args...)
	if err != nil {
		return nil, err
	}

	return res, nil
}

func (tp *TestProxy) GetPGParameters() (common.Parameters, error) {
	return GetPGParameters(tp)
}

func (tp *TestProxy) WaitRightMaster(tk *TestKeeper, timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		pgParameters, err := GetPGParameters(tp)
		if err != nil {
			goto end
		}
		if pgParameters["port"] == tk.pgPort {
			return nil
		}
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func StolonCtl(clusterName string, storeBackend store.Backend, storeEndpoints string, a ...string) error {
	args := []string{}
	args = append(args, fmt.Sprintf("--cluster-name=%s", clusterName))
	args = append(args, fmt.Sprintf("--store-backend=%s", storeBackend))
	args = append(args, fmt.Sprintf("--store-endpoints=%s", storeEndpoints))
	args = append(args, a...)

	bin := os.Getenv("STCTL_BIN")
	if bin == "" {
		return fmt.Errorf("missing STCTL_BIN env")
	}
	cmd := exec.Command(bin, args...)
	return cmd.Run()
}

type TestStore struct {
	t *testing.T
	Process
	listenAddress string
	port          string
	store         store.KVStore
	storeBackend  store.Backend
}

func NewTestStore(t *testing.T, dir string, a ...string) (*TestStore, error) {
	storeBackend := store.Backend(os.Getenv("STOLON_TEST_STORE_BACKEND"))
	switch storeBackend {
	case "consul":
		return NewTestConsul(t, dir, a...)
	case "etcd":
		storeBackend = "etcdv2"
		fallthrough
	case "etcdv2", "etcdv3":
		return NewTestEtcd(t, dir, storeBackend, a...)
	}
	return nil, fmt.Errorf("wrong store backend")
}

func NewTestEtcd(t *testing.T, dir string, backend store.Backend, a ...string) (*TestStore, error) {
	u := uuid.NewV4()
	uid := fmt.Sprintf("%x", u[:4])

	dataDir := filepath.Join(dir, fmt.Sprintf("etcd%s", uid))

	listenAddress, port, err := getFreePort(true, false)
	if err != nil {
		return nil, err
	}
	listenAddress2, port2, err := getFreePort(true, false)
	if err != nil {
		return nil, err
	}

	args := []string{}
	args = append(args, fmt.Sprintf("--name=%s", uid))
	args = append(args, fmt.Sprintf("--data-dir=%s", dataDir))
	args = append(args, fmt.Sprintf("--listen-client-urls=http://%s:%s", listenAddress, port))
	args = append(args, fmt.Sprintf("--advertise-client-urls=http://%s:%s", listenAddress, port))
	args = append(args, fmt.Sprintf("--listen-peer-urls=http://%s:%s", listenAddress2, port2))
	args = append(args, fmt.Sprintf("--initial-advertise-peer-urls=http://%s:%s", listenAddress2, port2))
	args = append(args, fmt.Sprintf("--initial-cluster=%s=http://%s:%s", uid, listenAddress2, port2))
	args = append(args, a...)

	storeEndpoints := fmt.Sprintf("%s:%s", listenAddress, port)

	storeConfig := store.Config{
		Backend:   store.Backend(backend),
		Endpoints: storeEndpoints,
	}
	kvstore, err := store.NewKVStore(storeConfig)
	if err != nil {
		return nil, fmt.Errorf("cannot create store: %v", err)
	}

	bin := os.Getenv("ETCD_BIN")
	if bin == "" {
		return nil, fmt.Errorf("missing ETCD_BIN env")
	}
	tstore := &TestStore{
		t: t,
		Process: Process{
			t:    t,
			uid:  uid,
			name: "etcd",
			bin:  bin,
			args: args,
		},
		listenAddress: listenAddress,
		port:          port,
		store:         kvstore,
		storeBackend:  backend,
	}
	return tstore, nil
}

func NewTestConsul(t *testing.T, dir string, a ...string) (*TestStore, error) {
	u := uuid.NewV4()
	uid := fmt.Sprintf("%x", u[:4])

	dataDir := filepath.Join(dir, fmt.Sprintf("consul%s", uid))

	listenAddress, portHTTP, err := getFreePort(true, false)
	if err != nil {
		return nil, err
	}
	_, portSerfLan, err := getFreePort(true, true)
	if err != nil {
		return nil, err
	}
	_, portSerfWan, err := getFreePort(true, true)
	if err != nil {
		return nil, err
	}
	_, portServer, err := getFreePort(true, false)
	if err != nil {
		return nil, err
	}

	f, err := os.Create(filepath.Join(dir, fmt.Sprintf("consul%s.json", uid)))
	if err != nil {
		return nil, err
	}
	defer f.Close()

	f.WriteString(fmt.Sprintf(`{
		"ports": {
			"dns": -1,
			"http": %s,
			"serf_lan": %s,
			"serf_wan": %s,
			"server": %s
		}
	}`, portHTTP, portSerfLan, portSerfWan, portServer))

	args := []string{}
	args = append(args, "agent")
	args = append(args, "-server")
	args = append(args, fmt.Sprintf("-config-file=%s", f.Name()))
	args = append(args, fmt.Sprintf("-data-dir=%s", dataDir))
	args = append(args, fmt.Sprintf("-bind=%s", listenAddress))
	args = append(args, fmt.Sprintf("-advertise=%s", listenAddress))
	args = append(args, "-bootstrap-expect=1")
	args = append(args, a...)

	storeEndpoints := fmt.Sprintf("%s:%s", listenAddress, portHTTP)

	storeConfig := store.Config{
		Backend:   store.CONSUL,
		Endpoints: storeEndpoints,
	}
	kvstore, err := store.NewKVStore(storeConfig)
	if err != nil {
		return nil, fmt.Errorf("cannot create store: %v", err)
	}

	bin := os.Getenv("CONSUL_BIN")
	if bin == "" {
		return nil, fmt.Errorf("missing CONSUL_BIN env")
	}
	ts := &TestStore{
		t: t,
		Process: Process{
			t:    t,
			uid:  uid,
			name: "consul",
			bin:  bin,
			args: args,
		},
		listenAddress: listenAddress,
		port:          portHTTP,
		store:         kvstore,
		storeBackend:  store.CONSUL,
	}
	return ts, nil
}

func (ts *TestStore) WaitUp(timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		_, err := ts.store.Get(context.TODO(), "anykey")
		ts.t.Logf("err: %v", err)
		if err != nil && err == store.ErrKeyNotFound {
			return nil
		}
		if err == nil {
			return nil
		}
		time.Sleep(sleepInterval)
	}

	return fmt.Errorf("timeout")
}

func (ts *TestStore) WaitDown(timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		_, err := ts.store.Get(context.TODO(), "anykey")
		if err != nil && err != store.ErrKeyNotFound {
			return nil
		}
		time.Sleep(sleepInterval)
	}

	return fmt.Errorf("timeout")
}

func WaitClusterDataUpdated(e *store.KVBackedStore, timeout time.Duration) error {
	icd, _, err := e.GetClusterData(context.TODO())
	if err != nil {
		return fmt.Errorf("unexpected err: %v", err)
	}
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}
		if !reflect.DeepEqual(icd, cd) {
			return nil
		}
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func WaitClusterDataWithMaster(e *store.KVBackedStore, timeout time.Duration) (string, error) {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}
		if cd.Cluster.Status.Phase == cluster.ClusterPhaseNormal && cd.Cluster.Status.Master != "" {
			return cd.DBs[cd.Cluster.Status.Master].Spec.KeeperUID, nil
		}
	end:
		time.Sleep(sleepInterval)
	}
	return "", fmt.Errorf("timeout")
}

func WaitClusterDataMaster(master string, e *store.KVBackedStore, timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}
		if cd.Cluster.Status.Phase == cluster.ClusterPhaseNormal && cd.Cluster.Status.Master != "" {
			if cd.DBs[cd.Cluster.Status.Master].Spec.KeeperUID == master {
				return nil
			}
		}
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func WaitClusterDataKeeperInitialized(keeperUID string, e *store.KVBackedStore, timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}
		// Check for db on keeper to be initialized
		for _, db := range cd.DBs {
			if db.Spec.KeeperUID == keeperUID {
				if db.Status.CurrentGeneration >= cluster.InitialGeneration {
					return nil
				}
			}
		}
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

// WaitClusterDataSynchronousStandbys waits for:
// * synchronous standby defined in masterdb spec
// * synchronous standby reported from masterdb status
func WaitClusterDataSynchronousStandbys(synchronousStandbys []string, e *store.KVBackedStore, timeout time.Duration) error {
	sort.Sort(sort.StringSlice(synchronousStandbys))
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}
		if cd.Cluster.Status.Phase == cluster.ClusterPhaseNormal && cd.Cluster.Status.Master != "" {
			masterDB := cd.DBs[cd.Cluster.Status.Master]
			// get keepers for db spec synchronousStandbys
			keepersUIDs := []string{}
			for _, dbUID := range masterDB.Spec.SynchronousStandbys {
				db, ok := cd.DBs[dbUID]
				if ok {
					keepersUIDs = append(keepersUIDs, db.Spec.KeeperUID)
				}
			}
			sort.Sort(sort.StringSlice(keepersUIDs))
			if !reflect.DeepEqual(synchronousStandbys, keepersUIDs) {
				goto end
			}

			// get keepers for db status synchronousStandbys
			keepersUIDs = []string{}
			for _, dbUID := range masterDB.Status.SynchronousStandbys {
				db, ok := cd.DBs[dbUID]
				if ok {
					keepersUIDs = append(keepersUIDs, db.Spec.KeeperUID)
				}
			}
			sort.Sort(sort.StringSlice(keepersUIDs))
			if !reflect.DeepEqual(synchronousStandbys, keepersUIDs) {
				goto end
			}
			return nil
		}
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func WaitClusterPhase(e *store.KVBackedStore, phase cluster.ClusterPhase, timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}
		if cd.Cluster.Status.Phase == phase {
			return nil
		}
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func WaitNumDBs(e *store.KVBackedStore, n int, timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}
		if len(cd.DBs) == n {
			return nil
		}
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func WaitStandbyKeeper(e *store.KVBackedStore, keeperUID string, timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}

		for _, db := range cd.DBs {
			if db.UID == cd.Cluster.Status.Master {
				continue
			}
			if db.Spec.KeeperUID == keeperUID && db.Spec.Role == common.RoleStandby {
				return nil
			}
		}
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func WaitClusterDataKeepers(keepersUIDs []string, e *store.KVBackedStore, timeout time.Duration) error {
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}
		if len(keepersUIDs) != len(cd.Keepers) {
			goto end
		}
		// Check for db on keeper to be initialized
		for _, keeper := range cd.Keepers {
			if !util.StringInSlice(keepersUIDs, keeper.UID) {
				goto end
			}
		}
		return nil
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

// WaitClusterSyncedXLogPos waits for all the specified keepers to have the same
// reported XLogPos and that it's >= than master XLogPos
func WaitClusterSyncedXLogPos(keepers []*TestKeeper, xLogPos uint64, e *store.KVBackedStore, timeout time.Duration) error {
	keepersUIDs := []string{}
	for _, sk := range keepers {
		keepersUIDs = append(keepersUIDs, sk.uid)
	}

	// check that master and all the keepers XLogPos are the same and >=
	// masterXLogPos
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		c := 0
		curXLogPos := uint64(0)
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}
		// Check for db on keeper to be initialized
		for _, keeper := range cd.Keepers {
			if !util.StringInSlice(keepersUIDs, keeper.UID) {
				continue
			}
			for _, db := range cd.DBs {
				if db.Spec.KeeperUID == keeper.UID {
					if db.Status.XLogPos < xLogPos {
						goto end
					}
					if c == 0 {
						curXLogPos = db.Status.XLogPos
					} else {
						if db.Status.XLogPos != curXLogPos {
							goto end
						}
					}
				}
			}
			c++
		}
		if c == len(keepersUIDs) {
			return nil
		}
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func WaitClusterDataEnabledProxiesNum(e *store.KVBackedStore, n int, timeout time.Duration) error {
	// TODO(sgotti) find a way to retrieve the proxies internally generated uids
	// and check for them instead of relying only on the number of proxies
	start := time.Now()
	for time.Now().Add(-timeout).Before(start) {
		cd, _, err := e.GetClusterData(context.TODO())
		if err != nil || cd == nil {
			goto end
		}
		if len(cd.Proxy.Spec.EnabledProxies) == n {
			return nil
		}
	end:
		time.Sleep(sleepInterval)
	}
	return fmt.Errorf("timeout")
}

func testFreeTCPPort(port int) error {
	ln, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
	if err != nil {
		return err
	}
	ln.Close()
	return nil
}

func testFreeUDPPort(port int) error {
	ln, err := net.ListenPacket("udp", fmt.Sprintf("localhost:%d", port))
	if err != nil {
		return err
	}
	ln.Close()
	return nil
}

// Hack to find a free tcp and udp port
func getFreePort(tcp bool, udp bool) (string, string, error) {
	portMutex.Lock()
	defer portMutex.Unlock()

	if !tcp && !udp {
		return "", "", fmt.Errorf("at least one of tcp or udp port shuld be required")
	}
	localhostIP, err := net.ResolveIPAddr("ip", "localhost")
	if err != nil {
		return "", "", fmt.Errorf("failed to resolve ip addr: %v", err)
	}
	for {
		curPort++
		if curPort > MaxPort {
			return "", "", fmt.Errorf("all available ports to test have been exausted")
		}
		if tcp {
			if err := testFreeTCPPort(curPort); err != nil {
				continue
			}
		}
		if udp {
			if err := testFreeUDPPort(curPort); err != nil {
				continue
			}
		}
		return localhostIP.IP.String(), strconv.Itoa(curPort), nil
	}
}

func writeClusterSpec(dir string, cs *cluster.ClusterSpec) (string, error) {
	csj, err := json.Marshal(cs)
	if err != nil {
		return "", err
	}
	tmpFile, err := ioutil.TempFile(dir, "initial-cluster-spec.json")
	if err != nil {
		return "", err
	}
	defer tmpFile.Close()
	if _, err := tmpFile.Write(csj); err != nil {
		return "", err
	}
	return tmpFile.Name(), nil

}


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

<TITLE>
ItemContents (FreeTTS 1.2)
</TITLE>

<META NAME="keywords" CONTENT="com.sun.speech.freetts.ItemContents class">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.sun.speech.freetts

Class ItemContents

java.lang.Object
  com.sun.speech.freetts.ItemContents

public class ItemContents
extends java.lang.Object

Contains the information that is shared between multiple items.

Constructor Summary

ItemContents()

          Class Constructor.

Method Summary

 void
addItemRelation(java.lang.String relationName,
                Item item)

          Adds the given item to the set of relations.

 FeatureSet
getFeatures()

          Returns the feature set for this item contents.

 Item
getItemRelation(java.lang.String relationName)

          Given the name of a relation, returns the item the shares the
 same ItemContents.

 void
removeItemRelation(java.lang.String relationName)

          Removes the relation/item mapping from this ItemContents.

 void
showRelations()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ItemContents

public ItemContents()

Class Constructor.

Method Detail

addItemRelation

public void addItemRelation(java.lang.String relationName,
                            Item item)

Adds the given item to the set of relations. Whenever an item
 is added to a relation, it should add the name and the Item reference
 to this set of name/item mappings. This allows an item to find
 out the set of all relations that it is contained in.

Parameters:
relationName - the name of the relation
item - the item reference in the relation

removeItemRelation

public void removeItemRelation(java.lang.String relationName)

Removes the relation/item mapping from this ItemContents.

Parameters:
relationName - the name of the relation/item to remove

showRelations

public void showRelations()

getItemRelation

public Item getItemRelation(java.lang.String relationName)

Given the name of a relation, returns the item the shares the
 same ItemContents.

Parameters:
relationName - the name of the relation of interest

Returns:
the item associated with this ItemContents in the named
 relation, or null if it does not exist

getFeatures

public FeatureSet getFeatures()

Returns the feature set for this item contents.

Returns:
the FeatureSet for this contents

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

redpajama_set_name: RedPajamaGithub


text:
angular.module(PKG.name + '.feature.mapreduce')
  .controller('MapreduceStatusController', function ($filter, $scope, $state, MyCDAPDataSource) {
    var myNumber = $filter('myNumber');
    if ($scope.RunsController.runs.length > 0) {
      var runid = $scope.RunsController.runs.selected.runid;

      var params = {
        namespace: $state.params.namespace,
        appId: $state.params.appId,
        mapreduceId: $state.params.programId,
        runId: runid,
        scope: $scope
      };

      var dataSrc = new MyCDAPDataSource($scope);

      /**
       * Changing it back to dataSrc because sometimes the backend returns NaN and JSON.parse error
       * out when the value is NaN. The way we are fixing this is to send the query with json: false.
       * $resource returns split string when the return value is just a simple string.
       **/
      dataSrc.poll({
        _cdapNsPath: '/apps/' + params.appId + '/mapreduce/' + params.mapreduceId + '/runs/' + params.runId + '/info',
        json: false
      }, function (res) {
        res = res.replace(/\bNaN\b/g, '"NaN"');
        try {
          res = JSON.parse(res);
        } catch(e) {
          console.warn('Unable parse response for Mapreduce program: ', params.mapreduceId);
          res = {};
        }

        this.info = res;

        this.mapProgress = Math.floor(res.mapProgress * 100);
        this.reduceProgress = Math.floor(res.reduceProgress * 100);

        this.mapperStats = getStats(this.info.mapTasks, this.info.complete);
        this.mapperStats.inputRecords = myNumber(this.info.counters.MAP_INPUT_RECORDS);
        this.mapperStats.outputRecords = myNumber(this.info.counters.MAP_OUTPUT_RECORDS);

        this.reducerStats = getStats(this.info.reduceTasks, this.info.complete);
        this.reducerStats.inputRecords = myNumber(this.info.counters.REDUCE_INPUT_RECORDS);
        this.reducerStats.outputRecords = myNumber(this.info.counters.REDUCE_OUTPUT_RECORDS);
      }.bind(this));
    }

    this.getFailedTasks = function (tasks) {
      var failed = 0;
      angular.forEach(tasks, function (task) {
        if(task.state === 'FAILED') {
          failed++;
        }
      });
      return failed;
    };

    function getStats(tasks, completeInfo) {
      var stats = {
        completed: 0,
        running: 0,
        pending: 0,
        killed: 0,
        failed: 0,
        total: 0
      };

      angular.forEach(tasks, function (task) {
        switch (task.state) {
          case 'SUCCEEDED':
            stats.completed++;
            break;
          case 'FAILED':
            stats.failed++;
            break;
          case 'SCHEDULED':
            stats.pending++;
            break;
          case 'RUNNING':
            stats.running++;
            break;
          case 'KILLED':
            stats.killed++;
            break;
        }

        stats.total++;
      });

      if (completeInfo === false) {
        var NA = 'NA';
        return {
          completed: NA,
          running: NA,
          pending: NA,
          killed: NA,
          failed: NA,
          total: stats.total
        };
      }

      angular.forEach(Object.keys(stats), function(key) {
        stats[key] = myNumber(stats[key]);
      });
      return stats;

    }

  });


text:
using System;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;

namespace Microsoft.DotNet.Build.Tasks.Packaging
{
    internal static class VersionUtility
    {
        public static readonly Version MaxVersion = new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue);

        public static bool IsCompatibleApiVersion(Version referenceVersion, Version definitionVersion)
        {
            return (referenceVersion.Major == definitionVersion.Major &&
                referenceVersion.Minor == definitionVersion.Minor &&
                referenceVersion.Build <= definitionVersion.Build &&
                referenceVersion.Revision <= definitionVersion.Revision);
        }

        public static Version GetAssemblyVersion(string assemblyPath)
        {
            using (var fileStream = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read))
            {
                return GetAssemblyVersion(fileStream);
            }
        }

        public static Version GetAssemblyVersion(Stream assemblyStream)
        {
            Version result = null;
            try
            {
                using (PEReader peReader = new PEReader(assemblyStream, PEStreamOptions.LeaveOpen))
                {
                    if (peReader.HasMetadata)
                    {
                        MetadataReader reader = peReader.GetMetadataReader();
                        if (reader.IsAssembly)
                        {
                            result = reader.GetAssemblyDefinition().Version;
                        }
                    }
                }
            }
            catch (BadImageFormatException)
            {
                // not a PE
            }

            return result;
        }

        public static Version As3PartVersion(Version version)
        {
            int build = version.Build;

            if (build == -1)
            {
                // we have a 2-part version
                build = 0;
            }
            else if (version.Revision == -1)
            {
                // we already have a 3-part version
                return version;
            }

            return new Version(version.Major, version.Minor, build);
        }

        public static Version As4PartVersion(Version version)
        {
            int build = version.Build, revision = version.Revision;

            if (build == -1)
            {
                // we have a 2-part version
                build = 0;
                revision = 0;
            }
            else if (revision == -1)
            {
                // we have a 3-part version
                revision = 0;
            }
            else
            {
                // we already have a 4-part version
                return version;
            }

            return new Version(version.Major, version.Minor, build, revision);
        }
    }
}


text:
namespace cxxu {
namespace sort {
namespace details {

namespace mpl = boost::mpl;

template <typename PodType>
struct radix_pod_info {
    // Real types are processed as integers
    typedef mpl::map<
        mpl::pair<float, uint32_t>,
        mpl::pair<double, uint64_t>
    > integer_map;

    typedef PodType pod_type;

    // Base type to process, either the same as pod_type or a corresponding
    // integer type for real types
    typedef typename mpl::eval_if<
        typename mpl::has_key<integer_map, pod_type>::type
      , mpl::at<integer_map, pod_type>
      , mpl::identity<pod_type>
    >::type radix_pod_type;
};

} // namespace details
} // namespace sort
} // namespace cxxu

#endif // __CXXU_SORT_DETAILS_RADIX_POD_INFO_H__


text:
cask 'vagrant-manager' do
  version '2.6.0'
  sha256 'ed9ad3f1b6a97e82c959812b0779036946903630627914b02684d53ad71b1052'

  # github.com/lanayotech/vagrant-manager was verified as official when first introduced to the cask
  url "https://github.com/lanayotech/vagrant-manager/releases/download/#{version}/vagrant-manager-#{version}.dmg"
  appcast 'https://github.com/lanayotech/vagrant-manager/releases.atom'
  name 'Vagrant Manager'
  homepage 'http://vagrantmanager.com/'

  app 'Vagrant Manager.app'

  uninstall login_item: 'Vagrant Manager',
            quit:       'lanayo.Vagrant-Manager'

  zap trash: [
               '~/Library/Caches/lanayo.Vagrant-Manager',
               '~/Library/Preferences/lanayo.Vagrant-Manager.plist',
             ]
end


text:
package kafka.utils

import java.nio.charset.StandardCharsets

import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node._
import kafka.utils.JsonTest.TestObject
import kafka.utils.json.JsonValue
import org.junit.Assert._
import org.junit.Test

import scala.jdk.CollectionConverters._
import scala.collection.Map

object JsonTest {
  case class TestObject(@JsonProperty("foo") foo: String, @JsonProperty("bar") bar: Int)
}

class JsonTest {

  @Test
  def testJsonParse(): Unit = {
    val jnf = JsonNodeFactory.instance

    assertEquals(Json.parseFull("{}"), Some(JsonValue(new ObjectNode(jnf))))

    assertEquals(Json.parseFull("""{"foo":"bar"s}"""), None)

    val objectNode = new ObjectNode(
      jnf,
      Map[String, JsonNode]("foo" -> new TextNode("bar"), "is_enabled" -> BooleanNode.TRUE).asJava
    )
    assertEquals(Json.parseFull("""{"foo":"bar", "is_enabled":true}"""), Some(JsonValue(objectNode)))

    val arrayNode = new ArrayNode(jnf)
    Vector(1, 2, 3).map(new IntNode(_)).foreach(arrayNode.add)
    assertEquals(Json.parseFull("[1, 2, 3]"), Some(JsonValue(arrayNode)))

    // Test with encoder that properly escapes backslash and quotes
    val map = Map("foo1" -> """bar1\,bar2""", "foo2" -> """\bar""")
    val encoded = Json.legacyEncodeAsString(map)
    val decoded = Json.parseFull(encoded)
    assertEquals(Json.parseFull("""{"foo1":"bar1\\,bar2", "foo2":"\\bar"}"""), decoded)
  }

  @Test
  def testLegacyEncodeAsString(): Unit = {
    assertEquals("null", Json.legacyEncodeAsString(null))
    assertEquals("1", Json.legacyEncodeAsString(1))
    assertEquals("1", Json.legacyEncodeAsString(1L))
    assertEquals("1", Json.legacyEncodeAsString(1.toByte))
    assertEquals("1", Json.legacyEncodeAsString(1.toShort))
    assertEquals("1.0", Json.legacyEncodeAsString(1.0))
    assertEquals(""""str"""", Json.legacyEncodeAsString("str"))
    assertEquals("true", Json.legacyEncodeAsString(true))
    assertEquals("false", Json.legacyEncodeAsString(false))
    assertEquals("[]", Json.legacyEncodeAsString(Seq()))
    assertEquals("[1,2,3]", Json.legacyEncodeAsString(Seq(1,2,3)))
    assertEquals("""[1,"2",[3]]""", Json.legacyEncodeAsString(Seq(1,"2",Seq(3))))
    assertEquals("{}", Json.legacyEncodeAsString(Map()))
    assertEquals("""{"a":1,"b":2}""", Json.legacyEncodeAsString(Map("a" -> 1, "b" -> 2)))
    assertEquals("""{"a":[1,2],"c":[3,4]}""", Json.legacyEncodeAsString(Map("a" -> Seq(1,2), "c" -> Seq(3,4))))
    assertEquals(""""str1\\,str2"""", Json.legacyEncodeAsString("""str1\,str2"""))
    assertEquals(""""\"quoted\""""", Json.legacyEncodeAsString(""""quoted""""))

  }

  @Test
  def testEncodeAsString(): Unit = {
    assertEquals("null", Json.encodeAsString(null))
    assertEquals("1", Json.encodeAsString(1))
    assertEquals("1", Json.encodeAsString(1L))
    assertEquals("1", Json.encodeAsString(1.toByte))
    assertEquals("1", Json.encodeAsString(1.toShort))
    assertEquals("1.0", Json.encodeAsString(1.0))
    assertEquals(""""str"""", Json.encodeAsString("str"))
    assertEquals("true", Json.encodeAsString(true))
    assertEquals("false", Json.encodeAsString(false))
    assertEquals("[]", Json.encodeAsString(Seq().asJava))
    assertEquals("[null]", Json.encodeAsString(Seq(null).asJava))
    assertEquals("[1,2,3]", Json.encodeAsString(Seq(1,2,3).asJava))
    assertEquals("""[1,"2",[3],null]""", Json.encodeAsString(Seq(1,"2",Seq(3).asJava,null).asJava))
    assertEquals("{}", Json.encodeAsString(Map().asJava))
    assertEquals("""{"a":1,"b":2,"c":null}""", Json.encodeAsString(Map("a" -> 1, "b" -> 2, "c" -> null).asJava))
    assertEquals("""{"a":[1,2],"c":[3,4]}""", Json.encodeAsString(Map("a" -> Seq(1,2).asJava, "c" -> Seq(3,4).asJava).asJava))
    assertEquals("""{"a":[1,2],"b":[3,4],"c":null}""", Json.encodeAsString(Map("a" -> Seq(1,2).asJava, "b" -> Seq(3,4).asJava, "c" -> null).asJava))
    assertEquals(""""str1\\,str2"""", Json.encodeAsString("""str1\,str2"""))
    assertEquals(""""\"quoted\""""", Json.encodeAsString(""""quoted""""))
  }

  @Test
  def testEncodeAsBytes(): Unit = {
    assertEquals("null", new String(Json.encodeAsBytes(null), StandardCharsets.UTF_8))
    assertEquals("1", new String(Json.encodeAsBytes(1), StandardCharsets.UTF_8))
    assertEquals("1", new String(Json.encodeAsBytes(1L), StandardCharsets.UTF_8))
    assertEquals("1", new String(Json.encodeAsBytes(1.toByte), StandardCharsets.UTF_8))
    assertEquals("1", new String(Json.encodeAsBytes(1.toShort), StandardCharsets.UTF_8))
    assertEquals("1.0", new String(Json.encodeAsBytes(1.0), StandardCharsets.UTF_8))
    assertEquals(""""str"""",  new String(Json.encodeAsBytes("str"), StandardCharsets.UTF_8))
    assertEquals("true", new String(Json.encodeAsBytes(true), StandardCharsets.UTF_8))
    assertEquals("false", new String(Json.encodeAsBytes(false), StandardCharsets.UTF_8))
    assertEquals("[]", new String(Json.encodeAsBytes(Seq().asJava), StandardCharsets.UTF_8))
    assertEquals("[null]", new String(Json.encodeAsBytes(Seq(null).asJava), StandardCharsets.UTF_8))
    assertEquals("[1,2,3]", new String(Json.encodeAsBytes(Seq(1,2,3).asJava), StandardCharsets.UTF_8))
    assertEquals("""[1,"2",[3],null]""", new String(Json.encodeAsBytes(Seq(1,"2",Seq(3).asJava,null).asJava), StandardCharsets.UTF_8))
    assertEquals("{}", new String(Json.encodeAsBytes(Map().asJava), StandardCharsets.UTF_8))
    assertEquals("""{"a":1,"b":2,"c":null}""", new String(Json.encodeAsBytes(Map("a" -> 1, "b" -> 2, "c" -> null).asJava), StandardCharsets.UTF_8))
    assertEquals("""{"a":[1,2],"c":[3,4]}""", new String(Json.encodeAsBytes(Map("a" -> Seq(1,2).asJava, "c" -> Seq(3,4).asJava).asJava), StandardCharsets.UTF_8))
    assertEquals("""{"a":[1,2],"b":[3,4],"c":null}""", new String(Json.encodeAsBytes(Map("a" -> Seq(1,2).asJava, "b" -> Seq(3,4).asJava, "c" -> null).asJava), StandardCharsets.UTF_8))
    assertEquals(""""str1\\,str2"""", new String(Json.encodeAsBytes("""str1\,str2"""), StandardCharsets.UTF_8))
    assertEquals(""""\"quoted\""""", new String(Json.encodeAsBytes(""""quoted""""), StandardCharsets.UTF_8))
  }

  @Test
  def testParseTo() = {
    val foo = "baz"
    val bar = 1

    val result = Json.parseStringAs[TestObject](s"""{"foo": "$foo", "bar": $bar}""")

    assertEquals(Right(TestObject(foo, bar)), result)
  }

  @Test
  def testParseToWithInvalidJson() = {
    val result = Json.parseStringAs[TestObject]("{invalid json}")
    assertEquals(Left(classOf[JsonParseException]), result.left.map(_.getClass))
  }
}


text:
import { initializeApp } from "firebase/app";
import { getFunctions } from "firebase/functions";

initializeApp({
  // Your Firebase Web SDK configuration
  // [START_EXCLUDE]
  projectId: "<PROJECT_ID>",
  apiKey: "<API_KEY>",
  // [END_EXCLUDE]
});

const functions = getFunctions();
// [END fb_functions_initialize_modular]


text:
package com.clouck.repository;

import static org.springframework.data.mongodb.core.query.Criteria.where;

import java.util.Collection;
import java.util.List;

import org.apache.commons.lang3.Validate;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import com.clouck.exception.ClouckUnexpectedConditionException;
import com.clouck.model.Region;
import com.clouck.model.ResourceType;
import com.clouck.model.aws.AbstractResource;
import com.clouck.model.aws.ec2.Ec2Version;
import com.clouck.model.aws.ec2.Ec2VersionMeta;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;

@Repository
public class AwsRepositoryImpl implements AwsRepository {
    private static final Logger log = LoggerFactory.getLogger(AwsRepositoryImpl.class);

    @Autowired
    private MongoOperations mongoOps;

    private Query createQuery(String accountId, ResourceType resourceType, Region region, DateTime dt,
            Boolean isIncludeTime, Boolean isAsc, boolean isUptoOrFrom, Pageable pageable) {
        Query query = new Query(createCriteria(accountId, resourceType, region, dt, isIncludeTime, isUptoOrFrom));

        if (isAsc != null) {
            if (isAsc) {
                query.with(new Sort(Direction.ASC, "timeDetected"));
            } else {
                query.with(new Sort(Direction.DESC, "timeDetected"));
            }
        }

        if (pageable != null) {
            query.with(pageable);
        }

        return query;
    }

    private Query createQuery(Criteria criteria, Boolean isAsc, Pageable pageable) {
        Query query = new Query(criteria);

        if (isAsc != null) {
            if (isAsc) {
                query.with(new Sort(Direction.ASC, "timeDetected"));
            } else {
                query.with(new Sort(Direction.DESC, "timeDetected"));
            }
        }

        if (pageable != null) {
            query.with(pageable);
        }

        return query;
    }

    private Criteria createCriteria(String accountId, ResourceType resourceType, Region region, DateTime dt,
            Boolean isIncludeTime, boolean isUptoOrFrom) {
        Validate.notNull(accountId);
        Validate.isTrue((dt != null && isIncludeTime != null) || (dt == null && isIncludeTime == null));
        Validate.isTrue(region == null ? true : !region.equals(Region.All));
        Criteria criteria = where("accountId").is(accountId);

        if (resourceType != null) {
            criteria = criteria.and("resourceType").is(resourceType);
        }

        if (region != null) {
            criteria = criteria.and("region").is(region);
        }

        if (dt != null) {
            if (isIncludeTime) {
                if (isUptoOrFrom) {
                    criteria = criteria.and("timeDetected").lte(dt.toDate());
                } else {
                    criteria = criteria.and("timeDetected").gte(dt.toDate());
                }
            } else {
                if (isUptoOrFrom) {
                    criteria = criteria.and("timeDetected").lt(dt.toDate());
                } else {
                    criteria = criteria.and("timeDetected").gt(dt.toDate());
                }
            }
        }

        return criteria;
    }

    @Override
    public Optional<Ec2Version> findEc2VersionUpto(String accountId, ResourceType resourceType, Region region, DateTime dt, Boolean isIncludeTime, boolean isAsc) {
        Query query = createQuery(accountId, resourceType, region, dt, isIncludeTime, isAsc, true, null);

        Ec2Version result = mongoOps.findOne(query, Ec2Version.class);

        if (result != null) {
            return Optional.of(result);
        } else {
            return Optional.absent();
        }
    }

    @Override
    public List<Ec2Version> findEc2VersionsUpto(String accountId, ResourceType resourceType, Region region, DateTime dt, Boolean isIncludeTime, boolean isAsc) {
        Query query = createQuery(accountId, resourceType, region, dt, isIncludeTime, isAsc, true, null);

        return mongoOps.find(query, Ec2Version.class);
    }

    @Override
    public long countEc2VersionsUpto(String accountId, ResourceType resourceType, Region region, DateTime dt, Boolean isIncludeTime) {
        Query query = createQuery(accountId, resourceType, region, dt, isIncludeTime, null, true, null);

        return mongoOps.count(query, Ec2Version.class);
    }

    @Override
    public List<Ec2Version> findEc2VersionsFrom(String accountId, ResourceType resourceType, Region region, DateTime dt, Boolean isIncludeTime, Boolean isAsc) {
        Query query = createQuery(accountId, resourceType, region, dt, isIncludeTime, isAsc, false, null);

        return mongoOps.find(query, Ec2Version.class);
    }

    @Override
    public Optional<Ec2Version> findEc2VersionAt(String accountId, ResourceType resourceType, DateTime dateTime) {
        Ec2Version result = mongoOps.findOne(
                new Query(where("accountId").is(accountId).
                        and("resourceType").is(resourceType).
                        and("timeDetected").is(dateTime.toDate())),
                        Ec2Version.class);
        if (result != null) {
            return Optional.of(result);
        } else {
            return Optional.absent();
        }
    }

    @Override
    public long countEc2VersionMetasUpto(String accountId, ResourceType resourceType, Region region, DateTime dt, Boolean isIncludeTime, String uniqueId) {
        Criteria criteria = createCriteria(accountId, resourceType, region, dt, isIncludeTime, true);
        if (uniqueId != null) {
            criteria = criteria.and("events.uniqueId").is(uniqueId);
        }

        Query query = createQuery(criteria, null, null);

        return mongoOps.count(query, Ec2VersionMeta.class);
    }

    @Override
    public Optional<Ec2VersionMeta> findEc2VersionMetaUpto(String accountId, ResourceType resourceType, Region region, DateTime dt, Boolean isIncludeTime, boolean isAsc) {
        Query query = createQuery(accountId, resourceType, region, dt, isIncludeTime, isAsc, true, null);

        Ec2VersionMeta result = mongoOps.findOne(query, Ec2VersionMeta.class);

        if (result != null) {
            return Optional.of(result);
        } else {
            return Optional.absent();
        }
    }

    @Override
    public List<Ec2VersionMeta> findEc2VersionMetasUpto(String accountId, ResourceType resourceType, Region region,
            DateTime dt, Boolean isIncludeTime, boolean isAsc, Pageable pageable, String uniqueId) {
        Criteria criteria = createCriteria(accountId, resourceType, region, dt, isIncludeTime, true);
        if (uniqueId != null) {
            criteria = criteria.and("events.uniqueId").is(uniqueId);
        }

        Query query = createQuery(criteria, isAsc, pageable);

        return mongoOps.find(query, Ec2VersionMeta.class);
    }

    @Override
    public List<Ec2VersionMeta> findEc2VersionMetasOrderByTimeDetectedDesc(String accountId, ResourceType rt, Region region, String uniqueId) {
        Criteria criteria = where("accountId").is(accountId).and("resourceType").is(rt).and("events.uniqueId").is(uniqueId);

        if (region != null) {
            criteria = criteria.and("region").is(region);
        }

        Query query = new Query(criteria).with(new Sort(Direction.DESC, "timeDetected"));

        return mongoOps.find(query, Ec2VersionMeta.class);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<AbstractResource<?>> findResources(Collection<String> ids, ResourceType resourceType) {
        return (List<AbstractResource<?>>) mongoOps.find(new Query(where("id").in(ids)), resourceType.getResourceClass());
    }

    @Override
    @SuppressWarnings("rawtypes")
    public Optional<AbstractResource> findResource(String resourceId, ResourceType resourceType) {
        AbstractResource result = mongoOps.findOne(
                new Query(where("id").is(resourceId)),
                        resourceType.getResourceClass());
        if (result != null) {
            return Optional.of(result);
        } else {
            return Optional.absent();
        }
    }

    @Override
    public List<? extends AbstractResource<?>> findResource(ResourceType resourceType, String accountId, String uniqueId) {
        return findResource(resourceType, accountId, uniqueId, null);
    }

    @Override
    public List<? extends AbstractResource<?>> findResource(ResourceType resourceType, String accountId, String uniqueId, String secondUniqueId) {
        List<String> uniqueIdNames = Lists.newArrayList(resourceType.getUniqueIdNames());

        switch (uniqueIdNames.size()) {
        case 1:
            return mongoOps.find(
                    new Query(where("resource." + uniqueIdNames.get(0)).is(uniqueId).
                            and("accountId").is(accountId)).
                            with(new Sort(Direction.DESC, "timeDetected")),
                            resourceType.getResourceClass());
        case 2:
            return mongoOps.find(
                    new Query(where("resource." + uniqueIdNames.get(0)).is(uniqueId).
                            and("resource." + uniqueIdNames.get(1)).is(secondUniqueId).
                            and("accountId").is(accountId)).
                            with(new Sort(Direction.DESC, "timeDetected")),
                            resourceType.getResourceClass());
        default:
            throw new ClouckUnexpectedConditionException("up to now, should only support up to two combinations");
        }
    }
}


text:
<?php

namespace Grid\Search\Controller;

use Grid\Search\Query;
use Zend\View\Model\JsonModel;
use Grid\Paragraph\View\Model\MetaContent;

/**
 * SearchController
 *
 * @author David Pozsar <david.pozsar@megaweb.hu>
 */
class SearchController extends AbstractSearchController
{

    /**
     * Search index action
     */
    public function indexAction()
    {
        /* @var $form \Zend\Form\Form */
        /* @var $items \Zend\Form\Element\Select */
        $results = $this->getResults();
        $form    = $this->getServiceLocator()
                        ->get( 'Form' )
                        ->get( 'Grid\Search\Search' );
        $items   = $form->get( 'items' );
        $options = $items->getValueOptions();
        $hasit   = false;

        $this->paragraphLayout();

        foreach ( $options as $option )
        {
            if ( is_array( $option ) )
            {
                $hasit = isset( $option['value'] ) && $option['value'] == $results['items'];
            }
            else if ( is_numeric( $option ) )
            {
                $hasit = $option == $results['items'];
            }

            if ( $hasit )
            {
                break;
            }
        }

        if ( ! $hasit )
        {
            $options[] = array(
                'label' => $results['items'],
                'value' => $results['items'],
            );

            $items->setValueOptions( $options );
        }

        $form->setData( array(
            'items' => $results['items'],
            'query' => $results['query'],
            'type'  => $results['type'],
            'all'   => ! empty( $results['all'] ),
        ) );

        $results['form'] = $form;
        return new MetaContent( 'search.results', $results );
    }

    /**
     * Search autocomplete action
     */
    public function autocompleteAction()
    {
        list( $suggestions ) = $this->getSuggestions();
        return new JsonModel( $suggestions );
    }

    /**
     * Debug query action
     */
    public function debugQueryAction()
    {
        $query  = $this->param( 'query' );
        $tokens = Query\Token::lexer( $query );
        $parsed = Query\Parser::parse( $query );
        $model  = $this->getServiceLocator()
                       ->get( 'Grid\Search\Model\Result\Model' );

        $this->paragraphLayout();

        return array(
            'query'             => $query,
            'tokens'            => $tokens,
            'parsed'            => $parsed,
            'toRepresentation'  => $parsed->toRepresentation(),
            'toQueryString'     => $tsquery = $parsed->toQueryString(),
            'effective'         => $model->debugQuery(
                (string) $this->locale(),
                $tsquery
            ),
        );
    }

}


text:
package org.wso2.developerstudio.eclipse.gmf.esb;

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

import org.eclipse.emf.common.util.Enumerator;

/**
 *
 * A representation of the literals of the enumeration 'Callout Security Type',
 * and utility methods for working with them.
 *
 * @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getCalloutSecurityType()
 * @model
 * @generated
 */
public enum CalloutSecurityType implements Enumerator {
	/**
	 * The 'FALSE' literal object.
	 *
	 *
	 * @see #FALSE_VALUE
	 * @generated
	 * @ordered
	 */
	FALSE(0, "FALSE", "FALSE"),

	/**
	 * The 'TRUE' literal object.
	 *
	 *
	 * @see #TRUE_VALUE
	 * @generated
	 * @ordered
	 */
	TRUE(1, "TRUE", "TRUE");

	/**
	 * The 'FALSE' literal value.
	 *
	 *

	 * If the meaning of 'FALSE' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #FALSE
	 * @model
	 * @generated
	 * @ordered
	 */
	public static final int FALSE_VALUE = 0;

	/**
	 * The 'TRUE' literal value.
	 *
	 *

	 * If the meaning of 'TRUE' literal object isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @see #TRUE
	 * @model
	 * @generated
	 * @ordered
	 */
	public static final int TRUE_VALUE = 1;

	/**
	 * An array of all the 'Callout Security Type' enumerators.
	 *
	 *
	 * @generated
	 */
	private static final CalloutSecurityType[] VALUES_ARRAY =
		new CalloutSecurityType[] {
			FALSE,
			TRUE,
		};

	/**
	 * A public read-only list of all the 'Callout Security Type' enumerators.
	 *
	 *
	 * @generated
	 */
	public static final List<CalloutSecurityType> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));

	/**
	 * Returns the 'Callout Security Type' literal with the specified literal value.
	 *
	 *
	 * @param literal the literal.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static CalloutSecurityType get(String literal) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			CalloutSecurityType result = VALUES_ARRAY[i];
			if (result.toString().equals(literal)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Callout Security Type' literal with the specified name.
	 *
	 *
	 * @param name the name.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static CalloutSecurityType getByName(String name) {
		for (int i = 0; i < VALUES_ARRAY.length; ++i) {
			CalloutSecurityType result = VALUES_ARRAY[i];
			if (result.getName().equals(name)) {
				return result;
			}
		}
		return null;
	}

	/**
	 * Returns the 'Callout Security Type' literal with the specified integer value.
	 *
	 *
	 * @param value the integer value.
	 * @return the matching enumerator or null.
	 * @generated
	 */
	public static CalloutSecurityType get(int value) {
		switch (value) {
			case FALSE_VALUE: return FALSE;
			case TRUE_VALUE: return TRUE;
		}
		return null;
	}

	/**
	 *
	 *
	 * @generated
	 */
	private final int value;

	/**
	 *
	 *
	 * @generated
	 */
	private final String name;

	/**
	 *
	 *
	 * @generated
	 */
	private final String literal;

	/**
	 * Only this class can construct instances.
	 *
	 *
	 * @generated
	 */
	private CalloutSecurityType(int value, String name, String literal) {
		this.value = value;
		this.name = name;
		this.literal = literal;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public int getValue() {
	  return value;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getName() {
	  return name;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getLiteral() {
	  return literal;
	}

	/**
	 * Returns the literal value of the enumerator, which is its string representation.
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		return literal;
	}

} //CalloutSecurityType


text:
<?php

declare(strict_types=1);

namespace SolariumSpecification\Test\QuerySpecification\Operation;

use Mockery;
use Mockery\MockInterface;
use PHPUnit\Framework\TestCase;
use SolariumSpecification\QueryInterface;
use SolariumSpecification\QuerySpecification\Operator\AndX;
use SolariumSpecification\QuerySpecificationInterface;

/**
 * @coversDefaultClass \SolariumSpecification\QuerySpecification\Operator\AndX
 */
class AndXTest extends TestCase
{
    /**
     * {@inheritdoc}
     */
    public function tearDown()
    {
        parent::tearDown();

        Mockery::close();
    }

    /**
     * @covers ::__construct
     * @covers ::append
     * @covers ::getQueryString
     */
    public function testQueryStringCanBeRetrieved()
    {
        /** @var QuerySpecificationInterface|MockInterface $mockQuerySpecification1 */
        $mockQuerySpecification1 = Mockery::mock(QuerySpecificationInterface::class, function (MockInterface $mock) {
            $mockQuery = Mockery::mock(QueryInterface::class, function (MockInterface $mock) {
                $mock->shouldReceive('getQueryString')->once()->withNoArgs()->andReturn('a');
            });

            $mock->shouldReceive('getQuery')->once()->withNoArgs()->andReturn($mockQuery);
        });

        /** @var QuerySpecificationInterface|MockInterface $mockQuerySpecification2 */
        $mockQuerySpecification2 = Mockery::mock(QuerySpecificationInterface::class, function (MockInterface $mock) {
            $mockQuery = Mockery::mock(QueryInterface::class, function (MockInterface $mock) {
                $mock->shouldReceive('getQueryString')->once()->withNoArgs()->andReturn('b');
            });

            $mock->shouldReceive('getQuery')->once()->withNoArgs()->andReturn($mockQuery);
        });

        $andX = new AndX([$mockQuerySpecification1]);

        $andX->append($mockQuerySpecification2);

        $this->assertEquals('a AND b', $andX->getQueryString());
    }

    /**
     * @covers ::getQuery
     */
    public function testQueryCanBeRetrieved()
    {
        $andX = new AndX();

        $this->assertSame($andX, $andX->getQuery());
    }
}


text:
<?php

namespace Joindin\Api;

class Response
{
    protected $resource;
    protected $url = '';
    protected $userUrl = '';
    protected $meta = array();

    public function __construct($resource, $meta)
    {
        $this->setResource($resource);
        $this->setMeta($meta);
    }

    /**
     * @return mixed
     */
    public function getResource()
    {
        return $this->resource;
    }

    /**
     * @param object|string[] $resource
     */
    public function setResource($resource)
    {
        $this->resource = $resource;
    }

    /**
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * @return string
     */
    public function getUserUrl()
    {
        return $this->userUrl;
    }

    /**
     * @return array
     */
    public function getMeta()
    {
        return $this->meta;
    }

    /**
     * @param array $meta
     */
    public function setMeta($meta)
    {
        $this->url = $meta['this_page'];
        $this->userUrl = isset($meta['user_uri']) ? $meta['user_uri'] : null;

        unset($meta['this_page']);
        unset($meta['user_uri']);

        $this->meta = $meta;
    }
}