<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// query_metrics_catalog.cpp
//
// Identification: src/catalog/query_metrics_catalog.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "catalog/query_metrics_catalog.h"
#include "catalog/catalog_defaults.h"
#include "common/macros.h"

namespace peloton {
namespace catalog {

QueryMetricsCatalog *QueryMetricsCatalog::GetInstance(
    concurrency::Transaction *txn) {
  static std::unique_ptr<QueryMetricsCatalog> query_metrics_catalog(
      new QueryMetricsCatalog(txn));

  return query_metrics_catalog.get();
}

QueryMetricsCatalog::QueryMetricsCatalog(concurrency::Transaction *txn)
    : AbstractCatalog(QUERY_METRICS_CATALOG_NAME,
                      "CREATE TABLE " CATALOG_DATABASE_NAME
                      "." QUERY_METRICS_CATALOG_NAME
                      " ("
                      "query_name   VARCHAR NOT NULL PRIMARY KEY, "
                      "database_oid INT NOT NULL PRIMARY KEY, "
                      "num_params   INT NOT NULL, "
                      "param_types    VARBINARY, "
                      "param_formats  VARBINARY, "
                      "param_values   VARBINARY, "
                      "reads    INT NOT NULL, "
                      "updates  INT NOT NULL, "
                      "deletes  INT NOT NULL, "
                      "inserts  INT NOT NULL, "
                      "latency  INT NOT NULL, "
                      "cpu_time INT NOT NULL);",
                      txn) {
  // Add secondary index here if necessary
}

QueryMetricsCatalog::~QueryMetricsCatalog() {}

/*@brief   private function for initialize schema of pg_query_metrics
* @return  unqiue pointer to schema
*/
std::unique_ptr<catalog::Schema> QueryMetricsCatalog::InitializeSchema() {
  // convenience variables
  catalog::Constraint not_null_constraint(ConstraintType::NOTNULL, "not_null");
  auto integer_type_size = type::Type::GetTypeSize(type::Type::INTEGER);
  // TODO: not sure if these varchar size is ok, copied from old code
  auto varchar_type_size = type::Type::GetTypeSize(type::Type::VARCHAR);
  auto varbinary_type_size = type::Type::GetTypeSize(type::Type::VARBINARY);

  // Add columns
  // Primary keys
  auto name_column = catalog::Column(type::Type::VARCHAR, varchar_type_size,
                                     "query_name", false);
  name_column.AddConstraint(
      catalog::Constraint(ConstraintType::PRIMARY, "primary_key"));
  name_column.AddConstraint(not_null_constraint);
  auto database_oid_column = catalog::Column(
      type::Type::INTEGER, integer_type_size, "database_oid", true);
  database_oid_column.AddConstraint(
      catalog::Constraint(ConstraintType::PRIMARY, "primary_key"));
  database_oid_column.AddConstraint(not_null_constraint);

  // Parameters
  auto num_params_column = catalog::Column(
      type::Type::INTEGER, integer_type_size, "num_params", true);
  num_params_column.AddConstraint(not_null_constraint);
  // For varbinary types, we don't want to inline it since it could be large
  auto param_types_column = catalog::Column(
      type::Type::VARBINARY, varbinary_type_size, "param_types", false);
  auto param_formats_column = catalog::Column(
      type::Type::VARBINARY, varbinary_type_size, "param_formats", false);
  auto param_values_column = catalog::Column(
      type::Type::VARBINARY, varbinary_type_size, "param_values", false);

  // Physical statistics
  auto reads_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "reads", true);
  reads_column.AddConstraint(not_null_constraint);
  auto updates_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "updates", true);
  updates_column.AddConstraint(not_null_constraint);
  auto deletes_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "deletes", true);
  deletes_column.AddConstraint(not_null_constraint);
  auto inserts_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "inserts", true);
  inserts_column.AddConstraint(not_null_constraint);
  auto latency_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "latency", true);
  latency_column.AddConstraint(not_null_constraint);
  auto cpu_time_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "cpu_time", true);

  // MAX_INT only tracks the number of seconds since epoch until 2037
  auto timestamp_column = catalog::Column(
      type::Type::INTEGER, integer_type_size, "time_stamp", true);
  timestamp_column.AddConstraint(not_null_constraint);

  std::unique_ptr<catalog::Schema> query_metrics_catalog_schema(
      new catalog::Schema({name_column, database_oid_column, num_params_column,
                           param_types_column, param_formats_column,
                           param_values_column, reads_column, updates_column,
                           deletes_column, inserts_column, latency_column,
                           cpu_time_column, timestamp_column}));
  return query_metrics_catalog_schema;
}

bool QueryMetricsCatalog::InsertQueryMetrics(
    const std::string &name, oid_t database_oid, int64_t num_params,
    const stats::QueryMetric::QueryParamBuf &type_buf,
    const stats::QueryMetric::QueryParamBuf &format_buf,
    const stats::QueryMetric::QueryParamBuf &value_buf, int64_t reads,
    int64_t updates, int64_t deletes, int64_t inserts, int64_t latency,
    int64_t cpu_time, int64_t time_stamp, type::AbstractPool *pool,
    concurrency::Transaction *txn) {
  std::unique_ptr<storage::Tuple> tuple(
      new storage::Tuple(catalog_table_->GetSchema(), true));

  auto val0 = type::ValueFactory::GetVarcharValue(name, nullptr);
  auto val1 = type::ValueFactory::GetIntegerValue(database_oid);
  auto val2 = type::ValueFactory::GetIntegerValue(num_params);

  auto val3 = type::ValueFactory::GetNullValueByType(type::Type::VARBINARY);
  auto val4 = type::ValueFactory::GetNullValueByType(type::Type::VARBINARY);
  auto val5 = type::ValueFactory::GetNullValueByType(type::Type::VARBINARY);

  if (num_params != 0) {
    val3 = type::ValueFactory::GetVarbinaryValue(type_buf.buf, type_buf.len,
                                                 false);
    val4 = type::ValueFactory::GetVarbinaryValue(format_buf.buf, format_buf.len,
                                                 false);
    val5 = type::ValueFactory::GetVarbinaryValue(value_buf.buf, value_buf.len,
                                                 false);
  }

  auto val6 = type::ValueFactory::GetIntegerValue(reads);
  auto val7 = type::ValueFactory::GetIntegerValue(updates);
  auto val8 = type::ValueFactory::GetIntegerValue(deletes);
  auto val9 = type::ValueFactory::GetIntegerValue(inserts);
  auto val10 = type::ValueFactory::GetIntegerValue(latency);
  auto val11 = type::ValueFactory::GetIntegerValue(cpu_time);
  auto val12 = type::ValueFactory::GetIntegerValue(time_stamp);

  tuple->SetValue(0, val0, pool);
  tuple->SetValue(1, val1, pool);
  tuple->SetValue(2, val2, pool);
  tuple->SetValue(3, val3, pool);
  tuple->SetValue(4, val4, pool);
  tuple->SetValue(5, val5, pool);
  tuple->SetValue(6, val6, pool);
  tuple->SetValue(7, val7, pool);
  tuple->SetValue(8, val8, pool);
  tuple->SetValue(9, val9, pool);
  tuple->SetValue(10, val10, pool);
  tuple->SetValue(11, val11, pool);
  tuple->SetValue(12, val12, pool);

  // Insert the tuple
  return InsertTuple(std::move(tuple), txn);
}

bool QueryMetricsCatalog::DeleteQueryMetrics(const std::string &name,
                                             oid_t database_oid,
                                             concurrency::Transaction *txn) {
  oid_t index_offset = IndexId::PRIMARY_KEY;  // Primary key index

  std::vector<type::Value> values;
  values.push_back(type::ValueFactory::GetVarcharValue(name, nullptr).Copy());
  values.push_back(type::ValueFactory::GetIntegerValue(database_oid).Copy());

  return DeleteWithIndexScan(index_offset, values, txn);
}

stats::QueryMetric::QueryParamBuf QueryMetricsCatalog::GetParamTypes(
    const std::string &name, oid_t database_oid,
    concurrency::Transaction *txn) {
  std::vector<oid_t> column_ids({ColumnId::PARAM_TYPES});  // param_types
  oid_t index_offset = IndexId::PRIMARY_KEY;               // Primary key index
  std::vector<type::Value> values;
  values.push_back(type::ValueFactory::GetVarcharValue(name, nullptr).Copy());
  values.push_back(type::ValueFactory::GetIntegerValue(database_oid).Copy());

  auto result_tiles =
      GetResultWithIndexScan(column_ids, index_offset, values, txn);

  stats::QueryMetric::QueryParamBuf param_types;
  PL_ASSERT(result_tiles->size() <= 1);  // unique
  if (result_tiles->size() != 0) {
    PL_ASSERT((*result_tiles)[0]->GetTupleCount() <= 1);
    if ((*result_tiles)[0]->GetTupleCount() != 0) {
      param_types = (*result_tiles)[0]
                        ->GetValue(0, 0)
                        .GetAs<stats::QueryMetric::QueryParamBuf>();
    }
  }

  return param_types;
}

int64_t QueryMetricsCatalog::GetNumParams(const std::string &name,
                                          oid_t database_oid,
                                          concurrency::Transaction *txn) {
  std::vector<oid_t> column_ids({ColumnId::NUM_PARAMS});  // num_params
  oid_t index_offset = IndexId::PRIMARY_KEY;              // Primary key index
  std::vector<type::Value> values;
  values.push_back(type::ValueFactory::GetVarcharValue(name, nullptr).Copy());
  values.push_back(type::ValueFactory::GetIntegerValue(database_oid).Copy());

  auto result_tiles =
      GetResultWithIndexScan(column_ids, index_offset, values, txn);

  int64_t num_params = 0;
  PL_ASSERT(result_tiles->size() <= 1);  // unique
  if (result_tiles->size() != 0) {
    PL_ASSERT((*result_tiles)[0]->GetTupleCount() <= 1);
    if ((*result_tiles)[0]->GetTupleCount() != 0) {
      num_params = (*result_tiles)[0]
                       ->GetValue(0, 0)
                       .GetAs<int>();  // After projection left 1 column
    }
  }

  return num_params;
}

}  // End catalog namespace
}  // End peloton namespace
<commit_msg>make example nicer<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// query_metrics_catalog.cpp
//
// Identification: src/catalog/query_metrics_catalog.cpp
//
// Copyright (c) 2015-17, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "catalog/query_metrics_catalog.h"
#include "catalog/catalog_defaults.h"
#include "common/macros.h"

namespace peloton {
namespace catalog {

QueryMetricsCatalog *QueryMetricsCatalog::GetInstance(
    concurrency::Transaction *txn) {
  static std::unique_ptr<QueryMetricsCatalog> query_metrics_catalog(
      new QueryMetricsCatalog(txn));

  return query_metrics_catalog.get();
}

QueryMetricsCatalog::QueryMetricsCatalog(concurrency::Transaction *txn)
    : AbstractCatalog(QUERY_METRICS_CATALOG_NAME,
                      "CREATE TABLE " CATALOG_DATABASE_NAME
                      "." QUERY_METRICS_CATALOG_NAME
                      " ("
                      "query_name   VARCHAR NOT NULL PRIMARY KEY, "
                      "database_oid INT NOT NULL PRIMARY KEY, "
                      "num_params   INT NOT NULL, "
                      "param_types    VARBINARY, "
                      "param_formats  VARBINARY, "
                      "param_values   VARBINARY, "
                      "reads    INT NOT NULL, "
                      "updates  INT NOT NULL, "
                      "deletes  INT NOT NULL, "
                      "inserts  INT NOT NULL, "
                      "latency  INT NOT NULL, "
                      "cpu_time INT NOT NULL);",
                      txn) {
  // Add secondary index here if necessary
}

QueryMetricsCatalog::~QueryMetricsCatalog() {}

/*@brief   private function for initialize schema of pg_query_metrics
* @return  unqiue pointer to schema
*/
std::unique_ptr<catalog::Schema> QueryMetricsCatalog::InitializeSchema() {
  // convenience variables
  catalog::Constraint not_null_constraint(ConstraintType::NOTNULL, "not_null");
  auto integer_type_size = type::Type::GetTypeSize(type::Type::INTEGER);
  auto varchar_type_size = type::Type::GetTypeSize(type::Type::VARCHAR);
  auto varbinary_type_size = type::Type::GetTypeSize(type::Type::VARBINARY);

  // Add columns
  // Primary keys
  auto name_column = catalog::Column(type::Type::VARCHAR, varchar_type_size,
                                     "query_name", false);
  name_column.AddConstraint(
      catalog::Constraint(ConstraintType::PRIMARY, "primary_key"));
  name_column.AddConstraint(not_null_constraint);
  auto database_oid_column = catalog::Column(
      type::Type::INTEGER, integer_type_size, "database_oid", true);
  database_oid_column.AddConstraint(
      catalog::Constraint(ConstraintType::PRIMARY, "primary_key"));
  database_oid_column.AddConstraint(not_null_constraint);

  // Parameters
  auto num_params_column = catalog::Column(
      type::Type::INTEGER, integer_type_size, "num_params", true);
  num_params_column.AddConstraint(not_null_constraint);
  // For varbinary types, we don't want to inline it since it could be large
  auto param_types_column = catalog::Column(
      type::Type::VARBINARY, varbinary_type_size, "param_types", false);
  auto param_formats_column = catalog::Column(
      type::Type::VARBINARY, varbinary_type_size, "param_formats", false);
  auto param_values_column = catalog::Column(
      type::Type::VARBINARY, varbinary_type_size, "param_values", false);

  // Physical statistics
  auto reads_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "reads", true);
  reads_column.AddConstraint(not_null_constraint);
  auto updates_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "updates", true);
  updates_column.AddConstraint(not_null_constraint);
  auto deletes_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "deletes", true);
  deletes_column.AddConstraint(not_null_constraint);
  auto inserts_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "inserts", true);
  inserts_column.AddConstraint(not_null_constraint);
  auto latency_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "latency", true);
  latency_column.AddConstraint(not_null_constraint);
  auto cpu_time_column =
      catalog::Column(type::Type::INTEGER, integer_type_size, "cpu_time", true);

  // MAX_INT only tracks the number of seconds since epoch until 2037
  auto timestamp_column = catalog::Column(
      type::Type::INTEGER, integer_type_size, "time_stamp", true);
  timestamp_column.AddConstraint(not_null_constraint);

  std::unique_ptr<catalog::Schema> query_metrics_catalog_schema(
      new catalog::Schema({name_column, database_oid_column, num_params_column,
                           param_types_column, param_formats_column,
                           param_values_column, reads_column, updates_column,
                           deletes_column, inserts_column, latency_column,
                           cpu_time_column, timestamp_column}));
  return query_metrics_catalog_schema;
}

bool QueryMetricsCatalog::InsertQueryMetrics(
    const std::string &name, oid_t database_oid, int64_t num_params,
    const stats::QueryMetric::QueryParamBuf &type_buf,
    const stats::QueryMetric::QueryParamBuf &format_buf,
    const stats::QueryMetric::QueryParamBuf &value_buf, int64_t reads,
    int64_t updates, int64_t deletes, int64_t inserts, int64_t latency,
    int64_t cpu_time, int64_t time_stamp, type::AbstractPool *pool,
    concurrency::Transaction *txn) {
  std::unique_ptr<storage::Tuple> tuple(
      new storage::Tuple(catalog_table_->GetSchema(), true));

  auto val0 = type::ValueFactory::GetVarcharValue(name, nullptr);
  auto val1 = type::ValueFactory::GetIntegerValue(database_oid);
  auto val2 = type::ValueFactory::GetIntegerValue(num_params);

  auto val3 = type::ValueFactory::GetNullValueByType(type::Type::VARBINARY);
  auto val4 = type::ValueFactory::GetNullValueByType(type::Type::VARBINARY);
  auto val5 = type::ValueFactory::GetNullValueByType(type::Type::VARBINARY);

  if (num_params != 0) {
    val3 = type::ValueFactory::GetVarbinaryValue(type_buf.buf, type_buf.len,
                                                 false);
    val4 = type::ValueFactory::GetVarbinaryValue(format_buf.buf, format_buf.len,
                                                 false);
    val5 = type::ValueFactory::GetVarbinaryValue(value_buf.buf, value_buf.len,
                                                 false);
  }

  auto val6 = type::ValueFactory::GetIntegerValue(reads);
  auto val7 = type::ValueFactory::GetIntegerValue(updates);
  auto val8 = type::ValueFactory::GetIntegerValue(deletes);
  auto val9 = type::ValueFactory::GetIntegerValue(inserts);
  auto val10 = type::ValueFactory::GetIntegerValue(latency);
  auto val11 = type::ValueFactory::GetIntegerValue(cpu_time);
  auto val12 = type::ValueFactory::GetIntegerValue(time_stamp);

  tuple->SetValue(ColumnId::NAME, val0, pool);
  tuple->SetValue(ColumnId::DATABASE_OID, val1, pool);
  tuple->SetValue(ColumnId::NUM_PARAMS, val2, pool);
  tuple->SetValue(ColumnId::PARAM_TYPES, val3, pool);
  tuple->SetValue(ColumnId::PARAM_FORMATS, val4, pool);
  tuple->SetValue(ColumnId::PARAM_VALUES, val5, pool);
  tuple->SetValue(ColumnId::READS, val6, pool);
  tuple->SetValue(ColumnId::UPDATES, val7, pool);
  tuple->SetValue(ColumnId::DELETES, val8, pool);
  tuple->SetValue(ColumnId::INSERTS, val9, pool);
  tuple->SetValue(ColumnId::LATENCY, val10, pool);
  tuple->SetValue(ColumnId::CPU_TIME, val11, pool);
  tuple->SetValue(ColumnId::TIME_STAMP, val12, pool);

  // Insert the tuple
  return InsertTuple(std::move(tuple), txn);
}

bool QueryMetricsCatalog::DeleteQueryMetrics(const std::string &name,
                                             oid_t database_oid,
                                             concurrency::Transaction *txn) {
  oid_t index_offset = IndexId::PRIMARY_KEY;  // Primary key index

  std::vector<type::Value> values;
  values.push_back(type::ValueFactory::GetVarcharValue(name, nullptr).Copy());
  values.push_back(type::ValueFactory::GetIntegerValue(database_oid).Copy());

  return DeleteWithIndexScan(index_offset, values, txn);
}

stats::QueryMetric::QueryParamBuf QueryMetricsCatalog::GetParamTypes(
    const std::string &name, oid_t database_oid,
    concurrency::Transaction *txn) {
  std::vector<oid_t> column_ids({ColumnId::PARAM_TYPES});  // param_types
  oid_t index_offset = IndexId::PRIMARY_KEY;               // Primary key index
  std::vector<type::Value> values;
  values.push_back(type::ValueFactory::GetVarcharValue(name, nullptr).Copy());
  values.push_back(type::ValueFactory::GetIntegerValue(database_oid).Copy());

  auto result_tiles =
      GetResultWithIndexScan(column_ids, index_offset, values, txn);

  stats::QueryMetric::QueryParamBuf param_types;
  PL_ASSERT(result_tiles->size() <= 1);  // unique
  if (result_tiles->size() != 0) {
    PL_ASSERT((*result_tiles)[0]->GetTupleCount() <= 1);
    if ((*result_tiles)[0]->GetTupleCount() != 0) {
      param_types_value = (*result_tiles)[0]->GetValue(0, 0);
      param_types.buf = param_types_value.GetData();
      param_types.len = param_types_value.GetLength();
    }
  }

  return param_types;
}

int64_t QueryMetricsCatalog::GetNumParams(const std::string &name,
                                          oid_t database_oid,
                                          concurrency::Transaction *txn) {
  std::vector<oid_t> column_ids({ColumnId::NUM_PARAMS});  // num_params
  oid_t index_offset = IndexId::PRIMARY_KEY;              // Primary key index
  std::vector<type::Value> values;
  values.push_back(type::ValueFactory::GetVarcharValue(name, nullptr).Copy());
  values.push_back(type::ValueFactory::GetIntegerValue(database_oid).Copy());

  auto result_tiles =
      GetResultWithIndexScan(column_ids, index_offset, values, txn);

  int64_t num_params = 0;
  PL_ASSERT(result_tiles->size() <= 1);  // unique
  if (result_tiles->size() != 0) {
    PL_ASSERT((*result_tiles)[0]->GetTupleCount() <= 1);
    if ((*result_tiles)[0]->GetTupleCount() != 0) {
      num_params = (*result_tiles)[0]
                       ->GetValue(0, 0)
                       .GetAs<int>();  // After projection left 1 column
    }
  }

  return num_params;
}

}  // End catalog namespace
}  // End peloton namespace
<|endoftext|>


<commit_before>// Copyright (c) 2011, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// STL
#include <memory>
#include <string>

// po6
#include <po6/net/ipaddr.h>
#include <po6/net/location.h>

// e
#include <e/convert.h>
#include <e/timer.h>

// HyperDex
#include <hyperclient/client.h>

const char* colnames[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
                          "11", "12", "13", "14", "15", "16", "17", "18", "19",
                          "20", "21", "22", "23", "24", "25", "26", "27", "28",
                          "29", "30", "31", "32"};

static int
usage();

void
handle_put(hyperclient::returncode ret)
{
    if (ret != hyperclient::SUCCESS)
    {
        std::cerr << "Put returned " << ret << "." << std::endl;
    }
}

void
handle_search(size_t* count,
              const e::buffer& expected_key,
              hyperclient::returncode ret,
              const e::buffer& key,
              const std::vector<e::buffer>& value)
{
    ++*count;

    if (*count > 1)
    {
        std::cerr << "Search returned more than 1 result." << std::endl;
    }

    if (expected_key != key)
    {
        std::cerr << "Search returned unexpected key:  " << expected_key.hex()
                  << " != " << key.hex() << std::endl;
    }
}

int
main(int argc, char* argv[])
{
    if (argc != 5)
    {
        return usage();
    }

    po6::net::ipaddr ip;
    uint16_t port;
    std::string space = argv[3];
    uint32_t numbers;

    try
    {
        ip = argv[1];
    }
    catch (std::invalid_argument& e)
    {
        std::cerr << "The IP address must be an IPv4 or IPv6 address." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        port = e::convert::to_uint16_t(argv[2]);
    }
    catch (std::domain_error& e)
    {
        std::cerr << "The port number must be an integer." << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::out_of_range& e)
    {
        std::cerr << "The port number must be suitably small." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        numbers = e::convert::to_uint32_t(argv[4]);
    }
    catch (std::domain_error& e)
    {
        std::cerr << "The number must be an integer." << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::out_of_range& e)
    {
        std::cerr << "The number must be suitably small." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        hyperclient::client cl(po6::net::location(ip, port));
        cl.connect();
        e::buffer one("one", 3);
        e::buffer zero("zero", 3);

        for (uint32_t num = 0; num < numbers; ++num)
        {
            e::buffer key;
            key.pack() << num;
            std::vector<e::buffer> value;

            for (size_t i = 0; i < 32; ++i)
            {
                value.push_back(e::buffer());

                if ((num & (1 << i)))
                {
                    value.back() = one;
                }
                else
                {
                    value.back() = zero;
                }
            }

            cl.put(space, key, value, handle_put);

            if (cl.outstanding() > 1000)
            {
                cl.flush(-1);
            }
        }

        cl.flush(-1);
        e::sleep_ms(1, 0);
        std::cerr << "Starting searches." << std::endl;
        timespec start;
        timespec end;

        clock_gettime(CLOCK_REALTIME, &start);

        for (uint32_t num = 0; num < numbers; ++num)
        {
            e::buffer key;
            key.pack() << num;
            std::map<std::string, e::buffer> search;

            for (size_t i = 0; i < 32; ++i)
            {
                if ((num & (1 << i)))
                {
                    search.insert(std::make_pair(colnames[i], one));
                }
                else
                {
                    search.insert(std::make_pair(colnames[i], zero));
                }
            }

            using std::tr1::bind;
            using std::tr1::placeholders::_1;
            using std::tr1::placeholders::_2;
            using std::tr1::placeholders::_3;
            size_t count = 0;
            cl.search(argv[3], search, std::tr1::bind(handle_search, &count, key, _1, _2, _3));
            cl.flush(-1);
        }

        clock_gettime(CLOCK_REALTIME, &end);
        timespec diff;

        if ((end.tv_nsec < start.tv_nsec) < 0)
        {
            diff.tv_sec = end.tv_sec - start.tv_sec - 1;
            diff.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
        }
        else
        {
            diff.tv_sec = end.tv_sec - start.tv_sec;
            diff.tv_nsec = end.tv_nsec - start.tv_nsec;
        }

        uint64_t nanosecs = diff.tv_sec * 1000000000 + diff.tv_nsec;
        std::cerr << "test took " << nanosecs << " nanoseconds for " << numbers << " searches" << std::endl;
    }
    catch (po6::error& e)
    {
        std::cerr << "There was a system error:  " << e.what();
        return EXIT_FAILURE;
    }
    catch (std::runtime_error& e)
    {
        std::cerr << "There was a runtime error:  " << e.what();
        return EXIT_FAILURE;
    }
    catch (std::bad_alloc& e)
    {
        std::cerr << "There was a memory allocation error:  " << e.what();
        return EXIT_FAILURE;
    }
    catch (std::exception& e)
    {
        std::cerr << "There was a generic error:  " << e.what();
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

int
usage()
{
    std::cerr << "Usage:  binary <coordinator ip> <coordinator port> <space name> <numbers>\n"
              << "This will create <numbers> points whose key is a number [0, <numbers>) and "
              << "then perform searches over the bits of the number.  The space should have 32 "
              << "secondary dimensions so that all bits of a number may be stored."
              << std::endl;
    return EXIT_FAILURE;
}
<commit_msg>Add range query tests to binary-test.<commit_after>// Copyright (c) 2011, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// STL
#include <memory>
#include <string>

// po6
#include <po6/net/ipaddr.h>
#include <po6/net/location.h>

// e
#include <e/convert.h>
#include <e/timer.h>

// HyperDex
#include <hyperclient/client.h>

const char* colnames[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
                          "11", "12", "13", "14", "15", "16", "17", "18", "19",
                          "20", "21", "22", "23", "24", "25", "26", "27", "28",
                          "29", "30", "31", "32"};

static int
usage();

void
handle_put(hyperclient::returncode ret)
{
    if (ret != hyperclient::SUCCESS)
    {
        std::cerr << "Put returned " << ret << "." << std::endl;
    }
}

void
handle_search(size_t* count,
              const e::buffer& expected_key,
              hyperclient::returncode ret,
              const e::buffer& key,
              const std::vector<e::buffer>& value)
{
    ++*count;

    if (*count > 1)
    {
        std::cerr << "Equality returned more than 1 result." << std::endl;
    }

    if (expected_key != key)
    {
        std::cerr << "Equality returned unexpected key:  "
                  << expected_key.size() << ":" << expected_key.hex()
                  << " != " << key.size() << ":" << key.hex() << std::endl;
    }
}

void
handle_range(size_t* count,
             const e::buffer& expected_key,
             hyperclient::returncode ret,
             const e::buffer& key,
             const std::vector<e::buffer>& value)
{
    ++*count;

    if (*count > 1)
    {
        std::cerr << "Range returned more than 1 result." << std::endl;
    }

    if (expected_key != key)
    {
        std::cerr << "Range returned unexpected key:  "
                  << expected_key.size() << ":" << expected_key.hex()
                  << " != " << key.size() << ":" << key.hex() << std::endl;
    }
}

int
main(int argc, char* argv[])
{
    if (argc != 5)
    {
        return usage();
    }

    po6::net::ipaddr ip;
    uint16_t port;
    std::string space = argv[3];
    uint32_t numbers;

    try
    {
        ip = argv[1];
    }
    catch (std::invalid_argument& e)
    {
        std::cerr << "The IP address must be an IPv4 or IPv6 address." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        port = e::convert::to_uint16_t(argv[2]);
    }
    catch (std::domain_error& e)
    {
        std::cerr << "The port number must be an integer." << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::out_of_range& e)
    {
        std::cerr << "The port number must be suitably small." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        numbers = e::convert::to_uint32_t(argv[4]);
    }
    catch (std::domain_error& e)
    {
        std::cerr << "The number must be an integer." << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::out_of_range& e)
    {
        std::cerr << "The number must be suitably small." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        hyperclient::client cl(po6::net::location(ip, port));
        cl.connect();
        e::buffer one("one", 3);
        e::buffer zero("zero", 3);

        for (uint32_t num = 0; num < numbers; ++num)
        {
            e::buffer key;
            key.pack() << num;
            std::vector<e::buffer> value;

            for (size_t i = 0; i < 32; ++i)
            {
                value.push_back(e::buffer());

                if ((num & (1 << i)))
                {
                    value.back() = one;
                }
                else
                {
                    value.back() = zero;
                }
            }

            char buf[4];
            memmove(buf, &num, sizeof(4));
            value.push_back(e::buffer(buf, 4));

            cl.put(space, key, value, handle_put);

            if (cl.outstanding() > 1000)
            {
                cl.flush(-1);
            }
        }

        cl.flush(-1);
        e::sleep_ms(1, 0);
        std::cerr << "Starting searches." << std::endl;
        timespec start;
        timespec end;

        clock_gettime(CLOCK_REALTIME, &start);

        for (uint32_t num = 0; num < numbers; ++num)
        {
            e::buffer key;
            key.pack() << num;
            std::map<std::string, e::buffer> search;

            for (size_t i = 0; i < 32; ++i)
            {
                if ((num & (1 << i)))
                {
                    search.insert(std::make_pair(colnames[i], one));
                }
                else
                {
                    search.insert(std::make_pair(colnames[i], zero));
                }
            }

            using std::tr1::bind;
            using std::tr1::placeholders::_1;
            using std::tr1::placeholders::_2;
            using std::tr1::placeholders::_3;
            size_t count = 0;
            cl.search(argv[3], search, std::tr1::bind(handle_search, &count, key, _1, _2, _3));
            cl.flush(100);

            if (count < 1)
            {
                std::cerr << "Search returned less than 1 result." << std::endl;
            }

            count = 0;
            std::map<std::string, std::pair<uint64_t, uint64_t> > range;
            range.insert(std::make_pair("range", std::make_pair(num, num + 1)));
            cl.search(argv[3], range, std::tr1::bind(handle_range, &count, key, _1, _2, _3));
            cl.flush(100);

            if (count < 1)
            {
                std::cerr << "Range returned less than 1 result." << std::endl;
            }
        }

        clock_gettime(CLOCK_REALTIME, &end);
        timespec diff;

        if ((end.tv_nsec < start.tv_nsec) < 0)
        {
            diff.tv_sec = end.tv_sec - start.tv_sec - 1;
            diff.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
        }
        else
        {
            diff.tv_sec = end.tv_sec - start.tv_sec;
            diff.tv_nsec = end.tv_nsec - start.tv_nsec;
        }

        uint64_t nanosecs = diff.tv_sec * 1000000000 + diff.tv_nsec;
        std::cerr << "test took " << nanosecs << " nanoseconds for " << numbers << " searches" << std::endl;
    }
    catch (po6::error& e)
    {
        std::cerr << "There was a system error:  " << e.what();
        return EXIT_FAILURE;
    }
    catch (std::runtime_error& e)
    {
        std::cerr << "There was a runtime error:  " << e.what();
        return EXIT_FAILURE;
    }
    catch (std::bad_alloc& e)
    {
        std::cerr << "There was a memory allocation error:  " << e.what();
        return EXIT_FAILURE;
    }
    catch (std::exception& e)
    {
        std::cerr << "There was a generic error:  " << e.what();
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

int
usage()
{
    std::cerr << "Usage:  binary <coordinator ip> <coordinator port> <space name> <numbers>\n"
              << "This will create <numbers> points whose key is a number [0, <numbers>) and "
              << "then perform searches over the bits of the number.  The space should have 32 "
              << "secondary dimensions so that all bits of a number may be stored."
              << std::endl;
    return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>/////////////////////////////////////////
//
//             OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////

// Net menu
// Created 12/8/02
// Jason Boettcher

#include "LieroX.h"
#include "sound/SoundsBase.h"
#include "Error.h"
#include "DeprecatedGUI/Menu.h"
#include "GfxPrimitives.h"
#include "DeprecatedGUI/CButton.h"
#include "DeprecatedGUI/CAnimation.h"
#include "DeprecatedGUI/CProgressbar.h"
#include "DeprecatedGUI/CLabel.h"
#include "DeprecatedGUI/CChatWidget.h"
#include "AuxLib.h"
#include "IRC.h"
#include "DedicatedControl.h"
#include "Debug.h"

namespace DeprecatedGUI {

enum {
	mn_Internet=0,
	mn_LAN,
	mn_Host,
	mn_Favourites,
	mn_News,
	mn_Chat,
};

// TODO: remove globals
int		iNetMode = net_main;
int		iHostType = 0;
CButton	cNetButtons[6];
SDL_Rect tLoadingRect;

///////////////////
// Initialize the net menu
bool Menu_NetInitialize(bool withSubMenu)
{
	if(bDedicated) return true; // just ignore

	tMenu->iMenuType = MNU_NETWORK;
	iNetMode = net_main;

	// Add all the network sockets to the notifier groups (for events)
	Menu_EnableNetEvents();

	// Create the buffer
	DrawImage(tMenu->bmpBuffer.get(),tMenu->bmpMainBack_common,0,0);
	if (tMenu->tFrontendInfo.bPageBoxes)
		Menu_DrawBox(tMenu->bmpBuffer.get(), 15,130, 625, 465);
	Menu_DrawSubTitle(tMenu->bmpBuffer.get(),SUB_NETWORK);
	Menu_RedrawMouse(true);

	// Setup the top buttons
	int image_ids[] = {BUT_INTERNET, BUT_LAN, BUT_HOST, BUT_FAVOURITES, BUT_NEWS, BUT_CHAT};
    for(size_t i=0; i < sizeof(image_ids) / sizeof(int); ++i) {
    	cNetButtons[i].setImage(tMenu->bmpButtons);
    	cNetButtons[i].setImageID(image_ids[i]);
        cNetButtons[i].Create();
    }

	cNetButtons[mn_Internet].Setup(mn_Internet, 75, 110, 95, 15);
	cNetButtons[mn_LAN].Setup(mn_LAN, 190, 110, 40, 15);
	cNetButtons[mn_Host].Setup(mn_Host, 255, 110, 50, 15);
	cNetButtons[mn_Favourites].Setup(mn_Favourites, 330, 110, 105, 15);
	cNetButtons[mn_News].Setup(mn_News, 460, 110, 50, 15);
	cNetButtons[mn_Chat].Setup(mn_Chat, 535, 110, 50, 15);
	//cNetButtons[4].Setup(4, 400, 110, 105, 15);

	// Initialize the IRC support
	InitializeIRC();

	// Return back to the menu we came from
	if(withSubMenu)
		switch(tMenu->iReturnTo)  {
		case net_internet:
			Menu_Net_NETInitialize();
			break;
		case net_lan:
			Menu_Net_LANInitialize();
			break;
		case net_favourites:
			Menu_Net_FavouritesInitialize();
			break;
		case net_news:
			Menu_Net_NewsInitialize();
			break;
		case net_chat:
			Menu_Net_ChatInitialize();
			break;
		default:
			Menu_Net_NETInitialize();
		}

	return true;
}

///////////////////
// Go to the host lobby
void Menu_Net_GotoHostLobby()
{
	notes << "Menu_Net_GotoHostLobby" << endl;

	tMenu->iMenuType = MNU_NETWORK;
	iNetMode = net_host;

	if(!bDedicated) {
		// Create the buffer
		DrawImage(tMenu->bmpBuffer.get(),tMenu->bmpMainBack_common,0,0);
		if (tMenu->tFrontendInfo.bPageBoxes)
			Menu_DrawBox(tMenu->bmpBuffer.get(), 15,130, 625, 465);
		Menu_DrawSubTitle(tMenu->bmpBuffer.get(),SUB_NETWORK);
		Menu_RedrawMouse(true);

		cNetButtons[mn_Internet].Setup(mn_Internet, 205, 110, 95, 15);
		cNetButtons[mn_LAN].Setup(mn_LAN, 320, 110, 40, 15);
		cNetButtons[mn_Host].Setup(mn_Host, 385, 110, 50, 15);
		cNetButtons[mn_Favourites].Setup(mn_Favourites, 460, 110, 50, 15);
		//cNetButtons[4].Setup(4, 460, 110, 50, 15);
	}

	Menu_Net_HostGotoLobby();

	SetQuitEngineFlag("Menu_Net_GotoHostLobby");
	iSkipStart = true;
}

///////////////////
// The main net menu frame
void Menu_NetFrame()
{
	int		mouse = 0;
	mouse_t	*Mouse = GetMouse();

	// Refresh the main window of the screen
	//DrawImageAdv(VideoPostProcessor::videoSurface(), tMenu->bmpBuffer, 20,140,  20,140,  620,340);
	//DrawImageAdv(VideoPostProcessor::videoSurface(), tMenu->bmpBuffer, 120,110, 120,110, 420,30);

	// Process the top buttons
	if((iNetMode != net_host || iHostType == 0) &&
	   (iNetMode != net_join)) {

		cNetButtons[iNetMode-1].MouseOver(Mouse);
		for(int i=mn_Internet; i<=mn_Chat && mouse == 0; i++) {

			cNetButtons[i].Draw(VideoPostProcessor::videoSurface());

			if( i == iNetMode-1 )
				continue;

			if( cNetButtons[i].InBox(Mouse->X, Mouse->Y) ) {
				cNetButtons[i].MouseOver(Mouse);
			}

			if( (cNetButtons[i].InBox(Mouse->X, Mouse->Y) && Mouse->Up) ||
				( i == mn_Chat && CChatWidget::GlobalEnabled() && iNetMode != net_chat ) ) {

				CChatWidget::GlobalSetEnabled(false);
				mouse = 1;

				PlaySoundSample(sfxGeneral.smpClick);

				// Call a shutdown on all the highest net menu's
				Menu_Net_MainShutdown();
				Menu_Net_LANShutdown();
				Menu_Net_NETShutdown();
				Menu_Net_HostShutdown();
				Menu_Net_FavouritesShutdown();
				Menu_Net_NewsShutdown();
				Menu_Net_ChatShutdown();

                iNetMode = i+1;

                // Redraw the window section
                DrawImageAdv(VideoPostProcessor::videoSurface(), tMenu->bmpBuffer, 20,140,  20,140,  620,340);

				// Initialize the appropriate menu
				switch(iNetMode) {

					// Main
					case net_main:
						Menu_Net_MainInitialize();
						break;

					// LAN
					case net_lan:
						Menu_Net_LANInitialize();
						break;

					// Internet
					case net_internet:
						Menu_Net_NETInitialize();
						break;

					// Host
					case net_host:
						Menu_Net_HostInitialize();
						break;

					// Favourites
					case net_favourites:
						Menu_Net_FavouritesInitialize();
						break;

					// News
					case net_news:
						Menu_Net_NewsInitialize();
						break;

					// Chat
					case net_chat:
						Menu_Net_ChatInitialize();
						break;
				}
			}
		}
	}

	// Run the frame of the current menu screen
	switch(iNetMode) {

		// Main
		case net_main:
			Menu_Net_MainFrame(mouse);
			break;

		// Internet
		case net_internet:
			Menu_Net_NETFrame(mouse);
			break;

		// LAN
		case net_lan:
			Menu_Net_LANFrame(mouse);
			break;

		// Host
		case net_host:
			Menu_Net_HostFrame(mouse);
			break;

		// Favourites
		case net_favourites:
			Menu_Net_FavouritesFrame(mouse);
			break;

		// Join
		case net_join:
			Menu_Net_JoinFrame(mouse);
			break;

		// News
		case net_news:
			Menu_Net_NewsFrame(mouse);
			break;

		// Chat
		case net_chat:
			Menu_Net_ChatFrame(mouse);
			break;
	}
}

////////////
// Shutdown
void Menu_NetShutdown()
{
	switch(iNetMode) {

		// Main
		case net_main:
			Menu_Net_MainShutdown();
			break;

		// Internet
		case net_internet:
			Menu_Net_NETShutdown();
			break;

		// LAN
		case net_lan:
			Menu_Net_LANShutdown();
			break;

		// Host
		case net_host:
			Menu_Net_HostShutdown();
			break;

		// Favourites
		case net_favourites:
			Menu_Net_FavouritesShutdown();
			break;

		// Join
		case net_join:
			Menu_Net_JoinShutdown();
			break;

		// News
		case net_news:
			Menu_Net_NewsShutdown();
			break;

		// Chat
		case net_chat:
			Menu_Net_ChatShutdown();
			break;
	}

	// Remove all the network sockets from the notifier groups (we don't want any events anymore)
	Menu_DisableNetEvents();
}

void Menu_Net_ServerList_Refresher() {
	if(bDedicated) return; // not needed to do that

	struct Refresher : Action {
		int handle() {
			switch(iNetMode) {
				case net_internet:
					Menu_Net_NET_ServerList_Refresher();
					break;
				case net_lan:
					Menu_Net_LAN_ServerList_Refresher();
					break;
				case net_favourites:
					Menu_Net_Favourites_ServerList_Refresher();
					break;
				default:
					// ignore
					break;
			}
			return 0;
		}
	};
	doActionInMainThread(new Refresher());
}

}; // namespace DeprecatedGUI

///////////////////
// Go to the join lobby
void GotoJoinLobby()
{
    notes << "GotoJoinLobby()" << endl;

	using namespace DeprecatedGUI;

	tMenu->iMenuType = MNU_NETWORK;
	iNetMode = net_join;

	if(!bDedicated) {

		// Create the buffer
		DrawImage(tMenu->bmpBuffer.get(),tMenu->bmpMainBack_common,0,0);
		if (tMenu->tFrontendInfo.bPageBoxes)
			Menu_DrawBox(tMenu->bmpBuffer.get(), 15,130, 625, 465);
		Menu_DrawSubTitle(tMenu->bmpBuffer.get(),SUB_NETWORK);
		Menu_RedrawMouse(true);

		cNetButtons[mn_Internet].Setup(mn_Internet, 205, 110, 95, 15);
		cNetButtons[mn_LAN].Setup(mn_LAN, 320, 110, 40, 15);
		cNetButtons[mn_Host].Setup(mn_Host, 385, 110, 50, 15);
		cNetButtons[mn_Favourites].Setup(mn_Favourites, 460, 110, 50, 15);
		//cNetButtons[4].Setup(4, 460, 110, 50, 15);

		Menu_Net_JoinGotoLobby();
	} else {
		if( DedicatedControl::Get() )
			DedicatedControl::Get()->BackToClientLobby_Signal();
	}

	SetQuitEngineFlag("GotoJoinLobby");
	iSkipStart = true;
}

<commit_msg>small fix: was the wrong thread :p<commit_after>/////////////////////////////////////////
//
//             OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////

// Net menu
// Created 12/8/02
// Jason Boettcher

#include "LieroX.h"
#include "sound/SoundsBase.h"
#include "Error.h"
#include "DeprecatedGUI/Menu.h"
#include "GfxPrimitives.h"
#include "DeprecatedGUI/CButton.h"
#include "DeprecatedGUI/CAnimation.h"
#include "DeprecatedGUI/CProgressbar.h"
#include "DeprecatedGUI/CLabel.h"
#include "DeprecatedGUI/CChatWidget.h"
#include "AuxLib.h"
#include "IRC.h"
#include "DedicatedControl.h"
#include "Debug.h"

namespace DeprecatedGUI {

enum {
	mn_Internet=0,
	mn_LAN,
	mn_Host,
	mn_Favourites,
	mn_News,
	mn_Chat,
};

// TODO: remove globals
int		iNetMode = net_main;
int		iHostType = 0;
CButton	cNetButtons[6];
SDL_Rect tLoadingRect;

///////////////////
// Initialize the net menu
bool Menu_NetInitialize(bool withSubMenu)
{
	if(bDedicated) return true; // just ignore

	tMenu->iMenuType = MNU_NETWORK;
	iNetMode = net_main;

	// Add all the network sockets to the notifier groups (for events)
	Menu_EnableNetEvents();

	// Create the buffer
	DrawImage(tMenu->bmpBuffer.get(),tMenu->bmpMainBack_common,0,0);
	if (tMenu->tFrontendInfo.bPageBoxes)
		Menu_DrawBox(tMenu->bmpBuffer.get(), 15,130, 625, 465);
	Menu_DrawSubTitle(tMenu->bmpBuffer.get(),SUB_NETWORK);
	Menu_RedrawMouse(true);

	// Setup the top buttons
	int image_ids[] = {BUT_INTERNET, BUT_LAN, BUT_HOST, BUT_FAVOURITES, BUT_NEWS, BUT_CHAT};
    for(size_t i=0; i < sizeof(image_ids) / sizeof(int); ++i) {
    	cNetButtons[i].setImage(tMenu->bmpButtons);
    	cNetButtons[i].setImageID(image_ids[i]);
        cNetButtons[i].Create();
    }

	cNetButtons[mn_Internet].Setup(mn_Internet, 75, 110, 95, 15);
	cNetButtons[mn_LAN].Setup(mn_LAN, 190, 110, 40, 15);
	cNetButtons[mn_Host].Setup(mn_Host, 255, 110, 50, 15);
	cNetButtons[mn_Favourites].Setup(mn_Favourites, 330, 110, 105, 15);
	cNetButtons[mn_News].Setup(mn_News, 460, 110, 50, 15);
	cNetButtons[mn_Chat].Setup(mn_Chat, 535, 110, 50, 15);
	//cNetButtons[4].Setup(4, 400, 110, 105, 15);

	// Initialize the IRC support
	InitializeIRC();

	// Return back to the menu we came from
	if(withSubMenu)
		switch(tMenu->iReturnTo)  {
		case net_internet:
			Menu_Net_NETInitialize();
			break;
		case net_lan:
			Menu_Net_LANInitialize();
			break;
		case net_favourites:
			Menu_Net_FavouritesInitialize();
			break;
		case net_news:
			Menu_Net_NewsInitialize();
			break;
		case net_chat:
			Menu_Net_ChatInitialize();
			break;
		default:
			Menu_Net_NETInitialize();
		}

	return true;
}

///////////////////
// Go to the host lobby
void Menu_Net_GotoHostLobby()
{
	notes << "Menu_Net_GotoHostLobby" << endl;

	tMenu->iMenuType = MNU_NETWORK;
	iNetMode = net_host;

	if(!bDedicated) {
		// Create the buffer
		DrawImage(tMenu->bmpBuffer.get(),tMenu->bmpMainBack_common,0,0);
		if (tMenu->tFrontendInfo.bPageBoxes)
			Menu_DrawBox(tMenu->bmpBuffer.get(), 15,130, 625, 465);
		Menu_DrawSubTitle(tMenu->bmpBuffer.get(),SUB_NETWORK);
		Menu_RedrawMouse(true);

		cNetButtons[mn_Internet].Setup(mn_Internet, 205, 110, 95, 15);
		cNetButtons[mn_LAN].Setup(mn_LAN, 320, 110, 40, 15);
		cNetButtons[mn_Host].Setup(mn_Host, 385, 110, 50, 15);
		cNetButtons[mn_Favourites].Setup(mn_Favourites, 460, 110, 50, 15);
		//cNetButtons[4].Setup(4, 460, 110, 50, 15);
	}

	Menu_Net_HostGotoLobby();

	SetQuitEngineFlag("Menu_Net_GotoHostLobby");
	iSkipStart = true;
}

///////////////////
// The main net menu frame
void Menu_NetFrame()
{
	int		mouse = 0;
	mouse_t	*Mouse = GetMouse();

	// Refresh the main window of the screen
	//DrawImageAdv(VideoPostProcessor::videoSurface(), tMenu->bmpBuffer, 20,140,  20,140,  620,340);
	//DrawImageAdv(VideoPostProcessor::videoSurface(), tMenu->bmpBuffer, 120,110, 120,110, 420,30);

	// Process the top buttons
	if((iNetMode != net_host || iHostType == 0) &&
	   (iNetMode != net_join)) {

		cNetButtons[iNetMode-1].MouseOver(Mouse);
		for(int i=mn_Internet; i<=mn_Chat && mouse == 0; i++) {

			cNetButtons[i].Draw(VideoPostProcessor::videoSurface());

			if( i == iNetMode-1 )
				continue;

			if( cNetButtons[i].InBox(Mouse->X, Mouse->Y) ) {
				cNetButtons[i].MouseOver(Mouse);
			}

			if( (cNetButtons[i].InBox(Mouse->X, Mouse->Y) && Mouse->Up) ||
				( i == mn_Chat && CChatWidget::GlobalEnabled() && iNetMode != net_chat ) ) {

				CChatWidget::GlobalSetEnabled(false);
				mouse = 1;

				PlaySoundSample(sfxGeneral.smpClick);

				// Call a shutdown on all the highest net menu's
				Menu_Net_MainShutdown();
				Menu_Net_LANShutdown();
				Menu_Net_NETShutdown();
				Menu_Net_HostShutdown();
				Menu_Net_FavouritesShutdown();
				Menu_Net_NewsShutdown();
				Menu_Net_ChatShutdown();

                iNetMode = i+1;

                // Redraw the window section
                DrawImageAdv(VideoPostProcessor::videoSurface(), tMenu->bmpBuffer, 20,140,  20,140,  620,340);

				// Initialize the appropriate menu
				switch(iNetMode) {

					// Main
					case net_main:
						Menu_Net_MainInitialize();
						break;

					// LAN
					case net_lan:
						Menu_Net_LANInitialize();
						break;

					// Internet
					case net_internet:
						Menu_Net_NETInitialize();
						break;

					// Host
					case net_host:
						Menu_Net_HostInitialize();
						break;

					// Favourites
					case net_favourites:
						Menu_Net_FavouritesInitialize();
						break;

					// News
					case net_news:
						Menu_Net_NewsInitialize();
						break;

					// Chat
					case net_chat:
						Menu_Net_ChatInitialize();
						break;
				}
			}
		}
	}

	// Run the frame of the current menu screen
	switch(iNetMode) {

		// Main
		case net_main:
			Menu_Net_MainFrame(mouse);
			break;

		// Internet
		case net_internet:
			Menu_Net_NETFrame(mouse);
			break;

		// LAN
		case net_lan:
			Menu_Net_LANFrame(mouse);
			break;

		// Host
		case net_host:
			Menu_Net_HostFrame(mouse);
			break;

		// Favourites
		case net_favourites:
			Menu_Net_FavouritesFrame(mouse);
			break;

		// Join
		case net_join:
			Menu_Net_JoinFrame(mouse);
			break;

		// News
		case net_news:
			Menu_Net_NewsFrame(mouse);
			break;

		// Chat
		case net_chat:
			Menu_Net_ChatFrame(mouse);
			break;
	}
}

////////////
// Shutdown
void Menu_NetShutdown()
{
	switch(iNetMode) {

		// Main
		case net_main:
			Menu_Net_MainShutdown();
			break;

		// Internet
		case net_internet:
			Menu_Net_NETShutdown();
			break;

		// LAN
		case net_lan:
			Menu_Net_LANShutdown();
			break;

		// Host
		case net_host:
			Menu_Net_HostShutdown();
			break;

		// Favourites
		case net_favourites:
			Menu_Net_FavouritesShutdown();
			break;

		// Join
		case net_join:
			Menu_Net_JoinShutdown();
			break;

		// News
		case net_news:
			Menu_Net_NewsShutdown();
			break;

		// Chat
		case net_chat:
			Menu_Net_ChatShutdown();
			break;
	}

	// Remove all the network sockets from the notifier groups (we don't want any events anymore)
	Menu_DisableNetEvents();
}

void Menu_Net_ServerList_Refresher() {
	if(bDedicated) return; // not needed to do that

	struct Refresher : Action {
		int handle() {
			switch(iNetMode) {
				case net_internet:
					Menu_Net_NET_ServerList_Refresher();
					break;
				case net_lan:
					Menu_Net_LAN_ServerList_Refresher();
					break;
				case net_favourites:
					Menu_Net_Favourites_ServerList_Refresher();
					break;
				default:
					// ignore
					break;
			}
			return 0;
		}
	};
	mainQueue->push(new Refresher());
}

}; // namespace DeprecatedGUI

///////////////////
// Go to the join lobby
void GotoJoinLobby()
{
    notes << "GotoJoinLobby()" << endl;

	using namespace DeprecatedGUI;

	tMenu->iMenuType = MNU_NETWORK;
	iNetMode = net_join;

	if(!bDedicated) {

		// Create the buffer
		DrawImage(tMenu->bmpBuffer.get(),tMenu->bmpMainBack_common,0,0);
		if (tMenu->tFrontendInfo.bPageBoxes)
			Menu_DrawBox(tMenu->bmpBuffer.get(), 15,130, 625, 465);
		Menu_DrawSubTitle(tMenu->bmpBuffer.get(),SUB_NETWORK);
		Menu_RedrawMouse(true);

		cNetButtons[mn_Internet].Setup(mn_Internet, 205, 110, 95, 15);
		cNetButtons[mn_LAN].Setup(mn_LAN, 320, 110, 40, 15);
		cNetButtons[mn_Host].Setup(mn_Host, 385, 110, 50, 15);
		cNetButtons[mn_Favourites].Setup(mn_Favourites, 460, 110, 50, 15);
		//cNetButtons[4].Setup(4, 460, 110, 50, 15);

		Menu_Net_JoinGotoLobby();
	} else {
		if( DedicatedControl::Get() )
			DedicatedControl::Get()->BackToClientLobby_Signal();
	}

	SetQuitEngineFlag("GotoJoinLobby");
	iSkipStart = true;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>

int main(int argc, char** argv)
{
	std::string cmd_line;
	while(1)
	{
		std::cout << "$ ";
		std::cin >> cmd_line;
		if(cmd_line.find("exit") != -1)
		{
			return 0;
		}
		int pid = fork();
		if(pid == -1)
		{
			perror("fork");
			exit(1);
		}
		else if(pid == 0)
		{
			execvp("cmd_line", argv);
		}
	}
}

<commit_msg>working for standard commands. Added wait(0) to kill child processes<commit_after>#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <errno.h>

int main(int argc, char** argv)
{
	std::string cmd_line;
	while(1)
	{
		std::cout << "$ ";
		std::cin >> cmd_line;
		char* cmd = const_cast<char*>(cmd_line.c_str());
		if(cmd_line == "exit")
		{
			return 0;
		}
		int pid = fork();
		if(pid == 0)
		{
			execvp(cmd, argv);
		}
		else
		{
			if(pid == -1)
			{
				perror("fork");
				exit(1);
			}
			wait(0);
		}
	}
}

<|endoftext|>


<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#include "mfem.hpp"
#include "catch.hpp"

using namespace mfem;

TEST_CASE("H1 Hexahedron Finite Element",
          "[H1_HexahedronElement]"
          "[NodalFiniteElement]"
          "[ScalarFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   H1_HexahedronElement fe(p);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                     );
      REQUIRE( fe.GetGeomType()       == Geometry::CUBE        );
      REQUIRE( fe.GetDof()            == (int)pow(p+1,3)       );
      REQUIRE( fe.GetOrder()          == p                     );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Qk     );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::SCALAR );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::VALUE  );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::GRAD   );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::H_CURL );
   }
}

TEST_CASE("Nedelec Hexahedron Finite Element",
          "[ND_HexahedronElement]"
          "[VectorFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   ND_HexahedronElement fe(p);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                     );
      REQUIRE( fe.GetGeomType()       == Geometry::CUBE        );
      REQUIRE( fe.GetDof()            == 3*p*(int)pow(p+1,2)   );
      REQUIRE( fe.GetOrder()          == p                     );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Qk     );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::H_CURL );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::CURL   );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::H_DIV  );
   }
}

TEST_CASE("Raviart-Thomas Hexahedron Finite Element",
          "[RT_HexahedronElement]"
          "[VectorFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   RT_HexahedronElement fe(p-1);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                       );
      REQUIRE( fe.GetGeomType()       == Geometry::CUBE          );
      REQUIRE( fe.GetDof()            == 3*(p+1)*(int)pow(p,2)   );
      REQUIRE( fe.GetOrder()          == p                       );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Qk       );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::VECTOR   );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::H_DIV    );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::DIV      );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::SCALAR   );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::INTEGRAL );
   }
}

TEST_CASE("L2 Hexahedron Finite Element",
          "[L2_HexahedronElement]"
          "[NodalFiniteElement]"
          "[ScalarFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   L2_HexahedronElement fe(p);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                     );
      REQUIRE( fe.GetGeomType()       == Geometry::CUBE        );
      REQUIRE( fe.GetDof()            == (int)pow(p+1,3)       );
      REQUIRE( fe.GetOrder()          == p                     );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Qk     );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::SCALAR );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::VALUE  );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::GRAD   );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::H_CURL );
   }
}
<commit_msg>Adding unit tests for H1 and L2 bases on Prisms<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License (as published by the Free
// Software Foundation) version 2.1 dated February 1999.

#include "mfem.hpp"
#include "catch.hpp"

using namespace mfem;

TEST_CASE("H1 Hexahedron Finite Element",
          "[H1_HexahedronElement]"
          "[NodalFiniteElement]"
          "[ScalarFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   H1_HexahedronElement fe(p);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                     );
      REQUIRE( fe.GetGeomType()       == Geometry::CUBE        );
      REQUIRE( fe.GetDof()            == (int)pow(p+1,3)       );
      REQUIRE( fe.GetOrder()          == p                     );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Qk     );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::SCALAR );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::VALUE  );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::GRAD   );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::H_CURL );
   }
}

TEST_CASE("Nedelec Hexahedron Finite Element",
          "[ND_HexahedronElement]"
          "[VectorFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   ND_HexahedronElement fe(p);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                     );
      REQUIRE( fe.GetGeomType()       == Geometry::CUBE        );
      REQUIRE( fe.GetDof()            == 3*p*(int)pow(p+1,2)   );
      REQUIRE( fe.GetOrder()          == p                     );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Qk     );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::H_CURL );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::CURL   );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::H_DIV  );
   }
}

TEST_CASE("Raviart-Thomas Hexahedron Finite Element",
          "[RT_HexahedronElement]"
          "[VectorFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   RT_HexahedronElement fe(p-1);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                       );
      REQUIRE( fe.GetGeomType()       == Geometry::CUBE          );
      REQUIRE( fe.GetDof()            == 3*(p+1)*(int)pow(p,2)   );
      REQUIRE( fe.GetOrder()          == p                       );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Qk       );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::VECTOR   );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::H_DIV    );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::DIV      );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::SCALAR   );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::INTEGRAL );
   }
}

TEST_CASE("L2 Hexahedron Finite Element",
          "[L2_HexahedronElement]"
          "[NodalFiniteElement]"
          "[ScalarFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   L2_HexahedronElement fe(p);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                     );
      REQUIRE( fe.GetGeomType()       == Geometry::CUBE        );
      REQUIRE( fe.GetDof()            == (int)pow(p+1,3)       );
      REQUIRE( fe.GetOrder()          == p                     );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Qk     );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::SCALAR );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::VALUE  );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::GRAD   );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::H_CURL );
   }
}

TEST_CASE("H1 Wedge Finite Element",
          "[H1_WedgeElement]"
          "[NodalFiniteElement]"
          "[ScalarFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   H1_WedgeElement fe(p);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                      );
      REQUIRE( fe.GetGeomType()       == Geometry::PRISM        );
      REQUIRE( fe.GetDof()            == (int)pow(p+1,2)*(p+2)/2);
      REQUIRE( fe.GetOrder()          == p                      );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Qk     );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::SCALAR );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::VALUE  );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::GRAD   );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::H_CURL );
   }
}

TEST_CASE("Nedelec Wedge Finite Element",
          "[ND_WedgeElement]"
          "[VectorFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   ND_WedgeElement fe(p);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                     );
      REQUIRE( fe.GetGeomType()       == Geometry::PRISM       );
      REQUIRE( fe.GetDof()            == 3*p*(p+1)*(p+2)/2     );
      REQUIRE( fe.GetOrder()          == p                     );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Pk     );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::H_CURL );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::CURL   );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::H_DIV  );
   }
}

TEST_CASE("Raviart-Thomas Wedge Finite Element",
          "[RT_WedgeElement]"
          "[VectorFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   RT_WedgeElement fe(p-1);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                       );
      REQUIRE( fe.GetGeomType()       == Geometry::PRISM         );
      REQUIRE( fe.GetDof()            == (int)pow(p+1,2)*p/2 +
               /*                     */ (int)pow(p,2)*(p+2)     );
      REQUIRE( fe.GetOrder()          == p                       );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Pk       );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::VECTOR   );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::H_DIV    );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::DIV      );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::SCALAR   );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::INTEGRAL );
   }
}

TEST_CASE("L2 Wedge Finite Element",
          "[L2_WedgeElement]"
          "[NodalFiniteElement]"
          "[ScalarFiniteElement]"
          "[FiniteElement]")
{
   int p = 1;

   L2_WedgeElement fe(p);

   SECTION("Attributes")
   {
      REQUIRE( fe.GetDim()            == 3                      );
      REQUIRE( fe.GetGeomType()       == Geometry::PRISM        );
      REQUIRE( fe.GetDof()            == (int)pow(p+1,2)*(p+2)/2);
      REQUIRE( fe.GetOrder()          == p                      );
      REQUIRE( fe.Space()             == (int) FunctionSpace::Qk     );
      REQUIRE( fe.GetRangeType()      == (int) FiniteElement::SCALAR );
      REQUIRE( fe.GetMapType()        == (int) FiniteElement::VALUE  );
      REQUIRE( fe.GetDerivType()      == (int) FiniteElement::GRAD   );
      REQUIRE( fe.GetDerivRangeType() == (int) FiniteElement::VECTOR );
      REQUIRE( fe.GetDerivMapType()   == (int) FiniteElement::H_CURL );
   }
}
<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright 2014 Cloudius Systems
 */

#define BOOST_TEST_MODULE core

#include <boost/test/included/unit_test.hpp>
#include <seastar/core/sstring.hh>
#include <list>

using namespace seastar;

BOOST_AUTO_TEST_CASE(test_construction) {
    BOOST_REQUIRE_EQUAL(sstring(compat::string_view("abc")), sstring("abc"));
}

BOOST_AUTO_TEST_CASE(test_equality) {
    BOOST_REQUIRE_EQUAL(sstring("aaa"), sstring("aaa"));
}

BOOST_AUTO_TEST_CASE(test_to_sstring) {
    BOOST_REQUIRE_EQUAL(to_sstring(1234567), sstring("1234567"));
}

BOOST_AUTO_TEST_CASE(test_add_literal_to_sstring) {
    BOOST_REQUIRE_EQUAL("x" + sstring("y"), sstring("xy"));
}

BOOST_AUTO_TEST_CASE(test_find_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").find('b'), 1u);
    BOOST_REQUIRE_EQUAL(sstring("babcde").find('b',1), 2u);
}

BOOST_AUTO_TEST_CASE(test_not_find_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").find('x'), sstring::npos);
}

BOOST_AUTO_TEST_CASE(test_str_find_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").find("bc"), 1u);
    BOOST_REQUIRE_EQUAL(sstring("abcbcde").find("bc", 2), 3u);
}

BOOST_AUTO_TEST_CASE(test_str_not_find_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").find("x"), sstring::npos);
}

BOOST_AUTO_TEST_CASE(test_substr_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").substr(1,2), "bc");
    BOOST_REQUIRE_EQUAL(sstring("abc").substr(1,2), "bc");
    BOOST_REQUIRE_EQUAL(sstring("abc").substr(1,3), "bc");
    BOOST_REQUIRE_EQUAL(sstring("abc").substr(0, 2), "ab");
    BOOST_REQUIRE_EQUAL(sstring("abc").substr(3, 2), "");
    BOOST_REQUIRE_EQUAL(sstring("abc").substr(1), "bc");
}

BOOST_AUTO_TEST_CASE(test_substr_eor_sstring) {
    BOOST_REQUIRE_THROW(sstring("abcde").substr(6,1), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(test_at_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").at(1), 'b');
    BOOST_REQUIRE_THROW(sstring("abcde").at(6), std::out_of_range);
    sstring s("abcde");
    s.at(1) = 'd';
    BOOST_REQUIRE_EQUAL(s, "adcde");
}

BOOST_AUTO_TEST_CASE(test_find_last_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("ababa").find_last_of('a'), 4u);
    BOOST_REQUIRE_EQUAL(sstring("ababa").find_last_of('a',5), 4u);
    BOOST_REQUIRE_EQUAL(sstring("ababa").find_last_of('a',4), 4u);
    BOOST_REQUIRE_EQUAL(sstring("ababa").find_last_of('a',3), 2u);
    BOOST_REQUIRE_EQUAL(sstring("ababa").find_last_of('x'), sstring::npos);
    BOOST_REQUIRE_EQUAL(sstring("").find_last_of('a'), sstring::npos);
}

BOOST_AUTO_TEST_CASE(test_append) {
    BOOST_REQUIRE_EQUAL(sstring("aba").append("1234", 3), "aba123");
    BOOST_REQUIRE_EQUAL(sstring("aba").append("1234", 4), "aba1234");
    BOOST_REQUIRE_EQUAL(sstring("aba").append("1234", 0), "aba");
}

BOOST_AUTO_TEST_CASE(test_replace) {
    BOOST_REQUIRE_EQUAL(sstring("abc").replace(1,1, "xyz", 1), "axc");
    BOOST_REQUIRE_EQUAL(sstring("abc").replace(3,2, "xyz", 2), "abcxy");
    BOOST_REQUIRE_EQUAL(sstring("abc").replace(2,2, "xyz", 2), "abxy");
    BOOST_REQUIRE_EQUAL(sstring("abc").replace(0,2, "", 0), "c");
    BOOST_REQUIRE_THROW(sstring("abc").replace(4,1, "xyz", 1), std::out_of_range);
    const char* s = "xyz";
    sstring str("abcdef");
    BOOST_REQUIRE_EQUAL(str.replace(str.begin() + 1 , str.begin() + 3, s + 1, s + 3), "ayzdef");
    BOOST_REQUIRE_THROW(sstring("abc").replace(4,1, "xyz", 1), std::out_of_range);

}

BOOST_AUTO_TEST_CASE(test_insert) {
    sstring str("abc");
    const char* s = "xyz";
    str.insert(str.begin() +1, s + 1, s + 2);
    BOOST_REQUIRE_EQUAL(str, "aybc");
    str = "abc";
    BOOST_REQUIRE_THROW(str.insert(str.begin() + 5, s + 1, s + 2), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(test_erase) {
    sstring str("abcdef");
    auto i = str.erase(str.begin() + 1, str.begin() + 3);
    BOOST_REQUIRE_EQUAL(*i, 'd');
    BOOST_REQUIRE_EQUAL(str, "adef");
    BOOST_REQUIRE_THROW(str.erase(str.begin() + 5, str.begin() + 6), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(test_ctor_iterator) {
    std::list<char> data{{'a', 'b', 'c'}};
    sstring s(data.begin(), data.end());
    BOOST_REQUIRE_EQUAL(s, "abc");
}

BOOST_AUTO_TEST_CASE(test_nul_termination) {
    using stype = basic_sstring<char, uint32_t, 15, true>;

    for (int size = 1; size <= 32; size *= 2) {
        auto s1 = uninitialized_string<stype>(size - 1);
        BOOST_REQUIRE_EQUAL(s1.c_str()[size - 1], '\0');
        auto s2 = uninitialized_string<stype>(size);
        BOOST_REQUIRE_EQUAL(s2.c_str()[size], '\0');

        s1 = stype("01234567890123456789012345678901", size - 1);
        BOOST_REQUIRE_EQUAL(s1.c_str()[size - 1], '\0');
        s2 = stype("01234567890123456789012345678901", size);
        BOOST_REQUIRE_EQUAL(s2.c_str()[size], '\0');

        s1 = stype(size - 1, ' ');
        BOOST_REQUIRE_EQUAL(s1.c_str()[size - 1], '\0');
        s2 = stype(size, ' ');
        BOOST_REQUIRE_EQUAL(s2.c_str()[size], '\0');

        s2 = s1;
        BOOST_REQUIRE_EQUAL(s2.c_str()[s1.size()], '\0');
        s2.resize(s1.size());
        BOOST_REQUIRE_EQUAL(s2.c_str()[s1.size()], '\0');
        BOOST_REQUIRE_EQUAL(s1, s2);

        auto new_size = size / 2;
        s2 = s1;
        s2.resize(new_size);
        BOOST_REQUIRE_EQUAL(s2.c_str()[new_size], '\0');
        BOOST_REQUIRE(!strncmp(s1.c_str(), s2.c_str(), new_size));

        new_size = size * 2;
        s2 = s1;
        s2.resize(new_size);
        BOOST_REQUIRE_EQUAL(s2.c_str()[new_size], '\0');
        BOOST_REQUIRE(!strncmp(s1.c_str(), s2.c_str(), std::min(s1.size(), s2.size())));

        new_size = size * 2;
        s2 = s1 + s1;
        BOOST_REQUIRE_EQUAL(s2.c_str()[s2.size()], '\0');
        BOOST_REQUIRE(!strncmp(s1.c_str(), s2.c_str(), std::min(s1.size(), s2.size())));
    }
}
<commit_msg>test_erase: Delete a broken part of the test<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright 2014 Cloudius Systems
 */

#define BOOST_TEST_MODULE core

#include <boost/test/included/unit_test.hpp>
#include <seastar/core/sstring.hh>
#include <list>

using namespace seastar;

BOOST_AUTO_TEST_CASE(test_construction) {
    BOOST_REQUIRE_EQUAL(sstring(compat::string_view("abc")), sstring("abc"));
}

BOOST_AUTO_TEST_CASE(test_equality) {
    BOOST_REQUIRE_EQUAL(sstring("aaa"), sstring("aaa"));
}

BOOST_AUTO_TEST_CASE(test_to_sstring) {
    BOOST_REQUIRE_EQUAL(to_sstring(1234567), sstring("1234567"));
}

BOOST_AUTO_TEST_CASE(test_add_literal_to_sstring) {
    BOOST_REQUIRE_EQUAL("x" + sstring("y"), sstring("xy"));
}

BOOST_AUTO_TEST_CASE(test_find_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").find('b'), 1u);
    BOOST_REQUIRE_EQUAL(sstring("babcde").find('b',1), 2u);
}

BOOST_AUTO_TEST_CASE(test_not_find_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").find('x'), sstring::npos);
}

BOOST_AUTO_TEST_CASE(test_str_find_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").find("bc"), 1u);
    BOOST_REQUIRE_EQUAL(sstring("abcbcde").find("bc", 2), 3u);
}

BOOST_AUTO_TEST_CASE(test_str_not_find_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").find("x"), sstring::npos);
}

BOOST_AUTO_TEST_CASE(test_substr_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").substr(1,2), "bc");
    BOOST_REQUIRE_EQUAL(sstring("abc").substr(1,2), "bc");
    BOOST_REQUIRE_EQUAL(sstring("abc").substr(1,3), "bc");
    BOOST_REQUIRE_EQUAL(sstring("abc").substr(0, 2), "ab");
    BOOST_REQUIRE_EQUAL(sstring("abc").substr(3, 2), "");
    BOOST_REQUIRE_EQUAL(sstring("abc").substr(1), "bc");
}

BOOST_AUTO_TEST_CASE(test_substr_eor_sstring) {
    BOOST_REQUIRE_THROW(sstring("abcde").substr(6,1), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(test_at_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("abcde").at(1), 'b');
    BOOST_REQUIRE_THROW(sstring("abcde").at(6), std::out_of_range);
    sstring s("abcde");
    s.at(1) = 'd';
    BOOST_REQUIRE_EQUAL(s, "adcde");
}

BOOST_AUTO_TEST_CASE(test_find_last_sstring) {
    BOOST_REQUIRE_EQUAL(sstring("ababa").find_last_of('a'), 4u);
    BOOST_REQUIRE_EQUAL(sstring("ababa").find_last_of('a',5), 4u);
    BOOST_REQUIRE_EQUAL(sstring("ababa").find_last_of('a',4), 4u);
    BOOST_REQUIRE_EQUAL(sstring("ababa").find_last_of('a',3), 2u);
    BOOST_REQUIRE_EQUAL(sstring("ababa").find_last_of('x'), sstring::npos);
    BOOST_REQUIRE_EQUAL(sstring("").find_last_of('a'), sstring::npos);
}

BOOST_AUTO_TEST_CASE(test_append) {
    BOOST_REQUIRE_EQUAL(sstring("aba").append("1234", 3), "aba123");
    BOOST_REQUIRE_EQUAL(sstring("aba").append("1234", 4), "aba1234");
    BOOST_REQUIRE_EQUAL(sstring("aba").append("1234", 0), "aba");
}

BOOST_AUTO_TEST_CASE(test_replace) {
    BOOST_REQUIRE_EQUAL(sstring("abc").replace(1,1, "xyz", 1), "axc");
    BOOST_REQUIRE_EQUAL(sstring("abc").replace(3,2, "xyz", 2), "abcxy");
    BOOST_REQUIRE_EQUAL(sstring("abc").replace(2,2, "xyz", 2), "abxy");
    BOOST_REQUIRE_EQUAL(sstring("abc").replace(0,2, "", 0), "c");
    BOOST_REQUIRE_THROW(sstring("abc").replace(4,1, "xyz", 1), std::out_of_range);
    const char* s = "xyz";
    sstring str("abcdef");
    BOOST_REQUIRE_EQUAL(str.replace(str.begin() + 1 , str.begin() + 3, s + 1, s + 3), "ayzdef");
    BOOST_REQUIRE_THROW(sstring("abc").replace(4,1, "xyz", 1), std::out_of_range);

}

BOOST_AUTO_TEST_CASE(test_insert) {
    sstring str("abc");
    const char* s = "xyz";
    str.insert(str.begin() +1, s + 1, s + 2);
    BOOST_REQUIRE_EQUAL(str, "aybc");
    str = "abc";
    BOOST_REQUIRE_THROW(str.insert(str.begin() + 5, s + 1, s + 2), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(test_erase) {
    sstring str("abcdef");
    auto i = str.erase(str.begin() + 1, str.begin() + 3);
    BOOST_REQUIRE_EQUAL(*i, 'd');
    BOOST_REQUIRE_EQUAL(str, "adef");
}

BOOST_AUTO_TEST_CASE(test_ctor_iterator) {
    std::list<char> data{{'a', 'b', 'c'}};
    sstring s(data.begin(), data.end());
    BOOST_REQUIRE_EQUAL(s, "abc");
}

BOOST_AUTO_TEST_CASE(test_nul_termination) {
    using stype = basic_sstring<char, uint32_t, 15, true>;

    for (int size = 1; size <= 32; size *= 2) {
        auto s1 = uninitialized_string<stype>(size - 1);
        BOOST_REQUIRE_EQUAL(s1.c_str()[size - 1], '\0');
        auto s2 = uninitialized_string<stype>(size);
        BOOST_REQUIRE_EQUAL(s2.c_str()[size], '\0');

        s1 = stype("01234567890123456789012345678901", size - 1);
        BOOST_REQUIRE_EQUAL(s1.c_str()[size - 1], '\0');
        s2 = stype("01234567890123456789012345678901", size);
        BOOST_REQUIRE_EQUAL(s2.c_str()[size], '\0');

        s1 = stype(size - 1, ' ');
        BOOST_REQUIRE_EQUAL(s1.c_str()[size - 1], '\0');
        s2 = stype(size, ' ');
        BOOST_REQUIRE_EQUAL(s2.c_str()[size], '\0');

        s2 = s1;
        BOOST_REQUIRE_EQUAL(s2.c_str()[s1.size()], '\0');
        s2.resize(s1.size());
        BOOST_REQUIRE_EQUAL(s2.c_str()[s1.size()], '\0');
        BOOST_REQUIRE_EQUAL(s1, s2);

        auto new_size = size / 2;
        s2 = s1;
        s2.resize(new_size);
        BOOST_REQUIRE_EQUAL(s2.c_str()[new_size], '\0');
        BOOST_REQUIRE(!strncmp(s1.c_str(), s2.c_str(), new_size));

        new_size = size * 2;
        s2 = s1;
        s2.resize(new_size);
        BOOST_REQUIRE_EQUAL(s2.c_str()[new_size], '\0');
        BOOST_REQUIRE(!strncmp(s1.c_str(), s2.c_str(), std::min(s1.size(), s2.size())));

        new_size = size * 2;
        s2 = s1 + s1;
        BOOST_REQUIRE_EQUAL(s2.c_str()[s2.size()], '\0');
        BOOST_REQUIRE(!strncmp(s1.c_str(), s2.c_str(), std::min(s1.size(), s2.size())));
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdio>
#include <sstream>
#include <cassert>
#include <vector>
#include <string>
#include <cstdlib>
#include <iomanip>
#include "bond_angle.h"

using namespace std;

extern int totalatoms;  //int totalatoms in extraction.cpp
extern vector< vector<string> > vector_coords;  //2D vector "vector_coords" in extraction.cpp

typedef vector<int> Row;
typedef vector<double> dblRow;
typedef vector<Row> Matrix;
typedef vector<dblRow> dblMatrix;
    dblMatrix R(totalatoms,dblRow(totalatoms));
    Matrix bond_exist(totalatoms,Row(totalatoms));

vector<double> angRow;
vector< vector<double> > bond_angle_v;

void atom_distance(int number_atoms) {

    ofstream outputfile;
    ofstream log;
    outputfile.open("outputfile.txt", ios::app);
    log.open("log.txt", ios::app);

    cout << "Interatomic distances (in Angstroms): " << endl;
    log << "Interatomic distances (in Angstroms): " << endl;
    outputfile << "Interatomic distances (in Angstroms): " << endl;

    int i, j;
    string atom1, atom2;
    string x1_string, x2_string, y1_string, y2_string, z1_string, z2_string;
    double x1_double, x2_double, y1_double, y2_double, z1_double, z2_double;
    double distance;

    for(i = 0; i < number_atoms; i++) {
        for(j = i + 1; j < number_atoms; j++) {

            atom1 = (vector_coords[i][0]);
            atom2 = (vector_coords[j][0]);
            x1_string = (vector_coords[i][2]);
            x2_string = (vector_coords[j][2]);
            y1_string = (vector_coords[i][3]);
            y2_string = (vector_coords[j][3]);
            z1_string = (vector_coords[i][4]);
            z2_string = (vector_coords[j][4]);

            x1_double = atof(x1_string.c_str());
            x2_double = atof(x2_string.c_str());
            y1_double = atof(y1_string.c_str());
            y2_double = atof(y2_string.c_str());
            z1_double = atof(z1_string.c_str());
            z2_double = atof(z2_string.c_str());

            distance = (sqrt(
                            ((pow(x2_double - x1_double, 2))) +
                            ((pow(y2_double - y1_double, 2))) +  //calculation of interatomic distances
                            ((pow(z2_double - z1_double, 2)))));

            R[i][j] = distance;
	    R[j][i] = distance;

	    if(distance < 1.55) {
	        bond_exist[i][j] = 1;
		bond_exist[j][i] = 1;
	    } else {
	        bond_exist[i][j] = 0;
		bond_exist[j][i] = 0;
              }

     	    cout << atom1 << "  " << atom2 << "    " << R[i][j] << endl;
            log << atom1 << "  " << atom2 << "    " << R[i][j] << endl;
            outputfile << atom1 << "  " << atom2 << "    " << R[i][j] << endl;

        }
    }

}

double unit_vectors(int a1, int a2, int col) {

    string x1_string, x2_string;
    double x1_double, x2_double;
    double ex;

    x1_string = (vector_coords[a1][col]);
    x2_string = (vector_coords[a2][col]);
    x1_double = atof(x1_string.c_str());
    x2_double = atof(x2_string.c_str());

    ex = ((-(x2_double - x1_double)) / R[a1][a2]);

    return ex;

}

void bond_angle_f(int number_atoms) {

    ofstream outputfile;
    ofstream log;
    outputfile.open("outputfile.txt", ios::app);
    log.open("log.txt", ios::app);

    int z = 0;
    double a1_double, a2_double, a3_double;
    int a1_int, a2_int, a3_int;
    string a1_string, a2_string, a3_string;
    double ex_ij, ey_ij, ez_ij;
    double ex_ik, ey_ik, ez_ik;
    double angle_phi;

    cout << "Bond angles (in degrees): " << endl;
    log << "Bond angles (in degrees): " << endl;
    outputfile << "Bond angles (in degrees): " << endl;

    for(int i = 0; i < number_atoms; i++) {
        for(int j = 0; j < number_atoms; j++) {
	    if(bond_exist[i][j] == 1) {
	        for(int k = j + 1; k < number_atoms; k++) {
		    if(bond_exist[i][k] == 1) {

		        angRow.clear();

		        ex_ij = unit_vectors(i,j,2);
		        ey_ij = unit_vectors(i,j,3);
		        ez_ij = unit_vectors(i,j,4);

		        ex_ik = unit_vectors(i,k,2);
		        ey_ik = unit_vectors(i,k,3);
		        ez_ik = unit_vectors(i,k,4);

		        angle_phi = ((acos(ex_ij * ex_ik +
			                  ey_ij * ey_ik +  //calculation of bond angle with conversion from radians to degrees
			                  ez_ij * ez_ik)) * (180/3.14159));

		        angRow.push_back(i);
		        angRow.push_back(j);
		        angRow.push_back(k);

		        angRow.push_back(ex_ij);
		        angRow.push_back(ey_ij);
		        angRow.push_back(ez_ij);

		        angRow.push_back(ex_ik);
		        angRow.push_back(ey_ik);
		        angRow.push_back(ez_ik);

		        angRow.push_back(angle_phi);

		        bond_angle_v.push_back(angRow);

		        z++;
		    }
	        }
	    }
        }
    }

    for(int i = 0; i < bond_angle_v.size(); i++) {
        a1_double = (bond_angle_v[i][0]);
	a2_double = (bond_angle_v[i][1]);
	a3_double = (bond_angle_v[i][2]);

	a1_int = a1_double;
	a2_int = a2_double;
	a3_int = a3_double;

	a1_string = (vector_coords[a1_int][0]);
	a2_string = (vector_coords[a2_int][0]);
	a3_string = (vector_coords[a3_int][0]);

	cout << a1_string << "  " << a2_string << "  " << a3_string << "  ";
        cout << a1_int << "  "   << a2_int << "  " << a3_int << "    ";
	cout << bond_angle_v[i][3] << "  ";
	cout << bond_angle_v[i][4] << "  ";
	cout << bond_angle_v[i][5] << "  ";
	cout << bond_angle_v[i][6] << "  ";
	cout << bond_angle_v[i][7] << "  ";
	cout << bond_angle_v[i][8] << "  ";
	cout << bond_angle_v[i][9];
	cout << endl;

    }

}

vector<double> torRow;
vector< vector<double> > dihedral_angle_v;

void torsion_angle_f(int number_atoms) {

cout << "Beginning torsion angle function" << endl;

int col;

    for(int ba = 0; ba < bond_angle_v.size(); ba++) {
       int i = (bond_angle_v[ba][0]);
       int j = (bond_angle_v[ba][1]);
       int k = (bond_angle_v[ba][2]);
       for(int l = 0; l < number_atoms; l++) {
           if(l != i && l != k) {
	       if(bond_exist[k][l] == 1) {

	           torRow.clear();

	           double ex_ij = (bond_angle_v[ba][3]);
		   double ey_ij = (bond_angle_v[ba][4]);
		   double ez_ij = (bond_angle_v[ba][5]);

		   double ex_ik = (bond_angle_v[ba][6]);
                   double ey_ik = (bond_angle_v[ba][7]);
                   double ez_ik = (bond_angle_v[ba][8]);

		   double ex_kl = (unit_vectors(k,l,2));
		   double ey_kl = (unit_vectors(k,l,3));
		   double ez_kl = (unit_vectors(k,l,4));

		   double angle_jik = bond_angle_v[ba][9];

		   double angle_phi_ikl = ((acos(ex_kl * ex_ik +
			                  ey_kl * ey_ik +  //calculation of bond angle with conversion from radians to degrees
			                  ez_kl * ez_ik)) * (180/3.14159));

                   double ex_ijk = ((ey_ij * ez_ik) - (ez_ij * ey_ik));
                   double ey_ijk = ((ez_ij * ex_ik) - (ex_ij * ez_ik));
                   double ez_ijk = ((ex_ij * ey_ik) - (ey_ij * ex_ik));
                   double ex_ikl = ((ey_kl * ez_kl) - (ez_ik * ey_kl));
                   double ey_ikl = ((ez_ik * ex_kl) - (ex_ik * ez_kl));
                   double ez_ikl = ((ex_ik * ey_kl) - (ey_ik * ex_kl));

                   double exx = (ex_ijk * ex_ikl);
                   double eyy = (ey_ijk * ey_ikl);
                   double ezz = (ez_ijk * ez_ikl);

                   double tau_ijkl = ((exx + eyy + ezz) / (sin(angle_jik)*sin(angle_phi_ikl))) * (180/3.14159);

		   torRow.push_back(i);
		   torRow.push_back(j);
		   torRow.push_back(k);
		   torRow.push_back(l);

		   torRow.push_back(ex_ij);
		   torRow.push_back(ey_ij);
		   torRow.push_back(ez_ij);

		   torRow.push_back(ex_ik);
		   torRow.push_back(ey_ik);
		   torRow.push_back(ez_ik);

		   torRow.push_back(ex_kl);
                   torRow.push_back(ey_kl);
                   torRow.push_back(ez_kl);

		   torRow.push_back(angle_jik);
		   torRow.push_back(angle_phi_ikl);
		   torRow.push_back(tau_ijkl);

		   dihedral_angle_v.push_back(torRow);
	        }
	    }
	}

    for(int l = 0; l < number_atoms; l++) {
           if(l != i && l != j) {
	       if(bond_exist[j][l] == 1) {

	           torRow.clear();

	           double ex_ij = (bond_angle_v[ba][3]);
		   double ey_ij = (bond_angle_v[ba][4]);
		   double ez_ij = (bond_angle_v[ba][5]);

		   double ex_ik = (bond_angle_v[ba][6]);
                   double ey_ik = (bond_angle_v[ba][7]);
                   double ez_ik = (bond_angle_v[ba][8]);

		   double ex_jl = (unit_vectors(j,l,2));
		   double ey_jl = (unit_vectors(j,l,3));
		   double ez_jl = (unit_vectors(j,l,4));

		   double angle_jik = bond_angle_v[ba][9];

		   double angle_phi_ijl = ((acos(ex_jl * ex_ik +
			                  ey_jl * ey_ik +  //calculation of bond angle with conversion from radians to degrees
			                  ez_jl * ez_ik)) * (180/3.14159));

                   double ex_ijk = ((ey_ij * ez_ik) - (ez_ij * ey_ik));
                   double ey_ijk = ((ez_ij * ex_ik) - (ex_ij * ez_ik));
                   double ez_ijk = ((ex_ij * ey_ik) - (ey_ij * ex_ik));
                   double ex_ijl = ((ey_jl * ez_jl) - (ez_ik * ey_jl));
                   double ey_ijl = ((ez_ik * ex_jl) - (ex_ik * ez_jl));
                   double ez_ijl = ((ex_ik * ey_jl) - (ey_ik * ex_jl));

                   double exx = (ex_ijk * ex_ijl);
                   double eyy = (ey_ijk * ey_ijl);
                   double ezz = (ez_ijk * ez_ijl);

                   double tau_ijkl = ((exx + eyy + ezz) / (sin(angle_jik)*sin(angle_phi_ijl))) * (180/3.14159);

		   torRow.push_back(i);
		   torRow.push_back(j);
		   torRow.push_back(k);
		   torRow.push_back(l);

		   torRow.push_back(ex_ij);
		   torRow.push_back(ey_ij);
		   torRow.push_back(ez_ij);

		   torRow.push_back(ex_ik);
		   torRow.push_back(ey_ik);
		   torRow.push_back(ez_ik);

		   torRow.push_back(ex_jl);
                   torRow.push_back(ey_jl);
                   torRow.push_back(ez_jl);

		   torRow.push_back(angle_jik);
		   torRow.push_back(angle_phi_ijl);
		   torRow.push_back(tau_ijkl);

		   dihedral_angle_v.push_back(torRow);
	        }
	    }
	}
    }

    for(int i = 0; i < dihedral_angle_v.size(); i++) {
        double a1_double = (dihedral_angle_v[i][0]);
	double a2_double = (dihedral_angle_v[i][1]);
	double a3_double = (dihedral_angle_v[i][2]);
	double a4_double = (dihedral_angle_v[i][3]);

	int a1_int = a1_double;
	int a2_int = a2_double;
	int a3_int = a3_double;
	int a4_int = a4_double;

	string a1_string = (vector_coords[a1_int][0]);
	string a2_string = (vector_coords[a2_int][0]);
	string a3_string = (vector_coords[a3_int][0]);
	string a4_string = (vector_coords[a4_int][0]);

	cout << a1_string << "  " << a2_string << "  " << a3_string << "  " << a4_string << "  ";
	cout << a1_int << "  " << a2_int << "  " << a3_int << "  " << a4_int << "    ";
        cout << dihedral_angle_v[i][15];
	cout << endl;

    }
}

    //ensure dihedral angle is not negative before addition of sign
 //   if(tau_ijkl < -1.0) tau_ijkl = acos(-1.0);
 // else if(tau_ijkl > 1.0) tau_ijkl = acos(1.0);
 //   else tau_ijkl = acos(tau);

 //   return tau_ijkl;

//determines sign of dihedral angle
//double sign_tau() {

//    double cross_yz = (ey_ijk * ez_jkl) - (ez_ijk * ey_jkl);

//    double cross_xz = (ez_ijk * ex_jkl) - (ex_ijk * ez_jkl);

//    double cross_xy = (ex_ijk * ey_jkl) - (ey_ijk * ex_jkl);

//    double normal = cross_yz * cross_yz + cross_xz * cross_xz + cross_xy * cross_xy;

//    cross_yz /= normal;

//    cross_xz /= normal;

//    cross_xy /= normal;

//    double sign = 1.0;

//    double dot = (cross_yz * ex_jk) + (cross_xz * ey_jk) + (cross_xy * ez_jk);

//    if(dot < 0.0) sign = -1.0;

//    return tau_ijkl * sign;

//    log << "Completed calculation of dihedral angle including sign of angle";

//    log.close();
<commit_msg>removed torsion angle stuff<commit_after>#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdio>
#include <sstream>
#include <cassert>
#include <vector>
#include <string>
#include <cstdlib>
#include <iomanip>
#include "bond_angle.h"

using namespace std;

extern vector< vector<string> > vector_coords;  //2D vector "vector_coords" in extraction.cpp

int number_atoms = (vector_coords.size());

typedef vector<int> Row;
typedef vector<double> dblRow;
typedef vector<Row> Matrix;
typedef vector<dblRow> dblMatrix;
    dblMatrix R(number_atoms,dblRow(number_atoms));
    Matrix bond_exist(number_atoms,Row(number_atoms));

vector<double> angRow;
vector< vector<double> > bond_angle_v;

void atom_distance_f(int number_atoms) {

    ofstream outputfile;
    ofstream log;
    outputfile.open("outputfile.txt", ios::app);
    log.open("log.txt", ios::app);

    cout << "Interatomic distances (in Angstroms): " << endl;
    log << "Interatomic distances (in Angstroms): " << endl;
    outputfile << "Interatomic distances (in Angstroms): " << endl;

    int i, j;

    for(i = 0; i < number_atoms; i++) {
        for(j = i + 1; j < number_atoms; j++) {

            string atom1 = (vector_coords[i][0]);
            string atom2 = (vector_coords[j][0]);
            string x1_string = (vector_coords[i][2]);
            string x2_string = (vector_coords[j][2]);
            string y1_string = (vector_coords[i][3]);
            string y2_string = (vector_coords[j][3]);
            string z1_string = (vector_coords[i][4]);
            string z2_string = (vector_coords[j][4]);

            double x1_double = atof(x1_string.c_str());
            double x2_double = atof(x2_string.c_str());
            double y1_double = atof(y1_string.c_str());
            double y2_double = atof(y2_string.c_str());
            double z1_double = atof(z1_string.c_str());
            double z2_double = atof(z2_string.c_str());

            double distance = (sqrt(
                            ((pow(x2_double - x1_double, 2))) +
                            ((pow(y2_double - y1_double, 2))) +  //calculation of interatomic distances
                            ((pow(z2_double - z1_double, 2)))));

            R[i][j] = distance;
	    R[j][i] = distance;

	    if(distance < 1.55) {
	        bond_exist[i][j] = 1;
		bond_exist[j][i] = 1;
	    } else {
	        bond_exist[i][j] = 0;
		bond_exist[j][i] = 0;
              }

     	    cout << atom1 << "  " << atom2 << "    " << R[i][j] << endl;
            log << atom1 << "  " << atom2 << "    " << R[i][j] << endl;
            outputfile << atom1 << "  " << atom2 << "    " << R[i][j] << endl;
        }
    }
}

double unit_vectors(int a1, int a2, int col) {

    string x1_string = (vector_coords[a1][col]);
    string x2_string = (vector_coords[a2][col]);
    double x1_double = atof(x1_string.c_str());
    double x2_double = atof(x2_string.c_str());

    double ex = ((-(x2_double - x1_double)) / R[a1][a2]);

    return ex;
}

void bond_angle_f(int number_atoms) {

    ofstream outputfile;
    ofstream log;
    outputfile.open("outputfile.txt", ios::app);
    log.open("log.txt", ios::app);

    int z = 0;

    cout << "Bond angles (in degrees): " << endl;
    log << "Bond angles (in degrees): " << endl;
    outputfile << "Bond angles (in degrees): " << endl;

    for(int i = 0; i < number_atoms; i++) {
        for(int j = 0; j < number_atoms; j++) {
	    if(bond_exist[i][j] == 1) {
	        for(int k = j + 1; k < number_atoms; k++) {
		    if(bond_exist[i][k] == 1) {

		        angRow.clear();

		        double ex_ij = unit_vectors(i,j,2);
		        double ey_ij = unit_vectors(i,j,3);
		        double ez_ij = unit_vectors(i,j,4);
		        double ex_ik = unit_vectors(i,k,2);
		        double ey_ik = unit_vectors(i,k,3);
		        double ez_ik = unit_vectors(i,k,4);
		        double angle_jik = ((acos(ex_ij * ex_ik +
			                          ey_ij * ey_ik +  //calculation of bond angle with conversion from radians to degrees
			                          ez_ij * ez_ik))
                                                  * (180/3.14159));
		        angRow.push_back(i);
		        angRow.push_back(j);
		        angRow.push_back(k);
		        angRow.push_back(ex_ij);
		        angRow.push_back(ey_ij);
		        angRow.push_back(ez_ij);
		        angRow.push_back(ex_ik);
		        angRow.push_back(ey_ik);
		        angRow.push_back(ez_ik);
		        angRow.push_back(angle_jik);
		        bond_angle_v.push_back(angRow);

		        z++;
		    }
	        }
	    }
        }
    }

    for(int i = 0; i < bond_angle_v.size(); i++) {
        double a1_double = (bond_angle_v[i][0]);
	double a2_double = (bond_angle_v[i][1]);
	double a3_double = (bond_angle_v[i][2]);
	int a1_int = a1_double;
	int a2_int = a2_double;
	int a3_int = a3_double;
	string a1_string = (vector_coords[a1_int][0]);
	string a2_string = (vector_coords[a2_int][0]);
	string a3_string = (vector_coords[a3_int][0]);

	cout << a1_string << "  " << a2_string << "  " << a3_string << "  ";
        cout << a1_int << "  "   << a2_int << "  " << a3_int << "    ";
	cout << bond_angle_v[i][3] << "  ";
	cout << bond_angle_v[i][4] << "  ";
	cout << bond_angle_v[i][5] << "  ";
	cout << bond_angle_v[i][6] << "  ";
	cout << bond_angle_v[i][7] << "  ";
	cout << bond_angle_v[i][8] << "  ";
	cout << bond_angle_v[i][9];
	cout << endl;
    }
}
<|endoftext|>