text:
package org.apache.rya.indexing.pcj.fluo.app.query;

import static java.util.Objects.requireNonNull;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Map;

import org.apache.fluo.api.client.SnapshotBase;
import org.apache.fluo.api.client.TransactionBase;
import org.apache.fluo.api.data.Bytes;
import org.apache.fluo.api.data.Column;
import org.apache.rya.indexing.pcj.fluo.app.ConstructGraph;
import org.apache.rya.indexing.pcj.fluo.app.ConstructGraphSerializer;
import org.apache.rya.indexing.pcj.fluo.app.NodeType;
import org.apache.rya.indexing.pcj.fluo.app.query.AggregationMetadata.AggregationElement;
import org.apache.rya.indexing.pcj.fluo.app.query.JoinMetadata.JoinType;
import org.apache.rya.indexing.pcj.storage.accumulo.VariableOrder;

import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;

import edu.umd.cs.findbugs.annotations.DefaultAnnotation;
import edu.umd.cs.findbugs.annotations.NonNull;

/**
 * Reads and writes {@link FluoQuery} instances and their components to/from
 * a Fluo table.
 */
@DefaultAnnotation(NonNull.class)
public class FluoQueryMetadataDAO {

    /**
     * Write an instance of {@link QueryMetadata} to the Fluo table.
     *
     * @param tx - The transaction that will be used to commit the metadata. (not null)
     * @param metadata - The Query node metadata that will be written to the table. (not null)
     */
    public void write(final TransactionBase tx, final QueryMetadata metadata) {
        requireNonNull(tx);
        requireNonNull(metadata);

        final String rowId = metadata.getNodeId();
        tx.set(rowId, FluoQueryColumns.QUERY_NODE_ID, rowId);
        tx.set(rowId, FluoQueryColumns.QUERY_VARIABLE_ORDER, metadata.getVariableOrder().toString());
        tx.set(rowId, FluoQueryColumns.QUERY_SPARQL, metadata.getSparql() );
        tx.set(rowId, FluoQueryColumns.QUERY_CHILD_NODE_ID, metadata.getChildNodeId() );
    }

    /**
     * Read an instance of {@link QueryMetadata} from the Fluo table.
     *
     * @param sx - The snapshot that will be used to read the metadata . (not null)
     * @param nodeId - The nodeId of the Query node that will be read. (not nul)
     * @return The {@link QueryMetadata} that was read from the table.
     */
    public QueryMetadata readQueryMetadata(final SnapshotBase sx, final String nodeId) {
        return readQueryMetadataBuilder(sx, nodeId).build();
    }

    private QueryMetadata.Builder readQueryMetadataBuilder(final SnapshotBase sx, final String nodeId) {
        requireNonNull(sx);
        requireNonNull(nodeId);

        // Fetch the values from the Fluo table.
        final String rowId = nodeId;
        final Map<Column, String> values = sx.gets(rowId,
                FluoQueryColumns.QUERY_VARIABLE_ORDER,
                FluoQueryColumns.QUERY_SPARQL,
                FluoQueryColumns.QUERY_CHILD_NODE_ID);

        // Return an object holding them.
        final String varOrderString = values.get(FluoQueryColumns.QUERY_VARIABLE_ORDER);
        final VariableOrder varOrder = new VariableOrder(varOrderString);

        final String sparql = values.get(FluoQueryColumns.QUERY_SPARQL);
        final String childNodeId = values.get(FluoQueryColumns.QUERY_CHILD_NODE_ID);

        return QueryMetadata.builder(nodeId)
                .setVariableOrder( varOrder )
                .setSparql( sparql )
                .setChildNodeId( childNodeId );
    }

    /**
     * Write an instance of {@link ConstructQueryMetadata} to the Fluo table.
     *
     * @param tx - The transaction that will be used to commit the metadata. (not null)
     * @param metadata - The Construct Query node metadata that will be written to the table. (not null)
     */
    public void write(final TransactionBase tx, final ConstructQueryMetadata metadata) {
        requireNonNull(tx);
        requireNonNull(metadata);

        final String rowId = metadata.getNodeId();
        tx.set(rowId, FluoQueryColumns.CONSTRUCT_NODE_ID, rowId);
        tx.set(rowId, FluoQueryColumns.CONSTRUCT_VARIABLE_ORDER, metadata.getVariableOrder().toString());
        tx.set(rowId, FluoQueryColumns.CONSTRUCT_CHILD_NODE_ID, metadata.getChildNodeId() );
        tx.set(rowId, FluoQueryColumns.CONSTRUCT_SPARQL, metadata.getSparql());
        tx.set(rowId, FluoQueryColumns.CONSTRUCT_GRAPH, ConstructGraphSerializer.toConstructString(metadata.getConstructGraph()));
    }

    /**
     * Read an instance of {@link ConstructQueryMetadata} from the Fluo table.
     *
     * @param sx - The snapshot that will be used to read the metadata . (not null)
     * @param nodeId - The nodeId of the Construct Query node that will be read. (not null)
     * @return The {@link ConstructQueryMetadata} that was read from table.
     */
    public ConstructQueryMetadata readConstructQueryMetadata(final SnapshotBase sx, final String nodeId) {
        return readConstructQueryMetadataBuilder(sx, nodeId).build();
    }

    private ConstructQueryMetadata.Builder readConstructQueryMetadataBuilder(final SnapshotBase sx, final String nodeId) {
        requireNonNull(sx);
        requireNonNull(nodeId);

        // Fetch the values from the Fluo table.
        final String rowId = nodeId;
        final Map<Column, String> values = sx.gets(rowId,
                FluoQueryColumns.CONSTRUCT_GRAPH,
                FluoQueryColumns.CONSTRUCT_SPARQL,
                FluoQueryColumns.CONSTRUCT_CHILD_NODE_ID);

        final String graphString = values.get(FluoQueryColumns.CONSTRUCT_GRAPH);
        final ConstructGraph graph = ConstructGraphSerializer.toConstructGraph(graphString);
        final String childNodeId = values.get(FluoQueryColumns.CONSTRUCT_CHILD_NODE_ID);
        final String sparql = values.get(FluoQueryColumns.CONSTRUCT_SPARQL);

        return ConstructQueryMetadata.builder()
                .setNodeId(nodeId)
                .setConstructGraph(graph)
                .setSparql(sparql)
                .setChildNodeId(childNodeId);
    }

    /**
     * Write an instance of {@link FilterMetadata} to the Fluo table.
     *
     * @param tx - The transaction that will be used to commit the metadata. (not null)
     * @param metadata - The Filter node metadata that will be written to the table. (not null)
     */
    public void write(final TransactionBase tx, final FilterMetadata metadata) {
        requireNonNull(tx);
        requireNonNull(metadata);

        final String rowId = metadata.getNodeId();
        tx.set(rowId, FluoQueryColumns.FILTER_NODE_ID, rowId);
        tx.set(rowId, FluoQueryColumns.FILTER_VARIABLE_ORDER, metadata.getVariableOrder().toString());
        tx.set(rowId, FluoQueryColumns.FILTER_ORIGINAL_SPARQL, metadata.getOriginalSparql() );
        tx.set(rowId, FluoQueryColumns.FILTER_INDEX_WITHIN_SPARQL, metadata.getFilterIndexWithinSparql()+"" );
        tx.set(rowId, FluoQueryColumns.FILTER_PARENT_NODE_ID, metadata.getParentNodeId() );
        tx.set(rowId, FluoQueryColumns.FILTER_CHILD_NODE_ID, metadata.getChildNodeId() );
    }

    /**
     * Read an instance of {@link FilterMetadata} from the Fluo table.
     *
     * @param sx - The snapshot that will be used to read the metadata. (not null)
     * @param nodeId - The nodeId of the Filter node that will be read. (not nul)
     * @return The {@link FilterMetadata} that was read from the table.
     */
    public FilterMetadata readFilterMetadata(final SnapshotBase sx, final String nodeId) {
        return readFilterMetadataBuilder(sx, nodeId).build();
    }

    private FilterMetadata.Builder readFilterMetadataBuilder(final SnapshotBase sx, final String nodeId) {
        requireNonNull(sx);
        requireNonNull(nodeId);

        // Fetch the values from the Fluo table.
        final String rowId = nodeId;
        final Map<Column, String> values = sx.gets(rowId,
                FluoQueryColumns.FILTER_VARIABLE_ORDER,
                FluoQueryColumns.FILTER_ORIGINAL_SPARQL,
                FluoQueryColumns.FILTER_INDEX_WITHIN_SPARQL,
                FluoQueryColumns.FILTER_PARENT_NODE_ID,
                FluoQueryColumns.FILTER_CHILD_NODE_ID);

        // Return an object holding them.
        final String varOrderString = values.get(FluoQueryColumns.FILTER_VARIABLE_ORDER);
        final VariableOrder varOrder = new VariableOrder(varOrderString);

        final String originalSparql = values.get(FluoQueryColumns.FILTER_ORIGINAL_SPARQL);
        final int filterIndexWithinSparql = Integer.parseInt(values.get(FluoQueryColumns.FILTER_INDEX_WITHIN_SPARQL));
        final String parentNodeId = values.get(FluoQueryColumns.FILTER_PARENT_NODE_ID);
        final String childNodeId = values.get(FluoQueryColumns.FILTER_CHILD_NODE_ID);

        return FilterMetadata.builder(nodeId)
                .setVarOrder(varOrder)
                .setOriginalSparql(originalSparql)
                .setFilterIndexWithinSparql(filterIndexWithinSparql)
                .setParentNodeId(parentNodeId)
                .setChildNodeId(childNodeId);
    }

    /**
     * Write an instance of {@link JoinMetadata} to the Fluo table.
     *
     * @param tx - The transaction that will be used to commit the metadata. (not null)
     * @param metadata - The Join node metadata that will be written to the table. (not null)
     */
    public void write(final TransactionBase tx, final JoinMetadata metadata) {
        requireNonNull(tx);
        requireNonNull(metadata);

        final String rowId = metadata.getNodeId();
        tx.set(rowId, FluoQueryColumns.JOIN_NODE_ID, rowId);
        tx.set(rowId, FluoQueryColumns.JOIN_VARIABLE_ORDER, metadata.getVariableOrder().toString());
        tx.set(rowId, FluoQueryColumns.JOIN_TYPE, metadata.getJoinType().toString() );
        tx.set(rowId, FluoQueryColumns.JOIN_PARENT_NODE_ID, metadata.getParentNodeId() );
        tx.set(rowId, FluoQueryColumns.JOIN_LEFT_CHILD_NODE_ID, metadata.getLeftChildNodeId() );
        tx.set(rowId, FluoQueryColumns.JOIN_RIGHT_CHILD_NODE_ID, metadata.getRightChildNodeId() );
    }

    /**
     * Read an instance of {@link JoinMetadata} from the Fluo table.
     *
     * @param sx - The snapshot that will be used to read the metadata. (not null)
     * @param nodeId - The nodeId of the Join node that will be read. (not nul)
     * @return The {@link JoinMetadata} that was read from the table.
     */
    public JoinMetadata readJoinMetadata(final SnapshotBase sx, final String nodeId) {
        return readJoinMetadataBuilder(sx, nodeId).build();
    }

    private JoinMetadata.Builder readJoinMetadataBuilder(final SnapshotBase sx, final String nodeId) {
        requireNonNull(sx);
        requireNonNull(nodeId);

        // Fetch the values from the Fluo table.
        final String rowId = nodeId;
        final Map<Column, String> values = sx.gets(rowId,
                FluoQueryColumns.JOIN_VARIABLE_ORDER,
                FluoQueryColumns.JOIN_TYPE,
                FluoQueryColumns.JOIN_PARENT_NODE_ID,
                FluoQueryColumns.JOIN_LEFT_CHILD_NODE_ID,
                FluoQueryColumns.JOIN_RIGHT_CHILD_NODE_ID);

        // Return an object holding them.
        final String varOrderString = values.get(FluoQueryColumns.JOIN_VARIABLE_ORDER);
        final VariableOrder varOrder = new VariableOrder(varOrderString);

        final String joinTypeString = values.get(FluoQueryColumns.JOIN_TYPE);
        final JoinType joinType = JoinType.valueOf(joinTypeString);

        final String parentNodeId = values.get(FluoQueryColumns.JOIN_PARENT_NODE_ID);
        final String leftChildNodeId = values.get(FluoQueryColumns.JOIN_LEFT_CHILD_NODE_ID);
        final String rightChildNodeId = values.get(FluoQueryColumns.JOIN_RIGHT_CHILD_NODE_ID);

        return JoinMetadata.builder(nodeId)
                .setVariableOrder(varOrder)
                .setJoinType(joinType)
                .setParentNodeId(parentNodeId)
                .setLeftChildNodeId(leftChildNodeId)
                .setRightChildNodeId(rightChildNodeId);
    }

    /**
     * Write an instance of {@link StatementPatternMetadata} to the Fluo table.
     *
     * @param tx - The transaction that will be used to commit the metadata. (not null)
     * @param metadata - The Statement Pattern node metadata that will be written to the table. (not null)
     */
    public void write(final TransactionBase tx, final StatementPatternMetadata metadata) {
        requireNonNull(tx);
        requireNonNull(metadata);

        final String rowId = metadata.getNodeId();
        tx.set(rowId, FluoQueryColumns.STATEMENT_PATTERN_NODE_ID, rowId);
        tx.set(rowId, FluoQueryColumns.STATEMENT_PATTERN_VARIABLE_ORDER, metadata.getVariableOrder().toString());
        tx.set(rowId, FluoQueryColumns.STATEMENT_PATTERN_PATTERN, metadata.getStatementPattern() );
        tx.set(rowId, FluoQueryColumns.STATEMENT_PATTERN_PARENT_NODE_ID, metadata.getParentNodeId());
    }

    /**
     * Read an instance of {@link StatementPatternMetadata} from the Fluo table.
     *
     * @param sx - The snapshot that will be used to read the metadata. (not null)
     * @param nodeId - The nodeId of the Statement Pattern node that will be read. (not nul)
     * @return The {@link StatementPatternMetadata} that was read from the table.
     */
    public StatementPatternMetadata readStatementPatternMetadata(final SnapshotBase sx, final String nodeId) {
        return readStatementPatternMetadataBuilder(sx, nodeId).build();
    }

    private StatementPatternMetadata.Builder readStatementPatternMetadataBuilder(final SnapshotBase sx, final String nodeId) {
        requireNonNull(sx);
        requireNonNull(nodeId);

        // Fetch the values from the Fluo table.
        final String rowId = nodeId;
        final Map<Column, String> values = sx.gets(rowId,
                FluoQueryColumns.STATEMENT_PATTERN_VARIABLE_ORDER,
                FluoQueryColumns.STATEMENT_PATTERN_PATTERN,
                FluoQueryColumns.STATEMENT_PATTERN_PARENT_NODE_ID);

        // Return an object holding them.
        final String varOrderString = values.get(FluoQueryColumns.STATEMENT_PATTERN_VARIABLE_ORDER);
        final VariableOrder varOrder = new VariableOrder(varOrderString);

        final String pattern = values.get(FluoQueryColumns.STATEMENT_PATTERN_PATTERN);
        final String parentNodeId = values.get(FluoQueryColumns.STATEMENT_PATTERN_PARENT_NODE_ID);

        return StatementPatternMetadata.builder(nodeId)
                .setVarOrder(varOrder)
                .setStatementPattern(pattern)
                .setParentNodeId(parentNodeId);
    }

    /**
     * Write an instance of {@link AggregationMetadata} to the Fluo table.
     *
     * @param tx - The transaction that will be used to commit the metadata. (not null)
     * @param metadata - The Aggregation node metadata that will be written to the table. (not null)
     */
    public void write(final TransactionBase tx, final AggregationMetadata metadata) {
        requireNonNull(tx);
        requireNonNull(metadata);

        final String rowId = metadata.getNodeId();
        tx.set(rowId, FluoQueryColumns.AGGREGATION_NODE_ID, rowId);
        tx.set(rowId, FluoQueryColumns.AGGREGATION_VARIABLE_ORDER, metadata.getVariableOrder().toString());
        tx.set(rowId, FluoQueryColumns.AGGREGATION_PARENT_NODE_ID, metadata.getParentNodeId());
        tx.set(rowId, FluoQueryColumns.AGGREGATION_CHILD_NODE_ID, metadata.getChildNodeId());

        // Store the Group By variable order.
        final VariableOrder groupByVars = metadata.getGroupByVariableOrder();
        final String groupByString = Joiner.on(";").join(groupByVars.getVariableOrders());
        tx.set(rowId, FluoQueryColumns.AGGREGATION_GROUP_BY_BINDING_NAMES, groupByString);

        // Serialize the collection of AggregationElements.
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try(final ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject( metadata.getAggregations() );
        } catch (final IOException e) {
            throw new RuntimeException("Problem encountered while writing AggregationMetadata to the Fluo table. Unable " +
                    "to serialize the AggregationElements to a byte[].", e);
        }
        tx.set(Bytes.of(rowId.getBytes(Charsets.UTF_8)), FluoQueryColumns.AGGREGATION_AGGREGATIONS, Bytes.of(baos.toByteArray()));
    }

    /**
     * Read an instance of {@link AggregationMetadata} from the Fluo table.
     *
     * @param sx - The snapshot that will be used to read the metadata. (not null)
     * @param nodeId - The nodeId of the Aggregation node that will be read. (not null)
     * @return The {@link AggregationMetadata} that was read from the table.
     */
    public AggregationMetadata readAggregationMetadata(final SnapshotBase sx, final String nodeId) {
        return readAggregationMetadataBuilder(sx, nodeId).build();
    }

    private AggregationMetadata.Builder readAggregationMetadataBuilder(final SnapshotBase sx, final String nodeId) {
        requireNonNull(sx);
        requireNonNull(nodeId);

        // Fetch the values from the Fluo table.
        final String rowId = nodeId;
        final Map<Column, String> values = sx.gets(rowId,
                FluoQueryColumns.AGGREGATION_VARIABLE_ORDER,
                FluoQueryColumns.AGGREGATION_PARENT_NODE_ID,
                FluoQueryColumns.AGGREGATION_CHILD_NODE_ID,
                FluoQueryColumns.AGGREGATION_GROUP_BY_BINDING_NAMES);

        // Return an object holding them.
        final String varOrderString = values.get(FluoQueryColumns.AGGREGATION_VARIABLE_ORDER);
        final VariableOrder varOrder = new VariableOrder(varOrderString);

        final String parentNodeId = values.get(FluoQueryColumns.AGGREGATION_PARENT_NODE_ID);
        final String childNodeId = values.get(FluoQueryColumns.AGGREGATION_CHILD_NODE_ID);

        // Read the Group By variable order if one was present.
        final String groupByString = values.get(FluoQueryColumns.AGGREGATION_GROUP_BY_BINDING_NAMES);
        final VariableOrder groupByVars = groupByString.isEmpty() ? new VariableOrder() : new VariableOrder( groupByString.split(";") );

        // Deserialize the collection of AggregationElements.
        final Bytes aggBytes = sx.get(Bytes.of(nodeId.getBytes(Charsets.UTF_8)), FluoQueryColumns.AGGREGATION_AGGREGATIONS);
        final Collection<AggregationElement> aggregations;
        try(final ObjectInputStream ois = new ObjectInputStream(aggBytes.toInputStream())) {
             aggregations = (Collection<AggregationElement>)ois.readObject();
        } catch (final IOException | ClassNotFoundException e) {
            throw new RuntimeException("Problem encountered while reading AggregationMetadata from the Fluo table. Unable " +
                    "to deserialize the AggregationElements from a byte[].", e);
        }

        final AggregationMetadata.Builder builder = AggregationMetadata.builder(nodeId)
                .setVariableOrder(varOrder)
                .setParentNodeId(parentNodeId)
                .setChildNodeId(childNodeId)
                .setGroupByVariableOrder(groupByVars);

        for(final AggregationElement aggregation : aggregations) {
            builder.addAggregation(aggregation);
        }

        return builder;
    }

    /**
     * Write an instance of {@link FluoQuery} to the Fluo table.
     *
     * @param tx - The transaction that will be used to commit the metadata. (not null)
     * @param query - The query metadata that will be written to the table. (not null)
     */
    public void write(final TransactionBase tx, final FluoQuery query) {
        requireNonNull(tx);
        requireNonNull(query);

        // Write the rest of the metadata objects.
        switch(query.getQueryType()) {
        case Construct:
            ConstructQueryMetadata constructMetadata = query.getConstructQueryMetadata().get();
            // Store the Query ID so that it may be looked up from the original SPARQL string.
            final String constructSparql = constructMetadata.getSparql();
            final String constructQueryId = constructMetadata.getNodeId();
            tx.set(Bytes.of(constructSparql), FluoQueryColumns.QUERY_ID, Bytes.of(constructQueryId));
            write(tx, constructMetadata);
            break;
        case Projection:
            QueryMetadata queryMetadata = query.getQueryMetadata().get();
            // Store the Query ID so that it may be looked up from the original SPARQL string.
            final String sparql = queryMetadata.getSparql();
            final String queryId = queryMetadata.getNodeId();
            tx.set(Bytes.of(sparql), FluoQueryColumns.QUERY_ID, Bytes.of(queryId));
            write(tx, queryMetadata);
            break;
        }

        for(final FilterMetadata filter : query.getFilterMetadata()) {
            write(tx, filter);
        }

        for(final JoinMetadata join : query.getJoinMetadata()) {
            write(tx, join);
        }

        for(final StatementPatternMetadata statementPattern : query.getStatementPatternMetadata()) {
            write(tx, statementPattern);
        }

        for(final AggregationMetadata aggregation : query.getAggregationMetadata()) {
            write(tx, aggregation);
        }
    }

    /**
     * Read an instance of {@link FluoQuery} from the Fluo table.
     *
     * @param sx - The snapshot that will be used to read the metadata from the Fluo table. (not null)
     * @param queryId - The ID of the query whose nodes will be read. (not null)
     * @return The {@link FluoQuery} that was read from table.
     */
    public FluoQuery readFluoQuery(final SnapshotBase sx, final String queryId) {
        requireNonNull(sx);
        requireNonNull(queryId);

        final FluoQuery.Builder fluoQueryBuilder = FluoQuery.builder();
        addChildMetadata(sx, fluoQueryBuilder, queryId);
        return fluoQueryBuilder.build();
    }

    private void addChildMetadata(final SnapshotBase sx, final FluoQuery.Builder builder, final String childNodeId) {
        requireNonNull(sx);
        requireNonNull(builder);
        requireNonNull(childNodeId);

        final NodeType childType = NodeType.fromNodeId(childNodeId).get();
        switch (childType) {
        case QUERY:
            // Add this node's metadata.
            final QueryMetadata.Builder queryBuilder = readQueryMetadataBuilder(sx, childNodeId);
            Preconditions.checkArgument(!builder.getQueryBuilder().isPresent());
            builder.setQueryMetadata(queryBuilder);

            // Add it's child's metadata.
            addChildMetadata(sx, builder, queryBuilder.build().getChildNodeId());
            break;

        case CONSTRUCT:
            final ConstructQueryMetadata.Builder constructBuilder = readConstructQueryMetadataBuilder(sx, childNodeId);
            Preconditions.checkArgument(!builder.getQueryBuilder().isPresent());
            builder.setConstructQueryMetadata(constructBuilder);

            // Add it's child's metadata.
            addChildMetadata(sx, builder, constructBuilder.build().getChildNodeId());
            break;

        case AGGREGATION:
            // Add this node's metadata.
            final AggregationMetadata.Builder aggregationBuilder = readAggregationMetadataBuilder(sx, childNodeId);
            builder.addAggregateMetadata(aggregationBuilder);

            // Add it's child's metadata.
            addChildMetadata(sx, builder, aggregationBuilder.build().getChildNodeId());
            break;

        case JOIN:
            // Add this node's metadata.
            final JoinMetadata.Builder joinBuilder = readJoinMetadataBuilder(sx, childNodeId);
            builder.addJoinMetadata(joinBuilder);

            // Add it's children's metadata.
            final JoinMetadata joinMetadata = joinBuilder.build();
            addChildMetadata(sx, builder, joinMetadata.getLeftChildNodeId());
            addChildMetadata(sx, builder, joinMetadata.getRightChildNodeId());
            break;

        case FILTER:
            // Add this node's metadata.
            final FilterMetadata.Builder filterBuilder = readFilterMetadataBuilder(sx, childNodeId);
            builder.addFilterMetadata(filterBuilder);

            // Add it's child's metadata.
            addChildMetadata(sx, builder, filterBuilder.build().getChildNodeId());
            break;

        case STATEMENT_PATTERN:
            // Add this node's metadata.
            final StatementPatternMetadata.Builder spBuilder = readStatementPatternMetadataBuilder(sx, childNodeId);
            builder.addStatementPatternBuilder(spBuilder);
            break;
        default:
            break;
        }
    }
}


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\User;

/**
 * UsersSearch represents the model behind the search form about `app\models\User`.
 */
class UserSearch extends User
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'birthday', 'bonus', 'money', 'created_at', 'updated_at', 'status'], 'integer'],
            [['name', 'first_name', 'second_name', 'last_name', 'phone', 'email', 'password_reset_token', 'password_hash', 'auth_key'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = User::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'birthday' => $this->birthday,
            'bonus' => $this->bonus,
            'money' => $this->money,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'first_name', $this->first_name])
            ->andFilterWhere(['like', 'second_name', $this->second_name])
            ->andFilterWhere(['like', 'last_name', $this->last_name])
            ->andFilterWhere(['like', 'phone', $this->phone])
            ->andFilterWhere(['like', 'email', $this->email])
            ->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])
            ->andFilterWhere(['like', 'password_hash', $this->password_hash])
            ->andFilterWhere(['like', 'auth_key', $this->auth_key]);

        return $dataProvider;
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.03.16 at 01:25:33 AM IST
//

package org.akomantoso.schema.v3.csd08;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <extension base="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD08}inline">
 *       <attribute name="width" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "fillIn")
public class FillIn
    extends ComplexTypeInline
{

    @XmlAttribute(name = "width")
    protected String width;

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

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

}


text:
#include "condor_common.h"
#include "condor_debug.h"
#include "process_control.WINDOWS.h"
#include "ntsysinfo.WINDOWS.h"
#include "HashTable.h"
#include "condor_softkill.h"

static char* soft_kill_binary = NULL;

void
set_windows_soft_kill_binary(char* binary)
{
	if (soft_kill_binary != NULL) {
		free(soft_kill_binary);
	}
	soft_kill_binary = strdup(binary);
	ASSERT(soft_kill_binary != NULL);
}

bool
windows_soft_kill(DWORD pid)
{
	// softkill on Windows is implemented by posting a WM_CLOSE to
	// a top-level window owned by the process (if the process owns
	// more than 1 top-level window, it is undefined which one will
	// get the WM_CLOSE). finding the window and posting the message
	// are done using the condor_softkill tool
	//

	// bail out if the binary wasn't set
	//
	if (soft_kill_binary == NULL) {
		dprintf(D_ALWAYS,
		        "windows_soft_kill error: softkill binary not set\n");
		return false;
	}

	// construct the command line for the call to CreateProcess
	//
	char command_line[1024];
	int ret = _snprintf(command_line,
	                    1024,
	                    "\"%s\" %u debug.txt",
	                    soft_kill_binary,
	                    pid);
	command_line[1023] = 0;
	if (ret < 0) {
		dprintf(D_ALWAYS,
		        "windows:soft_kill: snprintf error: %s (%d)\n",
		        strerror(errno),
		        errno);
		return false;
	}
	if (command_line[1023] != '\0') {
		dprintf(D_ALWAYS,
		        "windows_soft_kill: command line too long\n");
		return false;
	}

	// call CreateProcess to run the softkill executable
	//
	STARTUPINFO si;
	memset(&si, 0, sizeof(STARTUPINFO));
	PROCESS_INFORMATION pi;
	if (CreateProcess(NULL,         // get the executable from the command line
	                  command_line,
	                  NULL,         // default process security
	                  NULL,         // default security for primary thread
	                  FALSE,        // don't inherit handles
	                  0,            // no flags
	                  NULL,         // inherit our environment
	                  NULL,         // inherit our working directory
	                  &si,
	                  &pi) == FALSE)
	{
		dprintf(D_ALWAYS,
		        "windows_soft_kill: CreateProcess error: %u\n",
		        GetLastError());
		return false;
	}
	CloseHandle(pi.hThread);

	// wait for the exit code; fail if we can't get it or if
	// it indicates failure
	//
	if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_OBJECT_0) {
		dprintf(D_ALWAYS,
		        "windows_soft_kill: WaitForSingleObject error: %u\n",
		        GetLastError());
	}
	DWORD exit_code;
	BOOL result = GetExitCodeProcess(pi.hProcess, &exit_code);
	DWORD error = GetLastError();
	CloseHandle(pi.hProcess);
	if (result == FALSE) {
		dprintf(D_ALWAYS,
		        "windows_soft_kill: GetExitCodeProcess error: %u\n",
		        GetLastError());
		return false;
	}
	if (exit_code != SOFTKILL_SUCCESS) {
		dprintf(D_ALWAYS,
		        "windows_soft_kill: error code from condor_softkill: %u\n",
		        exit_code);
		return false;
	}

	// i guess it worked
	//
	return true;
}

bool
windows_hard_kill(DWORD pid)
{
	HANDLE process = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
	if (process == NULL) {
		dprintf(D_ALWAYS,
		        "windows_hard_kill: OpenProcess error: %u\n",
		        GetLastError());
		return false;
	}
	BOOL ok = TerminateProcess(process, 0);
	DWORD err = GetLastError();
	CloseHandle(process);
	if (ok == FALSE) {
		dprintf(D_ALWAYS,
		        "windows_hard_kill: TerminateProcess error: %u\n",
		        (unsigned)err);
		return false;
	}
	return true;
}

// stupid hash function for DWORD (need by the hash tables
// used in the suspend/contiunue code below)
//
static size_t
hash_func(const DWORD& n)
{
	return n;
}

// stupid object for getting the list of threads for a process
//
static CSysinfo sys_info;

// record to keep track of the threads in a suspended process
//
struct SuspendedThread {

	// cache a handle to each thread while the process is suspended
	//
	HANDLE handle;

	// how many suspends did we send this thread? (so we know how
	// many resumes to send!)
	//
	int num_suspends;
};

// for each suspended process we keep a hash table of its
// SuspendedThread structures (keyed on thread id)
//
typedef HashTable<DWORD, SuspendedThread*> SuspendedProcess;

// we keep track of all suspended processes via a hash table
// keyed on process id
//
static HashTable<DWORD, SuspendedProcess*> suspended_processes(hash_func);

bool
windows_suspend(DWORD pid)
{
	// make sure we haven't already suspended this process, then allocate
	// a SuspendedProcess object and add it to the hash table
	//
	SuspendedProcess* sp;
	int ret = suspended_processes.lookup(pid, sp);
	ASSERT(ret == -1);
	sp = new SuspendedProcess(hash_func);
	ASSERT(sp != NULL);
	ret = suspended_processes.insert(pid, sp);
	ASSERT(ret != -1);

	// we need to loop until iterating through the thread list for this
	// process shows that all threads are suspended
	//
	bool finished = false;
	while (!finished) {

		// assume we're going to succeed on this iteration until
		// proven otherwise
		//
		finished = true;

		// get the list of threads for this process
		//
		std::vector<DWORD> tid_array;
		int num_tids = sys_info.GetTIDs(pid, tid_array);
		if (num_tids == 0) {
			// TODO: we need to handle this case!!!
			//
			EXCEPT("windows_suspend_process failed: can't get threads for pid %u",
			       pid);
		}

		// go through the thread list, calling SuspendThread on each
		//
		for (size_t i = 0; i < tid_array.size(); i++) {

			// see if we already have a record for this thread
			//
			SuspendedThread* st;
			ret = sp->lookup(tid_array[i], st);
			if (ret == -1) {

				// no record yet; open up this thread's handle
				//
				HANDLE handle = OpenThread(THREAD_SUSPEND_RESUME, FALSE, tid_array[i]);
				if (handle == NULL) {

					// the thread probably exited; however, it may have called ResumeThread
					// or CreateThread first, so we'll have to loop again
					//
					finished = false;
					dprintf(D_FULLDEBUG,
					        "windows_suspend_process: OpenThread error: %u\n",
					        GetLastError());
					continue;
				}

				// now that we have a handle, create a record for this thread
				//
				st = new SuspendedThread;
				ASSERT(st != NULL);
				st->handle = handle;
				st->num_suspends = 0;
				ret = sp->insert(tid_array[i], st);
				ASSERT(ret != -1);
			}

			// now suspend the thread
			//
			DWORD result = SuspendThread(st->handle);
			if (result == (DWORD)-1) {

				// how can this happen? maybe the thread exited?
				//
				finished = false;
				dprintf(D_FULLDEBUG,
						"windows_suspend_process: SuspendThread error: %u\n",
						GetLastError());
				continue;
			}

			// if the thread was not suspended prior to our SuspendThread call,
			// it may have called CreateThread or ResumeThread so we need to loop
			// at least one more time
			//
			if (result == 0) {
				finished = false;
			}

			// keep track of how many suspends we've sent this thread
			//
			st->num_suspends++;
		}
	}

	return true;
}

bool
windows_continue(DWORD pid)
{
	// we should have a record from when we suspended this process
	//
	SuspendedProcess* sp;
	int ret = suspended_processes.lookup(pid, sp);

	// NOTE: In testing windows continuation the
	// procd can at times pass invalid pid's to this function
	// as a result, exit gracefully vs. assert.
	if (ret == -1)
	   return false;

	SuspendedThread* st;
	sp->startIterations();
	while (sp->iterate(st)) {

		// call ResumeThread as many times as we called SuspendThread
		// for this thread above
		//
		for (int i = 0; i < st->num_suspends; i++) {
			if (ResumeThread(st->handle) == (DWORD)-1) {
				dprintf(D_FULLDEBUG,
				        "windows_continue_process: ResumeThread error: %u\n",
				        GetLastError());
			}
		}

		// close our handle to this thread
		//
		if (CloseHandle(st->handle) == FALSE) {
			dprintf(D_FULLDEBUG,
			        "windows_continue_process: CloseHandle error: %u\n",
			        GetLastError());
		}

		// clean up this SuspendedThread object
		//
		delete st;
	}

	// clean up the SuspendedProcess object and remove it from the
	// hash table of processes
	//
	delete sp;
	ret = suspended_processes.remove(pid);
	ASSERT(ret != -1);

	return true;
}


text:
package org.openo.nfvo.jujuvnfmadapter.service.entity;

import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 *
 * Juju Driver Class.

 *

 *

 *
 * @author
 * @version     NFVO 0.5  Sep 10, 2016
 */
public class JujuDriver {

    private String serviceName;

    private String protocol;

    private String version;

    private String visualRange;

    private String url;

    private List nodes;

    private String ip;

    private String port;

    private String ttl;

    private String status;

    public static final String NOTES = "notes";

    public JujuDriver() {
       // Default Constructor
    }

    /**
     *
     * Constructor

     *

     *

     *
     * @param jujuJsonObject
     * @since  NFVO 0.5
     */
    public JujuDriver(JSONObject jujuJsonObject) {
        this.serviceName = jujuJsonObject.getString("serviceName");
        this.protocol = jujuJsonObject.getString("protocol");
        this.version = jujuJsonObject.getString("version");
        this.visualRange = jujuJsonObject.getString("visualRange");
        this.url = jujuJsonObject.getString("url");
        this.nodes = jujuJsonObject.getJSONArray("nodes");
        this.ip = jujuJsonObject.getJSONArray(NOTES).getString(0);
        this.port = jujuJsonObject.getJSONArray(NOTES).getString(1);
        this.ttl = jujuJsonObject.getJSONArray(NOTES).getString(2);
        this.status = jujuJsonObject.getString("status");
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public String getVisualRange() {
        return visualRange;
    }

    public void setVisualRange(String visualRange) {
        this.visualRange = visualRange;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public List getNodes() {
        return nodes;
    }

    public void setNodes(List nodes) {
        this.nodes = nodes;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getIP() {
        return ip;
    }

    public void setIP(String ip) {
        this.ip = ip;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getTtl() {
        return ttl;
    }

    public void setTtl(String ttl) {
        this.ttl = ttl;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((serviceName == null) ? 0 : serviceName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj) {
            return true;
        }
        if(obj == null) {
            return false;
        }
        if(!(obj instanceof JujuDriver)) {
            return false;
        }
        if(getClass() != obj.getClass()) {
            return false;
        }
        JujuDriver other = (JujuDriver)obj;
        if(serviceName == null) {
            if(other.serviceName != null) {
                return false;
            }
        } else if(!serviceName.equals(other.serviceName)) {
            return false;
        }
        return true;
    }

}


text:
<?php

namespace Application\Model\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ArticleAuthors
 *
 * @ORM\Table(name="article_authors", indexes={@ORM\Index(name="id_user", columns={"id_user"}), @ORM\Index(name="id_article", columns={"id_article"})})
 * @ORM\Entity
 */
class ArticleAuthors
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \Application\Model\Entity\User
     *
     * @ORM\ManyToOne(targetEntity="Application\Model\Entity\User")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_user", referencedColumnName="id")
     * })
     */
    private $idUser;

    /**
     * @var \Application\Model\Entity\Article
     *
     * @ORM\ManyToOne(targetEntity="Application\Model\Entity\Article")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_article", referencedColumnName="id")
     * })
     */
    private $idArticle;

}


text:
using Microsoft.CodeAnalysis.CodeFixes;
using System.Collections.Immutable;
using System.Threading.Tasks;

namespace Microsoft.CodeQuality.Analyzers.ApiReview
{
    /// <summary>
    /// CA2001: Avoid calling problematic methods
    /// </summary>
    public abstract class AvoidCallingProblematicMethodsFixer : CodeFixProvider
    {
        public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray<string>.Empty;

        public sealed override FixAllProvider GetFixAllProvider()
        {
            // See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers
            return WellKnownFixAllProviders.BatchFixer;
        }

        public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            // Fixer not yet implemented.
            return Task.CompletedTask;

        }
    }
}


text:
svnmerge merge -S rc .
pending=$(svn status | grep -v '^?' | wc -l)
if [ $pending != 0 ]; then
  echo "unmerged or uncommitted changes"
  exit 1
fi

# create the release branch
repo=https://www.dev.java.net/svn/hudson
RC=$repo/branches/rc
svn rm -m "deleting the old RC branch" $RC
svn cp -m "creating a new RC branch" $repo/trunk/hudson/main $RC

# update changelog.html
WWW=../../www
svn up $WWW/changelog.html
ruby rc.changelog.rb < $WWW/changelog.html > $WWW/changelog.new
mv $WWW/changelog.new $WWW/changelog.html

cd $WWW
svn commit -m "RC branch is created" changelog.html


text:
module.exports = function(Cartoparty) {
};


text:
package leveldb

import (
	"bytes"

	"github.com/cayleygraph/cayley/clog"
	ldbit "github.com/syndtr/goleveldb/leveldb/iterator"
	"github.com/syndtr/goleveldb/leveldb/opt"

	"github.com/cayleygraph/cayley/graph"
	"github.com/cayleygraph/cayley/graph/iterator"
	"github.com/cayleygraph/cayley/quad"
)

type Iterator struct {
	uid            uint64
	tags           graph.Tagger
	nextPrefix     []byte
	checkID        []byte
	dir            quad.Direction
	open           bool
	iter           ldbit.Iterator
	qs             *QuadStore
	ro             *opt.ReadOptions
	originalPrefix string
	result         graph.Value
}

func NewIterator(prefix string, d quad.Direction, value graph.Value, qs *QuadStore) *Iterator {
	vb := value.(Token)
	p := make([]byte, 0, 2+quad.HashSize)
	p = append(p, []byte(prefix)...)
	p = append(p, []byte(vb[1:])...)

	opts := &opt.ReadOptions{
		DontFillCache: true,
	}

	it := Iterator{
		uid:            iterator.NextUID(),
		nextPrefix:     p,
		checkID:        vb,
		dir:            d,
		originalPrefix: prefix,
		ro:             opts,
		iter:           qs.db.NewIterator(nil, opts),
		open:           true,
		qs:             qs,
	}

	ok := it.iter.Seek(it.nextPrefix)
	if !ok {
		it.open = false
		it.iter.Release()
		clog.Errorf("Opening LevelDB iterator couldn't seek to location %v", it.nextPrefix)
	}

	return &it
}

func (it *Iterator) UID() uint64 {
	return it.uid
}

func (it *Iterator) Reset() {
	if !it.open {
		it.iter = it.qs.db.NewIterator(nil, it.ro)
		it.open = true
	}
	ok := it.iter.Seek(it.nextPrefix)
	if !ok {
		it.open = false
		it.iter.Release()
	}
}

func (it *Iterator) Tagger() *graph.Tagger {
	return &it.tags
}

func (it *Iterator) TagResults(dst map[string]graph.Value) {
	for _, tag := range it.tags.Tags() {
		dst[tag] = it.Result()
	}

	for tag, value := range it.tags.Fixed() {
		dst[tag] = value
	}
}

func (it *Iterator) Clone() graph.Iterator {
	out := NewIterator(it.originalPrefix, it.dir, Token(it.checkID), it.qs)
	out.tags.CopyFrom(it)
	return out
}

func (it *Iterator) Close() error {
	if it.open {
		it.iter.Release()
		it.open = false
	}
	return nil
}

func (it *Iterator) Next() bool {
	if it.iter == nil {
		it.result = nil
		return false
	} else if !it.open {
		it.result = nil
		return false
	}
	for {
		if !it.iter.Valid() {
			it.result = nil
			it.Close()
			return false
		}
		if !bytes.HasPrefix(it.iter.Key(), it.nextPrefix) {
			it.Close()
			it.result = nil
			return false
		}
		if !isLiveValue(it.iter.Value()) {
			if !it.iter.Next() {
				it.Close()
				return false
			}
			continue
		}
		it.result = Token(clone(it.iter.Key()))
		ok := it.iter.Next()
		if !ok {
			it.Close()
		}
		return true
	}
}

func (it *Iterator) Err() error {
	return it.iter.Error()
}

func (it *Iterator) Result() graph.Value {
	return it.result
}

func (it *Iterator) NextPath() bool {
	return false
}

// No subiterators.
func (it *Iterator) SubIterators() []graph.Iterator {
	return nil
}

func PositionOf(prefix []byte, d quad.Direction, qs *QuadStore) int {
	if bytes.Equal(prefix, []byte("sp")) {
		switch d {
		case quad.Subject:
			return 2
		case quad.Predicate:
			return quad.HashSize + 2
		case quad.Object:
			return 2*quad.HashSize + 2
		case quad.Label:
			return 3*quad.HashSize + 2
		}
	}
	if bytes.Equal(prefix, []byte("po")) {
		switch d {
		case quad.Subject:
			return 2*quad.HashSize + 2
		case quad.Predicate:
			return 2
		case quad.Object:
			return quad.HashSize + 2
		case quad.Label:
			return 3*quad.HashSize + 2
		}
	}
	if bytes.Equal(prefix, []byte("os")) {
		switch d {
		case quad.Subject:
			return quad.HashSize + 2
		case quad.Predicate:
			return 2*quad.HashSize + 2
		case quad.Object:
			return 2
		case quad.Label:
			return 3*quad.HashSize + 2
		}
	}
	if bytes.Equal(prefix, []byte("cp")) {
		switch d {
		case quad.Subject:
			return 2*quad.HashSize + 2
		case quad.Predicate:
			return quad.HashSize + 2
		case quad.Object:
			return 3*quad.HashSize + 2
		case quad.Label:
			return 2
		}
	}
	panic("unreachable")
}

func (it *Iterator) Contains(v graph.Value) bool {
	val := v.(Token)
	if val.IsNode() {
		return false
	}
	offset := PositionOf(val[0:2], it.dir, it.qs)
	if bytes.HasPrefix(val[offset:], it.checkID[1:]) {
		// You may ask, why don't we check to see if it's a valid (not deleted) quad
		// again?
		//
		// We've already done that -- in order to get the graph.Value token in the
		// first place, we had to have done the check already; it came from a Next().
		//
		// However, if it ever starts coming from somewhere else, it'll be more
		// efficient to change the interface of the graph.Value for LevelDB to a
		// struct with a flag for isValid, to save another random read.
		return true
	}
	return false
}

func (it *Iterator) Size() (int64, bool) {
	return it.qs.SizeOf(Token(it.checkID)), true
}

func (it *Iterator) Describe() graph.Description {
	size, _ := it.Size()
	return graph.Description{
		UID:       it.UID(),
		Name:      quad.StringOf(it.qs.NameOf(Token(it.checkID))),
		Type:      it.Type(),
		Tags:      it.tags.Tags(),
		Size:      size,
		Direction: it.dir,
	}
}

var levelDBType graph.Type

func init() {
	levelDBType = graph.RegisterIterator("leveldb")
}

func Type() graph.Type { return levelDBType }

func (it *Iterator) Type() graph.Type { return levelDBType }
func (it *Iterator) Sorted() bool     { return false }

func (it *Iterator) Optimize() (graph.Iterator, bool) {
	return it, false
}

func (it *Iterator) Stats() graph.IteratorStats {
	s, exact := it.Size()
	return graph.IteratorStats{
		ContainsCost: 1,
		NextCost:     2,
		Size:         s,
		ExactSize:    exact,
	}
}

var _ graph.Iterator = &Iterator{}


text:
This covers installation of the RingCentral SDK and PubNub dependency for making event subscriptions. Both packages are hosted on NuGet as follows:

* [http://www.nuget.org/packages/RingCentralSDK/](http://www.nuget.org/packages/RingCentralSDK/)
* [http://www.nuget.org/packages/Pubnub/](http://www.nuget.org/packages/Pubnub/)

## Build PubNub Messaging DLL

The following steps will compile the required libraries.

1. clone `github.com/pubnub/c-sharp` repo
1. open `c-sharp/monotouch/PubnubMessaging/PubnubMessaging.Core.csproj` in Xamarin Studio
1. add Json.NET package (Newtonsoft.Json) from NuGet
1. Build All (⌘B)

This builds the following in `c-sharp/monotouch/PubnubMessaging/bin/Release/`

```bash
Newtonsoft.Json.dll
PubnubMessaging.dll
PubnubMessaging.dll.mdb
```

## Create New RingCentral Xamarin iOS Solution

Perform the following steps to load RingCentral and PubNub

1. Create a new Xamarin iOS app, e.g. Single View App
1. Add `RingCentral` package from Official NuGet Gallery
1. Add `PubnubMessaging.dll` reference by editing `.NET Assembly` and adding the DLL from previous step

## Start Coding

1. Add the following to your code:

```csharp
using RingCentral;
using RingCentral.Subscription; // if using subscriptions
```

## Notes

1. To run your simulator, you may need to set the target device to an actual device vs `iOS Device`


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('service:redux', 'Unit | Service | redux');

test('should initialize store', function(assert) {
  const service = this.subject();
  assert.ok(service.store);
});

test('should return the action on dispatch', function(assert) {
  const service = this.subject();
  const dispatchResult = service.dispatch({ type: 'DUMMY' });
  assert.deepEqual(dispatchResult, { type: 'DUMMY' });
});


text:
#region License

#endregion
using System.Text;
using System.Text.Html;
using System.Text.RegularExpressions;
using System.Primitives.DataTypes;
namespace System.Patterns.Schema
{
    /// <summary>
    /// MailToHtmlDecoder
    /// </summary>
    public class MailToHtmlDecoder : HtmlDecoderBase
    {
        private static readonly Regex s_emailRegExp = new Regex(EmailDataType.EmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        public override void Decode(StringBuilder b, HtmlFormatterBase formatter, string text)
        {
            // fix email addresses (mailto:x@x)
            int textLength = text.Length;
            int startIndex = 0;
            int commitIndex = startIndex;
            int index;
            while ((index = text.IndexOf("mailto:", startIndex, StringComparison.OrdinalIgnoreCase)) > -1)
            {
                startIndex = index + 7;
                // check for space prefix
                if ((index > 0) && (text[index - 1] != ' '))
                    continue;
                string email;
                // locate end of email
                int index2;
                for (index2 = startIndex; (index2 < textLength) && (EmailDataType.IsValidCharacterForTextParsing(text[index2])); index2++) ;
                if ((index2 < textLength) && (index2 > 0) && (".".IndexOf(text[index2]) > -1))
                    index2--;
                if (index2 < textLength)
                {
                    email = text.Substring(startIndex, index2 - startIndex);
                    startIndex = index2;
                }
                else
                {
                    email = text.Substring(startIndex);
                    startIndex = textLength;
                }
                // check if email
                if (s_emailRegExp.IsMatch(email))
                {
                    // commit to textBuilder
                    if (index > commitIndex)
                        b.Append(text.Substring(commitIndex, index - commitIndex));
                    commitIndex = startIndex;
                    b.Append(formatter.Format(email));
                }
            }
            // overflow commit to textBuilder
            if (commitIndex < textLength)
                b.Append(text.Substring(commitIndex));
        }
    }
}


text:
package utils

import (
	"errors"
	"fmt"

	"github.com/coreos/go-iptables/iptables"
)

const statusChainExists = 1

// EnsureChain idempotently creates the iptables chain. It does not
// return an error if the chain already exists.
func EnsureChain(ipt *iptables.IPTables, table, chain string) error {
	if ipt == nil {
		return errors.New("failed to ensure iptable chain: IPTables was nil")
	}
	exists, err := ChainExists(ipt, table, chain)
	if err != nil {
		return fmt.Errorf("failed to list iptables chains: %v", err)
	}
	if !exists {
		err = ipt.NewChain(table, chain)
		if err != nil {
			eerr, eok := err.(*iptables.Error)
			if eok && eerr.ExitStatus() != statusChainExists {
				return err
			}
		}
	}
	return nil
}

// ChainExists checks whether an iptables chain exists.
func ChainExists(ipt *iptables.IPTables, table, chain string) (bool, error) {
	if ipt == nil {
		return false, errors.New("failed to check iptable chain: IPTables was nil")
	}
	chains, err := ipt.ListChains(table)
	if err != nil {
		return false, err
	}

	for _, ch := range chains {
		if ch == chain {
			return true, nil
		}
	}
	return false, nil
}

// DeleteRule idempotently delete the iptables rule in the specified table/chain.
// It does not return an error if the referring chain doesn't exist
func DeleteRule(ipt *iptables.IPTables, table, chain string, rulespec ...string) error {
	if ipt == nil {
		return errors.New("failed to ensure iptable chain: IPTables was nil")
	}
	if err := ipt.Delete(table, chain, rulespec...); err != nil {
		eerr, eok := err.(*iptables.Error)
		switch {
		case eok && eerr.IsNotExist():
			// swallow here, the chain was already deleted
			return nil
		case eok && eerr.ExitStatus() == 2:
			// swallow here, invalid command line parameter because the referring rule is missing
			return nil
		default:
			return fmt.Errorf("Failed to delete referring rule %s %s: %v", table, chain, err)
		}
	}
	return nil
}

// DeleteChain idempotently deletes the specified table/chain.
// It does not return an errors if the chain does not exist
func DeleteChain(ipt *iptables.IPTables, table, chain string) error {
	if ipt == nil {
		return errors.New("failed to ensure iptable chain: IPTables was nil")
	}

	err := ipt.DeleteChain(table, chain)
	eerr, eok := err.(*iptables.Error)
	switch {
	case eok && eerr.IsNotExist():
		// swallow here, the chain was already deleted
		return nil
	default:
		return err
	}
}

// ClearChain idempotently clear the iptables rules in the specified table/chain.
// If the chain does not exist, a new one will be created
func ClearChain(ipt *iptables.IPTables, table, chain string) error {
	if ipt == nil {
		return errors.New("failed to ensure iptable chain: IPTables was nil")
	}
	err := ipt.ClearChain(table, chain)
	eerr, eok := err.(*iptables.Error)
	switch {
	case eok && eerr.IsNotExist():
		// swallow here, the chain was already deleted
		return EnsureChain(ipt, table, chain)
	default:
		return err
	}
}

// InsertUnique will add a rule to a chain if it does not already exist.
// By default the rule is appended, unless prepend is true.
func InsertUnique(ipt *iptables.IPTables, table, chain string, prepend bool, rule []string) error {
	exists, err := ipt.Exists(table, chain, rule...)
	if err != nil {
		return err
	}
	if exists {
		return nil
	}

	if prepend {
		return ipt.Insert(table, chain, 1, rule...)
	} else {
		return ipt.Append(table, chain, rule...)
	}
}


text:
#include "ets_sys.h"
#include "os_type.h"
#include "osapi.h"
#include "mem.h"
#include "user_interface.h"

#include "espconn.h"
#include "user_json.h"
#include "user_devicefind.h"

const char *device_find_request = "Are You Espressif IOT Smart Device?";
#if PLUG_DEVICE
const char *device_find_response_ok = "I'm Plug.";
#elif LIGHT_DEVICE
const char *device_find_response_ok = "I'm Light.";
#elif SENSOR_DEVICE
#if HUMITURE_SUB_DEVICE
const char *device_find_response_ok = "I'm Humiture.";
#elif FLAMMABLE_GAS_SUB_DEVICE
const char *device_find_response_ok = "I'm Flammable Gas.";
#endif
#endif

/*---------------------------------------------------------------------------*/
LOCAL struct espconn ptrespconn;

/******************************************************************************
 * FunctionName : user_devicefind_recv
 * Description  : Processing the received data from the host
 * Parameters   : arg -- Additional argument to pass to the callback function
 *                pusrdata -- The received data (or NULL when the connection has been closed!)
 *                length -- The length of received data
 * Returns      : none
*******************************************************************************/
LOCAL void ICACHE_FLASH_ATTR
user_devicefind_recv(void *arg, char *pusrdata, unsigned short length)
{
    char DeviceBuffer[40] = {0};
    char Device_mac_buffer[60] = {0};
    char hwaddr[6];
    remot_info *premot = NULL;
    struct ip_info ipconfig;

    if (wifi_get_opmode() != STATION_MODE) {
        wifi_get_ip_info(SOFTAP_IF, &ipconfig);
        wifi_get_macaddr(SOFTAP_IF, hwaddr);

        if (!ip_addr_netcmp((struct ip_addr *)ptrespconn.proto.udp->remote_ip, &ipconfig.ip, &ipconfig.netmask)) {
            wifi_get_ip_info(STATION_IF, &ipconfig);
            wifi_get_macaddr(STATION_IF, hwaddr);
        }
    } else {
        wifi_get_ip_info(STATION_IF, &ipconfig);
        wifi_get_macaddr(STATION_IF, hwaddr);
    }

    if (pusrdata == NULL) {
        return;
    }

    if (length == os_strlen(device_find_request) &&
            os_strncmp(pusrdata, device_find_request, os_strlen(device_find_request)) == 0) {
        os_sprintf(DeviceBuffer, "%s" MACSTR " " IPSTR, device_find_response_ok,
                   MAC2STR(hwaddr), IP2STR(&ipconfig.ip));

        os_printf("%s\n", DeviceBuffer);
        length = os_strlen(DeviceBuffer);
        if (espconn_get_connection_info(&ptrespconn, &premot, 0) != ESPCONN_OK)
        	return;
        os_memcpy(ptrespconn.proto.udp->remote_ip, premot->remote_ip, 4);
        ptrespconn.proto.udp->remote_port = premot->remote_port;
        espconn_sent(&ptrespconn, DeviceBuffer, length);
    } else if (length == (os_strlen(device_find_request) + 18)) {
        os_sprintf(Device_mac_buffer, "%s " MACSTR , device_find_request, MAC2STR(hwaddr));
        os_printf("%s", Device_mac_buffer);

        if (os_strncmp(Device_mac_buffer, pusrdata, os_strlen(device_find_request) + 18) == 0) {
            //os_printf("%s\n", Device_mac_buffer);
            length = os_strlen(DeviceBuffer);
            os_sprintf(DeviceBuffer, "%s" MACSTR " " IPSTR, device_find_response_ok,
                       MAC2STR(hwaddr), IP2STR(&ipconfig.ip));

            os_printf("%s\n", DeviceBuffer);
            length = os_strlen(DeviceBuffer);
			if (espconn_get_connection_info(&ptrespconn, &premot, 0) != ESPCONN_OK)
				return;
			os_memcpy(ptrespconn.proto.udp->remote_ip, premot->remote_ip, 4);
			ptrespconn.proto.udp->remote_port = premot->remote_port;
            espconn_sent(&ptrespconn, DeviceBuffer, length);
        } else {
            return;
        }
    }
}

/******************************************************************************
 * FunctionName : user_devicefind_init
 * Description  : the espconn struct parame init
 * Parameters   : none
 * Returns      : none
*******************************************************************************/
void ICACHE_FLASH_ATTR
user_devicefind_init(void)
{
    ptrespconn.type = ESPCONN_UDP;
    ptrespconn.proto.udp = (esp_udp *)os_zalloc(sizeof(esp_udp));
    ptrespconn.proto.udp->local_port = 1025;
    espconn_regist_recvcb(&ptrespconn, user_devicefind_recv);
    espconn_create(&ptrespconn);
}


text:
using HFEA.Connector.Service.Constants;
using System;
using System.Collections.Generic;
using System.Linq;

using System.Text;
using System.Threading.Tasks;

namespace HFEA.Connector.Service.Attributes
{
    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
    public class CallType : Attribute
    {
        public HttpMethod Method { get; private set; }
        public bool RequiresAuthentication { get; private set; }

        public CallType (HttpMethod method, bool requiresAuthentication)
        {
            this.Method = method;
            this.RequiresAuthentication = requiresAuthentication;
        }
    }
}


text:
package com.phloc.commons.text.resource;

import java.util.Enumeration;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import javax.annotation.Nonnull;

import com.phloc.commons.charset.CCharset;
import com.phloc.commons.charset.CharsetManager;

/**
 * Special property resource bundle that wraps all strings into UTF-8 strings.
 *
 * @author Philip Helger
 */
final class Utf8PropertyResourceBundle extends ResourceBundle
{
  private final PropertyResourceBundle m_aBundle;

  Utf8PropertyResourceBundle (@Nonnull final PropertyResourceBundle aBundle)
  {
    if (aBundle == null)
      throw new NullPointerException ("bundle");
    m_aBundle = aBundle;
  }

  @Override
  public Enumeration <String> getKeys ()
  {
    return m_aBundle.getKeys ();
  }

  @Override
  protected Object handleGetObject (final String sKey)
  {
    final String sValue = m_aBundle.getString (sKey);
    // This does the main trick of converting the String to UTF-8
    return CharsetManager.getAsStringInOtherCharset (sValue,
                                                     CCharset.CHARSET_ISO_8859_1_OBJ,
                                                     CCharset.CHARSET_UTF_8_OBJ);
  }
}


text:
-------------------------------------------------------------------------------
--  mail template
-------------------------------------------------------------------------------
CREATE TABLE MAIL_TEMPLATE(
        ID BIGINT auto_increment,
        NAME VARCHAR(50),
	RECEIVER VARCHAR(200),
	SENDER VARCHAR(200),
	CC VARCHAR(200),
	BCC VARCHAR(200),
	SUBJECT VARCHAR(200),
	CONTENT TEXT,
	MANUAL INT,
	SCOPE_ID VARCHAR(50),
        CONSTRAINT PK_MAIL_TEMPLATE PRIMARY KEY(ID)
) engine=innodb;


text:
package com.geth1b.coding.skills.lc;

import com.geth1b.coding.skills.lc._380_InsertDeleteGetRandomO1.RandomizedSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;

/**
 * @author geth1b
 */
public class _380_InsertDeleteGetRandomO1_Test {
  private _380_InsertDeleteGetRandomO1 obj;
  private RandomizedSet set;

  @Before public void setUp() {
    obj = new _380_InsertDeleteGetRandomO1();
    set = obj.new RandomizedSet();
  }

  @Test public void test() {
    assertTrue(set.insert(0));
    assertTrue(set.remove(0));
    assertTrue(set.insert(-1));
    assertFalse(set.remove(0));
    assertEquals(-1, set.getRandom());
    assertEquals(-1, set.getRandom());
  }

  @Test public void test_probability() {
    for (int i = 0; i < 6; i++) {
      set.insert(i);
    }
    int count = 0;
    for (int i = 0; i < 1000; i++) {
      count += set.getRandom() == 3 ? 1 : 0;
    }
    assertEquals(0.16, count/1000d, 0.03);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle" >
            <gradient
                android:startColor="#C000"
                android:endColor="#C000"
                android:angle="270"/>
        </shape>
    </item>

</layer-list>


text:
var	h_utils = require("./http_utils.js"),
	fs		= require("fs"),
	checkAuthentication = function (req, res, next) {
		if (typeof req.session_state.username === "undefined") {
			if (req.url.match("/login") === null) {
				h_utils.redirect(req, res, "/login.html");
			} else {
				next();
			}
		} else {
			if (req.session_state.username === "guest" &&
				req.url.match("/logout") === null) {
				h_utils.writeHtml(res, "Welcome " + req.session_state.username + "! (logout)");
			} else {
				next();
			}
		}
	};

module.exports.checkAuthentication = checkAuthentication;


text:
"use strict";

const Back = document.getElementById("back");
const Forward = document.getElementById("forward");
var StatTable = document.getElementById("statTable");
const Count = document.getElementById("count");

////////////////////////////////////////////////////////////////////////////////

Back.onclick = showPrev;
Forward.onclick = showNext;

////////////////////////////////////////////////////////////////////////////////

var gameState = "";
var request = null;
var showingTurn = 0;
var lastTurn = 0;
var botFiles = null;
var stat = {};
var field = [];

function sendReq(turn) {
    let xhr = new XMLHttpRequest();
    xhr.open("POST", "/game", true);
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

    xhr.timeout = 3000;

    xhr.ontimeout = function () {
        setTimeout(function () {
            sendReq(turn);
        }, 0);
    }

    xhr.onload = function () {
        if (this.status == 200) {
            updateData(xhr);
        }
        if (gameState == "running") {
            setTimeout(function () {
                sendReq(turn);
            }, 0);
        }
    }

    let data = {
        state: gameState,
        lastTurn: lastTurn,
        turn: turn || -1
    }

    if (request !== null) {
        request.abort();
    }
    request = xhr;

    let fdata = new FormData();
    fdata.append("content", JSON.stringify(data));
    xhr.send(fdata);
}

function updateData(xhr) {
    let data = JSON.parse(xhr.responseText);
    if (gameState == "running" && data.state == "finished") {
        Back.removeAttribute("disabled");
        Forward.removeAttribute("disabled");
    }
    if(data.state == "idle" || data.state == "building"){
        alert("Someone started a new game or you wanted to open the tab without a game running. This tab will be closed");
        window.close();
    }
    if(data.state == "error"){
        alert("game process finished with an error. this tab will be closed");
        window.close();
    }
    gameState = data.state || gameState;
    stat = data.stat || stat;
    showingTurn = data.turn || data.lastTurn;
    lastTurn = data.lastTurn || lastTurn;
    field = data.field;
    botFiles = botFiles || data.bots;

    fillTable();
    Count.innerHTML = showingTurn;
    /////////////////////////////

    myStage.sendMessage("gameData", field);
}

sendReq();

function showPrev(){
    if(showingTurn == 0){
        return;
    }
    showingTurn--;
    sendReq(showingTurn);
}

function showNext(){
    if(showingTurn == lastTurn){
        return;
    }
    showingTurn++;
    sendReq(showingTurn);
}

////////////////////////////////////////////////////////////////////////////////

var statRowCount = 0;
const colors = ["grey", "white",
    "lightpink", "lightgreen",
    "cyan", "magenta",
    "lightblue", "gold"
];

function addTableRow() {
    statRowCount += 1;
    let row = document.createElement("tr");
    row.setAttribute("style", "background:" + colors[statRowCount] + ";");
    let mas = [row];
    for (let i in arguments) {
        row.innerHTML += "<td>" + arguments[i] + "</td>";
        mas.push(arguments[i]);
    }
    StatTable.appendChild(row);
}

function clearTable() {
    StatTable.innerHTML = "";
    statRowCount = 0;
    addTableRow("Name", "points", "last turn", "armies", "farms", "towers", "moves");
}

function fillTable() {
    clearTable();
    for (let i in botFiles) {
        addTableRow(botFiles[i], stat.points[i], stat.last_turn[i],
            stat.built_armies[i], stat.built_farms[i], stat.built_towers[i], stat.moves[i]);
    }
}