text:
package org.kaazing.gateway.transport.wsn.specification.ws.connector;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.kaazing.test.util.ITUtil.timeoutRule;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.jmock.integration.junit4.JUnitRuleMockery;
import org.jmock.lib.concurrent.Synchroniser;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.kaazing.gateway.transport.test.Expectations;
import org.kaazing.k3po.junit.annotation.Specification;
import org.kaazing.k3po.junit.rules.K3poRule;
import org.kaazing.mina.core.session.IoSessionEx;
import org.kaazing.test.util.ITUtil;
import org.kaazing.test.util.MethodExecutionTrace;

public class OpeningHandshakeIT {
    private final WsnConnectorRule connector = new WsnConnectorRule();
    private final K3poRule k3po = new K3poRule().setScriptRoot("org/kaazing/specification/ws/opening");
    private final TestRule trace = new MethodExecutionTrace();
    private final TestRule timeoutRule = timeoutRule(10, SECONDS);

    private JUnitRuleMockery context = new JUnitRuleMockery() {
        {
            setThreadingPolicy(new Synchroniser());
        }
    };

    private TestRule contextRule = ITUtil.toTestRule(context);

    @Rule
    public TestRule chain = RuleChain.outerRule(trace).around(connector).around(k3po).around(timeoutRule)
            .around(contextRule);

    @Test
    @Specification({
        "response.header.sec.websocket.accept.missing/handshake.response"
        })
    public void missingSecWebSocketAcceptHeader() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                never(handler).sessionCreated(with(any(IoSessionEx.class)));
                never(handler).sessionOpened(with(any(IoSessionEx.class)));
                never(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                never(handler).sessionClosed(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertFalse(connectFuture.isConnected());

        k3po.finish();
        context.assertIsSatisfied();

    }

    @Test
    @Specification({
        "connection.established/handshake.response"
        })
    public void shouldEstablishConnection() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Specification({
        "request.headers.random.case/handshake.response"
        })
    public void shouldEstablishConnectionWithRandomCaseRequestHeaders() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Specification({
        "response.headers.random.case/handshake.response"
        })
    public void shouldEstablishConnectionWithRandomCaseResponseHeaders() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Specification({
        "request.header.origin/handshake.response"
        })
    public void shouldEstablishConnectionWithRequestHeaderOrigin() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Specification({
        "request.header.sec.websocket.protocol/handshake.response"
        })
    public void shouldEstablishConnectionWithRequestHeaderSecWebSocketProtocol() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
            }
        });

        String [] protocols = {"primary", " secondary"}; // Need the space to honor the script.
        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", protocols, null, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Ignore("Issue# 309: Missing Sec-WebSocket-Extensions header in the handshake request")
    @Specification({
        "request.header.sec.websocket.extensions/handshake.response"
        })
    public void shouldEstablishConnectionWithRequestHeaderSecWebSocketExtensions() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
            }
        });

        String[] extensions = {"primary", " secondary"}; // Need the space to honor the script.
        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, extensions, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Ignore("Issue# 309: Missing Sec-WebSocket-Extensions header in the handshake request")
    @Specification({
        "response.header.sec.websocket.extensions.partial.agreement/handshake.response"
        })
    public void shouldEstablishConnectionWithSomeExtensionsNegotiated() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
            }
        });

        String[] extensions = {"valid", " invalid"}; // Need the space to honor the script.
        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, extensions, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Ignore("Issue #309: Missing Sec-WebSocket-Extensions header in the handshake request")
    @Specification({
        "response.header.sec.websocket.extensions.reordered/handshake.response"
        })
    public void shouldEstablishConnectionWhenOrderOfExtensionsNegotiatedChanged() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                oneOf(handler).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler).sessionOpened(with(any(IoSessionEx.class)));
            }
        });

        String[] extensions = {"primary", " secondary"}; // Need the space to honor the script.
        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, extensions, handler);
        connectFuture.awaitUninterruptibly();
        assertTrue(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Ignore("Issue# 310: Connection header set to invalid value in the handshake response. "
            + " connectFuture.isConnected() must return false")
    @Specification({
        "response.header.connection.not.upgrade/handshake.response" })
    public void shouldFailConnectionWhenResponseHeaderConnectionNotUpgrade() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                never(handler).sessionCreated(with(any(IoSessionEx.class)));
                never(handler).sessionOpened(with(any(IoSessionEx.class)));
                never(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                never(handler).sessionClosed(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertFalse(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Ignore("Issue# 311: Missing Connection header in handshake response. connectFuture.isConnected() must return false")
    @Specification({
        "response.header.connection.missing/handshake.response" })
    public void shouldFailConnectionWhenResponseHeaderConnectionMissing() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                never(handler).sessionCreated(with(any(IoSessionEx.class)));
                never(handler).sessionOpened(with(any(IoSessionEx.class)));
                never(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                never(handler).sessionClosed(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertFalse(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Ignore("Issue# 312: Upgrade header set to invalid value in the handshake response."
            + " connectFuture.isConnected() must return false")
    @Specification({
        "response.header.upgrade.not.websocket/handshake.response" })
    public void shouldFailConnectionWhenResponseHeaderUpgradeNotWebSocket() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                never(handler).sessionCreated(with(any(IoSessionEx.class)));
                never(handler).sessionOpened(with(any(IoSessionEx.class)));
                never(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                never(handler).sessionClosed(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertFalse(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Ignore("Issue# 313: Missing Upgrade header in handshake response. connectFuture.isConnected() must return false")
    @Specification({
        "response.header.upgrade.missing/handshake.response" })
    public void shouldFailConnectionWhenResponseHeaderUpgradeMissing() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                never(handler).sessionCreated(with(any(IoSessionEx.class)));
                never(handler).sessionOpened(with(any(IoSessionEx.class)));
                never(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                never(handler).sessionClosed(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertFalse(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Ignore("Did not fail and should -- I think the script is hashing Sec-WebSocket-Accept. Need clarification.")
    @Specification({
        "response.header.sec.websocket.accept.not.hashed/handshake.response" })
    public void shouldFailConnectionWhenResponseHeaderSecWebSocketAcceptNotHashed() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                never(handler).sessionCreated(with(any(IoSessionEx.class)));
                never(handler).sessionOpened(with(any(IoSessionEx.class)));
                never(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                never(handler).sessionClosed(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertFalse(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Specification({
        "response.header.sec.websocket.accept.missing/handshake.response" })
    public void shouldFailConnectionWhenResponseHeaderSecWebSocketAcceptMissing() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                never(handler).sessionCreated(with(any(IoSessionEx.class)));
                never(handler).sessionOpened(with(any(IoSessionEx.class)));
                never(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                never(handler).sessionClosed(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, handler);
        connectFuture.awaitUninterruptibly();
        assertFalse(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Ignore("Issues# 309, 314: Missing Sec-WebSocket-Extensions header in the handshake request. connectFuture.isConnected()"
            + "must return false as the negotiated extension does not match the supported extensions.")
    @Specification({
        "response.header.sec.websocket.extensions.not.negotiated/handshake.response" })
    public void shouldFailConnectionWhenResponseHeaderSecWebSocketExtensionsNotNegotiated() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                never(handler).sessionCreated(with(any(IoSessionEx.class)));
                never(handler).sessionOpened(with(any(IoSessionEx.class)));
                never(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                never(handler).sessionClosed(with(any(IoSessionEx.class)));
            }
        });

        String[] extensions = {"primary", " secondary"};  // Need space to honor the script.
        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", null, extensions, handler);
        connectFuture.awaitUninterruptibly();
        assertFalse(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Ignore("Issue# 315: connectFuture.isConnected() must return false as the negotiated protocol does not match any"
            + "of the supported protocols")
    @Specification({
        "response.header.sec.websocket.protocol.not.negotiated/handshake.response" })
    public void shouldFailConnectionWhenResponseHeaderSecWebSocketProtocolNotNegotiated() throws Exception {
        final IoHandler handler = context.mock(IoHandler.class);

        context.checking(new Expectations() {
            {
                never(handler).sessionCreated(with(any(IoSessionEx.class)));
                never(handler).sessionOpened(with(any(IoSessionEx.class)));
                never(handler).exceptionCaught(with(any(IoSessionEx.class)), with(any(Throwable.class)));
                never(handler).sessionClosed(with(any(IoSessionEx.class)));
            }
        });

        String [] protocols = {"primary", " secondary"}; // Need the space to honor the script.
        ConnectFuture connectFuture = connector.connect("ws://localhost:8080/path?query", protocols, null, handler);
        connectFuture.awaitUninterruptibly();
        assertFalse(connectFuture.isConnected());

        k3po.finish();
    }

    @Test
    @Specification({
        "multiple.connections.established/handshake.responses"
        })
    public void shouldEstablishMultipleConnections() throws Exception {
        final IoHandler handler1 = context.mock(IoHandler.class, "handler1");
        final IoHandler handler2 = context.mock(IoHandler.class, "handler2");

        context.checking(new Expectations() {
            {
                oneOf(handler1).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler1).sessionOpened(with(any(IoSessionEx.class)));
                oneOf(handler2).sessionCreated(with(any(IoSessionEx.class)));
                oneOf(handler2).sessionOpened(with(any(IoSessionEx.class)));
            }
        });

        ConnectFuture connectFuture1 = connector.connect("ws://localhost:8080/path?query", null, handler1);
        connectFuture1.awaitUninterruptibly();
        assertTrue(connectFuture1.isConnected());

        ConnectFuture connectFuture2 = connector.connect("ws://localhost:8080/path?query", null, handler2);
        connectFuture2.awaitUninterruptibly();
        assertTrue(connectFuture2.isConnected());

        k3po.finish();
    }
}


text:
package com.phaseii.rxm.roomies.database.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.phaseii.rxm.roomies.database.contract.RoomiesContract;
import com.phaseii.rxm.roomies.database.model.RoomStats;
import com.phaseii.rxm.roomies.database.model.RoomiesModel;
import com.phaseii.rxm.roomies.database.provider.RoomStatsProvider;
import com.phaseii.rxm.roomies.utils.QueryParam;
import com.phaseii.rxm.roomies.utils.ServiceParam;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.RoomStats.STATS_ELECTRICITY_MARGIN;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.RoomStats.STATS_ELECTRICITY_SPENT;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.RoomStats.STATS_MAID_MARGIN;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.RoomStats.STATS_MAID_SPENT;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.RoomStats.STATS_MISCELLANEOUS_MARGIN;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.RoomStats.STATS_MISCELLANEOUS_SPENT;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.RoomStats.STATS_MONTH_YEAR;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.RoomStats.STATS_RENT_MARGIN;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.RoomStats.STATS_RENT_SPENT;
import static com.phaseii.rxm.roomies.database.contract.RoomiesContract.RoomStats.STATS_ROOM_ID;
import static com.phaseii.rxm.roomies.utils.RoomiesHelper.listToProjection;

/**
 * Created by Snehankur on 7/1/2015.
 */
public class RoomStatsDaoImpl implements RoomiesDao {
    Context mContext;
    private Uri statUri;
    private String[] projection;
    private String selection;
    private String[] selectionArgs;
    private String sortOrder;
    private ContentValues values;

    public RoomStatsDaoImpl(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public List<? extends RoomiesModel> getDetails(Map<ServiceParam, ?> queryMap) {
        prepareStatement(queryMap);

        List<RoomStats> roomStatsList = new ArrayList<>();
        Cursor cursor = null;
        try {
            cursor = mContext.getContentResolver().query(statUri, projection, selection,
                    selectionArgs, sortOrder);

            if (null != cursor) {
                cursor.moveToFirst();
                while (!cursor.isAfterLast()) {

                    RoomStats roomStats = new RoomStats();

                    roomStats.setRoomId(cursor.getColumnIndex(STATS_ROOM_ID) >= 0 ? cursor.getInt
                            (cursor.getColumnIndex(STATS_ROOM_ID)) : -1);
                    roomStats.setMonthYear(
                            cursor.getColumnIndex(STATS_MONTH_YEAR) >= 0 ? cursor.getString
                                    (cursor.getColumnIndex(STATS_MONTH_YEAR)) : null);
                    roomStats.setRentMargin(cursor.getColumnIndex(STATS_RENT_MARGIN) >= 0 ?
                            cursor.getInt(cursor.getColumnIndex(STATS_RENT_MARGIN)) : -1);
                    roomStats.setMaidMargin(cursor.getColumnIndex(STATS_MAID_MARGIN) >= 0 ?
                            cursor.getInt(cursor.getColumnIndex(STATS_MAID_MARGIN)) : -1);
                    roomStats.setElectricityMargin(
                            cursor.getColumnIndex(STATS_ELECTRICITY_MARGIN) >= 0 ?
                                    cursor.getInt(
                                            cursor.getColumnIndex(STATS_ELECTRICITY_MARGIN)) : -1);
                    roomStats.setMiscellaneousMargin(
                            cursor.getColumnIndex(STATS_MISCELLANEOUS_MARGIN) >= 0 ?
                                    cursor.getInt(
                                            cursor.getColumnIndex(STATS_MISCELLANEOUS_MARGIN)) :
                                    -1);
                    roomStats.setRentSpent(cursor.getColumnIndex(STATS_RENT_SPENT) >= 0 ?
                            cursor.getInt(cursor.getColumnIndex(STATS_RENT_SPENT)) : -1);
                    roomStats.setMaidSpent(cursor.getColumnIndex(STATS_MAID_SPENT) >= 0 ?
                            cursor.getInt(cursor.getColumnIndex(STATS_MAID_SPENT)) : -1);
                    roomStats.setElectricitySpent(
                            cursor.getColumnIndex(STATS_ELECTRICITY_SPENT) >= 0 ?
                                    cursor.getInt(
                                            cursor.getColumnIndex(STATS_ELECTRICITY_SPENT)) : -1);
                    roomStats.setMiscellaneousSpent(
                            cursor.getColumnIndex(STATS_MISCELLANEOUS_SPENT) >= 0 ?
                                    cursor.getInt(
                                            cursor.getColumnIndex(STATS_MISCELLANEOUS_SPENT)) : -1);

                    roomStatsList.add(roomStats);

                    cursor.moveToNext();
                }
            }
        } finally {
            if (null != cursor && !cursor.isClosed()) {
                cursor.close();
            }
        }

        return roomStatsList;
    }

    @Override
    public int insertDetails(Map<ServiceParam, ? extends RoomiesModel> detailsMap) {

        int row = 0;
        prepareStatement(detailsMap);
        Uri resultUri = mContext.getContentResolver().insert(RoomStatsProvider.CONTENT_URI,
                values);
        row = Integer.parseInt(resultUri.getLastPathSegment());

        return row;
    }

    /**
     *
     * @param detailsMap
     * @return
     */
    @Override public int deleteDetails(Map<ServiceParam, ?> detailsMap) {
        prepareStatement(detailsMap);
        return mContext.getContentResolver().delete(RoomStatsProvider.CONTENT_URI,
                selection, selectionArgs);
    }

    @Override
    public int updateDetails(Map<ServiceParam, ?> detailsMap) {
        return 0;
    }

    /**
     *

     * @param serviceParamMap
     */
    @Override public void prepareStatement(Map<ServiceParam, ?> serviceParamMap) {
        List<QueryParam> projectionList = (List<QueryParam>) serviceParamMap
                .get(ServiceParam.PROJECTION);
        List<QueryParam> selectionList = (List<QueryParam>) serviceParamMap
                .get(ServiceParam.SELECTION);
        List<String> selectionArgsList = (List<String>) serviceParamMap
                .get(ServiceParam.SELECTION_ARGS);
        Map<QueryParam, Object> selectionInMap = (Map<QueryParam, Object>) serviceParamMap
                .get(ServiceParam.SELECTION_IN);
        sortOrder = (String) serviceParamMap.get(ServiceParam.SORT_ORDER);

        projection = listToProjection(projectionList);
        if (null != selectionList && selectionList.size() > 0) {

            for (QueryParam select : selectionList) {
                if (null == selection) {
                    selection = select.toString() + " =?";
                } else {
                    selection = selection + " AND " + select.toString() + " =?";
                }
            }
        }

        if (null != selectionInMap) {
            for (QueryParam key : selectionInMap.keySet()) {
                if (null == selection) {
                    selection = key.toString() + " in (";
                } else {
                    selection = selection + " AND " + key.toString() + " in (";
                }

                List<String> selectionInArgsList = (List<String>) selectionInMap.get(key);
                int i = 0;
                for (String selectionInArgs : selectionInArgsList) {
                    i++;
                    if (i == selectionInArgsList.size()) {
                        selection = selection + "?)";
                    } else {
                        selection = selection + "?,";
                    }
                    selectionArgsList.add(selectionInArgs);
                }
            }
        }

        if (null != selectionArgsList && null != selection && selectionArgsList.size() > 0) {
            selectionArgs = new String[selectionArgsList.size()];
            selectionArgsList.toArray(selectionArgs);
        }

        String queryArg = null;
        Map<QueryParam, String> queryParams = (Map<QueryParam, String>) serviceParamMap.get
                (ServiceParam.QUERY_ARGS);
        if (null != queryParams && queryParams.size() > 0) {
            for (QueryParam param : queryParams.keySet()) {
                if (param.equals(QueryParam.MONTH_YEAR)) {
                    queryArg = "month/" + queryParams.get(param);
                } else if (param.equals(QueryParam.ROOM_ID)) {
                    queryArg = "room/" + queryParams.get(param);
                }
            }
        }

        if (null != queryArg) {
            statUri = Uri.withAppendedPath(RoomStatsProvider.CONTENT_URI, queryArg);
        } else {
            statUri = RoomStatsProvider.CONTENT_URI;
        }
        if (null != serviceParamMap.get(ServiceParam.MODEL)) {
            RoomStats roomStat = (RoomStats) serviceParamMap.get(ServiceParam.MODEL);

            values = new ContentValues();
            values.put(RoomiesContract.RoomStats.STATS_ROOM_ID, roomStat.getRoomId());
            values.put(RoomiesContract.RoomStats.STATS_MONTH_YEAR, roomStat.getMonthYear());
            values.put(RoomiesContract.RoomStats.STATS_RENT_MARGIN, roomStat.getRentMargin());
            values.put(RoomiesContract.RoomStats.STATS_MAID_MARGIN, roomStat.getMaidMargin());
            values.put(RoomiesContract.RoomStats.STATS_ELECTRICITY_MARGIN,
                    roomStat.getElectricityMargin());
            values.put(RoomiesContract.RoomStats.STATS_MISCELLANEOUS_MARGIN,
                    roomStat.getMiscellaneousMargin());
            values.put(RoomiesContract.RoomStats.STATS_RENT_SPENT, roomStat.getRentSpent());
            values.put(RoomiesContract.RoomStats.STATS_MAID_SPENT, roomStat.getMaidSpent());
            values.put(RoomiesContract.RoomStats.STATS_ELECTRICITY_SPENT,
                    roomStat.getElectricitySpent());
            values.put(RoomiesContract.RoomStats.STATS_MISCELLANEOUS_SPENT,
                    roomStat.getMiscellaneousSpent());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mem. Torrey bot. Club 12: 157 (1906)

#### Original name
Hydnum concrescens Pers., 1796

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements. See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership. The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied. See the License for the
 specific language governing permissions and limitations
 under the License.
-->
   <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wsrm="http://schemas.xmlsoap.org/ws/2005/02/rm" xmlns:wsa="http://www.w3.org/2005/08/addressing">
      <soapenv:Header>
         <wsa:MessageID soapenv:mustUnderstand="1">uuid:8d8f8d80-1624-11da-a28e-b3b9c4e71445</wsa:MessageID>
         <wsa:To soapenv:mustUnderstand="1">http://127.0.0.1:9070/axis/services/RMService</wsa:To>
         <wsa:Action soapenv:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/rm/AckRequested</wsa:Action>
         <wsa:From soapenv:mustUnderstand="1">
            <wsa:Address>http://localhost:8070/axis/services/TestService</wsa:Address>
         </wsa:From>
         <wsrm:AckRequested soapenv:mustUnderstand="1">
            <wsrm:Identifier>uuid:897ee740-1624-11da-a28e-b3b9c4e71445</wsrm:Identifier>
         </wsrm:AckRequested>
      </soapenv:Header>
      <soapenv:Body/>
   </soapenv:Envelope>


text:
describe('GOVUK.hideDepartmentChildren', function () {
  var departments

  beforeEach(function () {
    departments = $(
      '
' +
        '
' +
          '
' +
            '
child content
' +
          '
' +
        '
' +
      '
'
    )
    $(document.body).append(departments)

    this.oldWindowHash = window.location.hash
    window.location.hash = '#department-name'
  })

  afterEach(function () {
    window.location.hash = this.oldWindowHash
    departments.remove()
  })

  it('should create toggle link before department list', function () {
    GOVUK.hideDepartmentChildren.init()
    expect(departments.find('.view-all').length).toEqual(1)
  })

  it('should toggle class when clicking view all link', function () {
    GOVUK.hideDepartmentChildren.init()

    expect(departments.find('.department').hasClass('js-hiding-children')).toBeTrue()
    departments.find('.view-all').click()
    expect(departments.find('.department').hasClass('js-hiding-children')).toBeFalse()
  })

  it('should not toggle class of department with id in window hash', function () {
    departments.find('.organisations-box').append('')

    GOVUK.hideDepartmentChildren.init()

    expect(departments.find('.department').hasClass('js-hiding-children')).toBeFalse()
  })
})


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function getSymbolIterator() {
    if (typeof Symbol !== 'function' || !Symbol.iterator) {
        return '@@iterator';
    }
    return Symbol.iterator;
}
exports.getSymbolIterator = getSymbolIterator;
exports.iterator = getSymbolIterator();
exports.$$iterator = exports.iterator;
//# sourceMappingURL=iterator.js.map


text:
import song = require("../../Song");
import jsonScrap = require("./JsonScraper");

import winston = require("winston");

export class FluxFmScraper extends jsonScrap.JsonScraper {

	constructor(name:string) {
		super(name);
	}

	getUrl(scraperParam?:string): string {
		return "http://www.fluxfm.de/fluxfm-playlist/api.php?act=list&cuttime=1&limit=1&loc=berlin";
	}

	extractNowPlayingSong(jsonData:any): song.Song {
		return {
			Artist: jsonData.tracks[0].artist.trim(),
			Track: jsonData.tracks[0].title.trim()
		};
	}
}


text:
module PreferredUrl
  VERSION = "0.2.2"
end


text:
import boto
import datetime
import uuid
import json

import os
import errno
import sys

class LocalDataIngestSink:
  """Output data to Local filesystem"""

  def __init__(self, config):
    self.config = config

    path = self.config['path']

    now = datetime.datetime.utcnow().isoformat()

    unique = str(uuid.uuid4())

    self.folder = path + '/' + now + '-' + unique

    try:
        os.makedirs(self.folder)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

    print '[Local] Writing to folder ' + self.folder

  def write(self, source):

    self.record_index = 0
    self.file_index = 0

    if 'batch_size' in self.config:
      self.batch_size = int(self.config['batch_size'])
    else:
      self.batch_size = 50

    self.batch = [ ]

    for item in source:
      self.record_index = self.record_index + 1
      self.batch.append(item)
      sys.stdout.write('.') # write a record indicator to stdout
      sys.stdout.flush()

      if self.record_index >= self.batch_size:
        self.flush()

    self.flush()

  def flush(self):

    filename = str(self.file_index).zfill(7)

    file_path = self.folder + '/' + filename
    with open(file_path, 'w') as output_file:
      output_file.write(json.dumps(self.batch))

    self.file_index = self.file_index + 1

    self.batch = [ ]
    self.record_index = 0

    print('|') # Write a batch separator with a newline to stdout


text:
"""Invenio Circulation base transitions."""

import copy
from datetime import datetime

import arrow
from flask import current_app, has_request_context
from invenio_db import db

from ..api import Loan, is_item_available_for_checkout
from ..errors import DocumentDoNotMatchError, DocumentNotAvailableError, \
    InvalidLoanStateError, InvalidPermissionError, ItemNotAvailableError, \
    MissingRequiredParameterError, TransitionConditionsFailedError, \
    TransitionConstraintsViolationError
from ..proxies import current_circulation
from ..signals import loan_state_changed
from ..utils import str2datetime

def ensure_same_patron(f):
    """Validate that the patron PID exists and cannot be changed."""
    def inner(self, loan, **kwargs):
        new_patron_pid = kwargs.get("patron_pid")

        if not current_app.config["CIRCULATION_PATRON_EXISTS"](new_patron_pid):
            msg = "Patron '{0}' not found in the system".format(new_patron_pid)
            raise TransitionConstraintsViolationError(description=msg)

        if loan.get("patron_pid") and new_patron_pid != loan["patron_pid"]:
            msg = (
                "Cannot change patron to '{}' while performing an action "
                "on this loan".format(new_patron_pid)
            )
            raise TransitionConstraintsViolationError(description=msg)

        return f(self, loan, **kwargs)
    return inner

def ensure_same_document(f):
    """Validate that the document PID exists and cannot be changed."""
    def inner(self, loan, **kwargs):
        new_doc_pid = kwargs.get("document_pid")

        if not current_app.config["CIRCULATION_DOCUMENT_EXISTS"](new_doc_pid):
            msg = "Document '{0}' not found in the system".format(new_doc_pid)
            raise DocumentNotAvailableError(description=msg)

        if loan.get("document_pid") and new_doc_pid != loan["document_pid"]:
            msg = (
                "Cannot change document to '{}' while performing an action "
                "on this loan".format(new_doc_pid)
            )
            raise DocumentDoNotMatchError(description=msg)

        return f(self, loan, **kwargs)
    return inner

def ensure_required_params(f):
    """Decorator to ensure that all required parameters has been passed."""
    def inner(self, loan, **kwargs):
        missing = [p for p in self.REQUIRED_PARAMS if p not in kwargs]
        if missing:
            msg = "Required input parameters are missing '[{}]'".format(
                missing
            )
            raise MissingRequiredParameterError(description=msg)
        if all(param not in kwargs for param in self.PARTIAL_REQUIRED_PARAMS):
            msg = "One of the required parameters '[{}]' is missing.".format(
                self.PARTIAL_REQUIRED_PARAMS
            )
            raise MissingRequiredParameterError(description=msg)
        return f(self, loan, **kwargs)
    return inner

def has_permission(f):
    """Decorator to check the transition should be manually triggered."""
    def inner(self, loan, **kwargs):
        if not has_request_context():
            # no request context: a transition can be triggered via CLI
            return f(self, loan, **kwargs)

        if self.permission_factory and not self.permission_factory(loan).can():
            raise InvalidPermissionError(
                permission=self.permission_factory(loan)
            )
        return f(self, loan, **kwargs)
    return inner

def check_trigger(f):
    """Decorator to check the transition should be manually triggered."""
    def inner(self, loan, **kwargs):
        if kwargs.get("trigger", "next") != self.trigger:
            msg = "The transition with trigger '{}' does not exist."
            raise TransitionConditionsFailedError(
                description=msg.format(self.trigger)
            )
        return f(self, loan, **kwargs)
    return inner

class Transition(object):
    """A transition object that is triggered on conditions."""

    REQUIRED_PARAMS = [
        "transaction_user_pid",
        "patron_pid",
        "transaction_location_pid",
    ]

    PARTIAL_REQUIRED_PARAMS = ["item_pid", "document_pid"]

    def __init__(
        self, src, dest, trigger="next", permission_factory=None, **kwargs
    ):
        """Init transition object."""
        self.src = src
        self.dest = dest
        self.trigger = trigger
        default_perm = current_app.config[
            "CIRCULATION_LOAN_TRANSITIONS_DEFAULT_PERMISSION_FACTORY"
        ]
        self.permission_factory = permission_factory or default_perm
        self.validate_transition_states()

    def _check_item_before_availability(self, loan):
        """Common check on item before availability check."""
        if "item_pid" not in loan:
            msg = "Item not set for loan #'{}'".format(loan["pid"])
            raise TransitionConstraintsViolationError(description=msg)

        if not current_app.config["CIRCULATION_ITEM_EXISTS"](loan["item_pid"]):
            raise ItemNotAvailableError(
                item_pid=loan["item_pid"], transition=self.dest
            )

    def ensure_item_is_available_for_checkout(self, loan):
        """Validate that an item is available."""
        self._check_item_before_availability(loan)

        if not is_item_available_for_checkout(loan["item_pid"]):
            raise ItemNotAvailableError(
                item_pid=loan["item_pid"], transition=self.dest
            )

    def validate_transition_states(self):
        """Ensure that source and destination states are valid."""
        states = current_app.config["CIRCULATION_LOAN_TRANSITIONS"].keys()
        if not all([self.src in states, self.dest in states]):
            msg = "Source state '{0}' or destination state '{1}' " \
                  "not in [{2}]".format(self.src, self.dest, states)
            raise InvalidLoanStateError(description=msg)

    def _date_fields2datetime(self, kwargs):
        """Convert any extra kwargs string date to Python datetime."""
        for field in Loan.DATE_FIELDS + Loan.DATETIME_FIELDS:
            if field in kwargs:
                if type(kwargs[field]) is not datetime:
                    kwargs[field] = str2datetime(kwargs[field])

    def before(self, loan, initial_loan, transition_kwargs=None, **kwargs):
        """Validate input, evaluate conditions and raise if failed."""
        loan.update(kwargs)
        loan.setdefault("transaction_date", arrow.utcnow())

    @check_trigger
    @has_permission
    @ensure_required_params
    @ensure_same_document
    @ensure_same_patron
    def execute(self, loan, transition_kwargs=None, **kwargs):
        """Execute before actions, transition and after actions."""
        self._date_fields2datetime(kwargs)
        loan.date_fields2datetime()

        initial_loan = copy.deepcopy(loan)

        self.before(loan, initial_loan, transition_kwargs=transition_kwargs,
                    **kwargs)
        loan["state"] = self.dest
        self.after(loan, initial_loan, transition_kwargs=transition_kwargs,
                   **kwargs)

    def after(self, loan, initial_loan, transition_kwargs=None, **kwargs):
        """Commit record and index."""
        transition_kwargs = transition_kwargs or {}

        initial_loan.date_fields2str()
        loan.date_fields2str()

        loan.commit()
        db.session.commit()

        current_circulation.loan_indexer().index(loan)

        loan_state_changed.send(
            self,
            initial_loan=initial_loan,
            loan=loan,
            trigger=self.trigger,
            **transition_kwargs,
        )


text:
package proxy;

import java.util.Map;

import conversation.MessageResponse;

public class VoiceProxyUtilities {

    public VoiceProxyUtilities() {
    }

    /**
     * Determine if the action signal exists within the response
     */
    public boolean checkWCSActionSignal(MessageResponse response, String signal) {
        if (response.getOutput() != null) {
            if (response.getOutput().containsKey("action")) {
                String action = (String) response.getOutput().get("action");
                if (action.contains(signal)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Determine if the input contains the hangup signal
     */
    public boolean checkVGWHangUp(MessageResponse response) {
        if (response.getInput() != null) {
            if (response.getInput().containsKey("text")) {
                if (response.getInput().get("text") == "vgwHangUp") {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Remove all actions from the response output
     */
    public MessageResponse removeWCSActionSignal(MessageResponse response) {
        Map<String, Object> output = response.getOutput();
        if (output != null) {
            if (output.containsKey("action")) {
                output.remove("action");
                response.setOutput(output);
            }
        }

        return response;
    }
}


text:
See the [Project Charter](PROJECT_CHARTER.md)

- [x] Review Scope of Work/Work Order
- [x] Schedule and meet with BizDev to review contract and invoicing
- [x] Receive project objective(s)/permission to proceed from Devis Corporate
- [x] Record initial [project charter](PROJECT_CHARTER.md)

## Bring team members together
- [x] [Identify team members](PROJECT_CHARTER.md#team-roles), particularly key personnel from proposal
- [x] Bring the team members together to bring them up to speed/same starting point on project.
- [x] Conduct Internal Project Kickoff meeting
- [x] Identify project roles: BA, QA, Product Owner/proxy, ScrumMaster, other roles as project needs
- [x] Appoint Product Owner (Alan) responsible for project success. See [Team Roles](PROJECT_CHARTER.md#team-roles)

## Establish Standard Project Management Plan
- [x] Create X drive folders for sensitive project documents
- [x] Create Project Confluence Page
- [x] Create Project Plan
- [x] Develop [Risk Management Plan](RISK_MANAGEMENT.md)
- [x] Add Project and Staff Plan into Resource Spreadsheet

## Develop Communications

See the [Communications Plan](COMMUNICATIONS_PLAN.md)

- [x] Identify Stakeholders
- [x] Create Project [Communication plan](COMMUNICATIONS_PLAN.md)
- [x] Establish Scrum time
- [x] Create HipChat Room

## Develop project schedule
- [x] Determine [Release Schedule](README.md#release-planningiteration-planning)
- [x] Create project schedule
- [x] Review/communicate schedule with team

## Develop Project Environment
- [x] Identify [development stack](README.md#technical-approach) (Grails, Wordpress, node.js, Python, etc..)
- [x] Review high level architecture
- Setup production tools/environment
 - [x] Create Github repository
 - [x] Back-end stack software
 - [x] Waffle.io
 - [x] Coveralls
 - [x] CircleCI
 - [x] Datadog
- [x] Development environment established


text:
package io.clickhandler.web.router;

import javax.inject.Inject;

/**
 *
 */
public class RootRoute extends SimpleRouteProxy {
    @Inject
    public RootRoute() {
        super("/");
    }
}


text:
using UnityEngine;
using System.Collections;

namespace Plefnuts.ItemSystem
{
	public class ISObjectDatabase : ScriptableObjectDatabase<ISObject> {}
}


text:
<?php

namespace ClientFavorite\Mapper\Factory;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Stdlib\Hydrator\Aggregate\AggregateHydrator;
use ClientFavorite\Mapper\FavoriteMapper;
use ClientFavorite\Hydrator\FavoriteHydrator;
use ClientFavorite\Entity\FavoriteEntity;

/**
 *
 * @author jaimie <pacificnm@gmail.com>
 * @version 2.5.0
 *
 */
class FavoriteMapperFactory
{

    /**
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return \ClientFavorite\Mapper\FavoriteMapper
     */
    public function __invoke(ServiceLocatorInterface $serviceLocator)
    {
        $hydrator = new AggregateHydrator();

        $hydrator->add(new FavoriteHydrator());

        $prototype = new FavoriteEntity();

        $readAdapter = $serviceLocator->get('db1');

        $writeAdapter = $serviceLocator->get('db2');

        return new FavoriteMapper($readAdapter, $writeAdapter, $hydrator, $prototype);
    }
}


text:
layout: post
title: Jack Sparrow feat. by Michael Bolton
date: 2011-08-25 22:11
author: netravnen
comments: true
categories: [Michael Bolton, Random, The Lonely Island]
---
https://youtu.be/GI6CfKcMhjY


text:
namespace cc {

// static
scoped_ptr<VideoLayerImpl> VideoLayerImpl::Create(
    LayerTreeImpl* tree_impl,
    int id,
    VideoFrameProvider* provider) {
  scoped_ptr<VideoLayerImpl> layer(new VideoLayerImpl(tree_impl, id));
  layer->SetProviderClientImpl(VideoFrameProviderClientImpl::Create(provider));
  DCHECK(tree_impl->proxy()->IsImplThread());
  DCHECK(tree_impl->proxy()->IsMainThreadBlocked());
  return layer.Pass();
}

VideoLayerImpl::VideoLayerImpl(LayerTreeImpl* tree_impl, int id)
    : LayerImpl(tree_impl, id),
      frame_(NULL) {}

VideoLayerImpl::~VideoLayerImpl() {
  if (!provider_client_impl_->Stopped()) {
    // In impl side painting, we may have a pending and active layer
    // associated with the video provider at the same time. Both have a ref
    // on the VideoFrameProviderClientImpl, but we stop when the first
    // LayerImpl (the one on the pending tree) is destroyed since we know
    // the main thread is blocked for this commit.
    DCHECK(layer_tree_impl()->proxy()->IsImplThread());
    DCHECK(layer_tree_impl()->proxy()->IsMainThreadBlocked());
    provider_client_impl_->Stop();
  }
}

scoped_ptr<LayerImpl> VideoLayerImpl::CreateLayerImpl(
    LayerTreeImpl* tree_impl) {
  return scoped_ptr<LayerImpl>(new VideoLayerImpl(tree_impl, id()));
}

void VideoLayerImpl::PushPropertiesTo(LayerImpl* layer) {
  LayerImpl::PushPropertiesTo(layer);

  VideoLayerImpl* other = static_cast<VideoLayerImpl*>(layer);
  other->SetProviderClientImpl(provider_client_impl_);
}

void VideoLayerImpl::DidBecomeActive() {
  provider_client_impl_->set_active_video_layer(this);
}

bool VideoLayerImpl::WillDraw(DrawMode draw_mode,
                              ResourceProvider* resource_provider) {
  if (draw_mode == DRAW_MODE_RESOURCELESS_SOFTWARE)
    return false;

  // Explicitly acquire and release the provider mutex so it can be held from
  // WillDraw to DidDraw. Since the compositor thread is in the middle of
  // drawing, the layer will not be destroyed before DidDraw is called.
  // Therefore, the only thing that will prevent this lock from being released
  // is the GPU process locking it. As the GPU process can't cause the
  // destruction of the provider (calling StopUsingProvider), holding this
  // lock should not cause a deadlock.
  frame_ = provider_client_impl_->AcquireLockAndCurrentFrame();

  if (!frame_.get()) {
    // Drop any resources used by the updater if there is no frame to display.
    updater_.reset();

    provider_client_impl_->ReleaseLock();
    return false;
  }

  if (!LayerImpl::WillDraw(draw_mode, resource_provider))
    return false;

  if (!updater_)
    updater_.reset(new VideoResourceUpdater(resource_provider));

  VideoFrameExternalResources external_resources =
      updater_->CreateExternalResourcesFromVideoFrame(frame_);
  frame_resource_type_ = external_resources.type;

  if (external_resources.type ==
      VideoFrameExternalResources::SOFTWARE_RESOURCE) {
    software_resources_ = external_resources.software_resources;
    software_release_callback_ =
        external_resources.software_release_callback;
    return true;
  }

  for (size_t i = 0; i < external_resources.mailboxes.size(); ++i) {
    frame_resources_.push_back(
        resource_provider->CreateResourceFromTextureMailbox(
            external_resources.mailboxes[i]));
  }

  return true;
}

void VideoLayerImpl::AppendQuads(QuadSink* quad_sink,
                                 AppendQuadsData* append_quads_data) {
  DCHECK(frame_.get());

  SharedQuadState* shared_quad_state =
      quad_sink->UseSharedQuadState(CreateSharedQuadState());
  AppendDebugBorderQuad(quad_sink, shared_quad_state, append_quads_data);

  gfx::Rect quad_rect(content_bounds());
  gfx::Rect opaque_rect(contents_opaque() ? quad_rect : gfx::Rect());
  gfx::Rect visible_rect = frame_->visible_rect();
  gfx::Size coded_size = frame_->coded_size();

  // Pixels for macroblocked formats.
  float tex_width_scale =
      static_cast<float>(visible_rect.width()) / coded_size.width();
  float tex_height_scale =
      static_cast<float>(visible_rect.height()) / coded_size.height();

  switch (frame_resource_type_) {
    // TODO(danakj): Remove this, hide it in the hardware path.
    case VideoFrameExternalResources::SOFTWARE_RESOURCE: {
      DCHECK_EQ(frame_resources_.size(), 0u);
      DCHECK_EQ(software_resources_.size(), 1u);
      if (software_resources_.size() < 1u)
        break;
      bool premultiplied_alpha = true;
      gfx::PointF uv_top_left(0.f, 0.f);
      gfx::PointF uv_bottom_right(tex_width_scale, tex_height_scale);
      float opacity[] = {1.0f, 1.0f, 1.0f, 1.0f};
      bool flipped = false;
      scoped_ptr<TextureDrawQuad> texture_quad = TextureDrawQuad::Create();
      texture_quad->SetNew(shared_quad_state,
                           quad_rect,
                           opaque_rect,
                           software_resources_[0],
                           premultiplied_alpha,
                           uv_top_left,
                           uv_bottom_right,
                           SK_ColorTRANSPARENT,
                           opacity,
                           flipped);
      quad_sink->Append(texture_quad.PassAs<DrawQuad>(), append_quads_data);
      break;
    }
    case VideoFrameExternalResources::YUV_RESOURCE: {
      DCHECK_GE(frame_resources_.size(), 3u);
      if (frame_resources_.size() < 3u)
        break;
      gfx::SizeF tex_scale(tex_width_scale, tex_height_scale);
      scoped_ptr<YUVVideoDrawQuad> yuv_video_quad = YUVVideoDrawQuad::Create();
      yuv_video_quad->SetNew(shared_quad_state,
                             quad_rect,
                             opaque_rect,
                             tex_scale,
                             frame_resources_[0],
                             frame_resources_[1],
                             frame_resources_[2],
                             frame_resources_.size() > 3 ?
                                 frame_resources_[3] : 0);
      quad_sink->Append(yuv_video_quad.PassAs<DrawQuad>(), append_quads_data);
      break;
    }
    case VideoFrameExternalResources::RGB_RESOURCE: {
      DCHECK_EQ(frame_resources_.size(), 1u);
      if (frame_resources_.size() < 1u)
        break;
      bool premultiplied_alpha = true;
      gfx::PointF uv_top_left(0.f, 0.f);
      gfx::PointF uv_bottom_right(tex_width_scale, tex_height_scale);
      float opacity[] = {1.0f, 1.0f, 1.0f, 1.0f};
      bool flipped = false;
      scoped_ptr<TextureDrawQuad> texture_quad = TextureDrawQuad::Create();
      texture_quad->SetNew(shared_quad_state,
                           quad_rect,
                           opaque_rect,
                           frame_resources_[0],
                           premultiplied_alpha,
                           uv_top_left,
                           uv_bottom_right,
                           SK_ColorTRANSPARENT,
                           opacity,
                           flipped);
      quad_sink->Append(texture_quad.PassAs<DrawQuad>(), append_quads_data);
      break;
    }
    case VideoFrameExternalResources::STREAM_TEXTURE_RESOURCE: {
      DCHECK_EQ(frame_resources_.size(), 1u);
      if (frame_resources_.size() < 1u)
        break;
      gfx::Transform transform(
          provider_client_impl_->stream_texture_matrix());
      transform.Scale(tex_width_scale, tex_height_scale);
      scoped_ptr<StreamVideoDrawQuad> stream_video_quad =
          StreamVideoDrawQuad::Create();
      stream_video_quad->SetNew(shared_quad_state,
                                quad_rect,
                                opaque_rect,
                                frame_resources_[0],
                                transform);
      quad_sink->Append(stream_video_quad.PassAs<DrawQuad>(),
                        append_quads_data);
      break;
    }
    case VideoFrameExternalResources::IO_SURFACE: {
      DCHECK_EQ(frame_resources_.size(), 1u);
      if (frame_resources_.size() < 1u)
        break;
      gfx::Size visible_size(visible_rect.width(), visible_rect.height());
      scoped_ptr<IOSurfaceDrawQuad> io_surface_quad =
          IOSurfaceDrawQuad::Create();
      io_surface_quad->SetNew(shared_quad_state,
                              quad_rect,
                              opaque_rect,
                              visible_size,
                              frame_resources_[0],
                              IOSurfaceDrawQuad::UNFLIPPED);
      quad_sink->Append(io_surface_quad.PassAs<DrawQuad>(),
                        append_quads_data);
      break;
    }
#if defined(GOOGLE_TV)
    // This block and other blocks wrapped around #if defined(GOOGLE_TV) is not
    // maintained by the general compositor team. Please contact the following
    // people instead:
    //
    // wonsik@chromium.org
    // ycheo@chromium.org
    case VideoFrameExternalResources::HOLE: {
      DCHECK_EQ(frame_resources_.size(), 0u);
      scoped_ptr<SolidColorDrawQuad> solid_color_draw_quad =
          SolidColorDrawQuad::Create();

      // Create a solid color quad with transparent black and force no
      // blending / no anti-aliasing.
      solid_color_draw_quad->SetAll(
          shared_quad_state, quad_rect, quad_rect, quad_rect, false,
          SK_ColorTRANSPARENT, true);
      quad_sink->Append(solid_color_draw_quad.PassAs<DrawQuad>(),
                        append_quads_data);
      break;
    }
#endif
    case VideoFrameExternalResources::NONE:
      NOTIMPLEMENTED();
      break;
  }
}

void VideoLayerImpl::DidDraw(ResourceProvider* resource_provider) {
  LayerImpl::DidDraw(resource_provider);

  DCHECK(frame_.get());

  if (frame_resource_type_ ==
      VideoFrameExternalResources::SOFTWARE_RESOURCE) {
    for (size_t i = 0; i < software_resources_.size(); ++i)
      software_release_callback_.Run(0, false);

    software_resources_.clear();
    software_release_callback_.Reset();
  } else {
    for (size_t i = 0; i < frame_resources_.size(); ++i)
      resource_provider->DeleteResource(frame_resources_[i]);
    frame_resources_.clear();
  }

  provider_client_impl_->PutCurrentFrame(frame_);
  frame_ = NULL;

  provider_client_impl_->ReleaseLock();
}

void VideoLayerImpl::DidLoseOutputSurface() {
  updater_.reset();
}

void VideoLayerImpl::SetNeedsRedraw() {
  set_update_rect(gfx::UnionRects(update_rect(), gfx::RectF(bounds())));
  layer_tree_impl()->SetNeedsRedraw();
}

void VideoLayerImpl::SetProviderClientImpl(
    scoped_refptr<VideoFrameProviderClientImpl> provider_client_impl) {
  provider_client_impl_ = provider_client_impl;
}

const char* VideoLayerImpl::LayerTypeAsString() const {
  return "cc::VideoLayerImpl";
}

}  // namespace cc


text:
package org.gradle.initialization;

import org.gradle.api.InvalidUserDataException;
import org.gradle.api.internal.project.ProjectIdentifier;
import org.gradle.api.internal.project.ProjectRegistry;

import java.io.File;
import java.util.List;

public class ProjectDirectoryProjectSpec extends AbstractProjectSpec {
    private final File dir;

    public ProjectDirectoryProjectSpec(File dir) {
        this.dir = dir;
    }

    @Override
    protected String formatNoMatchesMessage(String settings) {
        return String.format("Project directory '%s' is not part of the build defined by %s.", dir, settings);
    }

    @Override
    protected String formatMultipleMatchesMessage(Iterable<? extends ProjectIdentifier> matches) {
        return String.format("Multiple projects in this build have project directory '%s': %s", dir, matches);
    }

    @Override
    protected <T extends ProjectIdentifier> void select(ProjectRegistry<? extends T> candidates, List<? super T> matches) {
        for (T candidate : candidates.getAllProjects()) {
            if (candidate.getProjectDir().equals(dir)) {
                matches.add(candidate);
            }
        }
    }

    @Override
    protected void checkPreconditions(ProjectRegistry<?> registry) {
        if (!dir.exists()) {
            throw new InvalidUserDataException(String.format("Project directory '%s' does not exist.", dir));
        }
        if (!dir.isDirectory()) {
            throw new InvalidUserDataException(String.format("Project directory '%s' is not a directory.", dir));
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine;

namespace HoloToolkit.Sharing.Utilities
{
    /// <summary>
    /// Utility class that writes the sharing service log messages to the Unity Engine's console.
    /// </summary>
    public class ConsoleLogWriter : LogWriter
    {
        public bool ShowDetailedLogs = false;

        public override void WriteLogEntry(LogSeverity severity, string message)
        {
            switch (severity)
            {
                case LogSeverity.Warning:
                    Debug.LogWarning(message);
                    break;
                case LogSeverity.Error:
                    Debug.LogError(message);
                    break;
                case LogSeverity.Info:
                default:
                    if (ShowDetailedLogs)
                    {
                        Debug.Log(message);
                    }
                    break;
            }
        }
    }
}


text:
package sas

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

// Info is a nested struct in sas response
type Info struct {
	Status       string `json:"Status" xml:"Status"`
	EventName    string `json:"EventName" xml:"EventName"`
	Ds           int64  `json:"Ds" xml:"Ds"`
	InternetIp   string `json:"InternetIp" xml:"InternetIp"`
	ProcessPath  string `json:"ProcessPath" xml:"ProcessPath"`
	Ip           string `json:"Ip" xml:"Ip"`
	GmtEvent     int64  `json:"GmtEvent" xml:"GmtEvent"`
	Count        int64  `json:"Count" xml:"Count"`
	IntranetIp   string `json:"IntranetIp" xml:"IntranetIp"`
	ProcessName  string `json:"ProcessName" xml:"ProcessName"`
	Uuid         string `json:"Uuid" xml:"Uuid"`
	EventType    string `json:"EventType" xml:"EventType"`
	InstanceName string `json:"InstanceName" xml:"InstanceName"`
	EventStatus  string `json:"EventStatus" xml:"EventStatus"`
	Path         string `json:"Path" xml:"Path"`
	Solution     string `json:"Solution" xml:"Solution"`
	Level        string `json:"Level" xml:"Level"`
	Id           int64  `json:"Id" xml:"Id"`
}


text:
CREATE TABLE AM_SYSTEM_APPS (
  ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1),
  NAME VARCHAR(50) NOT NULL,
  CONSUMER_KEY VARCHAR(512) NOT NULL,
  CONSUMER_SECRET VARCHAR(512) NOT NULL,
  CREATED_TIME TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  UNIQUE (NAME),
  UNIQUE (CONSUMER_KEY),
  PRIMARY KEY (ID)
)
/

CREATE TABLE AM_API_CLIENT_CERTIFICATE (
  TENANT_ID INT NOT NULL,
  ALIAS VARCHAR(45) NOT NULL,
  API_ID INTEGER NOT NULL,
  CERTIFICATE BLOB NOT NULL,
  REMOVED SMALLINT NOT NULL DEFAULT 0,
  TIER_NAME VARCHAR (512),
  FOREIGN KEY (API_ID) REFERENCES AM_API (API_ID) ON DELETE CASCADE,
  PRIMARY KEY (ALIAS, TENANT_ID, REMOVED)
)
/

ALTER TABLE AM_POLICY_SUBSCRIPTION
  ADD MONETIZATION_PLAN VARCHAR(25) DEFAULT NULL
  ADD FIXED_RATE VARCHAR(15) DEFAULT NULL
  ADD BILLING_CYCLE VARCHAR(15) DEFAULT NULL
  ADD PRICE_PER_REQUEST VARCHAR(15) DEFAULT NULL
  ADD CURRENCY VARCHAR(15) DEFAULT NULL
/

CREATE TABLE AM_MONETIZATION_USAGE_PUBLISHER (
	ID VARCHAR(100) NOT NULL,
	STATE VARCHAR(50) NOT NULL,
	STATUS VARCHAR(50) NOT NULL,
	STARTED_TIME VARCHAR(50) NOT NULL,
	PUBLISHED_TIME VARCHAR(50) NOT NULL,
	PRIMARY KEY(ID)
)/

ALTER TABLE AM_API_COMMENTS
    ALTER COLUMN COMMENT_ID
    SET DATA TYPE VARCHAR(255) NOT NULL
/

ALTER TABLE AM_API_RATINGS
    ALTER COLUMN RATING_ID
    SET DATA TYPE VARCHAR(255) NOT NULL
/

CREATE TABLE IF NOT EXISTS AM_NOTIFICATION_SUBSCRIBER (
    UUID VARCHAR(255) NOT NULL,
    CATEGORY VARCHAR(255) NOT NULL,
    NOTIFICATION_METHOD VARCHAR(255) NOT NULL,
    SUBSCRIBER_ADDRESS VARCHAR(255) NOT NULL,
    PRIMARY KEY(UUID, SUBSCRIBER_ADDRESS)
)
/

ALTER TABLE AM_EXTERNAL_STORES
ADD LAST_UPDATED_TIME TIMESTAMP DEFAULT CURRENT_TIMESTAMP
/

ALTER TABLE AM_API
  ADD API_TYPE VARCHAR(10) NULL DEFAULT NULL
/

CREATE TABLE AM_API_PRODUCT_MAPPING (
  API_PRODUCT_MAPPING_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1),
  API_ID INTEGER,
  URL_MAPPING_ID INTEGER,
  FOREIGN KEY (API_ID) REFERENCES AM_API(API_ID) ON DELETE CASCADE,
  FOREIGN KEY (URL_MAPPING_ID) REFERENCES AM_API_URL_MAPPING(URL_MAPPING_ID) ON DELETE CASCADE,
  PRIMARY KEY(API_PRODUCT_MAPPING_ID)
)
/

CREATE TABLE AM_REVOKED_JWT (
  UUID VARCHAR(255) NOT NULL,
  SIGNATURE VARCHAR(2048) NOT NULL,
  EXPIRY_TIMESTAMP BIGINT NOT NULL,
  TENANT_ID INTEGER DEFAULT -1,
  TOKEN_TYPE VARCHAR(15) DEFAULT 'DEFAULT',
  TIME_CREATED TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (UUID)
)
/

-- UMA tables --
CREATE TABLE IDN_UMA_RESOURCE (
  ID                  INTEGER   NOT NULL,
  RESOURCE_ID         VARCHAR(255),
  RESOURCE_NAME       VARCHAR(255),
  TIME_CREATED        TIMESTAMP NOT NULL,
  RESOURCE_OWNER_NAME VARCHAR(255),
  CLIENT_ID           VARCHAR(255),
  TENANT_ID           INTEGER DEFAULT -1234,
  USER_DOMAIN         VARCHAR(50),
  PRIMARY KEY (ID)
)
/

CREATE SEQUENCE IDN_UMA_RESOURCE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE
/

CREATE TRIGGER IDN_UMA_RESOURCE_TRIG NO CASCADE
BEFORE INSERT
  ON IDN_UMA_RESOURCE
  REFERENCING NEW AS NEW
  FOR EACH ROW MODE DB2SQL
  BEGIN ATOMIC
    SET (NEW.ID) = (NEXTVAL FOR IDN_UMA_RESOURCE_SEQ);
  END
/

CREATE INDEX IDX_RID ON IDN_UMA_RESOURCE (RESOURCE_ID)
/

CREATE INDEX IDX_USER ON IDN_UMA_RESOURCE (RESOURCE_OWNER_NAME, USER_DOMAIN)
/

CREATE TABLE IDN_UMA_RESOURCE_META_DATA (
  ID                INTEGER NOT NULL,
  RESOURCE_IDENTITY INTEGER NOT NULL,
  PROPERTY_KEY      VARCHAR(40),
  PROPERTY_VALUE    VARCHAR(255),
  PRIMARY KEY (ID),
  FOREIGN KEY (RESOURCE_IDENTITY) REFERENCES IDN_UMA_RESOURCE (ID) ON DELETE CASCADE
)
/

CREATE SEQUENCE IDN_UMA_RESOURCE_META_DATA_SEQ START WITH 1 INCREMENT BY 1 NOCACHE
/

CREATE TRIGGER IDN_UMA_RESOURCE_META_DATA_TRIG NO CASCADE
BEFORE INSERT
  ON IDN_UMA_RESOURCE_META_DATA
  REFERENCING NEW AS NEW
  FOR EACH ROW MODE DB2SQL
  BEGIN ATOMIC
    SET (NEW.ID) = (NEXTVAL FOR IDN_UMA_RESOURCE_META_DATA_SEQ);
  END
/

CREATE TABLE IDN_UMA_RESOURCE_SCOPE (
  ID                INTEGER NOT NULL,
  RESOURCE_IDENTITY INTEGER NOT NULL,
  SCOPE_NAME        VARCHAR(255),
  PRIMARY KEY (ID),
  FOREIGN KEY (RESOURCE_IDENTITY) REFERENCES IDN_UMA_RESOURCE (ID) ON DELETE CASCADE
)
/

CREATE SEQUENCE IDN_UMA_RESOURCE_SCOPE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE
/

CREATE TRIGGER IDN_UMA_RESOURCE_SCOPE_TRIG  NO CASCADE
BEFORE INSERT
  ON IDN_UMA_RESOURCE_SCOPE
  REFERENCING NEW AS NEW
  FOR EACH ROW MODE DB2SQL
  BEGIN ATOMIC
    SET (NEW.ID) = (NEXTVAL FOR IDN_UMA_RESOURCE_SCOPE_SEQ);
  END
/

CREATE INDEX IDX_RS ON IDN_UMA_RESOURCE_SCOPE (SCOPE_NAME)
/

CREATE TABLE IDN_UMA_PERMISSION_TICKET (
  ID              INTEGER      NOT NULL,
  PT              VARCHAR(255) NOT NULL,
  TIME_CREATED    TIMESTAMP    NOT NULL,
  EXPIRY_TIME     TIMESTAMP    NOT NULL,
  TICKET_STATE    VARCHAR(25) DEFAULT 'ACTIVE',
  TENANT_ID       INTEGER     DEFAULT -1234,
  PRIMARY KEY (ID)
)
/

CREATE SEQUENCE IDN_UMA_PERMISSION_TICKET_SEQ START WITH 1 INCREMENT BY 1 NOCACHE
/

CREATE TRIGGER IDN_UMA_PERMISSION_TICKET_TRIG NO CASCADE
BEFORE INSERT
  ON IDN_UMA_PERMISSION_TICKET
  REFERENCING NEW AS NEW
  FOR EACH ROW MODE DB2SQL
  BEGIN ATOMIC
    SET (NEW.ID) = (NEXTVAL FOR IDN_UMA_PERMISSION_TICKET_SEQ);
  END
/

CREATE INDEX IDX_PT ON IDN_UMA_PERMISSION_TICKET (PT)
/

CREATE TABLE IDN_UMA_PT_RESOURCE (
  ID             INTEGER NOT NULL,
  PT_RESOURCE_ID INTEGER NOT NULL,
  PT_ID          INTEGER NOT NULL,
  PRIMARY KEY (ID),
  FOREIGN KEY (PT_ID) REFERENCES IDN_UMA_PERMISSION_TICKET (ID) ON DELETE CASCADE,
  FOREIGN KEY (PT_RESOURCE_ID) REFERENCES IDN_UMA_RESOURCE (ID) ON DELETE CASCADE
)
/

CREATE SEQUENCE IDN_UMA_PT_RESOURCE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE
/

CREATE TRIGGER IDN_UMA_PT_RESOURCE_TRIG NO CASCADE
BEFORE INSERT
  ON IDN_UMA_PT_RESOURCE
  REFERENCING NEW AS NEW
  FOR EACH ROW MODE DB2SQL
  BEGIN ATOMIC
    SET (NEW.ID) = (NEXTVAL FOR IDN_UMA_PT_RESOURCE_SEQ);
  END
/

CREATE TABLE IDN_UMA_PT_RESOURCE_SCOPE (
  ID             INTEGER NOT NULL,
  PT_RESOURCE_ID INTEGER NOT NULL,
  PT_SCOPE_ID    INTEGER NOT NULL,
  PRIMARY KEY (ID),
  FOREIGN KEY (PT_RESOURCE_ID) REFERENCES IDN_UMA_PT_RESOURCE (ID) ON DELETE CASCADE,
  FOREIGN KEY (PT_SCOPE_ID) REFERENCES IDN_UMA_RESOURCE_SCOPE (ID) ON DELETE CASCADE
)
/

CREATE SEQUENCE IDN_UMA_PT_RESOURCE_SCOPE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE
/

CREATE TRIGGER IDN_UMA_PT_RESOURCE_SCOPE_TRIG NO CASCADE
BEFORE INSERT
  ON IDN_UMA_PT_RESOURCE_SCOPE
  REFERENCING NEW AS NEW
  FOR EACH ROW MODE DB2SQL
  BEGIN ATOMIC
    SET (NEW.ID) = (NEXTVAL FOR IDN_UMA_PT_RESOURCE_SCOPE_SEQ);
  END
/


text:
package com.qxcmp.spider;

import com.qxcmp.core.init.QxcmpInitializer;
import com.qxcmp.spider.event.AdminSpiderFinishEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 蜘蛛执行器
 *

 * 负责在平台启动的时候加载所有蜘蛛配置,然后根据加载的蜘蛛配置启动蜘蛛组,并且在蜘蛛结束时记录到蜘蛛日志中
 *
 * @author aaric
 */
@Order(Ordered.LOWEST_PRECEDENCE - 2)
@Slf4j
@Component
@RequiredArgsConstructor
public class SpiderRunner implements QxcmpInitializer {

    private final ApplicationContext applicationContext;
    private final TaskExecutor taskExecutor;
    private final SpiderContextHolder spiderContextHolder;
    private final SpiderLogService spiderLogService;

    /**
     * 启动蜘蛛运行器
     *

     * 从{@link SpiderContextHolder}中加载注册的蜘蛛配置信息根据分组数量对每个组启动一个任务来执行该组中所有的蜘蛛
     */
    void start() {
        spiderContextHolder.getSpiderDefinitions().keySet().forEach(group -> taskExecutor.execute(() -> startGroup(group)));
    }

    /**
     * 循环执行一个蜘蛛组任务
     *

     * 会从{@link SpiderContextHolder} 中注册的蜘蛛元数据动态状态一个蜘蛛组队列,依次执行该蜘蛛组中的每一个蜘蛛
     *

     * 当蜘蛛组中所有任务执行完成以后,重新执行该组的所有蜘蛛,如果在这期间蜘蛛的顺序发生变化,需要等到下一轮任务启动
     *
     * @param group 要启动的蜘蛛组的名称
     */
    private void startGroup(String group) {

        /*
         * 执行一个组的任务
         * */
        FutureTask<String> groupTask = new FutureTask<>(() -> {

            List<SpiderDefinition> spiderDefinitionList = spiderContextHolder.getSpiderDefinitions().get(group).stream().filter(spiderDefinition -> !spiderDefinition.isDisabled()).sorted(Comparator.comparing(SpiderDefinition::getOrder)).collect(Collectors.toList());

            if (spiderDefinitionList.isEmpty()) {
                try {
                    TimeUnit.MINUTES.sleep(1);
                } catch (Exception ignored) {

                }
            } else {
                spiderDefinitionList.forEach(this::startSpider);
            }

            return group;
        });

        taskExecutor.execute(groupTask);

        try {
            /*
             * 当一个组的任务执行完以后,重新执行该组的任务
             * */
            String groupName = groupTask.get();
            startGroup(groupName);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据蜘蛛元数据启动同步一个蜘蛛任务
     *
     * @param spiderDefinition 蜘蛛元数据
     */
    @SuppressWarnings("unchecked")
    private void startSpider(SpiderDefinition spiderDefinition) {

        if (spiderDefinition.isDisabled()) {
            return;
        }

        try {
            SpiderPageProcessor spiderPageProcessor = applicationContext.getBean(spiderDefinition.getPageProcess());

            us.codecraft.webmagic.Spider spider = us.codecraft.webmagic.Spider.create(spiderPageProcessor).thread(spiderDefinition.getThread());

            spiderDefinition.getStartUrls().forEach(spider::addUrl);

            spiderDefinition.getPipelines().forEach(aClass -> {
                SpiderPipeline spiderPipeline = applicationContext.getBean(aClass);
                spider.addPipeline(spiderPipeline);
                spiderPageProcessor.getSpiderPipelines().add(spiderPipeline);
            });

            log.info("Start spider: [{}]:[{}]", spiderDefinition.getGroup(), spiderDefinition.getName());

            SpiderRuntime spiderRuntime = new SpiderRuntime(spiderDefinition.getGroup(), spiderDefinition.getName(), spider, spiderPageProcessor);
            spiderContextHolder.getSpiderRuntimeInfo().add(spiderRuntime);
            spider.run();
            spiderContextHolder.getSpiderRuntimeInfo().remove(spiderRuntime);
            spiderLogService.save(spiderPageProcessor);
            applicationContext.publishEvent(new AdminSpiderFinishEvent(spiderDefinition, spiderPageProcessor));
        } catch (NoSuchBeanDefinitionException e) {
            log.error("Start spider failed, cause: {}", e.getMessage());
        }
    }

    private void loadSpiderDefinition() {
        applicationContext.getBeansOfType(SpiderPageProcessor.class).forEach((s, spiderPageProcessor) -> {
            try {
                spiderContextHolder.register(spiderPageProcessor);
            } catch (Exception e) {
                log.error("Can't register spider definition for {}, cause: {}", spiderPageProcessor.getClass().getName(), e.getMessage());
            }
        });
    }

    @Override
    public void init() {
        loadSpiderDefinition();
        start();
    }
}


text:
namespace Yupi.Model.Domain
{
    using System;

    public class TrophiesLayout : DefaultImageLayout
    {
        #region Properties

        public virtual TString Description
        {
            get; set;
        }

        public virtual TString Enscription
        {
            get; set;
        }

        [Ignore]
        public override string Name
        {
            get {
                return "trophies";
            }
        }

        [Ignore]
        public override TString[] Texts
        {
            get {
                return new TString[] { Description, Enscription };
            }
        }

        #endregion Properties

        #region Constructors

        public TrophiesLayout()
        {
            this.Description = string.Empty;
            this.Enscription = string.Empty;
        }

        #endregion Constructors
    }
}


text:
require 'spec_helper'

describe Consul::Core::Service do
  describe 'class methods' do
    subject(:klass)    { described_class }

    describe '.new_from_consul_data' do
      before(:each) do
        @services = klass.new_from_consul_data(services_data)
      end

      context 'data is an array' do
        let(:services_data) { response_for :service, 'web' }

        it 'returns an array of services' do
          @services.each do |service|
            service.should be_a klass
          end
        end
      end

      # consul does some weird stuff with this endpoint
      # TODO: fix Consul::Core::Service to return full objects possibly
      context 'data is a hash' do
        let(:services_data) { response_for :service }

        it 'returns an array of half initialized services' do
          @services.each do |service|
            service.should be_a klass
          end
        end
      end
    end
  end
end


text:
title: What is a friend?
date: 2016-07-20
description: Exploring the mechanics of friendship
categories:
  - friends
image: https://source.unsplash.com/collection/375719/2000x1322?a=.png
author_staff_member: anna
---
Friendship is a relationship of mutual affection between people. Friendship is a stronger form of interpersonal bond than an association. Friendship has been studied in academic fields such as sociology, social psychology, anthropology, and philosophy. Various academic theories of friendship have been proposed, including social exchange theory, equity theory, relational dialectics, and attachment styles. A World Happiness Database study found that people with close friendships are happier.

![Checkmate](https://source.unsplash.com/random/1500x1000)

## Forms of friendship

Although there are many forms of friendship, some of which may vary from place to place, certain characteristics are present in many types of bond. Such characteristics include affection, sympathy, empathy, honesty, altruism, mutual understanding, and compassion, enjoyment of each other's company, trust, and the ability to be oneself, express one's feelings, and make mistakes without fear of judgment from the friend.

While there is no practical limit on what types of people can form a friendship, friends tend to share common backgrounds, occupations, or interests and have similar demographics.

![Raspberries](https://source.unsplash.com/random/1500x1001)


text:
#include "spi.h"

/* Function to send user provided buffer to ST95HF through SPI */
int st95hf_spi_send(struct st95hf_spi_context *spicontext,
		    unsigned char *buffertx,
		    int datalen,
		    enum req_type reqtype)
{
	struct spi_message m;
	int result = 0;
	struct spi_device *spidev = spicontext->spidev;
	struct spi_transfer tx_transfer = {
		.tx_buf = buffertx,
		.len = datalen,
	};

	mutex_lock(&spicontext->spi_lock);

	if (reqtype == SYNC) {
		spicontext->req_issync = true;
		reinit_completion(&spicontext->done);
	} else {
		spicontext->req_issync = false;
	}

	spi_message_init(&m);
	spi_message_add_tail(&tx_transfer, &m);

	result = spi_sync(spidev, &m);
	if (result) {
		dev_err(&spidev->dev, "error: sending cmd to st95hf using SPI = %d\n",
			result);
		mutex_unlock(&spicontext->spi_lock);
		return result;
	}

	/* return for asynchronous or no-wait case */
	if (reqtype == ASYNC) {
		mutex_unlock(&spicontext->spi_lock);
		return 0;
	}

	result = wait_for_completion_timeout(&spicontext->done,
					     msecs_to_jiffies(1000));
	/* check for timeout or success */
	if (!result) {
		dev_err(&spidev->dev, "error: response not ready timeout\n");
		result = -ETIMEDOUT;
	} else {
		result = 0;
	}

	mutex_unlock(&spicontext->spi_lock);

	return result;
}
EXPORT_SYMBOL_GPL(st95hf_spi_send);

/* Function to Receive command Response */
int st95hf_spi_recv_response(struct st95hf_spi_context *spicontext,
			     unsigned char *receivebuff)
{
	int len = 0;
	struct spi_transfer tx_takedata;
	struct spi_message m;
	struct spi_device *spidev = spicontext->spidev;
	unsigned char readdata_cmd = ST95HF_COMMAND_RECEIVE;
	struct spi_transfer t[2] = {
		{.tx_buf = &readdata_cmd, .len = 1,},
		{.rx_buf = receivebuff, .len = 2, .cs_change = 1,},
	};

	int ret = 0;

	memset(&tx_takedata, 0x0, sizeof(struct spi_transfer));

	mutex_lock(&spicontext->spi_lock);

	/* First spi transfer to know the length of valid data */
	spi_message_init(&m);
	spi_message_add_tail(&t[0], &m);
	spi_message_add_tail(&t[1], &m);

	ret = spi_sync(spidev, &m);
	if (ret) {
		dev_err(&spidev->dev, "spi_recv_resp, data length error = %d\n",
			ret);
		mutex_unlock(&spicontext->spi_lock);
		return ret;
	}

	/* As 2 bytes are already read */
	len = 2;

	/* Support of long frame */
	if (receivebuff[0] & 0x60)
		len += (((receivebuff[0] & 0x60) >> 5) << 8) | receivebuff[1];
	else
		len += receivebuff[1];

	/* Now make a transfer to read only relevant bytes */
	tx_takedata.rx_buf = &receivebuff[2];
	tx_takedata.len = len - 2;

	spi_message_init(&m);
	spi_message_add_tail(&tx_takedata, &m);

	ret = spi_sync(spidev, &m);

	mutex_unlock(&spicontext->spi_lock);
	if (ret) {
		dev_err(&spidev->dev, "spi_recv_resp, data read error = %d\n",
			ret);
		return ret;
	}

	return len;
}
EXPORT_SYMBOL_GPL(st95hf_spi_recv_response);

int st95hf_spi_recv_echo_res(struct st95hf_spi_context *spicontext,
			     unsigned char *receivebuff)
{
	unsigned char readdata_cmd = ST95HF_COMMAND_RECEIVE;
	struct spi_transfer t[2] = {
		{.tx_buf = &readdata_cmd, .len = 1,},
		{.rx_buf = receivebuff, .len = 1,},
	};
	struct spi_message m;
	struct spi_device *spidev = spicontext->spidev;
	int ret = 0;

	mutex_lock(&spicontext->spi_lock);

	spi_message_init(&m);
	spi_message_add_tail(&t[0], &m);
	spi_message_add_tail(&t[1], &m);
	ret = spi_sync(spidev, &m);

	mutex_unlock(&spicontext->spi_lock);

	if (ret)
		dev_err(&spidev->dev, "recv_echo_res, data read error = %d\n",
			ret);

	return ret;
}
EXPORT_SYMBOL_GPL(st95hf_spi_recv_echo_res);


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/aaa"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="提交"
        android:onClick="aaa"
        />

</LinearLayout>


text:
from django.conf import settings
from django.conf.urls.defaults import patterns, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

from .examples import urls

from funfactory.monkeypatches import patch
patch()

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Example:
    (r'', include(urls)),
    (r'^browserid/', include('django_browserid.urls')),

    # Generate a robots.txt
    (r'^robots\.txt$',
        lambda r: HttpResponse(
            "User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow' ,
            mimetype="text/plain"
        )
    ),

    # Uncomment the admin/doc line below to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
	(r'^admin/', include(admin.site.urls)),
)

## In DEBUG mode, serve media files through Django.
if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()


text:
package cloudstack

import (
	"fmt"
	"strings"
	"testing"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
	"github.com/xanzy/go-cloudstack/cloudstack"
)

func TestAccCloudStackPortForward_basic(t *testing.T) {
	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckCloudStackPortForwardDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccCloudStackPortForward_basic,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckCloudStackPortForwardsExist("cloudstack_port_forward.foo"),
					resource.TestCheckResourceAttr(
						"cloudstack_port_forward.foo", "ip_address_id", CLOUDSTACK_PUBLIC_IPADDRESS),
					resource.TestCheckResourceAttr(
						"cloudstack_port_forward.foo", "forward.#", "1"),
				),
			},
		},
	})
}

func TestAccCloudStackPortForward_update(t *testing.T) {
	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckCloudStackPortForwardDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccCloudStackPortForward_basic,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckCloudStackPortForwardsExist("cloudstack_port_forward.foo"),
					resource.TestCheckResourceAttr(
						"cloudstack_port_forward.foo", "ip_address_id", CLOUDSTACK_PUBLIC_IPADDRESS),
					resource.TestCheckResourceAttr(
						"cloudstack_port_forward.foo", "forward.#", "1"),
				),
			},

			resource.TestStep{
				Config: testAccCloudStackPortForward_update,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckCloudStackPortForwardsExist("cloudstack_port_forward.foo"),
					resource.TestCheckResourceAttr(
						"cloudstack_port_forward.foo", "ip_address_id", CLOUDSTACK_PUBLIC_IPADDRESS),
					resource.TestCheckResourceAttr(
						"cloudstack_port_forward.foo", "forward.#", "2"),
				),
			},
		},
	})
}

func testAccCheckCloudStackPortForwardsExist(n string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No port forward ID is set")
		}

		for k, id := range rs.Primary.Attributes {
			if !strings.Contains(k, "uuid") {
				continue
			}

			cs := testAccProvider.Meta().(*cloudstack.CloudStackClient)
			_, count, err := cs.Firewall.GetPortForwardingRuleByID(id)

			if err != nil {
				return err
			}

			if count == 0 {
				return fmt.Errorf("Port forward for %s not found", k)
			}
		}

		return nil
	}
}

func testAccCheckCloudStackPortForwardDestroy(s *terraform.State) error {
	cs := testAccProvider.Meta().(*cloudstack.CloudStackClient)

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "cloudstack_port_forward" {
			continue
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No port forward ID is set")
		}

		for k, id := range rs.Primary.Attributes {
			if !strings.Contains(k, "uuid") {
				continue
			}

			_, _, err := cs.Firewall.GetPortForwardingRuleByID(id)
			if err == nil {
				return fmt.Errorf("Port forward %s still exists", rs.Primary.ID)
			}
		}
	}

	return nil
}

var testAccCloudStackPortForward_basic = fmt.Sprintf(`
resource "cloudstack_instance" "foobar" {
  name = "terraform-test"
  service_offering= "%s"
  network = "%s"
  template = "%s"
  zone = "%s"
  expunge = true
}

resource "cloudstack_port_forward" "foo" {
  ip_address_id = "%s"

  forward {
    protocol = "tcp"
    private_port = 443
    public_port = 8443
    virtual_machine_id = "${cloudstack_instance.foobar.id}"
  }
}`,
	CLOUDSTACK_SERVICE_OFFERING_1,
	CLOUDSTACK_NETWORK_1,
	CLOUDSTACK_TEMPLATE,
	CLOUDSTACK_ZONE,
	CLOUDSTACK_PUBLIC_IPADDRESS)

var testAccCloudStackPortForward_update = fmt.Sprintf(`
resource "cloudstack_instance" "foobar" {
  name = "terraform-test"
  service_offering= "%s"
  network = "%s"
  template = "%s"
  zone = "%s"
  expunge = true
}

resource "cloudstack_port_forward" "foo" {
  ip_address_id = "%s"

  forward {
    protocol = "tcp"
    private_port = 443
    public_port = 8443
    virtual_machine_id = "${cloudstack_instance.foobar.id}"
  }

  forward {
    protocol = "tcp"
    private_port = 80
    public_port = 8080
    virtual_machine_id = "${cloudstack_instance.foobar.id}"
  }
}`,
	CLOUDSTACK_SERVICE_OFFERING_1,
	CLOUDSTACK_NETWORK_1,
	CLOUDSTACK_TEMPLATE,
	CLOUDSTACK_ZONE,
	CLOUDSTACK_PUBLIC_IPADDRESS)


text:
"use strict";

const crypto = require("crypto");
const asn1 = require("asn1.js");

module.exports = function dhparam(bits) {
  return asn1.define("", function() {
    this.seq().obj(this.key("p").int(), this.key("g").int());
  }).encode({
    p: crypto.createDiffieHellman(bits || 2048).getPrime(),
    g: 2
  }, "pem", {label: "DH PARAMETERS"});
};


text:
exception handler tests - 6
--FILE--
<?php

set_exception_handler("foo");
set_exception_handler("foo1");

restore_exception_handler();

function foo($e) {
	var_dump(__FUNCTION__."(): ".get_class($e)." thrown!");
}

function foo1($e) {
	var_dump(__FUNCTION__."(): ".get_class($e)." thrown!");
}

throw new excEption();

echo "Done\n";
?>
--EXPECTF--
string(24) "foo(): Exception thrown!"


text:
import React from 'react';
import EventItem from '../EventItem/EventItem';

export default function EventsList({events}) {
  const titleList = events.map( (element, index) => {
    return (
      <EventItem event={element} key={index}/>
    );
  });

  return (

{titleList}

  );
}

EventsList.propTypes = {
  events: React.PropTypes.array,
};


text:
package org.keycloak.dom.saml.v2.assertion;

import java.io.Serializable;

/**
 *

 * Java class for SubjectLocalityType complex type.
 *
 *

 * The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="SubjectLocalityType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <attribute name="Address" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       <attribute name="DNSName" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 */
public class SubjectLocalityType implements Serializable {

    protected String address;

    protected String dnsName;

    /**
     * Gets the value of the address property.
     *
     * @return possible object is {@link String }
     */
    public String getAddress() {
        return address;
    }

    /**
     * Sets the value of the address property.
     *
     * @param value allowed object is {@link String }
     */
    public void setAddress(String value) {
        this.address = value;
    }

    /**
     * Gets the value of the dnsName property.
     *
     * @return possible object is {@link String }
     */
    public String getDNSName() {
        return dnsName;
    }

    /**
     * Sets the value of the dnsName property.
     *
     * @param value allowed object is {@link String }
     */
    public void setDNSName(String value) {
        this.dnsName = value;
    }
}


text:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

/**
 *  An ersatz setsid command for those Unixes (e.g. Mac OS X) that
 *  don't have one.  Intended to work like (or enough like) the one
 *  from the util-linux-ng package that I can run the RabbitMQ test
 *  suite post summer 2011 on a Mac OS X dev machine.
 *
 *  Synopsis:
 *      setsid program [arg...]
 *
 *  Description:
 *      setsid runs a program in a new session.
 *
 *  See Also:
 *      setsid(2)
 *
 */
int
main(int argc, char *argv[])
{
    if( argc < 2 )
    {
        fprintf(stderr,
                "usage: %s program [arg ...]\n",
                (char *)argv[0]);
    }

    // Are we the leader of a process group (i.e. is our process id
    // equal to our process group id?)?
    if (getpgrp() == getpid())
    {

        switch(fork())
        {
            case 0:
                // We're in the child process...
                break;
            case -1:
                // We're in the parent process and child creation
                // failed, so squawk and exit with error code...
                perror("fork");
                exit(1);
            default:
                // We're in the parent process (setsid itself), child
                // creation was OK...
                exit(0);
        }
    }

    // Create a new session and make this setsid process the session
    // leader for the new session; This setsid process also becomes
    // the process group leader of a new process group and has no
    // controlling terminal...
    if (setsid() < 0)
    {
        perror("setsid");
        exit(1);
    }

    // Execute the requested command with the given arguments,
    // replacing our current process image (which now has its own
    // happy session and group) with a new process image...
    execvp(argv[1], argv + 1);

    // If we got to here, squawk and exit with an error code...
    perror("execvp");
    exit(1);
}


text:
/*jshint globalstrict:false, strict:false */
/* global assertTrue, assertEqual, assertMatch, arango, fail */

////////////////////////////////////////////////////////////////////////////////
/// @brief test for security-related server options
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB Inc, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2019, ArangoDB Inc, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

let jsunity = require('jsunity');
const _ = require('lodash');
const pu = require('@arangodb/testutils/process-utils');
const crypto = require('@arangodb/crypto');
const request = require("@arangodb/request");
const time = require("internal").time;
const db = require("internal").db;
const errors = require("internal").errors;

const {
  getCtrlCoordinators,
} = require('@arangodb/test-helper');

const cn = "UnitTestsCollection";

function testSuite() {
  let waitForAlive = function (timeout, baseurl, data) {
    let tries = 0, res;
    let all = Object.assign(data || {}, { method: "get", timeout: 1, url: baseurl + "/_api/version" });
    const end = time() + timeout;
    while (time() < end) {
      res = request(all);
      if (res.status === 200 || res.status === 401 || res.status === 403) {
        break;
      }
      console.warn("waiting for server response from url " + baseurl);
      require('internal').sleep(0.5);
    }
    return res.status;
  };

  let sendRequest = function (method, endpoint, body, headers) {
    const envelope = {
      json: true,
      method,
      url: endpoint,
      headers,
    };
    if (method !== 'GET') {
      envelope.body = body;
    }
    let res = request(envelope);

    if (typeof res.body === "string") {
      if (res.body === "") {
        res.body = {};
      } else {
        res.body = JSON.parse(res.body);
      }
    }
    return res;
  };

  return {
    setUp : function() {
      db._create(cn);
    },

    tearDown: function () {
      db._drop(cn);
    },

    testRestartCoordinatorsDuringTransaction : function() {
      let trx = db._createTransaction({
        collections: { write: cn }
      });

      let tc = trx.collection(cn);
      tc.insert({ _key: "test1" });

      let coordinators = getCtrlCoordinators();
      assertTrue(coordinators.length > 1);

      for (let i = 0; i < coordinators.length; ++i) {
        let coordinator = coordinators[i];
        coordinator.shutdownArangod(false);
        coordinator.waitForInstanceShutdown(30);
        coordinator.exitStatus = null;
        coordinator.pid = null;
        console.warn("Restarting coordinator...", coordinator.getStructure());

        coordinator.restartOneInstance({
          "server.authentication": "false"
        });

        waitForAlive(30, coordinator.url, {});
      }

      // connection to server was closed, so next request may fail.
      try {
        // issue a dummy request to the server. if that fails because of
        // a broken connection, we don't care.
        tc.count();
        // all following requests should be fine again
      } catch (err) {}

      // will fail, because the coordinator owning the
      // transaction got restarted
      try {
        tc.insert({ _key: "test2" });
        fail();
      } catch (err) {
        assertEqual(errors.ERROR_TRANSACTION_NOT_FOUND.code, err.errorNum);
      }

      // contact all coordinators - all the requests must fail everywhere
      for (let i = 0; i < coordinators.length; ++i) {
        let result = sendRequest('PUT', coordinators[i].url + "/_api/transaction/" + encodeURIComponent(trx._id), {}, {});
        assertEqual(errors.ERROR_TRANSACTION_NOT_FOUND.code, result.body.errorNum);
        assertMatch(/cannot find target server/, result.body.errorMessage);
      }

      // we should be able to start a new transaction, however
      trx = db._createTransaction({
        collections: { write: cn }
      });

      try {
        tc = trx.collection(cn);
        tc.insert({ _key: "test1" });

        assertEqual(1, tc.count());

        // contact all coordinators - all these requests must succeed
        for (let i = 0; i < coordinators.length; ++i) {
          let result = sendRequest('POST', coordinators[i].url + "/_api/document/" + encodeURIComponent(cn), { _key: "coord" + i }, { "x-arango-trx-id" : trx._id });
          assertEqual(202, result.status);
        }

        assertEqual(1 + coordinators.length, tc.count());
      } finally {
        trx.abort();
      }
    },

  };
}
jsunity.run(testSuite);
return jsunity.done();