text:
package com.linkedin.pinot.integration.tests;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * The QueryGenerator class is used to generate random equivalent PQL/SQL query pairs based on Avro files.
 *

 *

 *     Supports COMPARISON, IN and BETWEEN predicate for both single-value and multi-value columns.
 *

 *
For multi-value columns, does not support NOT EQUAL and NOT IN.

 *
The reason for this restriction is that number of elements in multi-value columns is not fixed.

 *

 *

 *
Supports single-value data type: BOOLEAN, INT, LONG, FLOAT, DOUBLE, STRING.

 *
Supports multi-value data type: INT, LONG, FLOAT, DOUBLE, STRING.

 *

 *     Supports aggregation function: SUM, MIN, MAX, AVG, COUNT, DISTINCTCOUNT.
 *

 *
SUM, MIN, MAX, AVG can only work on numeric single-value columns.

 *
COUNT, DISTINCTCOUNT can work on any single-value columns.

 *

 *

 *

 */
public class QueryGenerator {
  // Configurable variables.
  private static final int MAX_NUM_SELECTION_COLUMNS = 3;
  private static final int MAX_NUM_AGGREGATION_COLUMNS = 3;
  private static final int MAX_NUM_ORDER_BY_COLUMNS = 3;
  private static final int MAX_NUM_GROUP_BY_COLUMNS = 3;
  private static final int MAX_NUM_PREDICATES = 3;
  private static final int MAX_NUM_IN_CLAUSE_VALUES = 5;
  private static final int MAX_RESULT_LIMIT = 30;
  private static final int MAX_COUNT_FUNCTION_RESULT = 1000;
  private static final float MAX_FLOAT_FOR_HAVING_CLAUSE_PREDICATE = 10000;
  private static final int MAX_INT_FOR_HAVING_CLAUSE_PREDICATE = 10000;
  private static final List<String> BOOLEAN_OPERATORS = Arrays.asList("OR", "AND");
  private static final List<String> COMPARISON_OPERATORS = Arrays.asList("=", "<>", "<", ">", "<=", ">=");

  // TODO: fix DISTINCTCOUNT implementation and add it back.
  // Currently for DISTINCTCOUNT we use hashcode as the key, should change it to use raw values.
  private static final List<String> AGGREGATION_FUNCTIONS =
      Arrays.asList("SUM", "MIN", "MAX", "AVG", "COUNT"/*, "DISTINCTCOUNT"*/);
  private static final Random RANDOM = new Random();

  private final Map<String, Set<String>> _columnToValueSet = new HashMap<>();
  private final Map<String, List<String>> _columnToValueList = new HashMap<>();
  private final List<String> _columnNames = new ArrayList<>();
  private final List<String> _singleValueColumnNames = new ArrayList<>();
  private final List<String> _singleValueNumericalColumnNames = new ArrayList<>();
  private final Map<String, Integer> _multiValueColumnMaxNumElements = new HashMap<>();

  private final List<QueryGenerationStrategy> _queryGenerationStrategies =
      Arrays.asList(new SelectionQueryGenerationStrategy(), new AggregationQueryGenerationStrategy());
  private final List<PredicateGenerator> _singleValuePredicateGenerators =
      Arrays.asList(new SingleValueComparisonPredicateGenerator(), new SingleValueInPredicateGenerator(),
          new SingleValueBetweenPredicateGenerator(), new SingleValueRegexPredicateGenerator());
  private final List<PredicateGenerator> _multiValuePredicateGenerators =
      Arrays.asList(new MultiValueComparisonPredicateGenerator(), new MultiValueInPredicateGenerator(),
          new MultiValueBetweenPredicateGenerator());

  private final String _pinotTableName;
  private final String _h2TableName;
  private boolean _skipMultiValuePredicates = false;

  /**
   * Constructor for QueryGenerator.
   *
   * @param avroFiles list of Avro files.
   * @param pinotTableName Pinot table name.
   * @param h2TableName H2 table name.
   */
  public QueryGenerator(List<File> avroFiles, String pinotTableName, String h2TableName) {
    _pinotTableName = pinotTableName;
    _h2TableName = h2TableName;

    // Read Avro schema and initialize storage.
    File schemaAvroFile = avroFiles.get(0);
    GenericDatumReader<GenericRecord> datumReader = new GenericDatumReader<>();
    try (DataFileReader<GenericRecord> fileReader = new DataFileReader<>(schemaAvroFile, datumReader)) {
      Schema schema = fileReader.getSchema();
      for (Schema.Field field : schema.getFields()) {
        String fieldName = field.name();
        Schema fieldSchema = field.schema();
        Schema.Type fieldType = fieldSchema.getType();

        switch (fieldType) {
          case UNION:
            _columnNames.add(fieldName);
            _columnToValueSet.put(fieldName, new HashSet<String>());
            Schema.Type type = fieldSchema.getTypes().get(0).getType();
            if (type == Schema.Type.ARRAY) {
              _multiValueColumnMaxNumElements.put(fieldName, 0);
            } else {
              _singleValueColumnNames.add(fieldName);
              if (type != Schema.Type.STRING && type != Schema.Type.BOOLEAN) {
                _singleValueNumericalColumnNames.add(fieldName);
              }
            }
            break;
          case ARRAY:
            _columnNames.add(fieldName);
            _columnToValueSet.put(fieldName, new HashSet<String>());
            _multiValueColumnMaxNumElements.put(fieldName, 0);
            break;
          case INT:
          case LONG:
          case FLOAT:
          case DOUBLE:
            _columnNames.add(fieldName);
            _columnToValueSet.put(fieldName, new HashSet<String>());
            _singleValueColumnNames.add(fieldName);
            _singleValueNumericalColumnNames.add(fieldName);
            break;
          case BOOLEAN:
          case STRING:
            _columnNames.add(fieldName);
            _columnToValueSet.put(fieldName, new HashSet<String>());
            _singleValueColumnNames.add(fieldName);
            break;
          default:
            break;
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    // Load Avro data into storage.
    for (File avroFile : avroFiles) {
      addAvroData(avroFile);
    }

    // Ignore multi-value columns with too many elements.
    prepareToGenerateQueries();
  }

  /**
   * Helper method to store an Avro value into the valid SQL String value set.
   *
   * @param valueSet value set.
   * @param avroValue Avro value.
   */
  private static void storeAvroValueIntoValueSet(Set<String> valueSet, Object avroValue) {
    if (avroValue instanceof Number) {
      // For Number object, store raw value.
      valueSet.add(avroValue.toString());
    } else {
      // For non-Number object, escape single quote.
      valueSet.add("'" + avroValue.toString().replace("'", "''") + "'");
    }
  }

  /**
   * Helper method to join several {@link String} elements with ' '.
   *
   * @param elements elements to be joined.
   * @return joined result.
   */
  private static String joinWithSpaces(String... elements) {
    StringBuilder stringBuilder = new StringBuilder();
    for (String element : elements) {
      if (!element.isEmpty()) {
        stringBuilder.append(element).append(' ');
      }
    }
    return stringBuilder.substring(0, stringBuilder.length() - 1);
  }

  /**
   * Sample main class for the query generator.
   *
   * @param args arguments.
   */
  public static void main(String[] args) throws Exception {
    File avroFile = new File("pinot-integration-tests/src/test/resources/On_Time_On_Time_Performance_2014_1.avro");
    QueryGenerator queryGenerator = new QueryGenerator(Collections.singletonList(avroFile), "mytable", "mytable");
    File outputFile = new File(
        "pinot-integration-tests/src/test/resources/On_Time_On_Time_Performance_2014_100k_subset.test_queries_10K");
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
      for (int i = 0; i < 10000; i++) {
        Query query = queryGenerator.generateQuery();
        JSONObject queryJson = new JSONObject();
        queryJson.put("pql", query.generatePql());
        queryJson.put("hsqls", new JSONArray(query.generateH2Sql()));
        writer.write(queryJson.toString());
        writer.newLine();
      }
    }
  }

  /**
   * Helper method to read in an Avro file and add data to the storage.
   *
   * @param avroFile Avro file.
   */
  private void addAvroData(File avroFile) {
    // Read in records and update the values stored.
    GenericDatumReader<GenericRecord> datumReader = new GenericDatumReader<>();
    try (DataFileReader<GenericRecord> fileReader = new DataFileReader<>(avroFile, datumReader)) {
      for (GenericRecord genericRecord : fileReader) {
        for (String columnName : _columnNames) {
          Set<String> values = _columnToValueSet.get(columnName);

          // Turn the Avro value into a valid SQL String token.
          Object avroValue = genericRecord.get(columnName);
          if (avroValue != null) {
            Integer storedMaxNumElements = _multiValueColumnMaxNumElements.get(columnName);
            if (storedMaxNumElements != null) {
              // Multi-value column
              GenericData.Array array = (GenericData.Array) avroValue;
              int numElements = array.size();
              if (storedMaxNumElements < numElements) {
                _multiValueColumnMaxNumElements.put(columnName, numElements);
              }
              for (Object element : array) {
                storeAvroValueIntoValueSet(values, element);
              }
            } else {
              // Single-value column
              storeAvroValueIntoValueSet(values, avroValue);
            }
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * Helper method to finish initialization of the QueryGenerator, removing multi-value columns with too
   * many elements and dumping storage into the final map from column name to list of column values.
   *
Called after all Avro data loaded.
   */
  private void prepareToGenerateQueries() {
    Iterator<String> columnNameIterator = _columnNames.iterator();
    while (columnNameIterator.hasNext()) {
      String columnName = columnNameIterator.next();

      // Remove multi-value columns with more than MAX_NUM_ELEMENTS_IN_MULTI_VALUE_TO_COMPARE elements.
      Integer maxNumElements = _multiValueColumnMaxNumElements.get(columnName);
      if (maxNumElements != null
          && maxNumElements > ClusterIntegrationTestUtils.MAX_NUM_ELEMENTS_IN_MULTI_VALUE_TO_COMPARE) {
        columnNameIterator.remove();
        _multiValueColumnMaxNumElements.remove(columnName);
      } else {
        _columnToValueList.put(columnName, new ArrayList<>(_columnToValueSet.get(columnName)));
      }
    }

    // Free the other copy of the data.
    _columnToValueSet.clear();
  }

  /**
   * Set whether to skip predicates on multi-value columns.
   *
   * @param skipMultiValuePredicates whether to skip predicates on multi-value columns.
   */
  public void setSkipMultiValuePredicates(boolean skipMultiValuePredicates) {
    _skipMultiValuePredicates = skipMultiValuePredicates;
  }

  /**
   * Helper method to pick a random value from the values list.
   *
   * @param list values list.
   * @param <T> type of the value.
   * @return randomly picked value.
   */
  private <T> T pickRandom(List<T> list) {
    return list.get(RANDOM.nextInt(list.size()));
  }

  /**
   * Generate one selection or aggregation query.
   *
   * @return generated query.
   */
  public Query generateQuery() {
    return pickRandom(_queryGenerationStrategies).generateQuery();
  }

  /**
   * Helper method to generate a predicate query fragment.
   *
   * @return generated predicate query fragment.
   */
  private PredicateQueryFragment generatePredicate() {
    // Generate at most MAX_NUM_PREDICATES predicates.
    int predicateCount = RANDOM.nextInt(MAX_NUM_PREDICATES + 1);

    List<QueryFragment> predicates = new ArrayList<>(predicateCount);
    while (predicates.size() < predicateCount) {
      String columnName = pickRandom(_columnNames);
      if (!_columnToValueList.get(columnName).isEmpty()) {
        if (!_multiValueColumnMaxNumElements.containsKey(columnName)) {
          // Single-value column.
          predicates.add(pickRandom(_singleValuePredicateGenerators).generatePredicate(columnName));
        } else if (!_skipMultiValuePredicates) {
          // Multi-value column.
          predicates.add(pickRandom(_multiValuePredicateGenerators).generatePredicate(columnName));
        }
      }
    }

    if (predicateCount < 2) {
      // No need to join.
      return new PredicateQueryFragment(predicates, Collections.<QueryFragment>emptyList());
    } else {
      // Join predicates with ANDs and ORs.
      List<QueryFragment> operators = new ArrayList<>(predicateCount - 1);
      for (int i = 1; i < predicateCount; i++) {
        operators.add(new StringQueryFragment(pickRandom(BOOLEAN_OPERATORS)));
      }
      return new PredicateQueryFragment(predicates, operators);
    }
  }

  /**
   * Query interface with capability of generating PQL and H2 SQL query.
   */
  public interface Query {

    /**
     * Generate PQL query.
     *
     * @return generated PQL query.
     */
    String generatePql();

    /**
     * Generate H2 SQL queries equivalent to the PQL query.
     *
     * @return generated H2 SQL queries.
     */
    List<String> generateH2Sql();
  }

  /**
   * Query fragment interface with capability of generating PQL and H2 SQL query fragment.
   */
  private interface QueryFragment {

    /**
     * Generate PQL query fragment.
     *
     * @return generated PQL query fragment.
     */
    String generatePql();

    /**
     * Generate H2 SQL query fragment equivalent to the PQL query fragment.
     *
     * @return generated H2 SQL query fragment.
     */
    String generateH2Sql();
  }

  /**
   * Query generation strategy interface with capability of generating query using specific strategy.
   */
  private interface QueryGenerationStrategy {

    /**
     * Generate a query using specific strategy.
     *
     * @return generated query.
     */
    Query generateQuery();
  }

  /**
   * Predicate generator interface with capability of generating a predicate query fragment on a column.
   */
  private interface PredicateGenerator {

    /**
     * Generate a predicate query fragment on a column.
     *
     * @param columnName column name.
     * @return generated predicate query fragment.
     */
    QueryFragment generatePredicate(String columnName);
  }

  /**
   * Selection query.
   */
  private class SelectionQuery implements Query {
    private final List<String> _projectionColumns;
    private final PredicateQueryFragment _predicate;
    private final OrderByQueryFragment _orderBy;
    private final LimitQueryFragment _limit;

    /**
     * Constructor for SelectionQuery.
     *
     * @param projectionColumns projection columns.
     * @param orderBy order by fragment.
     * @param predicate predicate fragment.
     * @param limit limit fragment.
     */
    public SelectionQuery(List<String> projectionColumns, PredicateQueryFragment predicate,
        OrderByQueryFragment orderBy, LimitQueryFragment limit) {
      _projectionColumns = projectionColumns;
      _orderBy = orderBy;
      _predicate = predicate;
      _limit = limit;
    }

    @Override
    public String generatePql() {
      return joinWithSpaces("SELECT", StringUtils.join(_projectionColumns, ", "), "FROM", _pinotTableName,
          _predicate.generatePql(), _orderBy.generatePql(), _limit.generatePql());
    }

    @Override
    public List<String> generateH2Sql() {
      List<String> h2ProjectionColumns = new ArrayList<>();
      for (String projectionColumn : _projectionColumns) {
        if (_multiValueColumnMaxNumElements.containsKey(projectionColumn)) {
          // Multi-value column.
          for (int i = 0; i < ClusterIntegrationTestUtils.MAX_NUM_ELEMENTS_IN_MULTI_VALUE_TO_COMPARE; i++) {
            h2ProjectionColumns.add(projectionColumn + "__MV" + i);
          }
        } else {
          // Single-value column.
          h2ProjectionColumns.add(projectionColumn);
        }
      }
      return Collections.singletonList(
          joinWithSpaces("SELECT", StringUtils.join(h2ProjectionColumns, ", "), "FROM", _h2TableName,
              _predicate.generateH2Sql(), _orderBy.generateH2Sql(), _limit.generateH2Sql()));
    }
  }

  /**
   * Aggregation query.
   */
  private class AggregationQuery implements Query {
    private List<String> _aggregateColumnsAndFunctions;
    private PredicateQueryFragment _predicate;
    private HavingQueryFragment _havingPredicate;
    private Set<String> _groupColumns;
    private TopQueryFragment _top;

    /**
     * Constructor for AggregationQuery.
     *
     * @param aggregateColumnsAndFunctions aggregation functions.
     * @param predicate predicate fragment.
     * @param groupColumns group-by columns.
     * @param top top fragment.
     */
    public AggregationQuery(List<String> aggregateColumnsAndFunctions, PredicateQueryFragment predicate,
        Set<String> groupColumns, TopQueryFragment top, HavingQueryFragment havingPredicate) {
      _aggregateColumnsAndFunctions = aggregateColumnsAndFunctions;
      _predicate = predicate;
      _groupColumns = groupColumns;
      _top = top;
      _havingPredicate = havingPredicate;
    }

    @Override
    public String generatePql() {
      if (_groupColumns.isEmpty()) {
        return joinWithSpaces("SELECT", StringUtils.join(_aggregateColumnsAndFunctions, ", "), "FROM", _pinotTableName,
            _predicate.generatePql(), _top.generatePql());
      } else {
        String groupByColumns = StringUtils.join(_groupColumns, ", ");

        // TODO: After fixing having clause, we need to add back the having predicate.
        return joinWithSpaces("SELECT", StringUtils.join(_aggregateColumnsAndFunctions, ", "), "FROM", _pinotTableName,
            _predicate.generatePql(), "GROUP BY", StringUtils.join(_groupColumns, ", "), _top.generatePql());
      }
    }

    @Override
    public List<String> generateH2Sql() {
      List<String> queries = new ArrayList<>();

      // For each aggregation function, generate one separate H2 SQL query.
      for (String aggregateColumnAndFunction : _aggregateColumnsAndFunctions) {
        // Make 'AVG' and 'DISTINCTCOUNT' compatible with H2 SQL query.
        if (aggregateColumnAndFunction.startsWith("AVG(")) {
          aggregateColumnAndFunction =
              aggregateColumnAndFunction.replace("AVG(", "AVG(CAST(").replace(")", " AS DOUBLE))");
        } else if (aggregateColumnAndFunction.startsWith("DISTINCTCOUNT(")) {
          aggregateColumnAndFunction = aggregateColumnAndFunction.replace("DISTINCTCOUNT(", "COUNT(DISTINCT ");
        }

        if (_groupColumns.isEmpty()) {
          // Aggregation query.
          queries.add(
              joinWithSpaces("SELECT", aggregateColumnAndFunction, "FROM", _h2TableName, _predicate.generateH2Sql(),
                  _top.generateH2Sql()));
        } else {
          // Group-by query.

          // Unlike PQL, SQL expects the group columns in select statements.
          String groupByColumns = StringUtils.join(_groupColumns, ", ");

          // TODO: After fixing having clause, we need to add back the having predicate.
          queries.add(joinWithSpaces("SELECT", groupByColumns + ",", aggregateColumnAndFunction, "FROM", _h2TableName,
              _predicate.generateH2Sql(), "GROUP BY", groupByColumns, _top.generateH2Sql()));
        }
      }

      return queries;
    }
  }

  /**
   * Most basic query fragment.
   */
  private class StringQueryFragment implements QueryFragment {
    String _pql;
    String _sql;

    /**
     * Constructor for with same PQL and H2 SQL query fragment.
     *
     * @param pql PQL (H2 SQL) query fragment.
     */
    StringQueryFragment(String pql) {
      _pql = pql;
      _sql = pql;
    }

    /**
     * Constructor for StringQueryFragment with different PQL and H2 SQL query fragment.
     *
     * @param pql PQL query fragment.
     * @param sql H2 SQL query fragment.
     */
    StringQueryFragment(String pql, String sql) {
      _pql = pql;
      _sql = sql;
    }

    @Override
    public String generatePql() {
      return _pql;
    }

    @Override
    public String generateH2Sql() {
      return _sql;
    }
  }

  /**
   * Limit query fragment for selection queries.
   *

   *
SELECT ... FROM ... WHERE ... 'LIMIT ...'

   *

   */
  private class LimitQueryFragment extends StringQueryFragment {
    LimitQueryFragment(int limit) {
      // When limit is MAX_RESULT_LIMIT, construct query without LIMIT.
      super(limit == MAX_RESULT_LIMIT ? "" : "LIMIT " + limit,
          "LIMIT " + ClusterIntegrationTestUtils.MAX_NUM_ROWS_TO_COMPARE);
    }
  }

  /**
   * Top query fragment for aggregation queries.
   *

   *
SELECT ... FROM ... WHERE ... 'TOP ...'

   *

   */
  private class TopQueryFragment extends StringQueryFragment {
    TopQueryFragment(int top) {
      // When top is MAX_RESULT_LIMIT, construct query without TOP.
      super(top == MAX_RESULT_LIMIT ? "" : "TOP " + top,
          "LIMIT " + ClusterIntegrationTestUtils.MAX_NUM_ROWS_TO_COMPARE);
    }
  }

  /**
   * Order by query fragment for aggregation queries.
   *

   *
SELECT ... FROM ... WHERE ... 'ORDER BY ...'

   *

   */
  private class OrderByQueryFragment extends StringQueryFragment {
    OrderByQueryFragment(Set<String> columns) {
      super(columns.isEmpty() ? "" : "ORDER BY " + StringUtils.join(columns, ", "));
    }
  }

  /**
   * Predicate query fragment.
   *

   *
SELECT ... FROM ... 'WHERE ...'

   *

   */
  private class PredicateQueryFragment implements QueryFragment {
    List<QueryFragment> _predicates;
    List<QueryFragment> _operators;

    /**
     * Constructor for PredicateQueryFragment.
     *
     * @param predicates predicates.
     * @param operators operators between predicates.
     */
    PredicateQueryFragment(List<QueryFragment> predicates, List<QueryFragment> operators) {
      _predicates = predicates;
      _operators = operators;
    }

    @Override
    public String generatePql() {
      if (_predicates.isEmpty()) {
        return "";
      } else {
        StringBuilder pql = new StringBuilder("WHERE ");

        // One less than the number of predicates.
        int operatorCount = _operators.size();
        for (int i = 0; i < operatorCount; i++) {
          pql.append(_predicates.get(i).generatePql()).append(' ').append(_operators.get(i).generatePql()).append(' ');
        }
        pql.append(_predicates.get(operatorCount).generatePql());

        return pql.toString();
      }
    }

    @Override
    public String generateH2Sql() {
      if (_predicates.isEmpty()) {
        return "";
      } else {
        StringBuilder sql = new StringBuilder("WHERE ");

        // One less than the number of predicates.
        int operatorCount = _operators.size();
        for (int i = 0; i < operatorCount; i++) {
          sql.append(_predicates.get(i).generateH2Sql())
              .append(' ')
              .append(_operators.get(i).generateH2Sql())
              .append(' ');
        }
        sql.append(_predicates.get(operatorCount).generateH2Sql());

        return sql.toString();
      }
    }
  }

  /**
   * Predicate query fragment.
   *

   *
SELECT ... FROM ... 'WHERE ... GROUP BY ... HAVING ...'

   *

   */
  private class HavingQueryFragment implements QueryFragment {
    private List<String> _havingClauseAggregationFunctions;
    private List<String> _havingClauseOperatorsAndValues;
    private List<String> _havingClauseBooleanOperators;

    /**
     * Constructor for PredicateQueryFragment.
     *
     * @param
     * @param
     */
    HavingQueryFragment(List<String> havingClauseAggregationFunctions, List<String> havingClauseOperatorsAndValues,
        List<String> havingClauseBooleanOperators) {
      _havingClauseAggregationFunctions = havingClauseAggregationFunctions;
      _havingClauseOperatorsAndValues = havingClauseOperatorsAndValues;
      _havingClauseBooleanOperators = havingClauseBooleanOperators;
    }

    @Override
    public String generatePql() {
      String pqlHavingClause = "";
      int aggregationFunctionCount = _havingClauseAggregationFunctions.size();
      if (aggregationFunctionCount > 0) {
        pqlHavingClause += "HAVING";
        pqlHavingClause = joinWithSpaces(pqlHavingClause, _havingClauseAggregationFunctions.get(0));
        pqlHavingClause = joinWithSpaces(pqlHavingClause, _havingClauseOperatorsAndValues.get(0));
        for (int i = 1; i < aggregationFunctionCount; i++) {
          pqlHavingClause = joinWithSpaces(pqlHavingClause, _havingClauseBooleanOperators.get(i - 1));
          pqlHavingClause = joinWithSpaces(pqlHavingClause, _havingClauseAggregationFunctions.get(i));
          pqlHavingClause = joinWithSpaces(pqlHavingClause, _havingClauseOperatorsAndValues.get(i));
        }
      }
      return pqlHavingClause;
    }

    @Override
    public String generateH2Sql() {
      String sqlHavingClause = "";
      int aggregationFunctionCount = _havingClauseAggregationFunctions.size();
      if (aggregationFunctionCount > 0) {
        sqlHavingClause += "HAVING";
        String aggregationFunction = _havingClauseAggregationFunctions.get(0);
        if (aggregationFunction.startsWith("AVG(")) {
          aggregationFunction = aggregationFunction.replace("AVG(", "AVG(CAST(").replace(")", " AS DOUBLE))");
        } else if (aggregationFunction.startsWith("DISTINCTCOUNT(")) {
          aggregationFunction = aggregationFunction.replace("DISTINCTCOUNT(", "COUNT(DISTINCT ");
        }
        sqlHavingClause = joinWithSpaces(sqlHavingClause, aggregationFunction);
        sqlHavingClause = joinWithSpaces(sqlHavingClause, _havingClauseOperatorsAndValues.get(0));
        for (int i = 1; i < aggregationFunctionCount; i++) {
          aggregationFunction = _havingClauseAggregationFunctions.get(i);
          if (aggregationFunction.startsWith("AVG(")) {
            aggregationFunction = aggregationFunction.replace("AVG(", "AVG(CAST(").replace(")", " AS DOUBLE))");
          } else if (aggregationFunction.startsWith("DISTINCTCOUNT(")) {
            aggregationFunction = aggregationFunction.replace("DISTINCTCOUNT(", "COUNT(DISTINCT ");
          }
          sqlHavingClause = joinWithSpaces(sqlHavingClause, _havingClauseBooleanOperators.get(i - 1));
          sqlHavingClause = joinWithSpaces(sqlHavingClause, aggregationFunction);
          sqlHavingClause = joinWithSpaces(sqlHavingClause, _havingClauseOperatorsAndValues.get(i));
        }
      }
      return sqlHavingClause;
    }
  }

  /**
   * Strategy to generate selection queries.
   *

   *
SELECT a, b FROM table WHERE a = 'foo' AND b = 'bar' ORDER BY c LIMIT 10

   *

   */
  private class SelectionQueryGenerationStrategy implements QueryGenerationStrategy {

    @Override
    public Query generateQuery() {
      // Select at most MAX_NUM_SELECTION_COLUMNS columns.
      int projectionColumnCount = Math.min(RANDOM.nextInt(MAX_NUM_SELECTION_COLUMNS) + 1, _columnNames.size());
      Set<String> projectionColumns = new HashSet<>();
      while (projectionColumns.size() < projectionColumnCount) {
        projectionColumns.add(pickRandom(_columnNames));
      }

      // Select at most MAX_NUM_ORDER_BY_COLUMNS columns for ORDER BY clause.
      int orderByColumnCount = Math.min(RANDOM.nextInt(MAX_NUM_ORDER_BY_COLUMNS + 1), _singleValueColumnNames.size());
      Set<String> orderByColumns = new HashSet<>();
      while (orderByColumns.size() < orderByColumnCount) {
        orderByColumns.add(pickRandom(_singleValueColumnNames));
      }

      // Generate a predicate.
      PredicateQueryFragment predicate = generatePredicate();

      // Generate a result limit of at most MAX_RESULT_LIMIT columns for ORDER BY clause.
      int resultLimit = RANDOM.nextInt(MAX_RESULT_LIMIT + 1);
      LimitQueryFragment limit = new LimitQueryFragment(resultLimit);

      return new SelectionQuery(new ArrayList<>(projectionColumns), predicate, new OrderByQueryFragment(orderByColumns),
          limit);
    }
  }

  /**
   * Strategy to generate aggregation queries.
   *

   *
SELECT SUM(a), MAX(b) FROM table WHERE a = 'foo' AND b = 'bar' GROUP BY c TOP 10

   *

   */
  private class AggregationQueryGenerationStrategy implements QueryGenerationStrategy {

    @Override
    public Query generateQuery() {
      // Generate at most MAX_NUM_AGGREGATION_COLUMNS columns on which to aggregate, map 0 to 'COUNT(*)'.
      int aggregationColumnCount = RANDOM.nextInt(MAX_NUM_AGGREGATION_COLUMNS + 1);
      Set<String> aggregationColumnsAndFunctions = new HashSet<>();
      if (aggregationColumnCount == 0) {
        aggregationColumnsAndFunctions.add("COUNT(*)");
      } else {
        while (aggregationColumnsAndFunctions.size() < aggregationColumnCount) {
          aggregationColumnsAndFunctions.add(createRandomAggregationFunction());
        }
      }
      // Generate a predicate.
      PredicateQueryFragment predicate = generatePredicate();
      // Generate at most MAX_NUM_GROUP_BY_COLUMNS columns on which to group.
      int groupColumnCount = Math.min(RANDOM.nextInt(MAX_NUM_GROUP_BY_COLUMNS + 1), _singleValueColumnNames.size());
      Set<String> groupColumns = new HashSet<>();
      while (groupColumns.size() < groupColumnCount) {
        groupColumns.add(pickRandom(_singleValueColumnNames));
      }
      //Generate a HAVING predicate
      ArrayList<String> arrayOfAggregationColumnsAndFunctions = new ArrayList<>(aggregationColumnsAndFunctions);
      HavingQueryFragment havingPredicate= generateHavingPredicate(arrayOfAggregationColumnsAndFunctions);
      // Generate a result limit of at most MAX_RESULT_LIMIT.
      TopQueryFragment top = new TopQueryFragment(RANDOM.nextInt(MAX_RESULT_LIMIT + 1));
      return new AggregationQuery(arrayOfAggregationColumnsAndFunctions, predicate, groupColumns, top, havingPredicate);
    }

    /**
     * Helper method to generate a having predicate query fragment.
     *
     * @return generated predicate query fragment.
     */
    private HavingQueryFragment generateHavingPredicate(ArrayList<String> arrayOfAggregationColumnsAndFunctions) {
      //Generate a HAVING clause for group by query
      List<String> havingClauseAggregationFunctions = new ArrayList<String>();
      List<String> havingClauseOperatorsAndValues = new ArrayList<String>();
      List<String> havingClauseBooleanOperators = new ArrayList<String>();
      createHavingClause(arrayOfAggregationColumnsAndFunctions, havingClauseAggregationFunctions,
          havingClauseOperatorsAndValues, havingClauseBooleanOperators);
      return new HavingQueryFragment(havingClauseAggregationFunctions,havingClauseOperatorsAndValues,havingClauseBooleanOperators);
    }

    private void createHavingClause(ArrayList<String> arrayOfAggregationColumnsAndFunctions,
        List<String> havingClauseAggregationFunctions, List<String> havingClauseOperatorsAndValues,
        List<String> havingClauseBooleanOperators) {
      int numOfFunctionsInSelectList = arrayOfAggregationColumnsAndFunctions.size();
      int aggregationFunctionCount = RANDOM.nextInt(numOfFunctionsInSelectList + 1);
      ArrayList<String> aggregationPredicates = new ArrayList<>();
      for (int i = 0; i < aggregationFunctionCount; i++) {
        int aggregationFunctionIndex = RANDOM.nextInt(numOfFunctionsInSelectList);
        String aggregationFunction = arrayOfAggregationColumnsAndFunctions.get(aggregationFunctionIndex);
        havingClauseAggregationFunctions.add(aggregationFunction);
        havingClauseOperatorsAndValues.add(createOperatorAndValueForAggregationFunction(aggregationFunction));
      }
      int aggregationFunctionNotInSelectListCount = RANDOM.nextInt(MAX_NUM_AGGREGATION_COLUMNS + 1);
      for (int i = 0; i < aggregationFunctionNotInSelectListCount; i++) {
        String aggregationFunction = createRandomAggregationFunction();
        havingClauseAggregationFunctions.add(aggregationFunction);
        havingClauseOperatorsAndValues.add(createOperatorAndValueForAggregationFunction(aggregationFunction));
      }
      aggregationFunctionCount += aggregationFunctionNotInSelectListCount;
      for (int i = 1; i < aggregationFunctionCount; i++) {
        havingClauseBooleanOperators.add(pickRandom(BOOLEAN_OPERATORS));
      }
    }

    private String createRandomAggregationFunction() {
      String aggregationFunction = pickRandom(AGGREGATION_FUNCTIONS);
      String aggregationColumn;
      switch (aggregationFunction) {
        // "COUNT" and "DISTINCTCOUNT" support all single-value columns.
        case "COUNT":
        case "DISTINCTCOUNT":
          aggregationColumn = pickRandom(_singleValueColumnNames);
          break;
        // Other functions only support single-value numeric columns.
        default:
          aggregationColumn = pickRandom(_singleValueNumericalColumnNames);
      }
      return aggregationFunction + "(" + aggregationColumn + ")";
    }

    private String createOperatorAndValueForAggregationFunction(String aggregationFunction) {
      boolean comparisonOperatorNotBetweenOrIN = RANDOM.nextBoolean();
      String valueOperator = new String();
      String comparisonOperator = new String();
      if (comparisonOperatorNotBetweenOrIN) {
        String functionValue = new String();
        comparisonOperator = pickRandom(COMPARISON_OPERATORS);
        if (aggregationFunction.startsWith("COUNT") || aggregationFunction.startsWith("DISTINCTCOUNT")) {
          functionValue = Integer.toString(RANDOM.nextInt(MAX_COUNT_FUNCTION_RESULT) + 1);
        } else {
          functionValue = Float.toString(RANDOM.nextFloat() * MAX_FLOAT_FOR_HAVING_CLAUSE_PREDICATE);
        }
        valueOperator = joinWithSpaces(valueOperator, comparisonOperator);
        valueOperator = joinWithSpaces(valueOperator, functionValue);
      } else {
        boolean isItBetween = RANDOM.nextBoolean();
        if (isItBetween) {
          String leftValue = Float.toString(RANDOM.nextFloat() * MAX_FLOAT_FOR_HAVING_CLAUSE_PREDICATE);
          String rightValue = Float.toString(RANDOM.nextFloat() * MAX_FLOAT_FOR_HAVING_CLAUSE_PREDICATE);
          comparisonOperator = "BETWEEN " + leftValue + " AND " + rightValue;
          valueOperator = comparisonOperator;
        } else {
          int numValues = RANDOM.nextInt(MAX_NUM_IN_CLAUSE_VALUES) + 1;
          Set<String> values = new HashSet<>();
          while (values.size() < numValues) {
            values.add(Integer.toString(RANDOM.nextInt(MAX_INT_FOR_HAVING_CLAUSE_PREDICATE)));
          }
          comparisonOperator = StringUtils.join(values, ", ");
          boolean isItIn = RANDOM.nextBoolean();
          if (isItIn) {
            comparisonOperator = "IN (" + comparisonOperator;
            comparisonOperator += ")";
          } else {
            comparisonOperator = "NOT IN (" + comparisonOperator;
            comparisonOperator += ")";
          }
          valueOperator = comparisonOperator;
        }
      }
      return valueOperator;
    }
  }

  /**
   * Generator for single-value column comparison predicate query fragment.
   */
  private class SingleValueComparisonPredicateGenerator implements PredicateGenerator {

    @Override
    public QueryFragment generatePredicate(String columnName) {
      String columnValue = pickRandom(_columnToValueList.get(columnName));
      String comparisonOperator = pickRandom(COMPARISON_OPERATORS);
      return new StringQueryFragment(joinWithSpaces(columnName, comparisonOperator, columnValue));
    }
  }

  /**
   * Generator for single-value column IN predicate query fragment.
   */
  private class SingleValueInPredicateGenerator implements PredicateGenerator {

    @Override
    public QueryFragment generatePredicate(String columnName) {
      List<String> columnValues = _columnToValueList.get(columnName);

      int numValues = Math.min(RANDOM.nextInt(MAX_NUM_IN_CLAUSE_VALUES) + 1, columnValues.size());
      Set<String> values = new HashSet<>();
      while (values.size() < numValues) {
        values.add(pickRandom(columnValues));
      }
      String inValues = StringUtils.join(values, ", ");

      boolean notIn = RANDOM.nextBoolean();
      if (notIn) {
        return new StringQueryFragment(columnName + " NOT IN (" + inValues + ")");
      } else {
        return new StringQueryFragment(columnName + " IN (" + inValues + ")");
      }
    }
  }

  /**
   * Generator for single-value column BETWEEN predicate query fragment.
   */
  private class SingleValueBetweenPredicateGenerator implements PredicateGenerator {

    @Override
    public QueryFragment generatePredicate(String columnName) {
      List<String> columnValues = _columnToValueList.get(columnName);
      String leftValue = pickRandom(columnValues);
      String rightValue = pickRandom(columnValues);
      return new StringQueryFragment(columnName + " BETWEEN " + leftValue + " AND " + rightValue);
    }
  }

  /**
   * Generator for single-value column REGEX predicate query fragment.
   */
  private class SingleValueRegexPredicateGenerator implements PredicateGenerator {
    Random random = new Random();

    @Override
    public QueryFragment generatePredicate(String columnName) {
      List<String> columnValues = _columnToValueList.get(columnName);
      String value;
      value = pickRandom(columnValues);
      StringBuilder pqlRegexBuilder = new StringBuilder();
      StringBuilder sqlRegexBuilder = new StringBuilder();
      // do regex only for string type
      if (value.startsWith("'") && value.endsWith("'")) {
        // replace only one character for now with .* ignore the first and last character
        int indexToReplaceWithRegex = 1 + random.nextInt(value.length() - 2);
        for (int i = 1; i < value.length() - 1; i++) {
          if (i == indexToReplaceWithRegex) {
            pqlRegexBuilder.append(".*");
            sqlRegexBuilder.append(".*");
          } else {
            pqlRegexBuilder.append(value.charAt(i));
            sqlRegexBuilder.append(value.charAt(i));
          }
        }

        String pql = String.format(" REGEXP_LIKE(%s, '%s')", columnName, pqlRegexBuilder.toString());
        String sql = String.format(" REGEXP_LIKE(%s, '%s', 'i')", columnName, sqlRegexBuilder.toString());
        return new StringQueryFragment(pql, sql);
      } else {
        String equalsPredicate = String.format("%s = %s", columnName, value);
        return new StringQueryFragment(equalsPredicate);
      }
    }
  }

  /**
   * Generator for multi-value column comparison predicate query fragment.
   *
DO NOT SUPPORT 'NOT EQUAL'.
   */
  private class MultiValueComparisonPredicateGenerator implements PredicateGenerator {

    @Override
    public QueryFragment generatePredicate(String columnName) {
      String columnValue = pickRandom(_columnToValueList.get(columnName));
      String comparisonOperator = pickRandom(COMPARISON_OPERATORS);

      // Not equal works differently on multi-value, so avoid '<>' comparison.
      while (comparisonOperator.equals("<>")) {
        comparisonOperator = pickRandom(COMPARISON_OPERATORS);
      }

      List<String> h2ComparisonClauses =
          new ArrayList<>(ClusterIntegrationTestUtils.MAX_NUM_ELEMENTS_IN_MULTI_VALUE_TO_COMPARE);
      for (int i = 0; i < ClusterIntegrationTestUtils.MAX_NUM_ELEMENTS_IN_MULTI_VALUE_TO_COMPARE; i++) {
        h2ComparisonClauses.add(joinWithSpaces(columnName + "__MV" + i, comparisonOperator, columnValue));
      }

      return new StringQueryFragment(joinWithSpaces(columnName, comparisonOperator, columnValue),
          "(" + StringUtils.join(h2ComparisonClauses, " OR ") + ")");
    }
  }

  /**
   * Generator for multi-value column IN predicate query fragment.
   *
DO NOT SUPPORT 'NOT IN'.
   */
  private class MultiValueInPredicateGenerator implements PredicateGenerator {

    @Override
    public QueryFragment generatePredicate(String columnName) {
      List<String> columnValues = _columnToValueList.get(columnName);

      int numValues = Math.min(RANDOM.nextInt(MAX_NUM_IN_CLAUSE_VALUES) + 1, columnValues.size());
      Set<String> values = new HashSet<>();
      while (values.size() < numValues) {
        values.add(pickRandom(columnValues));
      }
      String inValues = StringUtils.join(values, ", ");

      List<String> h2InClauses =
          new ArrayList<>(ClusterIntegrationTestUtils.MAX_NUM_ELEMENTS_IN_MULTI_VALUE_TO_COMPARE);
      for (int i = 0; i < ClusterIntegrationTestUtils.MAX_NUM_ELEMENTS_IN_MULTI_VALUE_TO_COMPARE; i++) {
        h2InClauses.add(columnName + "__MV" + i + " IN (" + inValues + ")");
      }

      return new StringQueryFragment(columnName + " IN (" + inValues + ")",
          "(" + StringUtils.join(h2InClauses, " OR ") + ")");
    }
  }

  /**
   * Generator for multi-value column BETWEEN predicate query fragment.
   */
  private class MultiValueBetweenPredicateGenerator implements PredicateGenerator {

    @Override
    public QueryFragment generatePredicate(String columnName) {
      List<String> columnValues = _columnToValueList.get(columnName);
      String leftValue = pickRandom(columnValues);
      String rightValue = pickRandom(columnValues);

      List<String> h2ComparisonClauses =
          new ArrayList<>(ClusterIntegrationTestUtils.MAX_NUM_ELEMENTS_IN_MULTI_VALUE_TO_COMPARE);
      for (int i = 0; i < ClusterIntegrationTestUtils.MAX_NUM_ELEMENTS_IN_MULTI_VALUE_TO_COMPARE; i++) {
        h2ComparisonClauses.add(columnName + "__MV" + i + " BETWEEN " + leftValue + " AND " + rightValue);
      }

      return new StringQueryFragment(columnName + " BETWEEN " + leftValue + " AND " + rightValue,
          "(" + StringUtils.join(h2ComparisonClauses, " OR ") + ")");
    }
  }
}


text:
body{font-family: Geneva, Arial, Helvetica, sans-serif, serif;font-size:12px;line-height:1.5em;background:#A8C05E url(bg.jpg) no-repeat center top;color:#000;}
h1,h2,h3,h4,h5,h6,form,body,dd,dt,dl,li,ul{padding:0;margin:0}
td,th,div{word-break:break-all;word-wrap:break-word}
img{border:0; background:#D7EDE8}
.c{clear:both;height:1px;font:0px/0px Arial;overflow:hidden}
.tal,.tl{text-align:left}
.tac,.tc{text-align:center}
.tar,.tr{text-align:right}
.fr,.right{float:right}
.fl,.left{float:left}
.b{ font-weight:bold}
.tdn{ text-decoration:none}
.small{ font-size:10px;}
.big{ font-size:14px;}
.fsn{ font-size:12px}
.fn{ font-weight:normal}
.lh0{ line-height:0}
.yellow {color:#fff; background:#7EA433}
.gray{ color:#73992C}
.keep{ word-break:keep-all; word-spacing:normal}
.ip{ padding:2px; border:1px solid #fff; background:none}
.bt{background:#D55E9F;color:#fff;font-size:12px;}
/*a link 基本连接颜色*/
a{color:#0C5896}
a:hover{color:#fff; background:#0C5896}
a.noul{ text-decoration:none}
a.active{background:#0C5896; color:#fff}
a.active:hover{color:#0C5896; background:none}

h1{color:#0c2f86;font-size:20px; padding:.6em 0 0; margin-top:2em; }

h2{ font-size:15px; padding:.5em .6em .3em; color:#0c2f86; }
h3{ font-size:14px; color:#000}
h4{ font:16px Georgia; display:inline}
.bb{ border-bottom:1px solid #fff; padding:0 0 .6em; margin:0 0 .3em; line-height:2em;}
#container{ width:96%;margin:0 auto; max-width:900px;}
#header{ height:150px;margin-bottom:1em}
#title{ width:98%; height:120px; margin:auto; overflow:hidden}
#title a{background:#446810; color:#fff}
#guide{ padding:0; margin:0; border-bottom:1px solid #fff; float:left; width:100%;filter:alpha(opacity=90);-moz-opacity:0.9}
#guide li{ display:inline}
#guide li a{ float:left; border:1px solid #fff; border-bottom: 0; background:#D0A5AC; color:#fff; text-decoration:none;display:block; font:13px/1.2em Arial; padding:.4em 1em; margin:0 2px}
#guide li a:hover{ color:#fff;background:#49B9C5;text-decoration:none}
#guide li.active a{background:#0c1966;color:#fff }
#site-dsc{color:#fff;background:#7EA433; float:left; margin-top:.2em}
#toolbar{ margin-top:1em}

#main{ width:73.5%;}
#side{ width:25%;}
.box{ border:1px #fff solid; margin:0 0 .7em;background:url(boxbg.png);width:100%; overflow:hidden; height:auto }
/*for ie 6.0*/
* html #container { width:900px}
* html .box { background:#D5EDE6; filter:alpha(opacity=80);}
* html .profile-pic div{ position:relative}
/*for ie 6.0*/
.text{ margin:.5em 1em 1em;}
#main .text { margin: 1em;}
#side .list { margin:1em .5em 1.5em 2.5em;}
#side .list ul{ margin:0 0 1em 1em}
#side .list ul li{ margin:.5em 0}
#side .list li{ margin:.5em 0}
.profile-pic{margin:0 auto 1em;padding:1px;width:95%;}
.profile-pic div{ margin:0 auto 0;width:100%;padding:0;overflow:hidden;text-align:center;line-height:0}
.profile-pic div img{border:1px solid #ccc;padding:0; margin:0;}
.profile dd{ margin:.3em 0 0; line-height:120%}

/*#calendar */
.calendar table{ width:98%; margin:0 auto 1em; table-layout:fixed}
.calendar table td{ height: 15px;font:11px/150% Tahoma;text-align:center;}
.calendar table th{ text-align: center}
.calendar table td a{color:#fff;font:11px/12px Arial;background:#0C5896;padding:0px 3px 2px}
.calendar table td a:hover{background:#012E53;text-decoration:none}

/*blog*/

.blog-content{ margin:1.5em 0 2em; table-layout:fixed; width:100%; vertical-align:top}
.blog-content td{ font-size:13px; line-height:1.5em;overflow:hidden}
.blog-content td img { padding:5px; border:1px solid #28AFC5; line-height:0}
.blog-content td a:hover img { border-color: #666}

#footer{ margin-top:2em; border-top:1px solid #fff; padding:.5em;}
#footer ul,#footer li { display:inline; list-style:none ; margin:0 0 0 1em}

/*photos-album*/
.pic-list li{ height:50px; width:50px; list-style:none; float:left}
.pic-list li a img{ padding:2px; width:40px; height:40px}
.pic-list li a:hover img { position:absolute; width:79px;height:79px; margin:-20px 0 0 -20px}
.front-cover{ padding:0 1em 2em 0}

/*favorite*/
.fav dl{ margin-bottom:1.5em}
.fav dt{ margin-bottom:.5em}

/*goods*/
.goods-list li{ width:80px; height:80px; text-align:center; line-height:110%; margin:0 .3em 1em }
.goods-list li a:hover img { margin:-20px 0 0 -42px}
.goods-dl { width:400px}
.goods-dl dd{ border-bottom:1px solid #B9E1ED; margin: 0 1em 0 0; line-height:2em}

/*friends*/
.frends-list li{ float:left; width:48%;height:120px; overflow:hidden; margin-left:1%}
.frends-list li a img{ padding:2px; float:left; margin-right:.5em}

/*comment*/
.comment dl{ display:block;clear:both;float:left;margin:.2em 0;border:1px solid #ACB9AC;width:90%;padding:.5em}
.comment dl:hover{border-color:#33994D}
.comment dd{ margin:0 .8em .5em 0;padding:0;line-height:120%;}
.comment dd.comment-content{ margin:1em 0;width:85%;display:block;float:left}
.post-comment{ width:70%;margin: 0 0 1em}
.post-comment div{ margin:0 0 .5em }
.re-comment{ margin:1em 0 0;border:1px solid #ACB9AC ;padding:1em}
.re-comment b{ color:#73992C}
.re-comment div{ margin-top:.5em;}

/*itable*/
.itable td,.itable th{padding:.3em .5em}
.itable td{vertical-align: middle;border-bottom: 1px solid #749D88;}
.itable tr.tr1 td{ background:#749D88;}
.itable td img {border:0;padding:0;background:none}

/*pages*/
.pages{margin-top:10px;margin-bottom:10px;text-align: center ;clear:both}
.pages *{vertical-align: middle;}
.pages a{padding:1px 4px 2px;border:1px solid #fff;margin:0 1px;text-align: center;text-decoration: none;font:normal 10px Tahoma ;}
.pages a:hover{border:#2ABFD5 1px solid;text-decoration:none;}
.pages input{border:1px solid #fff;background:none;height:14px;font: 9px Tahoma;padding-top:1px;text-align: center;}
.pages b{padding:2px ; margin: 0 3px;font:bold  10px/12px Tahoma}

/*menu*/
.menu{position:absolute;background:#fff;border:1px solid $tablecolor;}
.menu td, .menu li,.menu ul{background:#fff;padding:0; margin:0}
.menu li{list-style:none;}
.menu a{display:block;padding:3px 15px 3px 15px;background:#fff;}
.menu a:hover{background:$linkcolor;text-decoration:none;color:#fff;}
.menu ul.ul1 li a{display:inline;padding:0}

.listPic dl{ width:24.5%; float:left; text-align:center; padding:0; margin:.5em 0}
.listPic dt a{ color:#333}
.listPic dd{ padding:0 0 .5em 0; margin:0; text-indent:0; height:90px; vertical-align:middle}
.listPic dd img{ width:85px;height:85px; padding:2px; border:1px solid #eee;}

.listPic1 dl{ width:33%; float:left; text-align:center; padding:0; margin:.5em 0}
.listPic1 dt a{ color:#333}
.listPic1 dd{ padding:0 0 .5em 0; margin:0; text-indent:0; height:55px; vertical-align:middle}
.listPic1 dd img{ width:50px;height:50px; padding:2px; border:1px solid #eee;}
.listPic-albumn dd { height:105px;}
.listPic-albumn dd img { width:90px; height:90px; padding:4px 4px 8px; border:0; background:url(albumn-bg.gif)}

.moduleA{ margin:.2em; border:1px solid #A6CBE7; line-height:110%; border-bottom-color:#66A0CC; border-right-color:#66A0CC;}
.moduleA h3{ color: #0066FF;padding:.5em; margin:0;font-family:Tahoma;font-size:12px;cursor:move }
.tableA { table-layout:fixed}
.tableAtd{ border:1px solid #D4E8F7;height:50px;}
.editButton{ float:right; font:12px/120% Tahoma; color:#CCC; text-decoration:none ; padding-left:0.5em; background:url($imgpath/button_edit.gif) no-repeat 0 .1em}
.editButton:hover{ background-position:.1em .2em}
.editBox{ background:#FFFFCF; margin:0 .2em .2em ; padding:.2em }
.editArea {border:1px solid #eee; width:96%; margin:auto;padding:.2em; background:#fff}
.menu1{position:absolute;border:1px solid #CCCCCC;background:#FFFFFF;z-index:1000;width:200px;height:255px;overflow-Y:auto}
.menu1 h3{background:$headcolor;text-align:left;color:$headfontone;padding:5px 7px 3px 7px;cursor:move}
.menu1 div{padding:5px 10px;}
.checkon{border:1px solid #0A9800;background:#CAFFC0;cursor:move}
.move{position:absolute;}

#colorbox{width:91px;height:78px;padding:3px 0 0 3px;overflow:hidden;}
#colorbox div{cursor:pointer;width:8px;height:8px;float:left;margin:0 3px 3px 0;border:1px #000 solid;font:0/8px arial}

.smile{ height:23px;padding:7px 0 0 8px;text-align:left;background:#E0F0F9 url(th1.png);cursor:move}
.smile div{ width:56px;height:18px;text-align:center;padding:5px 0 0;cursor:pointer;}
.smile div.lian{ background:#ffffff url(tag.jpg) no-repeat;cursor:auto;}

.user-info{ position:absolute;line-height:160%; margin-left:-1.5em; margin-top:-1em}
.user-infoWrap{background:#FFF; border:1px solid #004C7D; border-top:1px #A6CBE7 solid; border-left:1px solid #A6CBE7; padding:.5em 1em; margin-left:20px;display:block;}
.user-info .co{position:absolute; width:10px;height:20px; margin-left:-1.8em; margin-top:2em; background:url(user-info-co.png)}

/*menu_sm*/
.menu_sm{ position:absolute;background:#fffcd9;border-bottom:1px solid #e7d62b; width:100%;}
.menu_sm a{padding:5px 15px 5px 15px;  color:#f79305;}
.menu_sm a:hover{text-decoration:none;color:#fff;}

@media screen and (min-width:0px){
.goods-list li a:hover img{ margin:-20px -20px 0 0}
}

redpajama_set_name: RedPajamaGithub


text:
Pressure Solver

Define the attributes of the pressure-Poisson solver.

type - Specifies the preconditioner - Krylov solver combination, type (string, default=AMG). Values can be one of the following:

AMG - Algebraic multigrid with the conjugate gradient method,

SSORCG - Successive over-relaxation preconditioner with the conjugate gradient method, or

JPCG - Jacobi preconditioner with the conjugate gradient method.

amgpc - Specifies the preconditioner package for the AMG solver, amgpc (string, default=ML). Only effective if type=AMG. Values can be one of the following:

ML - Multilevel preconditioner package, or

HYPRE - Hypre preconditioner package.

hypre_type - Specifies the preconditioner sub-package for the Hypre/AMG solver, hypre_type (string, default=BOOMERAMG). Only effective if type=AMG and amgpc=HYPRE. Values can be one of the following:

BOOMERAMG - BoomerAMG preconditioner.

cycle - Specifies the type of AMG cycle, cycle (string, default=V). Values may be one of the following:

V - Use a V-cycle, or

W - Use a W-cycle.

solver - Specifies the underlying Krylov solver to be used with AMG, solver (string, default=CG). Values can be one of the following:

CG - Conjugate gradient method,

BCGS - Stabilized bi-conjugate gradient squared method, or

FGMRES - Flexible generalized minimum residual method.

pre_smooth - Set the number of pre-smoothing sweeps for AMG, pre_smooth (integer, default=1).

post_smooth - Set the number of post-smoothing sweeps for AMG, pre_smooth (integer, default=1).

levels - Set the maximum number of AMG levels to use in the multigrid cycle, levels (integer, default=20).

nitmax - Set the maximum number of iterations, Nitmax (int, default=500). In the case of AMG, this is the maximum number of V or W cycles.

nitchk - Set the number of iterations to take before checking convergence criteria, Nitchk (int, default=2).

eps - Define the convergence criteria for linear solver, ε (float, default=1.0E-5).

pivot - Specify the value of a zero pivot for preconditioner, pivot (float, default=1.0E-16).

convergence - Enable/disable the convergence metrics for the linear solver, convergence (string, default=Off).

On - Activate convergence output, or

Off - Suppress convergence output.

diagnostics - Enable/disable the diagnostic information from the linear solver, diagnostics (string, default=Off).

On - Activate diagnostic output, or

Off - Suppress diagnostic output.


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.contrib.gis.db.models.fields

class Migration(migrations.Migration):

    dependencies = [
        ('survey', '0003_auto_20141231_1235'),
    ]

    operations = [
        migrations.AlterField(
            model_name='blockface',
            name='geom',
            field=django.contrib.gis.db.models.fields.MultiLineStringField(srid=3857, db_column='the_geom_webmercator'),
        ),
    ]


text:
package openmods.depcheck.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.objectweb.asm.Type;

public enum ElementType {
    FIELD {
        @Override
        public boolean isInClass(Class<?> cls, String name, String desc) {
            try {
                final Field f = cls.getDeclaredField(name);
                final String actualDesc = Type.getDescriptor(f.getType());
                return desc.equals(actualDesc);
            } catch (NoSuchFieldException e) {
                return false;
            }
        }
    },
    METHOD {
        @Override
        public boolean isInClass(Class<?> cls, String name, String desc) {
            for (Method m : cls.getDeclaredMethods())
                if (m.getName().equals(name) &&
                        Type.getMethodDescriptor(m).equals(desc))
                    return true;

            return false;
        }
    };

    public abstract boolean isInClass(Class<?> cls, String name, String desc);
}


text:
package to.kit.drink.controller;

import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import com.google.api.services.drive.model.File;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import to.kit.drink.data.DataAccessor;
import to.kit.drink.data.DataAccessorFactory;
import to.kit.drink.data.TableRecord;
import to.kit.drink.dto.Description;
import to.kit.drink.dto.Item;
import to.kit.drink.dto.ItemRequest;
import to.kit.drink.rest.GaDrive;
import to.kit.util.NameUtils;
import to.kit.util.RomanConverter;
import to.kit.util.SysEnv;

/**
 * アイテムコントローラー.
 * @author Hidetaka Sasai
 */
public class ItemController extends BaseController<ItemRequest> {
	private static final List<String> EXCLUDE_FIELDS =
			Arrays.asList(new String[] {"abv", "id", "fileId", "filtertext", "imgsrc", "kindId", "tags", "thumbnail", "updated", "user"});
	private static final int MAX_NAME_LENGTH = 100;
	private static final int MAX_DESCRIPTION_LENGTH = 200;
	private DataAccessor dao = DataAccessorFactory.getInstance();
	private GaDrive drive = new GaDrive();
	private RomanConverter romanConverter = RomanConverter.getInstance();

	/**
	 * ユーザー情報取得.
	 * @return ユーザー情報
	 */
	private User getUser() {
		if (!SysEnv.isLocal()) {
			UserService service = UserServiceFactory.getUserService();

			return service.getCurrentUser();
		}
		return new User("ぶちきち", "");
	}

	private Item toItem(String lang, Map<String, ?> map) throws Exception {
		Item item = toBean(map, lang, Item.class);
		String tags = StringUtils.defaultString(item.getTags());

		if (StringUtils.isNotBlank(tags)) {
			item.setTagList(Arrays.asList(tags.split(",", -1)));
		}
		TableRecord descriptionTable = read("description", item.getId());
		Description description = toBean(descriptionTable, lang, Description.class);
		String text = StringUtils.defaultString(description.getText());

		if ("null".equals(text)) {
			text = "";
		}
		item.setDescription(text);
		return item;
	}

	private String makeFilter(TableRecord... records) {
		Set<String> wordSet = new HashSet<>();

		for (TableRecord rec : records) {
			for (Map.Entry<String, Object> entry : rec.entrySet()) {
				if (EXCLUDE_FIELDS.contains(entry.getKey())) {
					continue;
				}
				String word = String.valueOf(entry.getValue());

				wordSet.add(NameUtils.toKatakana(word));
				wordSet.add(word.toLowerCase());
			}
		}
		return StringUtils.join(wordSet, "\t");
	}

	private void saveImage(TableRecord rec, ItemRequest form) throws Exception {
		String id = form.getId();
		String text = form.getText();
		String fileId = (String) rec.get("fileId");

		if (StringUtils.isNotBlank(fileId)) {
			this.drive.delete(fileId);
		}
		File file = this.drive.create(id, text, form.getType(), form.getPicture());

		rec.put("fileId", file.getId());
		rec.put("imgsrc", file.getWebContentLink());
		rec.put("thumbnail", file.getThumbnailLink());
	}

	/**
	 * アイテムを保存.
	 * @param form フォーム
	 * @return 保存したアイテム
	 * @throws Exception 例外
	 */
	public Object save(ItemRequest form) throws Exception {
		String lang = form.getLang();
		String id = form.getId();
		String text = StringUtils.left(form.getText(), MAX_NAME_LENGTH);
		byte[] bytes = form.getPicture();
		String descriptionText = StringUtils.left(form.getDescription(), MAX_DESCRIPTION_LENGTH);
		boolean isNew = StringUtils.isBlank(id);
		TableRecord item = read("item", id);
		TableRecord description = read("description", id);

		if (isNew) {
			for (String key : DEFAULT_LANG) {
				item.put(key, text);
			}
		} else {
			item.put(lang, text);
		}
		if (bytes != null && 0 < bytes.length) {
			saveImage(item, form);
		}
		item.put("kindId", form.getKindId());
		item.put("countryCd", form.getCountryCd());
		item.put("abv", form.getAbv());
		item.put("tags", StringUtils.join(form.getTagList(), ','));
		description.put(lang, descriptionText);
		item.put("filtertext", makeFilter(item, description));
		item.put("user", getUser().getEmail());
		item.put("updated", DateFormatUtils.ISO_DATETIME_FORMAT.format(new Date()));
		this.dao.save(item);
		this.dao.save(description);
		item.put("id", item.getKey());
		return toItem(lang, item);
	}

	/**
	 * イメージを取得.
	 * @param path パス
	 * @return バックグラウンドイメージ
	 * @throws Exception 例外
	 */
	public byte[] image(String path) throws Exception {
		byte[] image = null;
		TableRecord table = new TableRecord("item");

		table.setKey(path);
		Map<String, Object> map = this.dao.read(table);
		String imgsrc = (String) map.get("imgsrc");

		if (imgsrc != null && !imgsrc.isEmpty()) {
			byte[] bytes = this.drive.getImage(imgsrc);

			image = bytes;
		}
//		try (InputStream in = ActorController.class.getResourceAsStream(name)) {
//			image = IOUtils.toByteArray(in);
//		} catch (@SuppressWarnings("unused") IOException e) {
//			// nop
//		}
		return image;
	}

	/**
	 * アイテムを取得.
	 * @param form フォーム
	 * @return アイテム
	 * @throws Exception 例外
	 */
	public Object read(ItemRequest form) throws Exception {
		String lang = form.getLang();
		String id = form.getId();
		TableRecord table = read("item", id);

		table.put("id", id);
		Item rec = toItem(lang, table);

		rec.setId(id);
		return rec;
	}

	private String[] makeKeywords(final String keyword) {
		Set<String> set = new HashSet<>();

		if (StringUtils.isNotBlank(keyword)) {
			for (String word : keyword.split("[\\s,]")) {
				String kana = this.romanConverter.convert(word);

				if (StringUtils.isNotBlank(kana)) {
					set.add(NameUtils.toKatakana(kana));
				}
				set.add(NameUtils.toKatakana(word));
				set.add(word);
			}
		}
		return set.toArray(new String[set.size()]);
	}

	/**
	 * アイテム一覧を取得.
	 * @param form フォーム
	 * @return アイテム一覧
	 * @throws Exception 例外
	 */
	public Object list(ItemRequest form) throws Exception {
		List<Item> list = new ArrayList<>();
		String lang = form.getLang();
		List<String> countries = form.getCountries();
		List<String> tagList = form.getTagList();
		String[] keywords = makeKeywords(form.getKeyword());

//System.out.println("Item.list: begin.");
		for (Map<String, Object> map : this.dao.list(new TableRecord("item").addSort("en"))) {
//System.out.print("*filter*");
			Item rec = toItem(lang, map);

			if (!countries.isEmpty() && !countries.contains(rec.getCountryCd())) {
				continue;
			}
			if (!tagList.isEmpty()) {
				boolean isMatch = false;

				for (String tagId : tagList) {
					if (rec.getTags().contains(tagId)) {
						isMatch = true;
						break;
					}
				}
				if (!isMatch) {
					continue;
				}
			}
			String filtertext = StringUtils.defaultString(rec.getFiltertext());
			boolean isMatch = keywords.length == 0;

			for (String word : keywords) {
				if (filtertext.contains(word)) {
					isMatch = true;
					break;
				}
			}
			if (!isMatch) {
				continue;
			}
			list.add(rec);
		}
//System.out.println("Item.list: end.");
		return list;
	}

	/**
	 * 新規作成画面へ.
	 * @param form
	 * @return 転送先画面
	 * @throws Exception 例外
	 */
	public Object create(ItemRequest form) throws Exception {
		User user = getUser();

		if (user == null) {
			UserService service = UserServiceFactory.getUserService();

			return new URL(service.createLoginURL("/item/create"));
		}
		return new URI("/detail.html?lang=" + form.getLang());
	}

	@Override
	public Object execute(ItemRequest form) {
		return null;
	}
}


text:
using namespace std;

struct LogTime {
    string date;
    string time;
public:
    LogTime(const std::string &d, const std::string &t) : date(d), time(t) { }

    bool empty() const {
        return this->date.empty() && this->time.empty();
    }

    bool operator==(const LogTime &val) const {
        if (date.compare(val.date)) {
            return false;
        }
        if (time.compare(val.time)) {
            return false;
        }
        return true;
    }

    bool operator<(const LogTime &val) const {
        int i = date.compare(val.date);
        if (i < 0) {
            return true;
        } else if (i == 0 && time.compare(val.time) < 0) {
            return true;
        }
        return false;
    }

    bool operator>=(const LogTime &val) const {
        return !(*this < val);
    }

    bool operator<=(const LogTime &val) const {
        return *this < val || *this == val;
    }

    static LogTime from(const string &date, const string &time);
};

#endif //WNSLOGHELPER_LOGTIME_H


text:
namespace doanimate {
    namespace shapes {
        nodes::Node* line();

        nodes::Node* polygon();

        nodes::Node* regular_polygon();

        nodes::Node* ellipse();

        nodes::Node* circle();
    }
}
#endif


text:
const jsonSchema = require('../utils/json-schema');
const config = require('../../../../../../shared/config');
const {i18n} = require('../../../../../lib/common');
const errors = require('@tryghost/errors');
const {imageSize, blogIcon} = require('../../../../../lib/image');

const profileImage = (frame) => {
    return imageSize.getImageSizeFromPath(frame.file.path).then((response) => {
        // save the image dimensions in new property for file
        frame.file.dimensions = response;

        // CASE: file needs to be a square
        if (frame.file.dimensions.width !== frame.file.dimensions.height) {
            return Promise.reject(new errors.ValidationError({
                message: i18n.t('errors.api.images.isNotSquare')
            }));
        }
    });
};

const icon = (frame) => {
    const iconExtensions = (config.get('uploads').icons && config.get('uploads').icons.extensions) || [];

    const validIconFileSize = (size) => {
        return (size / 1024) <= 100;
    };

    // CASE: file should not be larger than 100kb
    if (!validIconFileSize(frame.file.size)) {
        return Promise.reject(new errors.ValidationError({
            message: i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions})
        }));
    }

    return blogIcon.getIconDimensions(frame.file.path).then((response) => {
        // save the image dimensions in new property for file
        frame.file.dimensions = response;

        // CASE: file needs to be a square
        if (frame.file.dimensions.width !== frame.file.dimensions.height) {
            return Promise.reject(new errors.ValidationError({
                message: i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions})
            }));
        }

        // CASE: icon needs to be bigger than or equal to 60px
        // .ico files can contain multiple sizes, we need at least a minimum of 60px (16px is ok, as long as 60px are present as well)
        if (frame.file.dimensions.width < 60) {
            return Promise.reject(new errors.ValidationError({
                message: i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions})
            }));
        }

        // CASE: icon needs to be smaller than or equal to 1000px
        if (frame.file.dimensions.width > 1000) {
            return Promise.reject(new errors.ValidationError({
                message: i18n.t('errors.api.icons.invalidFile', {extensions: iconExtensions})
            }));
        }
    });
};

module.exports = {
    upload(apiConfig, frame) {
        return Promise.resolve()
            .then(() => {
                const schema = require('./schemas/images-upload');
                const definitions = require('./schemas/images');
                return jsonSchema.validate(schema, definitions, frame.data);
            })
            .then(() => {
                if (frame.data.purpose === 'profile_image') {
                    return profileImage(frame);
                }
            })
            .then(() => {
                if (frame.data.purpose === 'icon') {
                    return icon(frame);
                }
            });
    }
};


text:
/**
 * Cesium Navigation - https://github.com/alberto-acevedo/cesium-navigation
 *
 * The plugin is 100% based on open source libraries. The same license that applies to Cesiumjs and terriajs applies also to this plugin. Feel free to use it,  modify it, and improve it.
 */


text:
<?php
if(empty($last_winner_script)){
$last_winner_script = 'true';
$qr = "select a.auctionID,username,a.productID as productID,a.categoryID as categoryID,auc_start_price,auc_final_price,auc_start_date,auc_end_date,auc_start_time,auc_end_time,auc_status,auc_type,auc_recurr,buy_user,
        auc_fixed_price,fixedpriceauction,pennyauction,nailbiterauction,offauction,nightauction,openauction,time_duration,auc_final_end_date,total_time,pause_status,shipping_id,future_tstamp,recurr_count,auction_min_price,min_win_price,
        use_free,allowbuynow,buynowprice,reverseauction,uniqueauction,halfbackauction,bidpack,a.tax1,a.tax2,bidpack_name,bidpack_banner,bidpack_price,price,bid_size,freebids ,p.name,p.picture1,short_desc " .
        "from auction a left join products p on a.productID=p.productID left join bidpack b on b.id=a.productID left join registration r on a.buy_user=r.id " .
        "where a.auc_status=3 and auc_final_price not like '0.00' and buy_user!='0' order by a.auc_final_end_date desc limit 0, 1";

$rs = db_query($qr);

$tot = db_num_rows($rs);
echo db_error();
$ob = db_fetch_object($rs);

db_free_result($rs);

if ($tot > 0) {

    $qrytotalbids = "select sum(bid_count) as totalwinnerbid from " . ($ob->use_free == 1 ? "free_account" : "bid_account") .
            " where auction_id=" . $ob->auctionID . " and bid_flag='d' and user_id=" . $ob->buy_user . " group by auction_id";

    $restotalbids = db_query($qrytotalbids);

    $objtotalbids = db_fetch_object($restotalbids);

    db_free_result($restotalbids);
}

	//end latest winner
?>

<?php echo LATEST_WINNERS; ?>

<?
    if ($tot > 0) {
        if ($ob->fixedpriceauction == 1) {
            $fprice1 = $ob->auc_fixed_price;
        } elseif ($ob->offauction == 1) {
            $fprice1 = "0.00";
        } else {
            $fprice1 = $ob->auc_final_price;
        }
        $pname = $ob->bidpack ? $ob->bidpack_name : $ob->name;
        $picture = $ob->bidpack ? $ob->bidpack_banner : $ob->picture1;
        $price = $ob->bidpack ? $ob->bidpack_price : $ob->price;
        if ($price == 0) {
            $saving_percent1 = 100;
        } else {
            $saving_percent1 = ($price - $fprice1) * 100 / $price;
        }

	//////////////////////////////////////////////////////////////////////////////////
	/// Begin Bugfix
	/// Clear Idea Technology
   /// Trent Raber
   /// 2012-05-02
	/// Fix to display the correct info if a bidpack is the auction that was just won
	//////////////////////////////////////////////////////////////////////////////////
	if( $ob->bidpack <= 0 )
	{
		$fAmount = $Currency;
		$fAmount .= number_format($fprice1, 2);

		$sProdLink = "name, $ob->auctionID, 'n')."'>";
		$sProdLink .= "A ".htmlspecialchars(stripcslashes($ob->name), ENT_QUOTES)." ";
		$sProdLink .= "for $fAmount";
	}
	else
	{
		$fAmount = $Currency;
		$fAmount .= number_format($fprice1, 2);

		$sProdLink = "auctionID, 'n')."'>";
		$sProdLink .= "A ".htmlspecialchars(stripcslashes($ob->bidpack_name), ENT_QUOTES)." ";
		$sProdLink .= "for $fAmount";
	}

	//////////////////////////////////////////////////////////////////////////////////
	/// End Bugfix
	//////////////////////////////////////////////////////////////////////////////////

?>

            <a href="<?php echo SEOSupport::getProductUrl($pname, $ob->auctionID, 'n'); ?>"><img src="<?= $UploadImagePath; ?>products/thumbs/thumb_<?= $picture; ?>" border="0" style="border: 1px solid #E39F13;" />

<?php echo CONGRATULATIONS; ?>, <?= $ob->username != "" ? $ob->username . "!" : "---"; ?>

					<?php
					//////////////////////////////////////////////////////////////////////////////////
					/// Begin Bugfix
					/// Clear Idea Technology
					/// Trent Raber
					/// 2012-05-02
					/// Fix to display the correct info if a bidpack is the auction that was just won
					//////////////////////////////////////////////////////////////////////////////////
					echo WHO_JUST_WON." ";
					echo $sProdLink;
					//////////////////////////////////////////////////////////////////////////////////
					/// End Bugfix
					//////////////////////////////////////////////////////////////////////////////////
					?>

<?php echo THAT_S; ?> <?= number_format($saving_percent1, 2); ?>% <?php echo OFF_THE_RETAIL_PRICE; ?>

    <?php } ?>

<?php } ?>


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Catch.Skinning.Default
{
    public class Pulp : Circle
    {
        public readonly Bindable<Color4> AccentColour = new Bindable<Color4>();

        public Pulp()
        {
            RelativePositionAxes = Axes.Both;
            Anchor = Anchor.Centre;
            Origin = Anchor.Centre;

            Blending = BlendingParameters.Additive;
            Colour = Color4.White.Opacity(0.9f);
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            AccentColour.BindValueChanged(updateAccentColour, true);
        }

        private void updateAccentColour(ValueChangedEvent<Color4> colour)
        {
            EdgeEffect = new EdgeEffectParameters
            {
                Type = EdgeEffectType.Glow,
                Radius = DrawWidth / 2,
                Colour = colour.NewValue.Darken(0.2f).Opacity(0.75f)
            };
        }
    }
}


text:
{-# LANGUAGE DataKinds #-}

import GHC.TypeLits
import Numeric.LinearAlgebra.Static
import qualified Numeric.LinearAlgebra.HMatrix as LA

a = row (vec4 1 2 3 4)
u = vec4 10 20 30 40
v = vec2 5 0 & 0 & 3 & 7


text:
<?xml version="1.0" encoding="UTF-8"?>
<tei xmlns="http://www.tei-c.org/ns/1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML">
	<teiHeader>
		<fileDesc>
			<sourceDesc>
				<biblStruct>
					<analytic>
						<author>

 Aus der
						<affiliation>
							<orgName type="institution">Shell Grundlagenforschung-Gesellschaft mbH</orgName>,
							<address>
								<addrLine>SchloR Birlinghoven</addrLine>,
								<settlement>Siegkreis</settlement>
							</address>
						</affiliation>

						</author>
					</analytic>
				</biblStruct>
			</sourceDesc>
		</fileDesc>
	</teiHeader>
</tei>


text:
namespace {

const char kRefreshToken[] = "fake-refresh-token";
// Set managed auth token for Android managed accounts.
const char kManagedAuthToken[] = "managed-auth-token";
// Set unmanaged auth token for other Android unmanaged accounts.
const char kUnmanagedAuthToken[] = "unmanaged-auth-token";
const char kWellKnownConsumerName[] = "test@gmail.com";
const char kFakeUserName[] = "test@example.com";

}  // namespace

namespace arc {

// Base ArcAuthService observer.
class ArcAuthServiceObserver : public ArcAuthService::Observer {
 public:
  // ArcAuthService::Observer:
  ~ArcAuthServiceObserver() override {
    ArcAuthService::Get()->RemoveObserver(this);
  }

  void Wait() {
    run_loop_.reset(new base::RunLoop);
    run_loop_->Run();
    run_loop_.reset();
  }

 protected:
  ArcAuthServiceObserver() { ArcAuthService::Get()->AddObserver(this); }

  std::unique_ptr<base::RunLoop> run_loop_;

 private:
  DISALLOW_COPY_AND_ASSIGN(ArcAuthServiceObserver);
};

// Observer of ArcAuthService state change.
class ArcAuthServiceStateObserver : public ArcAuthServiceObserver {
 public:
  ArcAuthServiceStateObserver() : ArcAuthServiceObserver() {}

  // ArcAuthService::Observer:
  void OnOptInChanged(ArcAuthService::State state) override {
    if (!run_loop_)
      return;
    run_loop_->Quit();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ArcAuthServiceStateObserver);
};

// Observer of ARC bridge shutdown.
class ArcAuthServiceShutdownObserver : public ArcAuthServiceObserver {
 public:
  ArcAuthServiceShutdownObserver() : ArcAuthServiceObserver() {}

  // ArcAuthService::Observer:
  void OnShutdownBridge() override {
    if (!run_loop_)
      return;
    run_loop_->Quit();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ArcAuthServiceShutdownObserver);
};

class ArcAuthServiceTest : public InProcessBrowserTest {
 protected:
  ArcAuthServiceTest() {}

  // InProcessBrowserTest:
  ~ArcAuthServiceTest() override {}

  void SetUpInProcessBrowserTestFixture() override {
    // Start test device management server.
    test_server_.reset(new policy::LocalPolicyTestServer());
    ASSERT_TRUE(test_server_->Start());

    // Specify device management server URL.
    std::string url = test_server_->GetServiceURL().spec();
    base::CommandLine* const command_line =
        base::CommandLine::ForCurrentProcess();
    command_line->AppendSwitchASCII(policy::switches::kDeviceManagementUrl,
                                    url);

    // Enable ARC.
    command_line->AppendSwitch(chromeos::switches::kEnableArc);
    chromeos::FakeSessionManagerClient* const fake_session_manager_client =
        new chromeos::FakeSessionManagerClient;
    fake_session_manager_client->set_arc_available(true);
    chromeos::DBusThreadManager::GetSetterForTesting()->SetSessionManagerClient(
        std::unique_ptr<chromeos::SessionManagerClient>(
            fake_session_manager_client));

    // Mock out ARC bridge.
    fake_arc_bridge_instance_.reset(new FakeArcBridgeInstance);
    ArcServiceManager::SetArcBridgeServiceForTesting(
        base::WrapUnique(new ArcBridgeServiceImpl(base::WrapUnique(
            new FakeArcBridgeBootstrap(fake_arc_bridge_instance_.get())))));
  }

  void SetUpOnMainThread() override {
    user_manager_enabler_.reset(new chromeos::ScopedUserManagerEnabler(
        new chromeos::FakeChromeUserManager));
    // Init ArcAuthService for testing.
    ArcAuthService::DisableUIForTesting();
    ArcAuthService::EnableCheckAndroidManagementForTesting();

    EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());

    // Create test profile.
    TestingProfile::Builder profile_builder;
    profile_builder.SetPath(temp_dir_.path().AppendASCII("TestArcProfile"));
    profile_builder.SetProfileName(kFakeUserName);
    profile_builder.AddTestingFactory(
        ProfileOAuth2TokenServiceFactory::GetInstance(),
        BuildFakeProfileOAuth2TokenService);
    profile_ = profile_builder.Build();
    token_service_ = static_cast<FakeProfileOAuth2TokenService*>(
        ProfileOAuth2TokenServiceFactory::GetForProfile(profile()));
    token_service_->UpdateCredentials("", kRefreshToken);

    profile()->GetPrefs()->SetBoolean(prefs::kArcSignedIn, true);

    const AccountId account_id(
        AccountId::FromUserEmailGaiaId(kFakeUserName, "1234567890"));
    GetFakeUserManager()->AddUser(account_id);
    GetFakeUserManager()->LoginUser(account_id);

    // Set up ARC for test profile.
    ArcServiceManager::Get()->OnPrimaryUserProfilePrepared(
        multi_user_util::GetAccountIdFromProfile(profile()));
    ArcAuthService::Get()->OnPrimaryUserProfilePrepared(profile());
  }

  void TearDownOnMainThread() override {
    ArcAuthService::Get()->Shutdown();
    profile_.reset();
    user_manager_enabler_.reset();
  }

  chromeos::FakeChromeUserManager* GetFakeUserManager() const {
    return static_cast<chromeos::FakeChromeUserManager*>(
        user_manager::UserManager::Get());
  }

  void set_profile_name(const std::string& username) {
    profile_->set_profile_name(username);
  }

  Profile* profile() { return profile_.get(); }

  FakeProfileOAuth2TokenService* token_service() { return token_service_; }

 private:
  std::unique_ptr<policy::LocalPolicyTestServer> test_server_;
  std::unique_ptr<FakeArcBridgeInstance> fake_arc_bridge_instance_;
  std::unique_ptr<chromeos::ScopedUserManagerEnabler> user_manager_enabler_;
  base::ScopedTempDir temp_dir_;
  std::unique_ptr<TestingProfile> profile_;
  FakeProfileOAuth2TokenService* token_service_;

  DISALLOW_COPY_AND_ASSIGN(ArcAuthServiceTest);
};

IN_PROC_BROWSER_TEST_F(ArcAuthServiceTest, ConsumerAccount) {
  PrefService* const prefs = profile()->GetPrefs();
  prefs->SetBoolean(prefs::kArcEnabled, true);
  token_service()->IssueTokenForAllPendingRequests(kUnmanagedAuthToken,
                                                   base::Time::Max());
  ArcAuthServiceStateObserver observer;
  observer.Wait();
  ASSERT_EQ(ArcAuthService::State::ACTIVE, ArcAuthService::Get()->state());
}

IN_PROC_BROWSER_TEST_F(ArcAuthServiceTest, WellKnownConsumerAccount) {
  set_profile_name(kWellKnownConsumerName);
  PrefService* const prefs = profile()->GetPrefs();

  prefs->SetBoolean(prefs::kArcEnabled, true);
  ASSERT_EQ(ArcAuthService::State::ACTIVE, ArcAuthService::Get()->state());
}

IN_PROC_BROWSER_TEST_F(ArcAuthServiceTest, ManagedChromeAccount) {
  policy::ProfilePolicyConnector* const connector =
      policy::ProfilePolicyConnectorFactory::GetForBrowserContext(profile());
  connector->OverrideIsManagedForTesting(true);

  PrefService* const pref = profile()->GetPrefs();

  pref->SetBoolean(prefs::kArcEnabled, true);
  ASSERT_EQ(ArcAuthService::State::ACTIVE, ArcAuthService::Get()->state());
}

IN_PROC_BROWSER_TEST_F(ArcAuthServiceTest, ManagedAndroidAccount) {
  PrefService* const prefs = profile()->GetPrefs();

  prefs->SetBoolean(prefs::kArcEnabled, true);
  token_service()->IssueTokenForAllPendingRequests(kManagedAuthToken,
                                                   base::Time::Max());
  ArcAuthServiceShutdownObserver observer;
  observer.Wait();
  ASSERT_EQ(ArcAuthService::State::STOPPED, ArcAuthService::Get()->state());
}

}  // namespace arc


text:
require 'pact_broker/repositories'
require 'pact_broker/logging'
require 'base64'

module PactBroker

  module Services
    class WebhookService

      extend Repositories
      include Logging

      def self.next_uuid
        SecureRandom.urlsafe_base64
      end

      def self.errors webhook
        contract = PactBroker::Api::Contracts::WebhookContract.new(webhook)
        contract.validate
        contract.errors
      end

      def self.create uuid, webhook, consumer, provider
        webhook_repository.create uuid, webhook, consumer, provider
      end

      def self.find_by_uuid uuid
        webhook_repository.find_by_uuid uuid
      end

      def self.delete_by_uuid uuid
        webhook_repository.delete_by_uuid uuid
      end

      def self.delete_by_pacticipant pacticipant
        webhook_repository.delete_by_pacticipant pacticipant
      end

      def self.find_all
        webhook_repository.find_all
      end

      def self.execute_webhook_now webhook
        webhook.execute
      end

      def self.find_by_consumer_and_provider consumer, provider
        webhook_repository.find_by_consumer_and_provider consumer, provider
      end

      def self.execute_webhooks pact
        webhooks = webhook_repository.find_by_consumer_and_provider pact.consumer, pact.provider
        if webhooks.any?
          run_later(webhooks)
        else
          logger.debug "No webhook found for consumer \"#{pact.consumer.name}\" and provider \"#{pact.provider.name}\""
        end
      end

      # TODO background job?
      def self.run_later webhooks
        Thread.new do
          webhooks.each do | webhook |
            begin
              webhook.execute
            rescue StandardError => e
              # Exceptions are already logged, no need to log again.
            end
          end
        end
      end
    end
  end
end


text:
package androidx.annotation;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.RetentionPolicy.SOURCE;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

/**
 * Denotes that the annotated String element, represents a logical
 * type and that its value should be one of the explicitly named constants.
 *

 * Example:
 *

 *  @Retention(SOURCE)
 *  @StringDef({
 *     POWER_SERVICE,
 *     WINDOW_SERVICE,
 *     LAYOUT_INFLATER_SERVICE
 *  })
 *  public @interface ServiceName {}
 *  public static final String POWER_SERVICE = "power";
 *  public static final String WINDOW_SERVICE = "window";
 *  public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";
 *  ...
 *  public abstract Object getSystemService(@ServiceName String name);
 *

 */
@Retention(SOURCE)
@Target({ANNOTATION_TYPE})
public @interface StringDef {
    /** Defines the allowed constants for this element */
    String[] value() default {};
}


text:
API Reference
=============

Appliance class
---------------

.. autoclass:: askhome.Appliance
    :special-members: __init__
    :members:
    :undoc-members:

Smarthome class
---------------

.. autoclass:: askhome.Smarthome
    :special-members: __init__
    :members:
    :undoc-members:

Requests
--------

.. automodule:: askhome.requests
    :special-members: __init__
    :members:
    :undoc-members:

Exceptions
----------

.. automodule:: askhome.exceptions
    :special-members: __init__
    :members:
    :undoc-members:

Utils
-----

.. automodule:: askhome.utils
    :members:
    :undoc-members:
    :show-inheritance:


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Python: module time</title>

<big><big>time</big></big>	index
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/time.so
Module Docs

<tt>This module provides various functions to manipulate time values.

There are two standard representations of time.  One is the number

of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer

or a floating point number (to represent fractions of seconds).

The Epoch is system-defined; on Unix, it is generally January 1st, 1970.

The actual value can be retrieved by calling gmtime(0).

The other representation is a tuple of 9 integers giving local time.

The tuple items are:

  year (four digits, e.g. 1998)

  month (1-12)

  day (1-31)

  hours (0-23)

  minutes (0-59)

  seconds (0-59)

  weekday (0-6, Monday is 0)

  Julian day (day in the year, 1-366)

  DST (Daylight Savings Time) flag (-1, 0 or 1)

If the DST flag is 0, the time is given in the regular time zone;

if it is 1, the time is given in the DST time zone;

if it is -1, mktime() should guess based on the date and time.

Variables:

timezone -- difference in seconds between UTC and local standard time

altzone -- difference in  seconds between UTC and local DST time

daylight -- whether local time should reflect DST

tzname -- tuple of (standard time zone name, DST time zone name)

Functions:

time() -- return current time in seconds since the Epoch as a float

clock() -- return CPU time since process start as a float

sleep() -- delay for a number of seconds given as a float

gmtime() -- convert seconds since Epoch to UTC tuple

localtime() -- convert seconds since Epoch to local time tuple

asctime() -- convert time tuple to string

ctime() -- convert time in seconds to string

mktime() -- convert local time tuple to seconds since Epoch

strftime() -- convert time tuple to string according to format specification

strptime() -- parse string to time tuple according to format specification

tzset() -- change the local timezone</tt>

<big>Classes</big>

<tt>      </tt>

__builtin__.object

struct_time

class struct_time(__builtin__.object)

<tt>   </tt>
<tt>The time value as returned by gmtime(), localtime(), and strptime(), and

accepted by asctime(), mktime() and strftime().  May be considered as a

sequence of 9 integers.

Note that several fields' values are not the same as those defined by

the C language standard for struct tm.  For example, the value of the

field tm_year is the actual year, not year - 1900.  See individual

fields' descriptions for details.
 </tt>

Methods defined here:

__add__(...)

<tt>x.__add__(y) <==> x+y</tt>

__contains__(...)

<tt>x.__contains__(y) <==> y in x</tt>

__eq__(...)

<tt>x.__eq__(y) <==> x==y</tt>

__ge__(...)

<tt>x.__ge__(y) <==> x>=y</tt>

__getitem__(...)

<tt>x.__getitem__(y) <==> x[y]</tt>

__getslice__(...)

<tt>x.__getslice__(i, j) <==> x[i:j]

Use of negative indices is not supported.</tt>

__gt__(...)

<tt>x.__gt__(y) <==> x>y</tt>

__hash__(...)

<tt>x.__hash__() <==> hash(x)</tt>

__le__(...)

<tt>x.__le__(y) <==> x<=y</tt>

__len__(...)

<tt>x.__len__() <==> len(x)</tt>

__lt__(...)

<tt>x.__lt__(y) <==> x<y</tt>

__mul__(...)

<tt>x.__mul__(n) <==> x*n</tt>

__ne__(...)

<tt>x.__ne__(y) <==> x!=y</tt>

__reduce__(...)

__repr__(...)

<tt>x.__repr__() <==> repr(x)</tt>

__rmul__(...)

<tt>x.__rmul__(n) <==> n*x</tt>

Data descriptors defined here:

tm_hour

<tt>hours, range [0, 23]</tt>

tm_isdst

<tt>1 if summer time is in effect, 0 if not, and -1 if unknown</tt>

tm_mday

<tt>day of month, range [1, 31]</tt>

tm_min

<tt>minutes, range [0, 59]</tt>

tm_mon

<tt>month of year, range [1, 12]</tt>

tm_sec

<tt>seconds, range [0, 61])</tt>

tm_wday

<tt>day of week, range [0, 6], Monday is 0</tt>

tm_yday

<tt>day of year, range [1, 366]</tt>

tm_year

<tt>year, for example, 1993</tt>

Data and other attributes defined here:

__new__ = <built-in method __new__ of type object>
<tt>T.__new__(S, ...) -> a new object with type S, a subtype of T</tt>

n_fields = 9

n_sequence_fields = 9

n_unnamed_fields = 0

<big>Functions</big>

<tt>      </tt>

asctime(...)

<tt>asctime([tuple]) -> string

Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.

When the time tuple is not present, current time as returned by localtime()

is used.</tt>

clock(...)

<tt>clock() -> floating point number

Return the CPU time or real time since the start of the process or since

the first call to clock().  This has as much precision as the system

records.</tt>

ctime(...)

<tt>ctime(seconds) -> string

Convert a time in seconds since the Epoch to a string in local time.

This is equivalent to asctime(localtime(seconds)). When the time tuple is

not present, current time as returned by localtime() is used.</tt>

gmtime(...)

<tt>gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,

                       tm_sec, tm_wday, tm_yday, tm_isdst)

Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.

GMT).  When 'seconds' is not passed in, convert the current time instead.</tt>

localtime(...)

<tt>localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,

                          tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time.

When 'seconds' is not passed in, convert the current time instead.</tt>

mktime(...)

<tt>mktime(tuple) -> floating point number

Convert a time tuple in local time to seconds since the Epoch.</tt>

sleep(...)

<tt>sleep(seconds)

Delay execution for a given number of seconds.  The argument may be

a floating point number for subsecond precision.</tt>

strftime(...)

<tt>strftime(format[, tuple]) -> string

Convert a time tuple to a string according to a format specification.

See the library reference manual for formatting codes. When the time tuple

is not present, current time as returned by localtime() is used.</tt>

strptime(...)

<tt>strptime(string, format) -> struct_time

Parse a string to a time tuple according to a format specification.

See the library reference manual for formatting codes (same as strftime()).</tt>

time(...)

<tt>time() -> floating point number

Return the current time in seconds since the Epoch.

Fractions of a second may be present if the system clock provides them.</tt>

tzset(...)

<tt>tzset()

Initialize, or reinitialize, the local timezone to the value stored in

os.environ['TZ']. The TZ environment variable should be specified in

standard Unix timezone format as documented in the tzset man page

(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently

fall back to UTC. If the TZ environment variable is not set, the local

timezone is set to the systems best guess of wallclock time.

Changing the TZ environment variable without calling tzset *may* change

the local timezone used by methods such as localtime, but this behaviour

should not be relied on.</tt>

<big>Data</big>

<tt>      </tt>
accept2dyear = 1

altzone = 14400

daylight = 1

timezone = 18000

tzname = ('EST', 'EDT')


text:
/* -*- mode: js; js-indent-level: 2; indent-tabs-mode: nil -*- */

'use strict';

// http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#conversion-to-vcard
jQuery.microdata.vcard = function(selector) {
  var $ = jQuery;

  var vcardURI = 'http://microformats.org/profile/hcard';

  function extract($vcard, memory) {
    var output = '';
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#add-a-vcard-line
    function addLine(type, params, value) {
      var line = '';
      line += type.toUpperCase();
      for (var i=0; i<params.length; i++) {
        line += ';';
        line += params[i].name;
        line += '=';
        line += params[i].value;
      }
      line += ':';
      line += value;
      var maxLen = 75;
      while (line.length > maxLen) {
        output += line.substr(0, maxLen);
        line = line.substr(maxLen);
        output += '\r\n ';
        maxLen = 74;
      }
      output += line;
      output += '\r\n';
    }
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#escaping-the-vcard-text-string
    function escapeString(value, chars) {
      var re = new RegExp('(['+(chars||'\\\\,;')+'])', 'g');
      return value.replace(re, '\\$1').replace(/\r\n|\r|\n/g, '\\n');
    }
    addLine('BEGIN', [], 'VCARD');
    addLine('PROFILE', [], 'VCARD');
    addLine('VERSION', [], '3.0');
    addLine('SOURCE', [], escapeString(document.location.href));
    var $title = $('title').first();
    if ($title.length > 0)
      addLine('NAME', [], escapeString($title.text()));
    if ($vcard.itemId())
      addLine('UID', [], escapeString($vcard.itemId()));
    $vcard.properties().each(function() {
      var $prop = $(this);
      $.each($prop.itemProp(), function() {
        var name = this;
        var params = [];
        var value;
        function addParam(n, v) {
          params.push({name:n,value:v});
        }
        function addTypeParam() {
          var $type = $subitem.properties('type').first();
          if ($type.length > 0 && !$type.itemScope() &&
              /^[0-9A-Za-z]*$/.test($type.itemValue()))
            addParam('TYPE', $type.itemValue());
        }
        function escapeProps(name) {
          return $subitem.properties(name)
            .filter(function(){return !$(this).itemScope();})
            .map(function(){return escapeString($(this).itemValue());})
            .toArray().join(',');
        }
        function escapeFirstProp(name) {
          var $first = $subitem.properties(name).first();
          return ($first.length > 0 && !$first.itemScope()) ? escapeString($first.itemValue()) : '';
        }

        if ($prop.itemScope()) {
          var $subitem = $prop;
          if (name == 'n') {
            value = escapeFirstProp('family-name')+';'+
              escapeFirstProp('given-name')+';'+
              escapeFirstProp('additional-name')+';'+
              escapeFirstProp('honorific-prefix')+';'+
              escapeFirstProp('honorific-suffix');
          } else if (name == 'adr') {
            value = escapeProps('post-office-box')+';'+
              escapeProps('extended-address')+';'+
              escapeProps('street-address')+';'+
              escapeFirstProp('locality')+';'+
              escapeFirstProp('region')+';'+
              escapeFirstProp('postal-code')+';'+
              escapeFirstProp('country-name');
            addTypeParam();
          } else if (name == 'org') {
            value = escapeFirstProp('organization-name', $subitem);
            $subitem.properties('organization-unit').each(function() {
              if (!$(this).itemScope())
                value += ';' + escapeString($(this).itemValue());
            });
          } else if (name == 'agent' && $subitem.itemType().contains(vcardURI)) {
            if ($.inArray($subitem[0], memory) != -1) {
              value = 'ERROR';
            } else {
              memory.push($vcard[0]);
              value = escapeString(extract($subitem, memory));
              memory.pop();
            }
            addParam('VALUE', 'VCARD');
          } else {
            // the property's value is an item and name is none of the above
            value = escapeFirstProp('value', $subitem);
            addTypeParam();
          }
        } else {
          // the property's value is not an item
          value = $prop.itemValue();
          var tag = $prop.get(0).tagName.toUpperCase();
          // http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#url-property-elements
          if (/^A|AREA|AUDIO|EMBED|IFRAME|IMG|LINK|OBJECT|SOURCE|TRACK|VIDEO$/.test(tag)) {
            addParam('VALUE', 'URI');
          } else if (tag == 'TIME') {
            if ($.microdata.isValidDateString($prop.itemValue())) {
              addParam('VALUE', 'DATE');
            } else if ($.microdata.isValidGlobalDateAndTimeString($prop.itemValue())) {
              addParam('VALUE', 'DATE-TIME');
            }
          }
          value = escapeString(value, name=='geo'?'\\\\,':'\\\\,;');
        }
        addLine(name, params, value);
      });
    });
    addLine('END', [], 'VCARD');
    return output;
  }

  var $vcard = (selector ?
                $(selector).filter(function() {
                  var $this = $(this);
                  return $this.itemScope() && $this.itemType().contains(vcardURI);
                }) :
                $(document).items(vcardURI)).first();
  if ($vcard.length == 1)
    return extract($vcard, []);
};


text:
/*!
	@file
	@author		Albert Semenov
	@date		01/2009
*/
#ifndef __COMPOUND_H__
#define __COMPOUND_H__

#include "XmlDocument.h"

namespace wrapper
{

	class Compound
	{
	public:
		typedef std::vector<std::string> VectorString;
		typedef std::pair<std::string, std::string> PairString;
		typedef std::vector<PairString> VectorPairString;
		typedef std::vector<Compound*> VectorCompound;
		typedef utility::Enumerator<VectorCompound> Enumerator;

	public:
		Compound() { }

		Compound(xml::ElementPtr _element, const std::string& _type)
		{
			mType = _type;
			mName = getItemName(_element);
			mKind = _element->findAttribute("kind");
			mId = _element->findAttribute("refid");

			xml::ElementEnumerator child_item = _element->getElementEnumerator();
			while (child_item.next())
			{
				if (child_item->getName() == "compound")
					mChilds.push_back(new Compound(child_item.current(), child_item->getName()));
				else if (child_item->getName() == "member")
					mChilds.push_back(new Compound(child_item.current(), child_item->getName()));
			}
		}

		virtual ~Compound()
		{
			Enumerator childs = Enumerator(mChilds.begin(), mChilds.end());
			while (childs.next()) delete childs.current();
			mChilds.clear();
		}

		const std::string& getKind() const
		{
			return mKind;
		}
		const std::string& getName() const
		{
			return mName;
		}
		const std::string& getId() const
		{
			return mId;
		}
		const std::string& getType() const
		{
			return mType;
		}

		Enumerator getEnumerator() const
		{
			return Enumerator(mChilds.begin(), mChilds.end());
		}

	private:
		std::string getItemName(xml::ElementPtr _element)
		{
			xml::ElementEnumerator child_item = _element->getElementEnumerator();
			while (child_item.next("name"))
				return child_item->getContent();
			return "";
		}

	protected:
		std::string mName;
		std::string mKind;
		std::string mId;
		std::string mType;
		VectorCompound mChilds;
	};

} // namespace wrapper

#endif // __COMPOUND_H__