text:
//go:build windows
// +build windows

package winio

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net"
	"os"
	"syscall"
	"time"
	"unsafe"

	"golang.org/x/sys/windows"

	"github.com/Microsoft/go-winio/internal/socket"
	"github.com/Microsoft/go-winio/pkg/guid"
)

const afHVSock = 34 // AF_HYPERV

// Well known Service and VM IDs
//https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/user-guide/make-integration-service#vmid-wildcards

// HvsockGUIDWildcard is the wildcard VmId for accepting connections from all partitions.
func HvsockGUIDWildcard() guid.GUID { // 00000000-0000-0000-0000-000000000000
	return guid.GUID{}
}

// HvsockGUIDBroadcast is the wildcard VmId for broadcasting sends to all partitions.
func HvsockGUIDBroadcast() guid.GUID { //ffffffff-ffff-ffff-ffff-ffffffffffff
	return guid.GUID{
		Data1: 0xffffffff,
		Data2: 0xffff,
		Data3: 0xffff,
		Data4: [8]uint8{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
	}
}

// HvsockGUIDLoopback is the Loopback VmId for accepting connections to the same partition as the connector.
func HvsockGUIDLoopback() guid.GUID { // e0e16197-dd56-4a10-9195-5ee7a155a838
	return guid.GUID{
		Data1: 0xe0e16197,
		Data2: 0xdd56,
		Data3: 0x4a10,
		Data4: [8]uint8{0x91, 0x95, 0x5e, 0xe7, 0xa1, 0x55, 0xa8, 0x38},
	}
}

// HvsockGUIDSiloHost is the address of a silo's host partition:
//   - The silo host of a hosted silo is the utility VM.
//   - The silo host of a silo on a physical host is the physical host.
func HvsockGUIDSiloHost() guid.GUID { // 36bd0c5c-7276-4223-88ba-7d03b654c568
	return guid.GUID{
		Data1: 0x36bd0c5c,
		Data2: 0x7276,
		Data3: 0x4223,
		Data4: [8]byte{0x88, 0xba, 0x7d, 0x03, 0xb6, 0x54, 0xc5, 0x68},
	}
}

// HvsockGUIDChildren is the wildcard VmId for accepting connections from the connector's child partitions.
func HvsockGUIDChildren() guid.GUID { // 90db8b89-0d35-4f79-8ce9-49ea0ac8b7cd
	return guid.GUID{
		Data1: 0x90db8b89,
		Data2: 0xd35,
		Data3: 0x4f79,
		Data4: [8]uint8{0x8c, 0xe9, 0x49, 0xea, 0xa, 0xc8, 0xb7, 0xcd},
	}
}

// HvsockGUIDParent is the wildcard VmId for accepting connections from the connector's parent partition.
// Listening on this VmId accepts connection from:
//   - Inside silos: silo host partition.
//   - Inside hosted silo: host of the VM.
//   - Inside VM: VM host.
//   - Physical host: Not supported.
func HvsockGUIDParent() guid.GUID { // a42e7cda-d03f-480c-9cc2-a4de20abb878
	return guid.GUID{
		Data1: 0xa42e7cda,
		Data2: 0xd03f,
		Data3: 0x480c,
		Data4: [8]uint8{0x9c, 0xc2, 0xa4, 0xde, 0x20, 0xab, 0xb8, 0x78},
	}
}

// hvsockVsockServiceTemplate is the Service GUID used for the VSOCK protocol.
func hvsockVsockServiceTemplate() guid.GUID { // 00000000-facb-11e6-bd58-64006a7986d3
	return guid.GUID{
		Data2: 0xfacb,
		Data3: 0x11e6,
		Data4: [8]uint8{0xbd, 0x58, 0x64, 0x00, 0x6a, 0x79, 0x86, 0xd3},
	}
}

// An HvsockAddr is an address for a AF_HYPERV socket.
type HvsockAddr struct {
	VMID      guid.GUID
	ServiceID guid.GUID
}

type rawHvsockAddr struct {
	Family    uint16
	_         uint16
	VMID      guid.GUID
	ServiceID guid.GUID
}

var _ socket.RawSockaddr = &rawHvsockAddr{}

// Network returns the address's network name, "hvsock".
func (*HvsockAddr) Network() string {
	return "hvsock"
}

func (addr *HvsockAddr) String() string {
	return fmt.Sprintf("%s:%s", &addr.VMID, &addr.ServiceID)
}

// VsockServiceID returns an hvsock service ID corresponding to the specified AF_VSOCK port.
func VsockServiceID(port uint32) guid.GUID {
	g := hvsockVsockServiceTemplate() // make a copy
	g.Data1 = port
	return g
}

func (addr *HvsockAddr) raw() rawHvsockAddr {
	return rawHvsockAddr{
		Family:    afHVSock,
		VMID:      addr.VMID,
		ServiceID: addr.ServiceID,
	}
}

func (addr *HvsockAddr) fromRaw(raw *rawHvsockAddr) {
	addr.VMID = raw.VMID
	addr.ServiceID = raw.ServiceID
}

// Sockaddr returns a pointer to and the size of this struct.
//
// Implements the [socket.RawSockaddr] interface, and allows use in
// [socket.Bind] and [socket.ConnectEx].
func (r *rawHvsockAddr) Sockaddr() (unsafe.Pointer, int32, error) {
	return unsafe.Pointer(r), int32(unsafe.Sizeof(rawHvsockAddr{})), nil
}

// Sockaddr interface allows use with `sockets.Bind()` and `.ConnectEx()`.
func (r *rawHvsockAddr) FromBytes(b []byte) error {
	n := int(unsafe.Sizeof(rawHvsockAddr{}))

	if len(b) < n {
		return fmt.Errorf("got %d, want %d: %w", len(b), n, socket.ErrBufferSize)
	}

	copy(unsafe.Slice((*byte)(unsafe.Pointer(r)), n), b[:n])
	if r.Family != afHVSock {
		return fmt.Errorf("got %d, want %d: %w", r.Family, afHVSock, socket.ErrAddrFamily)
	}

	return nil
}

// HvsockListener is a socket listener for the AF_HYPERV address family.
type HvsockListener struct {
	sock *win32File
	addr HvsockAddr
}

var _ net.Listener = &HvsockListener{}

// HvsockConn is a connected socket of the AF_HYPERV address family.
type HvsockConn struct {
	sock          *win32File
	local, remote HvsockAddr
}

var _ net.Conn = &HvsockConn{}

func newHVSocket() (*win32File, error) {
	fd, err := syscall.Socket(afHVSock, syscall.SOCK_STREAM, 1)
	if err != nil {
		return nil, os.NewSyscallError("socket", err)
	}
	f, err := makeWin32File(fd)
	if err != nil {
		syscall.Close(fd)
		return nil, err
	}
	f.socket = true
	return f, nil
}

// ListenHvsock listens for connections on the specified hvsock address.
func ListenHvsock(addr *HvsockAddr) (_ *HvsockListener, err error) {
	l := &HvsockListener{addr: *addr}
	sock, err := newHVSocket()
	if err != nil {
		return nil, l.opErr("listen", err)
	}
	sa := addr.raw()
	err = socket.Bind(windows.Handle(sock.handle), &sa)
	if err != nil {
		return nil, l.opErr("listen", os.NewSyscallError("socket", err))
	}
	err = syscall.Listen(sock.handle, 16)
	if err != nil {
		return nil, l.opErr("listen", os.NewSyscallError("listen", err))
	}
	return &HvsockListener{sock: sock, addr: *addr}, nil
}

func (l *HvsockListener) opErr(op string, err error) error {
	return &net.OpError{Op: op, Net: "hvsock", Addr: &l.addr, Err: err}
}

// Addr returns the listener's network address.
func (l *HvsockListener) Addr() net.Addr {
	return &l.addr
}

// Accept waits for the next connection and returns it.
func (l *HvsockListener) Accept() (_ net.Conn, err error) {
	sock, err := newHVSocket()
	if err != nil {
		return nil, l.opErr("accept", err)
	}
	defer func() {
		if sock != nil {
			sock.Close()
		}
	}()
	c, err := l.sock.prepareIO()
	if err != nil {
		return nil, l.opErr("accept", err)
	}
	defer l.sock.wg.Done()

	// AcceptEx, per documentation, requires an extra 16 bytes per address.
	//
	// https://docs.microsoft.com/en-us/windows/win32/api/mswsock/nf-mswsock-acceptex
	const addrlen = uint32(16 + unsafe.Sizeof(rawHvsockAddr{}))
	var addrbuf [addrlen * 2]byte

	var bytes uint32
	err = syscall.AcceptEx(l.sock.handle, sock.handle, &addrbuf[0], 0 /*rxdatalen*/, addrlen, addrlen, &bytes, &c.o)
	if _, err = l.sock.asyncIO(c, nil, bytes, err); err != nil {
		return nil, l.opErr("accept", os.NewSyscallError("acceptex", err))
	}

	conn := &HvsockConn{
		sock: sock,
	}
	// The local address returned in the AcceptEx buffer is the same as the Listener socket's
	// address. However, the service GUID reported by GetSockName is different from the Listeners
	// socket, and is sometimes the same as the local address of the socket that dialed the
	// address, with the service GUID.Data1 incremented, but othertimes is different.
	// todo: does the local address matter? is the listener's address or the actual address appropriate?
	conn.local.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[0])))
	conn.remote.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[addrlen])))

	// initialize the accepted socket and update its properties with those of the listening socket
	if err = windows.Setsockopt(windows.Handle(sock.handle),
		windows.SOL_SOCKET, windows.SO_UPDATE_ACCEPT_CONTEXT,
		(*byte)(unsafe.Pointer(&l.sock.handle)), int32(unsafe.Sizeof(l.sock.handle))); err != nil {
		return nil, conn.opErr("accept", os.NewSyscallError("setsockopt", err))
	}

	sock = nil
	return conn, nil
}

// Close closes the listener, causing any pending Accept calls to fail.
func (l *HvsockListener) Close() error {
	return l.sock.Close()
}

// HvsockDialer configures and dials a Hyper-V Socket (ie, [HvsockConn]).
type HvsockDialer struct {
	// Deadline is the time the Dial operation must connect before erroring.
	Deadline time.Time

	// Retries is the number of additional connects to try if the connection times out, is refused,
	// or the host is unreachable
	Retries uint

	// RetryWait is the time to wait after a connection error to retry
	RetryWait time.Duration

	rt *time.Timer // redial wait timer
}

// Dial the Hyper-V socket at addr.
//
// See [HvsockDialer.Dial] for more information.
func Dial(ctx context.Context, addr *HvsockAddr) (conn *HvsockConn, err error) {
	return (&HvsockDialer{}).Dial(ctx, addr)
}

// Dial attempts to connect to the Hyper-V socket at addr, and returns a connection if successful.
// Will attempt (HvsockDialer).Retries if dialing fails, waiting (HvsockDialer).RetryWait between
// retries.
//
// Dialing can be cancelled either by providing (HvsockDialer).Deadline, or cancelling ctx.
func (d *HvsockDialer) Dial(ctx context.Context, addr *HvsockAddr) (conn *HvsockConn, err error) {
	op := "dial"
	// create the conn early to use opErr()
	conn = &HvsockConn{
		remote: *addr,
	}

	if !d.Deadline.IsZero() {
		var cancel context.CancelFunc
		ctx, cancel = context.WithDeadline(ctx, d.Deadline)
		defer cancel()
	}

	// preemptive timeout/cancellation check
	if err = ctx.Err(); err != nil {
		return nil, conn.opErr(op, err)
	}

	sock, err := newHVSocket()
	if err != nil {
		return nil, conn.opErr(op, err)
	}
	defer func() {
		if sock != nil {
			sock.Close()
		}
	}()

	sa := addr.raw()
	err = socket.Bind(windows.Handle(sock.handle), &sa)
	if err != nil {
		return nil, conn.opErr(op, os.NewSyscallError("bind", err))
	}

	c, err := sock.prepareIO()
	if err != nil {
		return nil, conn.opErr(op, err)
	}
	defer sock.wg.Done()
	var bytes uint32
	for i := uint(0); i <= d.Retries; i++ {
		err = socket.ConnectEx(
			windows.Handle(sock.handle),
			&sa,
			nil, // sendBuf
			0,   // sendDataLen
			&bytes,
			(*windows.Overlapped)(unsafe.Pointer(&c.o)))
		_, err = sock.asyncIO(c, nil, bytes, err)
		if i < d.Retries && canRedial(err) {
			if err = d.redialWait(ctx); err == nil {
				continue
			}
		}
		break
	}
	if err != nil {
		return nil, conn.opErr(op, os.NewSyscallError("connectex", err))
	}

	// update the connection properties, so shutdown can be used
	if err = windows.Setsockopt(
		windows.Handle(sock.handle),
		windows.SOL_SOCKET,
		windows.SO_UPDATE_CONNECT_CONTEXT,
		nil, // optvalue
		0,   // optlen
	); err != nil {
		return nil, conn.opErr(op, os.NewSyscallError("setsockopt", err))
	}

	// get the local name
	var sal rawHvsockAddr
	err = socket.GetSockName(windows.Handle(sock.handle), &sal)
	if err != nil {
		return nil, conn.opErr(op, os.NewSyscallError("getsockname", err))
	}
	conn.local.fromRaw(&sal)

	// one last check for timeout, since asyncIO doesn't check the context
	if err = ctx.Err(); err != nil {
		return nil, conn.opErr(op, err)
	}

	conn.sock = sock
	sock = nil

	return conn, nil
}

// redialWait waits before attempting to redial, resetting the timer as appropriate.
func (d *HvsockDialer) redialWait(ctx context.Context) (err error) {
	if d.RetryWait == 0 {
		return nil
	}

	if d.rt == nil {
		d.rt = time.NewTimer(d.RetryWait)
	} else {
		// should already be stopped and drained
		d.rt.Reset(d.RetryWait)
	}

	select {
	case <-ctx.Done():
	case <-d.rt.C:
		return nil
	}

	// stop and drain the timer
	if !d.rt.Stop() {
		<-d.rt.C
	}
	return ctx.Err()
}

// assumes error is a plain, unwrapped syscall.Errno provided by direct syscall.
func canRedial(err error) bool {
	//nolint:errorlint // guaranteed to be an Errno
	switch err {
	case windows.WSAECONNREFUSED, windows.WSAENETUNREACH, windows.WSAETIMEDOUT,
		windows.ERROR_CONNECTION_REFUSED, windows.ERROR_CONNECTION_UNAVAIL:
		return true
	default:
		return false
	}
}

func (conn *HvsockConn) opErr(op string, err error) error {
	// translate from "file closed" to "socket closed"
	if errors.Is(err, ErrFileClosed) {
		err = socket.ErrSocketClosed
	}
	return &net.OpError{Op: op, Net: "hvsock", Source: &conn.local, Addr: &conn.remote, Err: err}
}

func (conn *HvsockConn) Read(b []byte) (int, error) {
	c, err := conn.sock.prepareIO()
	if err != nil {
		return 0, conn.opErr("read", err)
	}
	defer conn.sock.wg.Done()
	buf := syscall.WSABuf{Buf: &b[0], Len: uint32(len(b))}
	var flags, bytes uint32
	err = syscall.WSARecv(conn.sock.handle, &buf, 1, &bytes, &flags, &c.o, nil)
	n, err := conn.sock.asyncIO(c, &conn.sock.readDeadline, bytes, err)
	if err != nil {
		var eno windows.Errno
		if errors.As(err, &eno) {
			err = os.NewSyscallError("wsarecv", eno)
		}
		return 0, conn.opErr("read", err)
	} else if n == 0 {
		err = io.EOF
	}
	return n, err
}

func (conn *HvsockConn) Write(b []byte) (int, error) {
	t := 0
	for len(b) != 0 {
		n, err := conn.write(b)
		if err != nil {
			return t + n, err
		}
		t += n
		b = b[n:]
	}
	return t, nil
}

func (conn *HvsockConn) write(b []byte) (int, error) {
	c, err := conn.sock.prepareIO()
	if err != nil {
		return 0, conn.opErr("write", err)
	}
	defer conn.sock.wg.Done()
	buf := syscall.WSABuf{Buf: &b[0], Len: uint32(len(b))}
	var bytes uint32
	err = syscall.WSASend(conn.sock.handle, &buf, 1, &bytes, 0, &c.o, nil)
	n, err := conn.sock.asyncIO(c, &conn.sock.writeDeadline, bytes, err)
	if err != nil {
		var eno windows.Errno
		if errors.As(err, &eno) {
			err = os.NewSyscallError("wsasend", eno)
		}
		return 0, conn.opErr("write", err)
	}
	return n, err
}

// Close closes the socket connection, failing any pending read or write calls.
func (conn *HvsockConn) Close() error {
	return conn.sock.Close()
}

func (conn *HvsockConn) IsClosed() bool {
	return conn.sock.IsClosed()
}

// shutdown disables sending or receiving on a socket.
func (conn *HvsockConn) shutdown(how int) error {
	if conn.IsClosed() {
		return socket.ErrSocketClosed
	}

	err := syscall.Shutdown(conn.sock.handle, how)
	if err != nil {
		// If the connection was closed, shutdowns fail with "not connected"
		if errors.Is(err, windows.WSAENOTCONN) ||
			errors.Is(err, windows.WSAESHUTDOWN) {
			err = socket.ErrSocketClosed
		}
		return os.NewSyscallError("shutdown", err)
	}
	return nil
}

// CloseRead shuts down the read end of the socket, preventing future read operations.
func (conn *HvsockConn) CloseRead() error {
	err := conn.shutdown(syscall.SHUT_RD)
	if err != nil {
		return conn.opErr("closeread", err)
	}
	return nil
}

// CloseWrite shuts down the write end of the socket, preventing future write operations and
// notifying the other endpoint that no more data will be written.
func (conn *HvsockConn) CloseWrite() error {
	err := conn.shutdown(syscall.SHUT_WR)
	if err != nil {
		return conn.opErr("closewrite", err)
	}
	return nil
}

// LocalAddr returns the local address of the connection.
func (conn *HvsockConn) LocalAddr() net.Addr {
	return &conn.local
}

// RemoteAddr returns the remote address of the connection.
func (conn *HvsockConn) RemoteAddr() net.Addr {
	return &conn.remote
}

// SetDeadline implements the net.Conn SetDeadline method.
func (conn *HvsockConn) SetDeadline(t time.Time) error {
	// todo: implement `SetDeadline` for `win32File`
	if err := conn.SetReadDeadline(t); err != nil {
		return fmt.Errorf("set read deadline: %w", err)
	}
	if err := conn.SetWriteDeadline(t); err != nil {
		return fmt.Errorf("set write deadline: %w", err)
	}
	return nil
}

// SetReadDeadline implements the net.Conn SetReadDeadline method.
func (conn *HvsockConn) SetReadDeadline(t time.Time) error {
	return conn.sock.SetReadDeadline(t)
}

// SetWriteDeadline implements the net.Conn SetWriteDeadline method.
func (conn *HvsockConn) SetWriteDeadline(t time.Time) error {
	return conn.sock.SetWriteDeadline(t)
}


text:
/* *
 *
 *  (c) 2020-2021 Highsoft AS
 *
 *  License: www.highcharts.com/license
 *
 *  !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
 *
 *  Authors:
 *  - Sophie Bremer
 *
 * */
'use strict';
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
import DataModifier from './DataModifier.js';
import DataTable from '../DataTable.js';
import U from '../../Core/Utilities.js';
var merge = U.merge;
/* *
 *
 *  Class
 *
 * */
/**
 * Groups table rows into subtables depending on column values.
 *
 * @private
 */
var GroupModifier = /** @class */ (function (_super) {
    __extends(GroupModifier, _super);
    /* *
     *
     *  Constructors
     *
     * */
    /**
     * Constructs an instance of the group modifier.
     *
     * @param {GroupModifier.Options} [options]
     * Options to configure the group modifier.
     */
    function GroupModifier(options) {
        var _this = _super.call(this) || this;
        _this.options = merge(GroupModifier.defaultOptions, options);
        return _this;
    }
    /* *
     *
     *  Functions
     *
     * */
    /**
     * Applies modifications to the table rows and returns a new table with
     * subtable, containing the grouped rows. The rows of the new table contain
     * three columns:
     * - `groupBy`: Column name used to group rows by.
     * - `table`: Subtable containing the grouped rows.
     * - `value`: containing the common value of the group
     *
     * @param {DataTable} table
     * Table to modify.
     *
     * @param {DataEventEmitter.EventDetail} [eventDetail]
     * Custom information for pending events.
     *
     * @return {DataTable}
     * Table with `modified` property as a reference.
     */
    GroupModifier.prototype.modifyTable = function (table, eventDetail) {
        var modifier = this;
        modifier.emit({ type: 'modify', detail: eventDetail, table: table });
        var byGroups = [], tableGroups = [], valueGroups = [], groupColumn = (modifier.options.groupColumn ||
            table.getColumnNames()[0]), valueColumn = (table.getColumn(groupColumn) ||
            []), _a = modifier.options, invalidValues = _a.invalidValues, validValues = _a.validValues, modified = table.modified = table.clone(true, eventDetail);
        var value, valueIndex;
        for (var i = 0, iEnd = valueColumn.length; i < iEnd; ++i) {
            value = valueColumn[i];
            if (typeof value !== 'undefined') {
                if (value instanceof DataTable ||
                    (invalidValues &&
                        invalidValues.indexOf(value) >= 0) || (validValues &&
                    validValues.indexOf(value) === -1)) {
                    continue;
                }
                valueIndex = valueGroups.indexOf(value);
                if (valueIndex === -1) {
                    var newTable = new DataTable();
                    newTable.setRows([table.getRowObject(i) || {}]);
                    byGroups.push(groupColumn);
                    tableGroups.push(newTable);
                    valueGroups.push(value);
                }
                else {
                    tableGroups[valueIndex].setRows([table.getRow(i) || []]);
                }
            }
        }
        modified.deleteColumns();
        modified.setColumns({
            groupBy: byGroups,
            table: tableGroups,
            value: valueGroups
        });
        modifier.emit({ type: 'afterModify', detail: eventDetail, table: table });
        return table;
    };
    /* *
     *
     *  Static Properties
     *
     * */
    /**
     * Default options to group table rows.
     */
    GroupModifier.defaultOptions = {
        modifier: 'Group',
        groupColumn: ''
    };
    return GroupModifier;
}(DataModifier));
/* *
 *
 *  Register
 *
 * */
DataModifier.addModifier(GroupModifier);
/* *
 *
 *  Export
 *
 * */
export default GroupModifier;

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe EuDecision, sidekiq: :inline do
  before do
    @taxon_concept = create(:taxon_concept)
  end

  describe :create do
    context "downloads cache should be populated" do
      before(:each) do
        DownloadsCache.clear_eu_decisions
        create(:eu_decision, :start_date => Time.utc(2013), :type => 'EuOpinion')
        Species::EuDecisionsExport.new(set: 'current', decision_types: {}).export
      end
      subject { Dir["#{DownloadsCache.eu_decisions_path}/*"] }
      specify { subject.should_not be_empty }
    end
  end

  describe :save do
    context "Eu decision type and SRG history can't be blank at the same time" do
      let(:eu_decision) { build(:eu_decision, srg_history_id: nil, eu_decision_type_id: nil) }
      subject { eu_decision.save }

      specify { subject.should be_falsey }

      it 'should have an error message' do
        subject
        expect(eu_decision.errors[:base]).to_not be_empty
      end
    end

    context 'Eu decision creates correctly if only Eu decision type is populated' do
      let(:eu_decision) { build(:eu_decision) }

      specify { subject.should be_truthy }
    end

    context 'Eu decision creates correctly if only SRG history is populated' do
      let(:eu_decision) { build(:eu_decision, eu_decision_type: nil, srg_history: create(:srg_history)) }

      specify { subject.should be_truthy }
    end

    context 'Eu decision creates correctly if both Eu decision type and SRG history are populated' do
      let(:eu_decision) { build(:eu_decision, srg_history: create(:srg_history)) }

      specify { subject.should be_truthy }
    end
  end

  describe :destroy do
    context "downloads cache should be cleared" do
      before(:each) do
        DownloadsCache.clear_eu_decisions
        d = create(:eu_decision, :start_date => Time.utc(2013))
        Species::EuDecisionsExport.new(set: 'current', decision_types: {}).export
        d.destroy
        Species::EuDecisionsExport.new(set: 'current', decision_types: {}).export
      end
      subject { Dir["#{DownloadsCache.eu_decisions_path}/*"] }
      specify { subject.should be_empty }
    end
  end

end


text:
twilio video chat in meteor

create a twilio account

clone this repo

install node packages:

```
meteor npm install --save twilio
```

```
meteor npm install --save twilio-video
```

may need to install babel-runtime or meteor-node-stubs depending on your version
the meteor console will say if it needs it

copy example-settings.json to settings.json

create a token for video chat using your twilio account

if your confused about the token or settings file, refer to the config values in
https://github.com/TwilioDevEd/video-quickstart-node

put your twilio account data into settings.json

run with:

```
meteor --settings settings.json
```

__turn your computers volume all the way down or you will hear loud feedback__
go to localhost:3000
enter a room number and hit enter
allow video camera access in you browser if necessary
make a new incognito window localhost:3000 on it
type the same room number and hit enter
video chat with your other browser instance
mute/unmute
then click the "end call" button


text:
#ifndef NE_SSPI_H
#define NE_SSPI_H

/* Win32 SSPI-based authentication interfaces.  PRIVATE TO NEON -- NOT
 * PART OF THE EXTERNAL API. */

#ifdef HAVE_SSPI

#include <windows.h>
#define SECURITY_WIN32
#include <security.h>

int ne_sspi_init(void);
int ne_sspi_deinit(void);

int ne_sspi_create_context(void **context, char * serverName, int ntlm);

int ne_sspi_destroy_context(void *context);

int ne_sspi_clear_context(void *context);

int ne_sspi_authenticate(void *context, const char *base64Token,
                         char **responseToken);

#endif /* HAVE_SSPI */

#endif /* NE_SSPI_H */


text:
//
//  XMNPhotoPickerKit.h
//  XMNPhotoPickerKitExample
//  Created by XMFraker on 16/1/28.
//  Copyright © 2016年 XMFraker. All rights reserved.
//

//  如果您觉得代码还行,请给个star
//  GitHub:  https://github.com/ws00801526/XMNPhotoPickerKit.git
//  如果您有任何关于本代码的问题
//  您可以在github上咨询我 或者QQ:3057600441

#ifndef XMNPhotoPickerKit_h
#define XMNPhotoPickerKit_h

#import "XMNPhotoManager.h"

#import "XMNPhotoPicker.h"

#import "XMNPhotoPickerController.h"

#endif /* XMNPhotoPickerKit_h */


text:
package org.apache.olingo.server.core.uri.parser;

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

import org.apache.olingo.commons.api.edm.Edm;
import org.apache.olingo.commons.api.edmx.EdmxReference;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriInfoKind;
import org.apache.olingo.server.api.uri.queryoption.expression.BinaryOperatorKind;
import org.apache.olingo.server.core.uri.parser.UriParserSemanticException.MessageKeys;
import org.apache.olingo.server.core.uri.testutil.FilterValidator;
import org.apache.olingo.server.core.uri.testutil.ResourceValidator;
import org.apache.olingo.server.core.uri.testutil.TestUriValidator;
import org.apache.olingo.server.core.uri.validator.UriValidationException;
import org.apache.olingo.server.tecsvc.provider.EdmTechProvider;
import org.apache.olingo.server.tecsvc.provider.EntityTypeProvider;
import org.apache.olingo.server.tecsvc.provider.PropertyProvider;
import org.junit.Test;

/** Tests of the URI parser as a whole - please put more specific tests elsewhere. */
public class UriParserTest {

  private static final Edm edm = OData.newInstance().createServiceMetadata(
      new EdmTechProvider(), Collections.<EdmxReference> emptyList()).getEdm();

  private final TestUriValidator testUri = new TestUriValidator().setEdm(edm);
  private final ResourceValidator testRes = new ResourceValidator().setEdm(edm);
  private final FilterValidator testFilter = new FilterValidator().setEdm(edm);

  @Test
  public void misc() throws Exception {
    testUri.run("")
        .isKind(UriInfoKind.service);
    testUri.run("/")
        .isKind(UriInfoKind.service);

    testUri.run("$all")
        .isKind(UriInfoKind.all);

    testUri.run("$batch")
        .isKind(UriInfoKind.batch);

    testUri.runEx("//").isExSyntax(UriParserSyntaxException.MessageKeys.MUST_BE_LAST_SEGMENT);
    testUri.runEx("$metadata/").isExSyntax(UriParserSyntaxException.MessageKeys.MUST_BE_LAST_SEGMENT);
    testUri.runEx("//$metadata").isExSyntax(UriParserSyntaxException.MessageKeys.MUST_BE_LAST_SEGMENT);
    testUri.runEx("ESKeyNav//$count").isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);

    testUri.runEx("$metadata/$ref").isExSyntax(UriParserSyntaxException.MessageKeys.MUST_BE_LAST_SEGMENT);
    testUri.runEx("$batch/$ref").isExSyntax(UriParserSyntaxException.MessageKeys.MUST_BE_LAST_SEGMENT);
    testUri.runEx("$all/$ref").isExSyntax(UriParserSyntaxException.MessageKeys.MUST_BE_LAST_SEGMENT);
    testUri.runEx("$entity/olingo.odata.test1.ETKeyNav/$ref")
        .isExSyntax(UriParserSyntaxException.MessageKeys.MUST_BE_LAST_SEGMENT);
    testUri.runEx("$entity/olingo.odata.test1.ETKeyNav")
        .isExSyntax(UriParserSyntaxException.MessageKeys.ENTITYID_MISSING_SYSTEM_QUERY_OPTION_ID);

    testUri.runEx("$wrong").isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);
    testUri.runEx("", "$wrong").isExSyntax(UriParserSyntaxException.MessageKeys.UNKNOWN_SYSTEM_QUERY_OPTION);

    testUri.runEx("ESKeyNav()").isExSemantic(MessageKeys.WRONG_NUMBER_OF_KEY_PROPERTIES);

    testRes.run("ESTwoKeyNav/olingo.odata.test1.BFC_RTESTwoKeyNav_()")
        .isEntitySet("ESTwoKeyNav")
        .n().isFunction("BFC_RTESTwoKeyNav_");

    testRes.run("ESAllPrim/olingo.odata.test1.BAESAllPrimRTETAllPrim")
        .isEntitySet("ESAllPrim")
        .n().isAction("BAESAllPrimRTETAllPrim");

    testRes.run("ESTwoKeyNav/olingo.odata.test1.BFC_RTESTwoKeyNav_()")
        .isEntitySet("ESTwoKeyNav")
        .n().isFunction("BFC_RTESTwoKeyNav_");

    testRes.run("ESMedia(1)/$value")
        .isEntitySet("ESMedia")
        .n().isValue();

    testRes.run("ESAllPrim/olingo.odata.test1.BAESAllPrimRTETAllPrim")
        .isEntitySet("ESAllPrim")
        .n().isAction("BAESAllPrimRTETAllPrim");

    testRes.run("ESTwoKeyNav/olingo.odata.test1.BFC_RTESTwoKeyNav_()")
        .isEntitySet("ESTwoKeyNav")
        .n().isFunction("BFC_RTESTwoKeyNav_");

    testRes.run("ESTwoKeyNav(PropertyInt16=1,PropertyString='2')/olingo.odata.test1.ETBaseTwoKeyNav")
        .isEntitySet("ESTwoKeyNav")
        .isKeyPredicate(0, "PropertyInt16", "1")
        .isKeyPredicate(1, "PropertyString", "'2'")
        .isType(EntityTypeProvider.nameETTwoKeyNav)
        .isTypeFilterOnEntry(EntityTypeProvider.nameETBaseTwoKeyNav);

    testRes.run("ESTwoKeyNav(PropertyInt16=1,PropertyString='2')/olingo.odata.test1.ETBaseTwoKeyNav/$ref")
        .isEntitySet("ESTwoKeyNav")
        .isKeyPredicate(0, "PropertyInt16", "1")
        .isKeyPredicate(1, "PropertyString", "'2'")
        .isType(EntityTypeProvider.nameETTwoKeyNav)
        .isTypeFilterOnEntry(EntityTypeProvider.nameETBaseTwoKeyNav)
        .n().isRef();

    testRes.run("ESKeyNav(1)/NavPropertyETTwoKeyNavMany(PropertyInt16=1,PropertyString='1')")
    .isEntityType("ETTwoKeyNav")
    .isKeyPredicateForNavSeg(0, "PropertyInt16", "1")
    .isKeyPredicateForNavSeg(1, "PropertyString", "'1'");

    testRes.run("ESKeyNav(1)/NavPropertyETMediaMany(1)")
    .isEntityType("ETMedia")
    .isKeyPredicateForNavSeg(0, "PropertyInt16", "1");
  }

  @Test
  public void enumAndTypeDefAsKey() throws Exception {
    testRes
        .run("ESMixEnumDefCollComp(PropertyEnumString=olingo.odata.test1.ENString'String1',PropertyDefString='abc')")
        .isEntitySet("ESMixEnumDefCollComp")
        .isKeyPredicate(0, "PropertyEnumString", "olingo.odata.test1.ENString'String1'")
        .isKeyPredicate(1, "PropertyDefString", "'abc'");

    testFilter.runOnETMixEnumDefCollComp("PropertyEnumString has Namespace1_Alias.ENString'String1'")
        .is("<<PropertyEnumString> has <olingo.odata.test1.ENString<String1>>>");

    testRes
        .run("ESMixEnumDefCollComp(PropertyEnumString=Namespace1_Alias.ENString'String1',PropertyDefString='abc')")
        .isEntitySet("ESMixEnumDefCollComp")
        .isKeyPredicate(0, "PropertyEnumString", "Namespace1_Alias.ENString'String1'")
        .isKeyPredicate(1, "PropertyDefString", "'abc'");
  }

  @Test
  public void crossjoin() throws Exception {
    testUri.run("$crossjoin(ESKeyNav)")
        .isKind(UriInfoKind.crossjoin)
        .isCrossJoinEntityList(Arrays.asList("ESKeyNav"));

    testUri.run("$crossjoin(ESKeyNav,ESTwoKeyNav)")
        .isKind(UriInfoKind.crossjoin)
        .isCrossJoinEntityList(Arrays.asList("ESKeyNav", "ESTwoKeyNav"));
  }

  @Test
  public void crossjoinFilter() throws Exception {
    testUri.run("$crossjoin(ESTwoPrim,ESMixPrimCollComp)",
        "$filter=ESTwoPrim/PropertyString eq ESMixPrimCollComp/PropertyComp/PropertyString")
        .goFilter()
        .isBinary(BinaryOperatorKind.EQ)
        .is("<<ESTwoPrim/PropertyString> eq <ESMixPrimCollComp/PropertyComp/PropertyString>>");
  }

  @Test
  public void crossjoinExpand() throws Exception {
    testUri.run("$crossjoin(ESTwoPrim,ESAllPrim)",
        "$expand=ESTwoPrim")
        .goExpand()
        .first().goPath().first().isEntitySet("ESTwoPrim");

    testUri.run("$crossjoin(ESTwoPrim,ESAllPrim)",
        "$expand=ESTwoPrim,ESAllPrim")
        .goExpand()
        .first().goPath().first().isEntitySet("ESTwoPrim")
        .goUpExpandValidator().next().goPath().first().isEntitySet("ESAllPrim");

    // TODO: Once crossjoin is implemented these tests should no longer result in errors
//    testUri.run("$crossjoin(ESTwoPrim,ESAllPrim)",
//        "$expand=ESAllPrim/NavPropertyETTwoPrimOne")
//        .goExpand()
//        .first().goPath().at(0).isEntitySet("ESAllPrim")
//        .at(1).isNavProperty("NavPropertyETTwoPrimOne", EntityTypeProvider.nameETTwoPrim, false);
  }

  @Test
  public void crossjoinError() throws Exception {
    testUri.runEx("$crossjoin").isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);
    testUri.runEx("$crossjoin/error").isExSyntax(UriParserSyntaxException.MessageKeys.MUST_BE_LAST_SEGMENT);
    testUri.runEx("$crossjoin()").isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);
    testUri.runEx("$crossjoin(ESKeyNav, ESTwoKeyNav)/invalid")
        .isExSyntax(UriParserSyntaxException.MessageKeys.MUST_BE_LAST_SEGMENT);
    testUri.runEx("$crossjoin(ESKeyNav)/$ref")
        .isExSyntax(UriParserSyntaxException.MessageKeys.MUST_BE_LAST_SEGMENT);
  }

  @Test
  public void entityId() throws Exception {
    // simple entity set
    testUri.run("$entity", "$id=ESAllPrim(1)").isKind(UriInfoKind.entityId)
        .isKind(UriInfoKind.entityId)
        .isIdText("ESAllPrim(1)");

    // simple entity set; $format before $id
    testUri.run("$entity", "$format=xml&$id=ESAllPrim(1)").isKind(UriInfoKind.entityId)
        .isFormatText("xml")
        .isIdText("ESAllPrim(1)");

    testUri.run("$entity", "$format=xml&abc=123&$id=ESAllPrim(1)").isKind(UriInfoKind.entityId)
        .isFormatText("xml")
        .isCustomParameter(0, "abc", "123")
        .isIdText("ESAllPrim(1)");

    // simple entity set; $format after $id
    testUri.run("$entity", "$id=ESAllPrim(1)&$format=xml").isKind(UriInfoKind.entityId)
        .isIdText("ESAllPrim(1)")
        .isFormatText("xml");

    // simple entity set; $format and custom parameter after $id
    testUri.run("$entity", "$id=ESAllPrim(1)&$format=xml&abc=123").isKind(UriInfoKind.entityId)
        .isIdText("ESAllPrim(1)")
        .isFormatText("xml")
        .isCustomParameter(0, "abc", "123");

    // simple entity set; $format before $id and custom parameter after $id
    testUri.run("$entity", "$format=xml&$id=ESAllPrim(1)&abc=123").isKind(UriInfoKind.entityId)
        .isFormatText("xml")
        .isIdText("ESAllPrim(1)")
        .isCustomParameter(0, "abc", "123");

    // simple entity set; with qualifiedentityTypeName
    testUri.run("$entity/olingo.odata.test1.ETTwoPrim", "$id=ESBase(111)")
        .isEntityType(EntityTypeProvider.nameETTwoPrim)
        .isIdText("ESBase(111)");

    // simple entity set; with qualifiedentityTypeName;
    testUri.run("$entity/olingo.odata.test1.ETBase", "$id=ESTwoPrim(1)")
        .isEntityType(EntityTypeProvider.nameETBase)
        .isKind(UriInfoKind.entityId)
        .isIdText("ESTwoPrim(1)");

    // simple entity set; with qualifiedentityTypeName; with format
    testUri.run("$entity/olingo.odata.test1.ETBase", "$id=ESTwoPrim(1)&$format=atom")
        .isKind(UriInfoKind.entityId)
        .isEntityType(EntityTypeProvider.nameETBase)
        .isIdText("ESTwoPrim(1)")
        .isFormatText("atom");

    // simple entity set; with qualifiedentityTypeName; with select
    testUri.run("$entity/olingo.odata.test1.ETBase", "$id=ESTwoPrim(1)&$select=*")
        .isKind(UriInfoKind.entityId)
        .isEntityType(EntityTypeProvider.nameETBase)
        .isIdText("ESTwoPrim(1)")
        .isSelectItemStar(0);

    // simple entity set; with qualifiedentityTypeName; with expand
    testUri.run("$entity/olingo.odata.test1.ETBase", "$id=ESTwoPrim(1)&$expand=*")
        .isKind(UriInfoKind.entityId)
        .isEntityType(EntityTypeProvider.nameETBase)
        .isIdText("ESTwoPrim(1)")
        .goExpand().first().isSegmentStar();

    try {
      testUri.run("$entity/olingo.odata.test1.ETAllNullable")
      .isKind(UriInfoKind.entityId)
      .isEntityType(EntityTypeProvider.nameETAllNullable);
    } catch (UriParserSyntaxException e) {
      testUri.isExSyntax(UriParserSyntaxException.MessageKeys.ENTITYID_MISSING_SYSTEM_QUERY_OPTION_ID);
    }
    testUri.run("$entity/Namespace1_Alias.ETAllPrim", "$id=ESAllPrim(32767)")
    .isKind(UriInfoKind.entityId)
    .isEntityType(EntityTypeProvider.nameETAllPrim)
    .isIdText("ESAllPrim(32767)");
    try {
      testUri.run("ESAllPrim/$entity")
    .isKind(UriInfoKind.resource);
    } catch (UriParserSyntaxException e) {
      testUri.isExSyntax(UriParserSyntaxException.MessageKeys.ENTITYID_MISSING_SYSTEM_QUERY_OPTION_ID);
    }
    try {
      testUri.run("ESAllPrim(32767)/NavPropertyETTwoPrimOne/$entity")
    .isKind(UriInfoKind.resource);
    } catch(UriParserSyntaxException e) {
      testUri.isExSyntax(UriParserSyntaxException.MessageKeys.ENTITYID_MISSING_SYSTEM_QUERY_OPTION_ID);
    }
    testUri.run("$entity", "$id=ESAllPrim(32767)/NavPropertyETTwoPrimOne")
      .isKind(UriInfoKind.entityId)
      .isEntityType(EntityTypeProvider.nameETTwoPrim)
    .isIdText("ESAllPrim(32767)/NavPropertyETTwoPrimOne");
    testUri.run("$entity", "$id=ESAllPrim(32767)", "$select=PropertyString", null)
    .isKind(UriInfoKind.entityId)
    .isEntityType(EntityTypeProvider.nameETAllPrim)
      .isIdText("ESAllPrim(32767)");
    testUri.run("$entity", "$id=ESAllPrim(32767)", "$expand=NavPropertyETTwoPrimOne", null)
    .isKind(UriInfoKind.entityId)
    .isEntityType(EntityTypeProvider.nameETAllPrim)
      .isIdText("ESAllPrim(32767)");
    testUri.run("$entity", "$id=http://localhost:8080/odata-server-tecsvc/odata.svc/"
        + "ESAllPrim(32767)/NavPropertyETTwoPrimOne", null,
        "http://localhost:8080/odata-server-tecsvc/odata.svc")
    .isKind(UriInfoKind.entityId)
    .isEntityType(EntityTypeProvider.nameETTwoPrim)
    .isIdText("http://localhost:8080/odata-server-tecsvc/odata.svc/"
        + "ESAllPrim(32767)/NavPropertyETTwoPrimOne");
    try {
      testUri.run("$entity/olingo.odata.test1.ETKeyNav", "$id=http://localhost:90/tecsvc/ESKeyNav(1)",
            null, "http://localhost:80/tecsvc")
          .isKind(UriInfoKind.entityId)
          .isEntityType(EntityTypeProvider.nameETKeyNav)
          .isIdText("http://localhost:90/tecsvc/ESKeyNav(1)");
    } catch (UriParserSemanticException e) {
      testUri.isExSemantic(UriParserSemanticException.MessageKeys.NOT_IMPLEMENTED_SYSTEM_QUERY_OPTION);
    }
    try {
      testUri.run("$entity/olingo.odata.test1.ETKeyNav", "$id=http://localhost:90/tecs%27v; c/ESKeyNav(1)",
            null, "http://localhost:80/tecs%27v; c")
          .isKind(UriInfoKind.entityId)
          .isEntityType(EntityTypeProvider.nameETKeyNav)
          .isIdText("http://localhost:90/tecs%27v; c/ESKeyNav(1)");
    } catch (UriParserSemanticException e) {
      testUri.isExSemantic(UriParserSemanticException.MessageKeys.NOT_IMPLEMENTED_SYSTEM_QUERY_OPTION);
    }
    testUri.run("$entity/olingo.odata.test1.ETKeyNav", "$id=http://localhost:90/tecs%27v%20c/ESKeyNav(1)",
        null, "http://localhost:90/tecs%27v%20c")
      .isKind(UriInfoKind.entityId)
      .isEntityType(EntityTypeProvider.nameETKeyNav);
    String idOption = UriDecoder.decode("http://localhost:90/tecs%27v%20c/ESKeyNav(1)");
    testUri.isIdText(idOption);
    testUri.run("$entity/olingo.odata.test1.ETKeyNav", "$id=http://localhost:90/tecs'v c/ESKeyNav(1)",
        null, "http://localhost:90/tecs'v c")
      .isKind(UriInfoKind.entityId)
      .isEntityType(EntityTypeProvider.nameETKeyNav)
      .isIdText("http://localhost:90/tecs'v c/ESKeyNav(1)");
  }

  @Test
  public void entityIdFailOnValidation() throws Exception {
    testUri.runEx("$entity/olingo.odata.test1.ETTwoPrim", "$filter=PropertyInt16 eq 123&$id=ESAllPrim(1)")
        .isExValidation(UriValidationException.MessageKeys.SYSTEM_QUERY_OPTION_NOT_ALLOWED);
  }

  @Test
  public void resourcePathWithApostrophe() throws Exception {
    testUri.runEx("ESAllPrim'").isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);
    testUri.runEx("ESAllPrim'InvalidStuff").isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);
    testFilter.runOnETKeyNavEx("PropertyInt16' eq 0").isExSemantic(MessageKeys.TYPES_NOT_COMPATIBLE);
    testFilter.runOnETKeyNavEx("PropertyInt16 eq' 0").isExSemantic(MessageKeys.TYPES_NOT_COMPATIBLE);
    testFilter.runOnETKeyNavEx("PropertyInt16 eq 0'")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION);
    testFilter.runOnETKeyNavEx("PropertyInt16 eq 'dsd''")
        .isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);
  }

  @Test
  public void metaData() throws Exception {
    // Parsing the fragment may be used if a uri has to be parsed on the consumer side.
    // On the producer side this feature is currently not supported, so the context fragment
    // part is only available as text.

    testUri.run("$metadata")
        .isKind(UriInfoKind.metadata);

    testUri.run("$metadata", "$format=atom")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom");

    // with context (client usage)
    testUri.run("$metadata", null, "$ref")
        .isKind(UriInfoKind.metadata)
        .isFragmentText("$ref");

    testUri.run("$metadata", "$format=atom", "$ref")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("$ref");

    testUri.run("$metadata", "$format=atom", "Collection($ref)")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("Collection($ref)");

    testUri.run("$metadata", "$format=atom", "Collection(Edm.EntityType)")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("Collection(Edm.EntityType)");

    testUri.run("$metadata", "$format=atom", "Collection(Edm.ComplexType)")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("Collection(Edm.ComplexType)");

    testUri.run("$metadata", "$format=atom", "SINav")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("SINav");

    testUri.run("$metadata", "$format=atom", "SINav/PropertyInt16")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("SINav/PropertyInt16");

    testUri.run("$metadata", "$format=atom", "SINav/NavPropertyETKeyNavOne")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("SINav/NavPropertyETKeyNavOne");

    testUri.run("$metadata", "$format=atom", "SINav/NavPropertyETKeyNavMany(1)")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("SINav/NavPropertyETKeyNavMany(1)");

    testUri.run("$metadata", "$format=atom", "SINav/NavPropertyETKeyNavOne/PropertyInt16")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("SINav/NavPropertyETKeyNavOne/PropertyInt16");

    testUri.run("$metadata", "$format=atom", "SINav/NavPropertyETKeyNavMany(1)/PropertyInt16")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("SINav/NavPropertyETKeyNavMany(1)/PropertyInt16");

    testUri.run("$metadata", "$format=atom", "SINav/olingo.odata.test1.ETTwoPrim/NavPropertyETKeyNavOne/PropertyInt16")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("SINav/olingo.odata.test1.ETTwoPrim/NavPropertyETKeyNavOne/PropertyInt16");

    testUri.run("$metadata", "$format=atom",
        "SINav/olingo.odata.test1.ETTwoPrim/NavPropertyETKeyNavMany(1)/PropertyInt16")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("SINav/olingo.odata.test1.ETTwoPrim/NavPropertyETKeyNavMany(1)/PropertyInt16");

    testUri.run("$metadata", "$format=atom", "olingo.odata.test1.ETAllKey")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("olingo.odata.test1.ETAllKey");

    testUri.run("$metadata", "$format=atom", "ESTwoPrim/$deletedEntity")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESTwoPrim/$deletedEntity");

    testUri.run("$metadata", "$format=atom", "ESTwoPrim/$link")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESTwoPrim/$link");

    testUri.run("$metadata", "$format=atom", "ESTwoPrim/$deletedLink")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESTwoPrim/$deletedLink");

    testUri.run("$metadata", "$format=atom", "ESKeyNav")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav");

    testUri.run("$metadata", "$format=atom", "ESKeyNav/PropertyInt16")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav/PropertyInt16");

    testUri.run("$metadata", "$format=atom", "ESKeyNav/NavPropertyETKeyNavOne")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav/NavPropertyETKeyNavOne");

    testUri.run("$metadata", "$format=atom", "ESKeyNav/NavPropertyETKeyNavMany(1)")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav/NavPropertyETKeyNavMany(1)");

    testUri.run("$metadata", "$format=atom", "ESKeyNav/NavPropertyETKeyNavOne/PropertyInt16")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav/NavPropertyETKeyNavOne/PropertyInt16");

    testUri.run("$metadata", "$format=atom", "ESKeyNav/NavPropertyETKeyNavMany(1)/PropertyInt16")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav/NavPropertyETKeyNavMany(1)/PropertyInt16");

    testUri.run("$metadata", "$format=atom",
        "ESKeyNav/olingo.odata.test1.ETTwoPrim/NavPropertyETKeyNavOne/PropertyInt16")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav/olingo.odata.test1.ETTwoPrim/NavPropertyETKeyNavOne/PropertyInt16");

    testUri.run(
        "$metadata", "$format=atom", "ESKeyNav/olingo.odata.test1.ETTwoPrim/NavPropertyETKeyNavMany(1)/PropertyInt16")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav/olingo.odata.test1.ETTwoPrim/NavPropertyETKeyNavMany(1)/PropertyInt16");

    testUri.run("$metadata", "$format=atom", "ESKeyNav(PropertyInt16,PropertyString)")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav(PropertyInt16,PropertyString)");

    testUri.run("$metadata", "$format=atom", "ESKeyNav/$entity")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav/$entity");

    testUri.run("$metadata", "$format=atom", "ESKeyNav/$delta")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav/$delta");

    testUri.run("$metadata", "$format=atom", "ESKeyNav/(PropertyInt16,PropertyString)/$delta")
        .isKind(UriInfoKind.metadata)
        .isFormatText("atom")
        .isFragmentText("ESKeyNav/(PropertyInt16,PropertyString)/$delta");
  }

  @Test
  public void top() throws Exception {
    testUri.run("ESKeyNav", "$top=1")
        .isKind(UriInfoKind.resource)
        .goPath().isEntitySet("ESKeyNav")
        .goUpUriValidator().isTop(1);

    testUri.run("ESKeyNav", "$top=0")
        .isKind(UriInfoKind.resource)
        .goPath().isEntitySet("ESKeyNav")
        .goUpUriValidator().isTop(0);

    testUri.runEx("ESKeyNav", "$top=undefined")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION);
    testUri.runEx("ESKeyNav", "$top=")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION);
    testUri.runEx("ESKeyNav", "$top=-3")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION);
  }

  @Test
  public void format() throws Exception {
    testUri.run("ESKeyNav(1)", "$format=atom")
        .isKind(UriInfoKind.resource)
        .isFormatText("atom");
    testUri.run("ESKeyNav(1)", "$format=json")
        .isKind(UriInfoKind.resource)
        .isFormatText("json");
    testUri.run("ESKeyNav(1)", "$format=xml")
        .isKind(UriInfoKind.resource)
        .isFormatText("xml");
    testUri.run("ESKeyNav(1)", "$format=IANA_content_type/must_contain_a_slash")
        .isKind(UriInfoKind.resource)
        .isFormatText("IANA_content_type/must_contain_a_slash");
    testUri.run("ESKeyNav(1)", "$format=Test_all_valid_signsSpecified_for_format_signs%26-._~$@%27/Aa123%26-._~$@%27")
        .isKind(UriInfoKind.resource)
        .isFormatText("Test_all_valid_signsSpecified_for_format_signs&-._~$@'/Aa123&-._~$@'");
    testUri.run("ESKeyNav(1)", "$format=" + ContentType.APPLICATION_ATOM_XML_ENTRY_UTF8)
        .isKind(UriInfoKind.resource)
        .isFormatText(ContentType.APPLICATION_ATOM_XML_ENTRY_UTF8.toContentTypeString());
    testUri.runEx("ESKeyNav(1)", "$format=noSlash")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION_FORMAT);
    testUri.runEx("ESKeyNav(1)", "$format=slashAtEnd/")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION_FORMAT);
    testUri.runEx("ESKeyNav(1)", "$format=/startsWithSlash")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION_FORMAT);
    testUri.runEx("ESKeyNav(1)", "$format=two/Slashes/tooMuch")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION_FORMAT);
    testUri.runEx("ESKeyNav(1)", "$format=")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION_FORMAT);
  }

  @Test
  public void count() throws Exception {
    testUri.run("ESAllPrim", "$count=true")
        .isKind(UriInfoKind.resource)
        .isInlineCount(true);
    testUri.run("ESAllPrim", "$count=false")
        .isKind(UriInfoKind.resource)
        .isInlineCount(false);
    testUri.runEx("ESAllPrim", "$count=undefined")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION);
    testUri.runEx("ESAllPrim", "$count=")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION);
  }

  @Test
  public void skip() throws Exception {
    testUri.run("ESAllPrim", "$skip=3")
        .isKind(UriInfoKind.resource)
        .isSkip(3);
    testUri.run("ESAllPrim", "$skip=0")
        .isKind(UriInfoKind.resource)
        .isSkip(0);

    testUri.runEx("ESAllPrim", "$skip=F")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION);
    testUri.runEx("ESAllPrim", "$skip=")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION);
    testUri.runEx("ESAllPrim", "$skip=-3")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION);
  }

  @Test
  public void skiptoken() throws Exception {
    testUri.run("ESAllPrim", "$skiptoken=foo")
        .isKind(UriInfoKind.resource)
        .isSkipTokenText("foo");

    testUri.runEx("ESAllPrim", "$skiptoken=")
        .isExSyntax(UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION);
  }

  @Test
  public void notExistingSystemQueryOption() throws Exception {
    testUri.runEx("ESAllPrim", "$wrong=error")
        .isExSyntax(UriParserSyntaxException.MessageKeys.UNKNOWN_SYSTEM_QUERY_OPTION);
  }

  @Test
  public void errors() {
    testUri.runEx("FICRTString(wrong1='ABC')/olingo.odata.test1.BFCStringRTESTwoKeyNav()")
        .isExSemantic(MessageKeys.FUNCTION_NOT_FOUND);
    testUri.runEx("FICRTString(wrong1='ABC',wrong2=1)/olingo.odata.test1.BFCStringRTESTwoKeyNav()")
        .isExSemantic(MessageKeys.FUNCTION_NOT_FOUND);

    // type filter for entity incompatible
    testUri.runEx("ESTwoKeyNav(PropertyInt16=1,PropertyString='2')/olingo.odata.test1.ETBase")
        .isExSemantic(MessageKeys.INCOMPATIBLE_TYPE_FILTER);

    // type filter for entity double on entry
    testUri.runEx("ESTwoKeyNav(PropertyInt16=1,PropertyString='2')"
        + "/olingo.odata.test1.ETBaseTwoKeyNav/olingo.odata.test1.ETBaseTwoKeyNav")
        .isExSemantic(MessageKeys.TYPE_FILTER_NOT_CHAINABLE);
    // type filter for entity double on collection
    testUri.runEx("ESTwoKeyNav/olingo.odata.test1.ETBaseTwoKeyNav/olingo.odata.test1.ETBaseTwoKeyNav")
        .isExSemantic(MessageKeys.TYPE_FILTER_NOT_CHAINABLE);
    // type filter for entity double on non key pred
    testUri.runEx("SINav/olingo.odata.test1.ETBaseTwoKeyNav/olingo.odata.test1.ETBaseTwoKeyNav")
        .isExSemantic(MessageKeys.TYPE_FILTER_NOT_CHAINABLE);

    // type filter for complex incompatible
    testUri.runEx("ESTwoKeyNav(PropertyInt16=1,PropertyString='2')/PropertyCompTwoPrim"
        + "/olingo.odata.test1.CTCollAllPrim")
        .isExSemantic(MessageKeys.INCOMPATIBLE_TYPE_FILTER);

    // type filter for complex double on entry
    testUri.runEx("FICRTCTTwoPrimTwoParam(ParameterInt16=1,ParameterString='2')"
        + "/olingo.odata.test1.CTBase/olingo.odata.test1.CTBase")
        .isExSemantic(MessageKeys.TYPE_FILTER_NOT_CHAINABLE);

    // type filter for complex double on collection
    testUri.runEx("FICRTCollCTTwoPrimTwoParam(ParameterInt16=1,ParameterString='2')"
        + "/olingo.odata.test1.CTBase/olingo.odata.test1.CTBase")
        .isExSemantic(MessageKeys.TYPE_FILTER_NOT_CHAINABLE);

    // type filter for complex double on non key pred
    testUri.runEx("ESTwoKeyNav(PropertyInt16=1,PropertyString='2')/PropertyCompTwoPrim"
        + "/olingo.odata.test1.CTBase/olingo.odata.test1.CTBase")
        .isExSemantic(MessageKeys.TYPE_FILTER_NOT_CHAINABLE);

    testUri.runEx("ESTwoKeyNav/olingo.odata.test1.BFC_RTESTwoKeyNav_")
        .isExSemantic(MessageKeys.UNKNOWN_TYPE);

    // $ref
    testUri.runEx("ESTwoKeyNav(PropertyInt16=1,PropertyString='2')/PropertyCompTwoPrim/$ref")
        .isExSemantic(MessageKeys.ONLY_FOR_ENTITY_TYPES);

    // $count
    testUri.runEx("ESTwoKeyNav(PropertyInt16=1,PropertyString='2')/PropertyCompTwoPrim/$count")
        .isExSemantic(MessageKeys.ONLY_FOR_COLLECTIONS);

    // Actions must not be followed by anything.
    testUri.runEx("ESTwoKeyNav(PropertyInt16=1,PropertyString='2')/"
        + "olingo.odata.test1.BA_RTETTwoKeyNav/olingo.odata.test1.ETTwoKeyNav")
        .isExValidation(UriValidationException.MessageKeys.UNALLOWED_RESOURCE_PATH);
    testUri.runEx("ESTwoKeyNav/olingo.odata.test1.BAESTwoKeyNavRTESTwoKeyNav/$count")
        .isExValidation(UriValidationException.MessageKeys.UNALLOWED_RESOURCE_PATH);
  }

  @Test
  public void doublePercentDecoding() throws Exception {
    testUri.runEx("ESAllPrim%252832767%29").isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);
  }

  @Test
  public void multipleKeysInResourcePath() throws Exception {
    // See OLINGO-730
    testUri.runEx("ESAllPrim(32767)(1)(2)").isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);
  }

  @Test
  public void startElementsInsteadOfNavigationProperties() {
    testUri.runEx("ESAllPrim(0)/ESAllPrim(0)/ESAllPrim(0)").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("ESAllPrim(0)/SINav").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("ESAllPrim(0)/FICRTString()").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("ESAllPrim(0)/AIRTString").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("SI/ESAllPrim(0)").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("SI/SINav").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("SI/FICRTString()").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("SI/AIRTString").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("FICRTETKeyNav()/ESAllPrim(0)").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("FICRTETKeyNav()/SINav").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("FICRTETKeyNav()/FICRTString()").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("FICRTETKeyNav()/AIRTString").isExSemantic(MessageKeys.PROPERTY_NOT_IN_TYPE);
    testUri.runEx("AIRTESAllPrimParam/ESAllPrim(0)")
        .isExValidation(UriValidationException.MessageKeys.UNALLOWED_RESOURCE_PATH);
    testUri.runEx("AIRTESAllPrimParam/SINav")
        .isExValidation(UriValidationException.MessageKeys.UNALLOWED_RESOURCE_PATH);
    testUri.runEx("AIRTESAllPrimParam/FICRTString()")
        .isExValidation(UriValidationException.MessageKeys.UNALLOWED_RESOURCE_PATH);
    testUri.runEx("AIRTESAllPrimParam/AIRTString")
        .isExValidation(UriValidationException.MessageKeys.UNALLOWED_RESOURCE_PATH);
  }

  @Test
  public void firstResourcePathWithNamespace() {
    testUri.runEx("olingo.odata.test1.ESAllPrim").isExSemantic(MessageKeys.NAMESPACE_NOT_ALLOWED_AT_FIRST_ELEMENT);
    testUri.runEx("olingo.odata.test1.ESAllPrim(0)").isExSemantic(MessageKeys.NAMESPACE_NOT_ALLOWED_AT_FIRST_ELEMENT);
    testUri.runEx("olingo.odata.test1.FINRTInt16()").isExSemantic(MessageKeys.NAMESPACE_NOT_ALLOWED_AT_FIRST_ELEMENT);
    testUri.runEx("olingo.odata.test1.AIRTString").isExSemantic(MessageKeys.NAMESPACE_NOT_ALLOWED_AT_FIRST_ELEMENT);
    testUri.runEx("olingo.odata.test1.SINav").isExSemantic(MessageKeys.NAMESPACE_NOT_ALLOWED_AT_FIRST_ELEMENT);
  }

  @Test
  public void alias() throws Exception {
    testUri.run("ESTwoKeyNav(PropertyInt16=1,PropertyString=@A)", "@A='2'").goPath()
        .isKeyPredicate(0, "PropertyInt16", "1")
        .isKeyPredicateAlias(1, "PropertyString", "@A")
        .goUpUriValidator().isInAliasToValueMap("@A", "'2'");
    testUri.run("ESAllPrim(PropertyInt16=@p1)", "@p1=1").goPath()
        .isKeyPredicateAlias(0, "PropertyInt16", "@p1")
        .goUpUriValidator().isInAliasToValueMap("@p1", "1");
    testUri.run("ESAllPrim(@p1)", "@p1=-2").goPath()
        .isKeyPredicateAlias(0, "PropertyInt16", "@p1")
        .goUpUriValidator().isInAliasToValueMap("@p1", "-2");

    testFilter.runOnETAllPrim("PropertyInt16 gt @alias&@alias=1")
        .is("<<PropertyInt16> gt <@alias>>")
        .right().isAlias("@alias");
    testFilter.runOnETAllPrim("@alias&@alias=@otherAlias&@otherAlias=true")
        .isAlias("@alias");

    testUri.runEx("ESAllPrim(@p1)")
        .isExValidation(UriValidationException.MessageKeys.MISSING_ALIAS);
    testUri.runEx("ESAllPrim(PropertyInt16=@p1)", "@p1='ewe'").isExSemantic(MessageKeys.UNKNOWN_PART);
    testUri.runEx("ESAllPrim(PropertyInt16=@p1)", "@p1='ewe")
        .isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);
    testFilter.runOnETKeyNavEx("PropertyInt16 gt @alias")
        .isInAliasToValueMap("@alias", null);
    testFilter.runOnETKeyNavEx("PropertyInt16 gt @alias&@alias=@alias")
        .isInAliasToValueMap("@alias", "@alias");
    testFilter.runOnETKeyNavEx("@alias&@alias=@alias2&@alias2=true or @alias")
        .isInAliasToValueMap("@alias", "@alias2");
  }

  @Test
  public void functionImportParameterAlias() throws Exception {
    testUri.run("FICRTCollESTwoKeyNavParam(ParameterInt16=@parameterAlias)", "@parameterAlias=1");
    testUri.run("FICRTCollESTwoKeyNavParam(ParameterInt16=@parameterAlias)/$count", "@parameterAlias=1");
    testUri.runEx("FICRTCollESTwoKeyNavParam(ParameterInt16=@invalidAlias)", "@validAlias=1")
        .isExValidation(UriValidationException.MessageKeys.MISSING_ALIAS);
  }

  @Test
  public void functionsWithComplexParameters() throws Exception {
    testUri.run("ESTwoKeyNav/olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1)", "@p1={\"PropertyInt16\":1,\"PropertyString\":\"1\"}")
        .goPath()
        .first().isEntitySet("ESTwoKeyNav")
        .n().isFunction("BFCESTwoKeyNavRTStringParam").isParameterAlias(0, "ParameterComp", "@p1")
        .goUpUriValidator().isInAliasToValueMap("@p1", "{\"PropertyInt16\":1,\"PropertyString\":\"1\"}");

    // Test JSON String lexer rule =\"3,Int16=abc},\\\nabc&test%test\b\f\r\t\u0022\\}\\{\\)\\(\\]\\[}
    final String stringValueEncoded = "=\\\"3,Int16=abc},\\\\\\nabc%26test%25test\\b\\f\\r\\t\\u0022\\\\}\\\\{\\\\)"
        + "\\\\(\\\\]\\\\[}";
    final String stringValueDecoded = "=\\\"3,Int16=abc},\\\\\\nabc&test%test\\b\\f\\r\\t\\u0022\\\\}\\\\{\\\\)"
        + "\\\\(\\\\]\\\\[}";

    testUri.run("ESTwoKeyNav/olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1)", "@p1={\"PropertyInt16\":1,\"PropertyString\":\"" + stringValueEncoded + "\"}")
        .goPath()
        .first().isEntitySet("ESTwoKeyNav")
        .n().isFunction("BFCESTwoKeyNavRTStringParam").isParameterAlias(0, "ParameterComp", "@p1")
        .goUpUriValidator()
        .isInAliasToValueMap("@p1", "{\"PropertyInt16\":1,\"PropertyString\":\"" + stringValueDecoded + "\"}");

    testFilter.runOnETTwoKeyNav("olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp={\"PropertyString\":\"Test\",\"PropertyInt16\":1}) eq 'Test'")
        .is("<<BFCESTwoKeyNavRTStringParam> eq <'Test'>>")
        .isBinary(BinaryOperatorKind.EQ)
        .left().isParameterText(0, "{\"PropertyString\":\"Test\",\"PropertyInt16\":1}");

    testFilter.runOnETTwoKeyNav("olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp={\"PropertyString\":\"" + stringValueEncoded + "\",\"PropertyInt16\":1}) eq 'Test'")
        .is("<<BFCESTwoKeyNavRTStringParam> eq <'Test'>>")
        .left().isParameterText(0, "{\"PropertyString\":\"" + stringValueDecoded + "\",\"PropertyInt16\":1}");

    testUri.run("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={\"PropertyInt16\":1,\"PropertyString\":\"1\"}");

    testUri.run("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={\"PropertyInt16\":1,\"PropertyString\":null}")
        .goFilter().left().isParameterText(0, null);

    testUri.run("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={}");

    testUri.run("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={\"PropertyInt16\":[1,2,3],\"PropertyString\":\"1\"}");

    testUri.run("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={\"PropertyInt16\":[\"1\",\"2\",\"3\"],\"PropertyString\":\"1\"}");

    testUri.run("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={\"PropertyInt16\":[{\"Prop1\":123,\"Prop2\":\"Test\",\"Prop3\":[1,2,3]},"
        + "{\"Prop1\":{\"Prop1\":[\"Prop\\\":{]\"]}}],\"PropertyString\":\"1\"}");

    testUri.run("FINRTByteNineParam(ParameterEnum=null,ParameterDef='x',ParameterComp=@c,"
        + "ParameterETTwoPrim=@c,CollParameterByte=@e,CollParameterEnum=@e,CollParameterDef=@e,"
        + "CollParameterComp=@e,CollParameterETTwoPrim=@e)",
        "@c={}&@e=[]");

    testUri.runEx("ESTwoKeyNav/olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1)", "@p1={\"PropertyInt16\":1,\"PropertyString\":'1'}")
        .isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);

    testUri.runEx("ESTwoKeyNav/olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp={\"PropertyInt16\":1,\"PropertyString\":\"Test\"})")
        .isExSemantic(MessageKeys.COMPLEX_PARAMETER_IN_RESOURCE_PATH);

    testUri.runEx("FICRTCTTwoPrimTwoParam(ParameterInt16=1,ParameterString=null)")
        .isExValidation(UriValidationException.MessageKeys.MISSING_PARAMETER);

    testUri.runEx("FICRTCTTwoPrimTwoParam(ParameterInt16=1,ParameterString=@test)")
        .isExValidation(UriValidationException.MessageKeys.MISSING_ALIAS);

    testUri.runEx("FICRTCTTwoPrimTwoParam(ParameterInt16=1,ParameterString=@test)", "@test=null")
        .isExValidation(UriValidationException.MessageKeys.MISSING_ALIAS);

    testUri.run("FICRTCTTwoPrimTwoParam(ParameterInt16=1,ParameterString=@test)", "@test='null'");

    testUri.runEx("FICRTCTTwoPrimTwoParam(ParameterInt16=1,ParameterString=@test,UnknownParam=1)", "@test='null'")
        .isExSemantic(MessageKeys.FUNCTION_NOT_FOUND);

    testUri.run("FICRTCollCTTwoPrimTwoParam(ParameterInt16=1,ParameterString=@test)", "@test='null'");
    testUri.run("FICRTCollCTTwoPrimTwoParam(ParameterInt16=1,ParameterString=@test)", "@test=null");
    testUri.run("FICRTCollCTTwoPrimTwoParam(ParameterInt16=1,ParameterString=@test)");
    testUri.run("FICRTCollCTTwoPrimTwoParam(ParameterInt16=1,ParameterString=null)");

    testUri.runEx("FICRTCollCTTwoPrimTwoParam(ParameterInt16=1,ParameterString=@test)", "@test=null&@test='1'")
        .isExSyntax(UriParserSyntaxException.MessageKeys.DUPLICATED_ALIAS);

    testFilter.runOnETKeyNavEx("FINRTInt16() eq 0")
        .isExSemantic(MessageKeys.EXPRESSION_PROPERTY_NOT_IN_TYPE);

    testUri.runEx("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={\"PropertyInt16\":1,\"PropertyString\":\"1\"")
        .isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);

    testUri.runEx("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={\"PropertyInt16\":1,\"PropertyString\":\"1\"}}")
        .isExSemantic(MessageKeys.UNKNOWN_PART);

    testUri.runEx("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={\"PropertyInt16\":[1,2,3]],\"PropertyString\":\"1\"}")
        .isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);

    testUri.runEx("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={\"PropertyInt16\":[1,2,3,\"PropertyString\":\"1\"}")
        .isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);

    testUri.runEx("ESTwoKeyNav", "$filter=olingo.odata.test1.BFCESTwoKeyNavRTStringParam"
        + "(ParameterComp=@p1) eq '0'&@p1={\"PropertyInt16\":[1,2,3},\"PropertyString\":\"1\"}")
        .isExSyntax(UriParserSyntaxException.MessageKeys.SYNTAX);
  }

  @Test
  public void allowedSystemQueryOptionsOnAll() throws Exception {
    testUri.run("$all", "$count=true&$format=json&$search=abc&$skip=5&$top=5&$skiptoken=abc")
        .isKind(UriInfoKind.all)
        .isInlineCount(true)
        .isFormatText("json")
        .isSearchSerialized("'abc'")
        .isSkip(5)
        .isTop(5)
        .isSkipTokenText("abc");
  }

  @Test
  public void allowedSystemQueryOptionsOnCrossjoin() throws Exception {
    testUri.run("$crossjoin(ESAllPrim,ESTwoPrim)", "$count=true&$expand=ESAllPrim"
        + "&$filter=ESAllPrim/PropertyInt16 eq 2&$format=json&$orderby=ESAllPrim/PropertyInt16"
        + "&$search=abc&$skip=5&$top=5&$skiptoken=abc")
        .isKind(UriInfoKind.crossjoin)
        .isInlineCount(true)
        .goExpand().goPath().isEntitySet("ESAllPrim")
        .goUpExpandValidator().goUpToUriValidator()
        .goFilter().left().goPath().first().isEntitySet("ESAllPrim")
        .n().isPrimitiveProperty("PropertyInt16", PropertyProvider.nameInt16, false)
        .goUpFilterValidator().goUpToUriValidator()
        .isFormatText("json")
        .isSearchSerialized("'abc'")
        .isSkip(5)
        .isTop(5)
        .isSkipTokenText("abc");
  }

  @Test
  public void trimQueryOptionsValue() throws Exception {
    // OLINGO-846 trim query option value
    testUri.run("ESAllPrim", "$filter= PropertyInt16 eq 12 ")
        .isKind(UriInfoKind.resource).goPath()
        .first().isEntitySet("ESAllPrim");
    // OLINGO-846 trim query option value
    testUri.run("ESAllPrim", "$filter= PropertyInt16 eq 12 ")
        .isKind(UriInfoKind.resource).goFilter().isBinary(BinaryOperatorKind.EQ).is("<<PropertyInt16> eq <12>>");

    testUri.run("ESAllPrim", "%20$filter%20=%20PropertyInt16%20%20eq%2012%20")
      .isKind(UriInfoKind.resource).goFilter().isBinary(BinaryOperatorKind.EQ).is("<<PropertyInt16> eq <12>>");
  }

  @Test
  public void customQueryOption() throws Exception {
    testUri.run("ESTwoKeyNav", "custom")
        .isCustomParameter(0, "custom", "");
    testUri.run("ESTwoKeyNav", "custom=ABC")
        .isCustomParameter(0, "custom", "ABC");
  }

  @Test
  public void testValidationOnFunctions() throws Exception {
    testUri.runEx("FICRTETTwoKeyNavParam(ParameterInt16='32')")
    .isExValidation(UriValidationException.MessageKeys.INVALID_VALUE_FOR_PROPERTY);

    testUri.runEx("FICRTETTwoKeyNavParam(ParameterInt16=null)")
    .isExValidation(UriValidationException.MessageKeys.MISSING_PARAMETER);

    testUri.runEx("FICRTETTwoKeyNavParam(ParameterInt16=@p1)", "@p1='32'")
    .isExSemantic(UriParserSemanticException.MessageKeys.UNKNOWN_PART);

    testUri.run("FICRTETTwoKeyNavParam(ParameterInt16=32)");
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<labels>
	Característiques generals
	Utilitzar la funcionalitat del mòdul
	Utilitzar el perfil
	Utilitzar l'àrea de contactes
	Persona
	Veure totes les persones internes
	Veure totes les persones
	Afegir persones
	Editar i eliminar totes les persones
	Afegir una conta
	Veure els comentaris de les persones
	Editar comentaris de les persones
	Empreses
	Veure totes les empreses
	Afegir empreses
	Editar l'empresa pròpia (treballador)
	Editar i eliinar totes les empreses
	Veure comentaris de les empreses
	Editar comentaris de les empreses
	Relació de contactes
	Veure tots els tipus d'informacions de contacte
	Veure adreça de casa
	Veure adreça professional
	Veure adreça de facturació
	Panel Widgets
	Selector de personals
	Exportar
</labels>


text:
package org.jboss.as.quickstarts.appclient.acc.client;

import java.util.Arrays;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.jboss.as.quickstarts.appclient.acc.client.interceptor.ClientInterceptor;
import org.jboss.as.quickstarts.appclient.server.ejb.StatelessSession;
import org.jboss.ejb.client.EJBClientContext;
import org.jboss.logging.Logger;

/**
 * A simple EJB client to demonstrate the use of the JBoss application container
 * to show that the injection will work for server EJB-beans.
 *
 * @author Wolf-Dieter Fink
 */
public class Main {
    private static final Logger LOG = Logger.getLogger(Main.class);

    /**
     *
According to the JavaEE Platform specification (EE7 JSR342 - chapter EE5.16)
     * the container must provide the following boolean property as TRUE
     * if this client runs in an ApplicationClientContainer.

     * If running in a Web or EJB container the property is FALSE.

     *
Can be used to ensure that the Injection works

     */
    @Resource(lookup = "java:comp/InAppClientContainer")
    private static boolean isInAppclient;
    @EJB
    private static StatelessSession slsb;

    /** no instance necessary */
    private Main() {
    }

    /**
     * @param args the command line arguments
     * @throws NamingException
     */
    public static void main(String args[]) throws NamingException {
        // Show that the client is started with arguments at command line
        LOG.info("Main started " + (args.length != 0 ? "with" : "without") + " arguments");
        if (args.length > 0)
            LOG.info("            " + Arrays.asList(args));

        // ensure that the program is running in an AppClientContainer
        // the value might be NULL if we are running as a simple Java program
        if (!Boolean.TRUE.equals(isInAppclient)) {
            throw new RuntimeException("Not running in an Application Client Container");
        }

        // add an client side interceptor to provide the client machine name to the server application
        EJBClientContext.getCurrent().registerInterceptor(0, new ClientInterceptor());
        LOG.info(slsb.getGreeting());
        slsb.invokeWithClientContext();
    }
}


text:
---
uid: SolidEdgeFramework.InterpartLink.Freeze
summary:
remarks:
---


text:
#include "ExprNamespaceFinder.h"
#include "ASTImport.h"

namespace ContextAnalyzer
{

StmntSymbolTable* ExprNamespaceFinder::FindNamespace(Expr& expr, const ArrayAccess* arrayAccess)
{
    /* Initialize array access */
    auto hasArray = (arrayAccess != nullptr);
    arrayAccess_    = arrayAccess;

    /* Reset temporary variables */
    declRef_        = nullptr;
    symTab_         = nullptr;

    /* Find namespace in expression */
    Visit(&expr);

    /* Return result */
    return (hasArray && arrayAccess_ != nullptr) ? nullptr : symTab_;
}

/*
 * ======= Private: =======
 */

/* --- Expressions --- */

DEF_VISIT_PROC(ExprNamespaceFinder, TernaryExpr)
{
    /* Visit expression for 'then' branch */
    Visit(ast->thenExpr);
    auto typeThenBranch = PopDeclRef();

    if (typeThenBranch)
    {
        /* Visit expression for 'else' branch */
        Visit(ast->elseExpr);
        auto typeElseBranch = PopDeclRef();

        if (typeElseBranch)
        {
            /* Find common denominator of namespaces */
            auto& denom = ClassDeclStmnt::FindCommonDenominator(*typeThenBranch, *typeElseBranch);
            StoreSymbolTable(&denom);
            return;
        }
    }

    StoreSymbolTable(nullptr);
}

DEF_VISIT_PROC(ExprNamespaceFinder, BinaryExpr)
{
    /*
    Only traverse the first sub-expression,
    since the their types must be compatible.
    */
    Visit(ast->lhsExpr);
}

DEF_VISIT_PROC(ExprNamespaceFinder, UnaryExpr)
{
    Visit(ast->expr);
}

DEF_VISIT_PROC(ExprNamespaceFinder, LiteralExpr)
{
    Visit(ast->typeDenoter);
}

DEF_VISIT_PROC(ExprNamespaceFinder, CastExpr)
{
    /* Cast to non-const type, since we do not modify any type denoter here */
    Visit(ast->castTypeDenoter.get());
}

DEF_VISIT_PROC(ExprNamespaceFinder, ProcCallExpr)
{
    auto ref = ast->procCall->declStmntRef;
    if (ref)
        Visit(ref->procSignature->returnTypeDenoter.get());
}

DEF_VISIT_PROC(ExprNamespaceFinder, PostfixValueExpr)
{
    if (ast->procCall)
    {
        auto ref = ast->procCall->declStmntRef;
        if (ref)
            Visit(ref->procSignature->returnTypeDenoter.get());
    }
    else if (ast->varName)
    {
        /* Cast to non-const type, since we do not modify any type denoter here */
        auto varType = ast->varName->GetTypeDenoter();
        Visit(const_cast<TypeDenoter*>(varType));
    }
    else if (ast->arrayAccess)
    {
        /* Cast to non-const type, since we do not modify any type denoter here */
        auto exprType = ast->primaryValueExpr->GetTypeDenoter()->GetLast(ast->arrayAccess.get());
        Visit(const_cast<TypeDenoter*>(exprType));
    }
}

DEF_VISIT_PROC(ExprNamespaceFinder, InstanceOfExpr)
{
    // do nothing -> 'instance of' expression is a boolean expression, and thus has no namespace
}

DEF_VISIT_PROC(ExprNamespaceFinder, AllocExpr)
{
    Visit(ast->typeDenoter);
}

DEF_VISIT_PROC(ExprNamespaceFinder, VarAccessExpr)
{
    /* Cast to non-const type, since we do not modify any type denoter here */
    Visit(const_cast<TypeDenoter*>(ast->varName->GetTypeDenoter()));
}

DEF_VISIT_PROC(ExprNamespaceFinder, InitListExpr)
{
    Visit(&ast->typeDenoter);
}

DEF_VISIT_PROC(ExprNamespaceFinder, RangeExpr)
{
    Visit(ast->lhsExpr);
    Visit(ast->rhsExpr);
}

/* --- Type denoters --- */

DEF_VISIT_PROC(ExprNamespaceFinder, ArrayTypeDenoter)
{
    if (arrayAccess_)
    {
        arrayAccess_ = arrayAccess_->next.get();
        Visit(ast->lowerTypeDenoter);
    }
    else
        StoreSymbolTable(ast->declRef);
}

DEF_VISIT_PROC(ExprNamespaceFinder, PointerTypeDenoter)
{
    StoreSymbolTable(ast->declRef);
}

ClassDeclStmnt* ExprNamespaceFinder::PopDeclRef()
{
    auto declRef = declRef_;
    declRef_ = nullptr;
    return declRef;
}

void ExprNamespaceFinder::StoreSymbolTable(ClassDeclStmnt* declRef)
{
    if (declRef)
    {
        declRef_    = declRef;
        symTab_     = &(declRef->symTab);
    }
    else
    {
        declRef_    = nullptr;
        symTab_     = nullptr;
    }
}

} // /namespace ContextAnalyzer

// ================================================================================


text:
<!doctype html>

    <link rel="icon"  href="img/Halo-icon.png">

    <title>HTML5 games workshop: One-screen platformer</title>
    <meta charset="utf-8">

<canvas></canvas>

    <audio src="audio/halom.mp3" autoplay="true" loop="true"></audio>


text:
import {Component} from '@angular/core';

import {DEMO_SNIPPETS} from './demos';

@Component({
  selector: 'ng2vd-modal',
  template: `
    <ng2vd-content-wrapper component="Modal">
      <ng2vd-api-docs-class type="Ng2vModal"></ng2vd-api-docs-class>
      <ng2vd-api-docs-class type="Ng2vModalOptions"></ng2vd-api-docs-class>
      <ng2vd-api-docs-class type="Ng2vModalRef"></ng2vd-api-docs-class>
      <ng2vd-api-docs-class type="Ng2vActiveModal"></ng2vd-api-docs-class>
      <ng2vd-example-box demoTitle="Modal with default options" [snippets]="snippets" component="modal" demo="basic">
          <ng2vd-modal-basic></ng2vd-modal-basic>
      </ng2vd-example-box>
      <ng2vd-example-box demoTitle="Components as content" [snippets]="snippets" component="modal" demo="component">
          <ng2vd-modal-component></ng2vd-modal-component>
      </ng2vd-example-box>
      <ng2vd-example-box demoTitle="Modal with custom class" [snippets]="snippets" component="modal" demo="customclass">
          <ng2vd-modal-customclass></ng2vd-modal-customclass>
      </ng2vd-example-box>
    </ng2vd-content-wrapper>
  `
})
export class Ng2vdModal {
  snippets = DEMO_SNIPPETS;
}


text:
from neomodel import (StructuredNode, StringProperty, IntegerProperty)
from neomodel.exception import UniqueProperty, DeflateError

class Customer(StructuredNode):
    email = StringProperty(unique_index=True, required=True)
    age = IntegerProperty(index=True)

def test_batch_create():
    users = Customer.create(
            {'email': 'jim1@aol.com', 'age': 11},
            {'email': 'jim2@aol.com', 'age': 7},
            {'email': 'jim3@aol.com', 'age': 9},
            {'email': 'jim4@aol.com', 'age': 7},
            {'email': 'jim5@aol.com', 'age': 99},
    )
    assert len(users) == 5
    assert users[0].age == 11
    assert users[1].age == 7
    assert users[1].email == 'jim2@aol.com'
    assert Customer.nodes.get(email='jim1@aol.com')

def test_batch_validation():
    # test validation in batch create
    try:
        Customer.create(
            {'email': 'jim1@aol.com', 'age': 'x'},
        )
    except DeflateError:
        assert True
    else:
        assert False

def test_batch_index_violation():
    for u in Customer.nodes.all():
        u.delete()

    users = Customer.create(
        {'email': 'jim6@aol.com', 'age': 3},
    )
    assert users
    try:
        Customer.create(
            {'email': 'jim6@aol.com', 'age': 3},
            {'email': 'jim7@aol.com', 'age': 5},
        )
    except UniqueProperty:
        assert True
    else:
        assert False

    # not found
    assert not Customer.nodes.filter(email='jim7@aol.com')


text:
package edu.tufts.contours.colorfulPiano;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;

/**
 * Created by Thomas on 5/25/15.
 */
public class BlackPianoKey extends PianoKey {

    public BlackPianoKey(Context context, Piano piano, int noteValue){
        super(context, piano, noteValue);
    }

    @Override
    public void layout(Rect drawingRect, int keyCount){
        int whiteKeyWidth = getWhiteKeyWidth(drawingRect, keyCount);
        int blackKeyWidth = getBlackKeyWidth(drawingRect, keyCount);

        colorRect.top = 0;
        colorRect.bottom = getBlackKeyHeight(drawingRect);
        colorRect.left = (((noteValue/12)*7) + key_positions.get(noteValue%12) + 1) *
                whiteKeyWidth - (blackKeyWidth/2);
        colorRect.right = colorRect.left + blackKeyWidth;

        mainRect.top = colorRect.top;
        mainRect.bottom = colorRect.bottom;
        mainRect.left = colorRect.left;
        mainRect.right = colorRect.right;
    }

    @Override
    public void draw(Canvas canvas){
        strokePaint.setColor(Color.BLACK);

        if (getTouches()) {
            fillPaint.setColor(Color.DKGRAY);
        } else {
            fillPaint.setColor(Color.BLACK);
        }

        canvas.drawRect(colorRect, fillPaint);
        canvas.drawRect(colorRect, strokePaint);
    }

}


text:
package exporter

import (
	"context"
	"strings"
	"testing"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	dto "github.com/prometheus/client_model/go"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"

	"github.com/percona/mongodb_exporter/internal/tu"
)

type ReplicasetConfig struct {
	Config RSConfig `bson:"config"`
}

type RSConfig struct {
	ID                                 string `bson:"_id"`
	Version                            int    `bson:"version"`
	ProtocolVersion                    int    `bson:"protocolVersion"`
	WriteConcernMajorityJournalDefault bool   `bson:"writeConcernMajorityJournalDefault"`
	Members                            []struct {
		ID           int      `bson:"_id"`
		Host         string   `bson:"host"`
		ArbiterOnly  bool     `bson:"arbiterOnly"`
		BuildIndexes bool     `bson:"buildIndexes"`
		Hidden       bool     `bson:"hidden"`
		Priority     int      `bson:"priority"`
		Tags         struct{} `bson:"tags"`
		SlaveDelay   int      `bson:"slaveDelay"`
		Votes        int      `bson:"votes"`
	} `bson:"members"`
	Settings struct {
		ChainingAllowed            bool     `bson:"chainingAllowed"`
		HeartbeatIntervalMillis    int      `bson:"heartbeatIntervalMillis"`
		HeartbeatTimeoutSecs       int      `bson:"heartbeatTimeoutSecs"`
		ElectionTimeoutMillis      int      `bson:"electionTimeoutMillis"`
		CatchUpTimeoutMillis       int      `bson:"catchUpTimeoutMillis"`
		CatchUpTakeoverDelayMillis int      `bson:"catchUpTakeoverDelayMillis"`
		GetLastErrorModes          struct{} `bson:"getLastErrorModes"`
		GetLastErrorDefaults       struct {
			W        int `bson:"w"`
			Wtimeout int `bson:"wtimeout"`
		} `bson:"getLastErrorDefaults"`
		ReplicaSetID primitive.ObjectID `bson:"replicaSetId"`
	} `bson:"settings"`
}

func TestSecondaryLag(t *testing.T) {
	t.Skip("This is failing in GitHub actions. Cannot make secondary to lag behind")
	secondsBehind := 3
	sleep := 2
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration((secondsBehind*2)+sleep)*time.Second)
	defer cancel()

	client := tu.DefaultTestClient(ctx, t)

	var rsConf, rsConfOld ReplicasetConfig
	var gg interface{}

	res := client.Database("admin").RunCommand(ctx, primitive.M{"replSetGetConfig": 1})
	require.NoError(t, res.Err())

	err := res.Decode(&gg) // To restore config after test
	assert.NoError(t, err)

	err = res.Decode(&rsConf)
	assert.NoError(t, err)

	rsConf.Config.Members[1].Priority = 0
	rsConf.Config.Members[1].Hidden = true
	rsConf.Config.Members[1].SlaveDelay = secondsBehind
	rsConf.Config.Version++

	var replSetReconfig struct {
		OK int `bson:"ok"`
	}
	err = client.Database("admin").RunCommand(ctx, primitive.M{"replSetReconfig": rsConf.Config}).Decode(&replSetReconfig)
	assert.NoError(t, err)

	res = client.Database("admin").RunCommand(ctx, primitive.M{"replSetGetConfig": 1})
	require.NoError(t, res.Err())

	// Generate documents so oplog is forced to have operations and the lag becomes real, otherwise
	// primary and secondary oplogs are the same. Generate more than one doc to ensure oplog is updated
	// quickly for the test.
	for i := 0; i < 100; i++ {
		_, err = client.Database("test").Collection("testc1").InsertOne(ctx, bson.M{"s": 1})
		require.NoError(t, err)
		time.Sleep(20 * time.Millisecond)
	}
	err = client.Database("test").Drop(ctx)
	assert.NoError(t, err)

	err = res.Decode(&rsConfOld) // To restore config after test
	assert.NoError(t, err)

	msclient := tu.TestClient(ctx, tu.MongoDBS1Secondary1Port, t)
	var m bson.M

	cmd := bson.D{{Key: "getDiagnosticData", Value: "1"}}
	res = msclient.Database("admin").RunCommand(ctx, cmd)

	err = res.Decode(&m)
	assert.NoError(t, err)

	m, _ = m["data"].(bson.M)
	metrics := replSetMetrics(m)
	var lag prometheus.Metric
	for _, m := range metrics {
		if strings.HasPrefix(m.Desc().String(), `Desc{fqName: "mongodb_mongod_replset_member_replication_lag"`) {
			lag = m

			break
		}
	}

	metric := &dto.Metric{}
	err = lag.Write(metric)
	assert.NoError(t, err)
	// Secondary is not exactly secondsBehind behind master
	assert.True(t, *metric.Gauge.Value > 0)

	rsConfOld.Config.Version = rsConf.Config.Version + 1
	err = client.Database("admin").RunCommand(ctx, primitive.M{"replSetReconfig": rsConfOld.Config}).Decode(&replSetReconfig)
	assert.NoError(t, err)
}