<commit_before>#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numeric>
#include <string>
#include <sstream>

#include <cmath>

// TODO: Replace this as soon as possible with a more modern option
// parser interface.
#include <getopt.h>

#include "filtrations/Data.hh"

#include "geometry/RipsExpander.hh"

#include "persistenceDiagrams/Norms.hh"
#include "persistenceDiagrams/PersistenceDiagram.hh"

#include "persistentHomology/ConnectedComponents.hh"

#include "topology/CliqueGraph.hh"
#include "topology/ConnectedComponents.hh"
#include "topology/Simplex.hh"
#include "topology/SimplicialComplex.hh"

#include "topology/io/EdgeLists.hh"
#include "topology/io/GML.hh"
#include "topology/io/Pajek.hh"

#include "utilities/Filesystem.hh"

using DataType           = double;
using VertexType         = unsigned;
using Simplex            = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex  = aleph::topology::SimplicialComplex<Simplex>;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;

std::string formatOutput( const std::string& prefix, unsigned k, unsigned K )
{
  std::ostringstream stream;
  stream << prefix;
  stream << std::setw( int( std::log10( K ) + 1 ) ) << std::setfill( '0' ) << k;
  stream << ".txt";

  return stream.str();
}

void usage()
{
  std::cerr << "Usage: clique-persistence-diagram [--invert-weights] [--reverse] FILE K\n"
            << "\n"
            << "Calculates the clique persistence diagram for FILE, which is\n"
            << "supposed to be a weighted graph. The K parameter denotes the\n"
            << "maximum dimension of a simplex for extracting a clique graph\n"
            << "and tracking persistence of clique communities.\n\n"
            << ""
            << "Optional arguments:\n"
            << " --invert-weights: If specified, inverts input weights. This\n"
            << "                   is useful if the original weights measure\n"
            << "                   the strength of a relationship, and not a\n"
            << "                   dissimilarity.\n"
            << "\n"
            << " --reverse       : Reverses the enumeration order of cliques\n"
            << "                   by looking for higher-dimensional cliques\n"
            << "                   before enumerating lower-dimensional ones\n"
            << "                   instead of the other way around.\n"
            << "\n\n";
}

int main( int argc, char** argv )
{
  static option commandLineOptions[] =
  {
    { "invert-weights", no_argument, nullptr, 'i' },
    { "reverse"       , no_argument, nullptr, 'r' },
    { nullptr         , 0          , nullptr,  0  }
  };

  bool invertWeights = false;
  bool reverse       = false;

  int option = 0;
  while( ( option = getopt_long( argc, argv, "ir", commandLineOptions, nullptr ) ) != -1 )
  {
    switch( option )
    {
    case 'i':
      invertWeights = true;
      break;

    case 'r':
      reverse = true;
      break;

    default:
      break;
    }
  }

  if( (argc - optind ) < 2 )
  {
    usage();
    return -1;
  }

  std::string filename = argv[optind++];
  unsigned maxK        = static_cast<unsigned>( std::stoul( argv[optind++] ) );

  SimplicialComplex K;

  // Input -------------------------------------------------------------

  std::cerr << "* Reading '" << filename << "'...";

  // Optional map of node labels. If the graph contains node labels and
  // I am able to read them, this map will be filled.
  std::map<VertexType, std::string> labels;

  if( aleph::utilities::extension( filename ) == ".gml" )
  {
    aleph::topology::io::GMLReader reader;
    reader( filename, K );

    auto labelMap = reader.getNodeAttribute( "label" );

    // Note that this assumes that the labels are convertible to
    // numbers.
    //
    // TODO: Solve this generically?
    for( auto&& pair : labelMap )
      if( !pair.second.empty() )
        labels[ static_cast<VertexType>( std::stoul( pair.first ) ) ] = pair.second;

    if( labels.empty() )
      labels.clear();
  }
  else if( aleph::utilities::extension( filename ) == ".net" )
  {
    aleph::topology::io::PajekReader reader;
    reader( filename, K );

    auto labelMap = reader.getLabelMap();

    // Note that this assumes that the labels are convertible to
    // numbers.
    //
    // TODO: Solve this generically?
    for( auto&& pair : labelMap )
      if( !pair.second.empty() )
        labels[ static_cast<VertexType>( std::stoul( pair.first ) ) ] = pair.second;

    if( labels.empty() )
      labels.clear();

  }
  else
  {
    aleph::io::EdgeListReader reader;
    reader.setReadWeights( true );
    reader.setTrimLines( true );

    reader( filename, K );
  }

  std::cerr << "finished\n";

  DataType maxWeight = std::numeric_limits<DataType>::lowest();
  for( auto&& simplex : K )
    maxWeight = std::max( maxWeight, simplex.data() );

  if( invertWeights )
  {
    std::cerr << "* Inverting filtration weights...";

    for( auto it = K.begin(); it != K.end(); ++it )
    {
      if( K.dimension() == 0 )
        continue;

      auto s = *it;
      s.setData( maxWeight - s.data() );

      K.replace( it, s );
    }

    std::cerr << "finished\n";
  }

  // Expansion ---------------------------------------------------------

  std::cerr << "* Expanding simplicial complex to k=" << maxK << "...";

  aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander;
  K = ripsExpander( K, maxK );
  K = ripsExpander.assignMaximumWeight( K );

  std::cerr << "finished\n"
            << "* Expanded simplicial complex has " << K.size() << " simplices\n";

  K.sort( aleph::filtrations::Data<Simplex>() );

  // Stores the accumulated persistence of vertices. Persistence
  // accumulates if a vertex participates in a clique community.
  std::map<VertexType, double> accumulatedPersistenceMap;

  // Stores the number of clique communities a vertex is a part of.
  // I am using this only for debugging the algorithm.
  std::map<VertexType, unsigned> numberOfCliqueCommunities;

  std::vector<double> totalPersistenceValues;
  totalPersistenceValues.reserve( maxK );

  for( unsigned k = 1; k <= maxK; k++ )
  {
    std::cerr << "* Extracting " << k << "-cliques graph...";

    auto C
        = aleph::topology::getCliqueGraph( K, k );

    C.sort( aleph::filtrations::Data<Simplex>() );

    std::cerr << "finished\n";

    std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n";

    if( C.empty() )
    {
      std::cerr << "* Stopping here because no further cliques for processing exist\n";
      break;
    }

    auto&& tuple = aleph::calculateZeroDimensionalPersistenceDiagram( C );
    auto&& pd    = std::get<0>( tuple );
    auto&& pp    = std::get<1>( tuple );

    auto itPoint = pd.begin();
    for( auto itPair = pp.begin(); itPair != pp.end(); ++itPair )
    {
      // Skip zero-dimensional persistence pairs
      if( itPoint->x() == itPoint->y() )
      {
        ++itPoint;
        continue;
      }

      SimplicialComplex filteredComplex;

      {
        std::vector<Simplex> simplices;
        if( itPair->second < C.size() )
        {
          simplices.reserve( itPair->second );

          std::copy( C.begin() + itPair->first, C.begin() + itPair->second, std::back_inserter( simplices ) );
          filteredComplex = SimplicialComplex( simplices.begin(), simplices.end() );
        }
        else
          filteredComplex = C;
      }

      auto uf          = calculateConnectedComponents( filteredComplex );
      auto desiredRoot = *C.at( itPair->first ).begin();
      auto root        = uf.find( desiredRoot ); // Normally, this should be a self-assignment,
                                                 // but in some cases the order of traversal is
                                                 // slightly different, resulting in unexpected
                                                 // roots.

      std::set<VertexType> cliqueVertices;
      std::vector<VertexType> vertices;
      uf.get( root, std::back_inserter( vertices ) );

      for( auto&& vertex : vertices )
      {
        // Notice that the vertex identifier represents the index
        // within the filtration of the _original_ complex, hence
        // I can just access the corresponding simplex that way.
        auto s = K.at( vertex );

        cliqueVertices.insert( s.begin(), s.end() );
      }

      for( auto&& cliqueVertex : cliqueVertices )
      {
        auto persistence = std::isfinite( itPoint->persistence() ) ? std::pow( itPoint->persistence(), 2 ) : std::pow( 2*maxWeight - itPoint->x(), 2 );

        accumulatedPersistenceMap[cliqueVertex] += persistence;
        numberOfCliqueCommunities[cliqueVertex] += 1;
      }

      ++itPoint;
    }

    {
      using namespace aleph::utilities;
      auto outputFilename = formatOutput( "/tmp/" + stem( basename( filename ) ) + "_k", k, maxK );

      std::cerr << "* Storing output in '" << outputFilename << "'...\n";

      pd.removeDiagonal();

      std::transform( pd.begin(), pd.end(), pd.begin(),
                      [&maxWeight] ( const PersistenceDiagram::Point& p )
                      {
                        if( !std::isfinite( p.y() ) )
                          return PersistenceDiagram::Point( p.x(), maxWeight );
                        else
                          return PersistenceDiagram::Point( p );
                      } );

      totalPersistenceValues.push_back( aleph::totalPersistence( pd, 1.0 ) );

      std::ofstream out( outputFilename );
      out << "# Original filename: " << filename << "\n";
      out << "# k                : " << k        << "\n";
      out << pd << "\n";
    }
  }

  {
    using namespace aleph::utilities;
    auto outputFilename = "/tmp/" + stem( basename( filename ) ) + ".txt";

    std::cerr << "* Storing accumulated persistence values in '" << outputFilename << "'...\n";

    std::ofstream out( outputFilename );

    auto normalizationFactor
      = std::accumulate( totalPersistenceValues.begin(), totalPersistenceValues.end(), 0.0 );

    for( auto&& pair : accumulatedPersistenceMap )
      out << pair.first << "\t" << pair.second / normalizationFactor << "\t" << numberOfCliqueCommunities.at(pair.first) <<  ( labels.empty() ? "" : "\t" + labels.at( pair.first ) ) << "\n";
  }
}
<commit_msg>Made calculation of centrality measure optional<commit_after>#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numeric>
#include <string>
#include <sstream>

#include <cmath>

// TODO: Replace this as soon as possible with a more modern option
// parser interface.
#include <getopt.h>

#include "filtrations/Data.hh"

#include "geometry/RipsExpander.hh"

#include "persistenceDiagrams/Norms.hh"
#include "persistenceDiagrams/PersistenceDiagram.hh"

#include "persistentHomology/ConnectedComponents.hh"

#include "topology/CliqueGraph.hh"
#include "topology/ConnectedComponents.hh"
#include "topology/Simplex.hh"
#include "topology/SimplicialComplex.hh"

#include "topology/io/EdgeLists.hh"
#include "topology/io/GML.hh"
#include "topology/io/Pajek.hh"

#include "utilities/Filesystem.hh"

using DataType           = double;
using VertexType         = unsigned;
using Simplex            = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex  = aleph::topology::SimplicialComplex<Simplex>;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;

std::string formatOutput( const std::string& prefix, unsigned k, unsigned K )
{
  std::ostringstream stream;
  stream << prefix;
  stream << std::setw( int( std::log10( K ) + 1 ) ) << std::setfill( '0' ) << k;
  stream << ".txt";

  return stream.str();
}

void usage()
{
  std::cerr << "Usage: clique-persistence-diagram [--invert-weights] [--reverse] FILE K\n"
            << "\n"
            << "Calculates the clique persistence diagram for FILE, which is\n"
            << "supposed to be a weighted graph. The K parameter denotes the\n"
            << "maximum dimension of a simplex for extracting a clique graph\n"
            << "and tracking persistence of clique communities.\n\n"
            << ""
            << "******************\n"
            << "Optional arguments\n"
            << "******************\n"
            << "\n"
            << " --centrality    : If specified, calculates centralities for\n"
            << "                   all vertices. Note that this uses copious\n"
            << "                   amounts of time because *all* communities\n"
            << "                   need to be extracted and inspected.\n"
            << "\n"
            << " --invert-weights: If specified, inverts input weights. This\n"
            << "                   is useful if the original weights measure\n"
            << "                   the strength of a relationship, and not a\n"
            << "                   dissimilarity.\n"
            << "\n"
            << " --reverse       : Reverses the enumeration order of cliques\n"
            << "                   by looking for higher-dimensional cliques\n"
            << "                   before enumerating lower-dimensional ones\n"
            << "                   instead of the other way around.\n"
            << "\n\n";
}

int main( int argc, char** argv )
{
  static option commandLineOptions[] =
  {
    { "centrality"    , no_argument, nullptr, 'c' },
    { "invert-weights", no_argument, nullptr, 'i' },
    { "reverse"       , no_argument, nullptr, 'r' },
    { nullptr         , 0          , nullptr,  0  }
  };

  bool calculateCentrality = false;
  bool invertWeights       = false;
  bool reverse             = false;

  int option = 0;
  while( ( option = getopt_long( argc, argv, "cir", commandLineOptions, nullptr ) ) != -1 )
  {
    switch( option )
    {
    case 'c':
      calculateCentrality = true;
      break;

    case 'i':
      invertWeights = true;
      break;

    case 'r':
      reverse = true;
      break;

    default:
      break;
    }
  }

  if( (argc - optind ) < 2 )
  {
    usage();
    return -1;
  }

  std::string filename = argv[optind++];
  unsigned maxK        = static_cast<unsigned>( std::stoul( argv[optind++] ) );

  SimplicialComplex K;

  // Input -------------------------------------------------------------

  std::cerr << "* Reading '" << filename << "'...";

  // Optional map of node labels. If the graph contains node labels and
  // I am able to read them, this map will be filled.
  std::map<VertexType, std::string> labels;

  if( aleph::utilities::extension( filename ) == ".gml" )
  {
    aleph::topology::io::GMLReader reader;
    reader( filename, K );

    auto labelMap = reader.getNodeAttribute( "label" );

    // Note that this assumes that the labels are convertible to
    // numbers.
    //
    // TODO: Solve this generically?
    for( auto&& pair : labelMap )
      if( !pair.second.empty() )
        labels[ static_cast<VertexType>( std::stoul( pair.first ) ) ] = pair.second;

    if( labels.empty() )
      labels.clear();
  }
  else if( aleph::utilities::extension( filename ) == ".net" )
  {
    aleph::topology::io::PajekReader reader;
    reader( filename, K );

    auto labelMap = reader.getLabelMap();

    // Note that this assumes that the labels are convertible to
    // numbers.
    //
    // TODO: Solve this generically?
    for( auto&& pair : labelMap )
      if( !pair.second.empty() )
        labels[ static_cast<VertexType>( std::stoul( pair.first ) ) ] = pair.second;

    if( labels.empty() )
      labels.clear();

  }
  else
  {
    aleph::io::EdgeListReader reader;
    reader.setReadWeights( true );
    reader.setTrimLines( true );

    reader( filename, K );
  }

  std::cerr << "finished\n";

  DataType maxWeight = std::numeric_limits<DataType>::lowest();
  for( auto&& simplex : K )
    maxWeight = std::max( maxWeight, simplex.data() );

  if( invertWeights )
  {
    std::cerr << "* Inverting filtration weights...";

    for( auto it = K.begin(); it != K.end(); ++it )
    {
      if( K.dimension() == 0 )
        continue;

      auto s = *it;
      s.setData( maxWeight - s.data() );

      K.replace( it, s );
    }

    std::cerr << "finished\n";
  }

  // Expansion ---------------------------------------------------------

  std::cerr << "* Expanding simplicial complex to k=" << maxK << "...";

  aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander;
  K = ripsExpander( K, maxK );
  K = ripsExpander.assignMaximumWeight( K );

  std::cerr << "finished\n"
            << "* Expanded simplicial complex has " << K.size() << " simplices\n";

  K.sort( aleph::filtrations::Data<Simplex>() );

  // Stores the accumulated persistence of vertices. Persistence
  // accumulates if a vertex participates in a clique community.
  std::map<VertexType, double> accumulatedPersistenceMap;

  // Stores the number of clique communities a vertex is a part of.
  // I am using this only for debugging the algorithm.
  std::map<VertexType, unsigned> numberOfCliqueCommunities;

  std::vector<double> totalPersistenceValues;
  totalPersistenceValues.reserve( maxK );

  for( unsigned k = 1; k <= maxK; k++ )
  {
    std::cerr << "* Extracting " << k << "-cliques graph...";

    auto C
        = aleph::topology::getCliqueGraph( K, k );

    C.sort( aleph::filtrations::Data<Simplex>() );

    std::cerr << "finished\n";

    std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n";

    if( C.empty() )
    {
      std::cerr << "* Stopping here because no further cliques for processing exist\n";
      break;
    }

    auto&& tuple = aleph::calculateZeroDimensionalPersistenceDiagram( C );
    auto&& pd    = std::get<0>( tuple );
    auto&& pp    = std::get<1>( tuple );

    pd.removeDiagonal();

    if( calculateCentrality )
    {
      std::cerr << "* Calculating centrality measure (this may take a very long time!)...";

      auto itPoint = pd.begin();
      for( auto itPair = pp.begin(); itPair != pp.end(); ++itPair )
      {
        SimplicialComplex filteredComplex;

        {
          std::vector<Simplex> simplices;
          if( itPair->second < C.size() )
          {
            simplices.reserve( itPair->second );

            std::copy( C.begin() + itPair->first, C.begin() + itPair->second, std::back_inserter( simplices ) );
            filteredComplex = SimplicialComplex( simplices.begin(), simplices.end() );
          }
          else
            filteredComplex = C;
        }

        auto uf          = calculateConnectedComponents( filteredComplex );
        auto desiredRoot = *C.at( itPair->first ).begin();
        auto root        = uf.find( desiredRoot ); // Normally, this should be a self-assignment,
                                                   // but in some cases the order of traversal is
                                                   // slightly different, resulting in unexpected
                                                   // roots.

        std::set<VertexType> cliqueVertices;
        std::vector<VertexType> vertices;
        uf.get( root, std::back_inserter( vertices ) );

        for( auto&& vertex : vertices )
        {
          // Notice that the vertex identifier represents the index
          // within the filtration of the _original_ complex, hence
          // I can just access the corresponding simplex that way.
          auto s = K.at( vertex );

          cliqueVertices.insert( s.begin(), s.end() );
        }

        for( auto&& cliqueVertex : cliqueVertices )
        {
          auto persistence = std::isfinite( itPoint->persistence() ) ? std::pow( itPoint->persistence(), 2 ) : std::pow( 2*maxWeight - itPoint->x(), 2 );

          accumulatedPersistenceMap[cliqueVertex] += persistence;
          numberOfCliqueCommunities[cliqueVertex] += 1;
        }

        ++itPoint;
      }

      std::cerr << "finished\n";
    }

    {
      using namespace aleph::utilities;
      auto outputFilename = formatOutput( "/tmp/" + stem( basename( filename ) ) + "_k", k, maxK );

      std::cerr << "* Storing output in '" << outputFilename << "'...\n";

      std::transform( pd.begin(), pd.end(), pd.begin(),
                      [&maxWeight] ( const PersistenceDiagram::Point& p )
                      {
                        if( !std::isfinite( p.y() ) )
                          return PersistenceDiagram::Point( p.x(), maxWeight );
                        else
                          return PersistenceDiagram::Point( p );
                      } );

      totalPersistenceValues.push_back( aleph::totalPersistence( pd, 1.0 ) );

      std::ofstream out( outputFilename );
      out << "# Original filename: " << filename << "\n";
      out << "# k                : " << k        << "\n";
      out << pd << "\n";
    }
  }

  {
    using namespace aleph::utilities;
    auto outputFilename = "/tmp/" + stem( basename( filename ) ) + ".txt";

    std::cerr << "* Storing accumulated persistence values in '" << outputFilename << "'...\n";

    std::ofstream out( outputFilename );

    auto normalizationFactor
      = std::accumulate( totalPersistenceValues.begin(), totalPersistenceValues.end(), 0.0 );

    for( auto&& pair : accumulatedPersistenceMap )
      out << pair.first << "\t" << pair.second / normalizationFactor << "\t" << numberOfCliqueCommunities.at(pair.first) <<  ( labels.empty() ? "" : "\t" + labels.at( pair.first ) ) << "\n";
  }
}
<|endoftext|>


<commit_before>/**
 *Licensed to the Apache Software Foundation (ASF) under one
 *or more contributor license agreements.  See the NOTICE file
 *distributed with this work for additional information
 *regarding copyright ownership.  The ASF licenses this file
 *to you under the Apache License, Version 2.0 (the
 *"License"); you may not use this file except in compliance
 *with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing,
 *software distributed under the License is distributed on an
 *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 *specific language governing permissions and limitations
 *under the License.
 */
/*
 * bundle_cache_test.cpp
 *
 *  \date       Feb 11, 2013
 *  \author     Apache Celix Project Team
 *  \copyright  Apache License, Version 2.0
 */
#include <stdlib.h>
#include <stdio.h>

#include "CppUTest/TestHarness.h"
#include "CppUTest/TestHarness_c.h"
#include "CppUTest/CommandLineTestRunner.h"
#include "CppUTestExt/MockSupport.h"

extern "C" {
#include <apr_file_io.h>
#include "bundle_cache_private.h"
}

int main(int argc, char** argv) {
	return RUN_ALL_TESTS(argc, argv);
}

TEST_GROUP(bundle_cache) {
	apr_pool_t *pool;

	void setup(void) {
		apr_initialize();
		apr_pool_create(&pool, NULL);
	}

	void teardown() {
		apr_pool_destroy(pool);
		mock().checkExpectations();
		mock().clear();
	}
};

TEST(bundle_cache, create) {
	properties_pt configuration = (properties_pt) 0x10;

	mock().expectOneCall("properties_get")
		.withParameter("properties", configuration)
		.withParameter("key", "org.osgi.framework.storage")
		.andReturnValue((char *) NULL);

	mock().expectOneCall("properties_destroy")
		.withParameter("properties", configuration);

	bundle_cache_pt cache = NULL;
	celix_status_t status = bundleCache_create(configuration, pool, &cache);
	LONGS_EQUAL(CELIX_SUCCESS, status);
}

TEST(bundle_cache, deleteTree) {
	bundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));
	char cacheDir[] = "bundle_cache_test_directory";
	char cacheFile[] = "bundle_cache_test_directory/temp";
	cache->cacheDir = cacheDir;
	cache->mp = pool;

	apr_dir_make(cacheDir, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);
	apr_file_t *file;
	apr_file_mktemp(&file, cacheFile, APR_UREAD|APR_UWRITE, pool);

	celix_status_t status = bundleCache_delete(cache);

	LONGS_EQUAL(CELIX_SUCCESS, status);

}

TEST(bundle_cache, getArchive) {
	bundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));
	char cacheDir[] = "bundle_cache_test_directory";
	cache->cacheDir = cacheDir;
	cache->mp = pool;

	char bundle0[] = "bundle_cache_test_directory/bundle0";
	char bundle1[] = "bundle_cache_test_directory/bundle1";
	apr_dir_make(cacheDir, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);
	apr_dir_make(bundle0, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);
	apr_dir_make(bundle1, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);

	bundle_archive_pt archive = (bundle_archive_pt) 0x10;
	mock().expectOneCall("bundleArchive_recreate")
		.withParameter("archiveRoot", bundle1)
		.withParameter("mp", pool)
		.andOutputParameter("bundle_archive", archive)
		.andReturnValue(CELIX_SUCCESS);

	array_list_pt archives = NULL;
	celix_status_t status = bundleCache_getArchives(cache, pool, &archives);

	LONGS_EQUAL(CELIX_SUCCESS, status);
	CHECK(archives);
	LONGS_EQUAL(1, arrayList_size(archives));
	POINTERS_EQUAL(archive, arrayList_get(archives, 0));

	apr_dir_remove(bundle0, pool);
	apr_dir_remove(bundle1, pool);
	apr_dir_remove(cacheDir, pool);
}

TEST(bundle_cache, createArchive) {
	bundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));
	char cacheDir[] = "bundle_cache_test_directory";
	cache->cacheDir = cacheDir;

	char archiveRoot[] = "bundle_cache_test_directory/bundle1";
	int id = 1;
	char location[] = "test.zip";
	bundle_archive_pt archive = (bundle_archive_pt) 0x10;
	mock().expectOneCall("bundleArchive_create")
		.withParameter("archiveRoot", archiveRoot)
		.withParameter("id", id)
		.withParameter("location", location)
		.withParameter("inputFile", (char *) NULL)
		.withParameter("mp", pool)
		.andOutputParameter("bundle_archive", archive)
		.andReturnValue(CELIX_SUCCESS);

	bundle_archive_pt actual;
	bundleCache_createArchive(cache, pool, 1l, location, NULL, &actual);
	POINTERS_EQUAL(archive, actual);
}
<commit_msg>CELIX-102: Fixed test.<commit_after>/**
 *Licensed to the Apache Software Foundation (ASF) under one
 *or more contributor license agreements.  See the NOTICE file
 *distributed with this work for additional information
 *regarding copyright ownership.  The ASF licenses this file
 *to you under the Apache License, Version 2.0 (the
 *"License"); you may not use this file except in compliance
 *with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *Unless required by applicable law or agreed to in writing,
 *software distributed under the License is distributed on an
 *"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 *specific language governing permissions and limitations
 *under the License.
 */
/*
 * bundle_cache_test.cpp
 *
 *  \date       Feb 11, 2013
 *  \author     Apache Celix Project Team
 *  \copyright  Apache License, Version 2.0
 */
#include <stdlib.h>
#include <stdio.h>

#include "CppUTest/TestHarness.h"
#include "CppUTest/TestHarness_c.h"
#include "CppUTest/CommandLineTestRunner.h"
#include "CppUTestExt/MockSupport.h"

extern "C" {
#include <apr_file_io.h>
#include "bundle_cache_private.h"
}

int main(int argc, char** argv) {
	return RUN_ALL_TESTS(argc, argv);
}

TEST_GROUP(bundle_cache) {
	apr_pool_t *pool;

	void setup(void) {
		apr_initialize();
		apr_pool_create(&pool, NULL);
	}

	void teardown() {
		apr_pool_destroy(pool);
		mock().checkExpectations();
		mock().clear();
	}
};

TEST(bundle_cache, create) {
	properties_pt configuration = (properties_pt) 0x10;

	mock().expectOneCall("properties_get")
		.withParameter("properties", configuration)
		.withParameter("key", "org.osgi.framework.storage")
		.andReturnValue((char *) NULL);

	bundle_cache_pt cache = NULL;
	celix_status_t status = bundleCache_create(configuration, pool, &cache);
	LONGS_EQUAL(CELIX_SUCCESS, status);
}

TEST(bundle_cache, deleteTree) {
	bundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));
	char cacheDir[] = "bundle_cache_test_directory";
	char cacheFile[] = "bundle_cache_test_directory/temp";
	cache->cacheDir = cacheDir;
	cache->mp = pool;

	apr_dir_make(cacheDir, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);
	apr_file_t *file;
	apr_file_mktemp(&file, cacheFile, APR_UREAD|APR_UWRITE, pool);

	celix_status_t status = bundleCache_delete(cache);

	LONGS_EQUAL(CELIX_SUCCESS, status);

}

TEST(bundle_cache, getArchive) {
	bundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));
	char cacheDir[] = "bundle_cache_test_directory";
	cache->cacheDir = cacheDir;
	cache->mp = pool;

	char bundle0[] = "bundle_cache_test_directory/bundle0";
	char bundle1[] = "bundle_cache_test_directory/bundle1";
	apr_dir_make(cacheDir, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);
	apr_dir_make(bundle0, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);
	apr_dir_make(bundle1, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);

	bundle_archive_pt archive = (bundle_archive_pt) 0x10;
	mock().expectOneCall("bundleArchive_recreate")
		.withParameter("archiveRoot", bundle1)
		.withParameter("mp", pool)
		.andOutputParameter("bundle_archive", archive)
		.andReturnValue(CELIX_SUCCESS);

	array_list_pt archives = NULL;
	celix_status_t status = bundleCache_getArchives(cache, pool, &archives);

	LONGS_EQUAL(CELIX_SUCCESS, status);
	CHECK(archives);
	LONGS_EQUAL(1, arrayList_size(archives));
	POINTERS_EQUAL(archive, arrayList_get(archives, 0));

	apr_dir_remove(bundle0, pool);
	apr_dir_remove(bundle1, pool);
	apr_dir_remove(cacheDir, pool);
}

TEST(bundle_cache, createArchive) {
	bundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));
	char cacheDir[] = "bundle_cache_test_directory";
	cache->cacheDir = cacheDir;

	char archiveRoot[] = "bundle_cache_test_directory/bundle1";
	int id = 1;
	char location[] = "test.zip";
	bundle_archive_pt archive = (bundle_archive_pt) 0x10;
	mock().expectOneCall("bundleArchive_create")
		.withParameter("archiveRoot", archiveRoot)
		.withParameter("id", id)
		.withParameter("location", location)
		.withParameter("inputFile", (char *) NULL)
		.withParameter("mp", pool)
		.andOutputParameter("bundle_archive", archive)
		.andReturnValue(CELIX_SUCCESS);

	bundle_archive_pt actual;
	bundleCache_createArchive(cache, pool, 1l, location, NULL, &actual);
	POINTERS_EQUAL(archive, actual);
}
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "MaterialPropertyIO.h"
#include "MaterialPropertyStorage.h"

const unsigned int MaterialPropertyIO::file_version = 1;

struct MSMPHeader
{
  char _id[4];                  // 4 letter ID
  unsigned int _file_version;   // file version
};

MaterialPropertyIO::MaterialPropertyIO(MaterialPropertyStorage & material_props, MaterialPropertyStorage & bnd_material_props) :
    _material_props(material_props),
    _bnd_material_props(bnd_material_props)
{
}

MaterialPropertyIO::~MaterialPropertyIO()
{
}

void
MaterialPropertyIO::write(const std::string & file_name)
{
  std::ofstream out(file_name.c_str(), std::ios::out | std::ios::binary);

  // header
  MSMPHeader head;
  memcpy(head._id, "MSMP", 4);
  head._file_version = file_version;
  out.write((const char *) &head, sizeof(head));

  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & props = _material_props.props();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & propsOld = _material_props.propsOld();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & propsOlder = _material_props.propsOlder();

  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_props = _bnd_material_props.props();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_propsOld = _bnd_material_props.propsOld();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_propsOlder = _bnd_material_props.propsOlder();

  // number of blocks
  // TODO: go over elements and figure out the groups of elements we are going to write in a file
  unsigned int n_blocks = 1;             // just one for right now
  out.write((const char *) &n_blocks, sizeof(n_blocks));

  // number of quadrature points
  // we go grab element 0, side 0 (it's volumetric mat. properties) and 0th property (all should be sized the same)
  unsigned int n_qps = props[0][0][0]->size();     // we expect to have element 0 always (lame)
  out.write((const char *) &n_qps, sizeof(n_qps));

  // save the number of elements in this block (since we do only 1 block right now, we store everything)
  unsigned int n_elems = props.size();
  out.write((const char *) &n_elems, sizeof(n_elems));

  // properties
  std::set<unsigned int> & stateful_props = _material_props.statefulProps();
  std::vector<unsigned int> prop_ids;
  prop_ids.insert(prop_ids.end(), stateful_props.begin(), stateful_props.end());
  std::sort(prop_ids.begin(), prop_ids.end());

  unsigned int n_props = prop_ids.size();        // number of properties in this block
  out.write((const char *) &n_props, sizeof(n_props));
  // property names
  for (unsigned int i = 0; i < n_props; ++i)
  {
    std::string prop_name = _material_props.statefulPropNames()[i];
    out.write(prop_name.c_str(), prop_name.length() + 1);                 // do not forget the trailing zero ;-)
  }

  // save current material properties
  for (unsigned int e = 0; e < n_elems; ++e)
  {
    unsigned int elem_id = e;
    out.write((const char *) &elem_id, sizeof(elem_id));

    // write out the properties themselves
    for (unsigned int i = 0; i < n_props; ++i)
    {
      unsigned int pid = prop_ids[i];
      props[e][0][pid]->store(out);
      propsOld[e][0][pid]->store(out);
      if (_material_props.hasOlderProperties())
        propsOlder[e][0][pid]->store(out);
    }
  }

  // save the material props on sides
  unsigned int n_sides = bnd_props[0].size();
  out.write((const char *) &n_sides, sizeof(n_sides));

  // save current material properties
  for (unsigned int e = 0; e < n_elems; ++e)
  {
    unsigned int elem_id = e;
    out.write((const char *) &elem_id, sizeof(elem_id));

    for (unsigned int s = 0; s < n_sides; ++s)
    {
      // write out the properties themselves
      for (unsigned int i = 0; i < n_props; ++i)
      {
        unsigned int pid = prop_ids[i];
        bnd_props[e][s][pid]->store(out);
        bnd_propsOld[e][s][pid]->store(out);
        if (_material_props.hasOlderProperties())
          bnd_propsOlder[e][s][pid]->store(out);
      }
    }
  }

  // TODO: end of the loop over blocks

  out.close();
}

void
MaterialPropertyIO::read(const std::string & file_name)
{
  std::ifstream in(file_name.c_str(), std::ios::in | std::ios::binary);

  // header
  MSMPHeader head;
  in.read((char *) &head, sizeof(head));

  // check the header
  if (!(head._id[0] == 'M' && head._id[1] == 'S' && head._id[2] == 'M' && head._id[3] == 'P'))
    mooseError("Corrupted material properties file");
  // check the file version
  if (head._file_version > file_version)
    mooseError("Trying to restart from a newer file version - you need to update MOOSE");

  // grab some references we will need to later
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & props = _material_props.props();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & propsOld = _material_props.propsOld();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & propsOlder = _material_props.propsOlder();

  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_props = _bnd_material_props.props();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_propsOld = _bnd_material_props.propsOld();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_propsOlder = _bnd_material_props.propsOlder();

  std::map<unsigned int, std::string> stateful_prop_names = _material_props.statefulPropNames();
  std::map<std::string, unsigned int> stateful_prop_ids;                                // inverse map of stateful_prop_names
  for (std::map<unsigned int, std::string>::iterator it = stateful_prop_names.begin(); it != stateful_prop_names.end(); ++it)
    stateful_prop_ids[it->second] = it->first;

  // number of blocks
  unsigned int n_blocks = 0;
  in.read((char *) &n_blocks, sizeof(n_blocks));

  // loop over block
  for (unsigned int blk_id = 0; blk_id < n_blocks; blk_id++)
  {
    // number of quadrature points
    unsigned int n_qps = 0;
    in.read((char *) &n_qps, sizeof(n_qps));
    // number of elements
    unsigned int n_elems = props.size();
    in.read((char *) &n_elems, sizeof(n_elems));
    // number of properties in this block
    unsigned int n_props = 0;
    in.read((char *) &n_props, sizeof(n_props));
    // property names
    std::vector<std::string> prop_names;

    for (unsigned int i = 0; i < n_props; ++i)
    {
      std::string prop_name;
      char ch = 0;
      do {
        in.read(&ch, 1);
        if (ch != '\0')
          prop_name += ch;
      } while (ch != '\0');
      prop_names.push_back(prop_name);
    }

    for (unsigned int e = 0; e < n_elems; ++e)
    {
      unsigned int elem_id = 0;
      in.read((char *) &elem_id, sizeof(elem_id));

      // read in the properties themselves
      for (unsigned int i = 0; i < n_props; ++i)
      {
        unsigned int pid = stateful_prop_ids[prop_names[i]];

        props[e][0][pid]->load(in);
        propsOld[e][0][pid]->load(in);
        if (_material_props.hasOlderProperties())               // this should actually check if the value is stored in the file (we do not store it right now)
          propsOlder[e][0][pid]->load(in);
      }
    }

    // load in the material props on sides
    unsigned int n_sides = 0;
    in.read((char *) &n_sides, sizeof(n_sides));

    for (unsigned int e = 0; e < n_elems; ++e)
    {
      unsigned int elem_id = 0;
      in.read((char *) &elem_id, sizeof(elem_id));

      for (unsigned int s = 0; s < n_sides; ++s)
      {
        // read in the properties themselves
        for (unsigned int i = 0; i < n_props; ++i)
        {
          unsigned int pid = stateful_prop_ids[prop_names[i]];

          bnd_props[e][s][pid]->load(in);
          bnd_propsOld[e][s][pid]->load(in);
          if (_material_props.hasOlderProperties())               // this should actually check if the value is stored in the file (we do not store it right now)
            bnd_propsOlder[e][s][pid]->load(in);
        }
      }
    }

  }

  in.close();
}
<commit_msg>Fixing incorrect indexing into material property names array (closes #1138)<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "MaterialPropertyIO.h"
#include "MaterialPropertyStorage.h"

const unsigned int MaterialPropertyIO::file_version = 1;

struct MSMPHeader
{
  char _id[4];                  // 4 letter ID
  unsigned int _file_version;   // file version
};

MaterialPropertyIO::MaterialPropertyIO(MaterialPropertyStorage & material_props, MaterialPropertyStorage & bnd_material_props) :
    _material_props(material_props),
    _bnd_material_props(bnd_material_props)
{
}

MaterialPropertyIO::~MaterialPropertyIO()
{
}

void
MaterialPropertyIO::write(const std::string & file_name)
{
  std::ofstream out(file_name.c_str(), std::ios::out | std::ios::binary);

  // header
  MSMPHeader head;
  memcpy(head._id, "MSMP", 4);
  head._file_version = file_version;
  out.write((const char *) &head, sizeof(head));

  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & props = _material_props.props();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & propsOld = _material_props.propsOld();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & propsOlder = _material_props.propsOlder();

  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_props = _bnd_material_props.props();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_propsOld = _bnd_material_props.propsOld();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_propsOlder = _bnd_material_props.propsOlder();

  // number of blocks
  // TODO: go over elements and figure out the groups of elements we are going to write in a file
  unsigned int n_blocks = 1;             // just one for right now
  out.write((const char *) &n_blocks, sizeof(n_blocks));

  // number of quadrature points
  // we go grab element 0, side 0 (it's volumetric mat. properties) and 0th property (all should be sized the same)
  unsigned int n_qps = props[0][0][0]->size();     // we expect to have element 0 always (lame)
  out.write((const char *) &n_qps, sizeof(n_qps));

  // save the number of elements in this block (since we do only 1 block right now, we store everything)
  unsigned int n_elems = props.size();
  out.write((const char *) &n_elems, sizeof(n_elems));

  // properties
  std::set<unsigned int> & stateful_props = _material_props.statefulProps();
  std::vector<unsigned int> prop_ids;
  prop_ids.insert(prop_ids.end(), stateful_props.begin(), stateful_props.end());
  std::sort(prop_ids.begin(), prop_ids.end());

  unsigned int n_props = prop_ids.size();        // number of properties in this block
  out.write((const char *) &n_props, sizeof(n_props));
  // property names
  for (unsigned int i = 0; i < n_props; i++)
  {
    unsigned int pid = prop_ids[i];
    std::string prop_name = _material_props.statefulPropNames()[pid];
    out.write(prop_name.c_str(), prop_name.length() + 1);                 // do not forget the trailing zero ;-)
  }

  // save current material properties
  for (unsigned int e = 0; e < n_elems; e++)
  {
    unsigned int elem_id = e;
    out.write((const char *) &elem_id, sizeof(elem_id));

    // write out the properties themselves
    for (unsigned int i = 0; i < n_props; i++)
    {
      unsigned int pid = prop_ids[i];
      props[e][0][pid]->store(out);
      propsOld[e][0][pid]->store(out);
      if (_material_props.hasOlderProperties())
        propsOlder[e][0][pid]->store(out);
    }
  }

  // save the material props on sides
  unsigned int n_sides = bnd_props[0].size();
  out.write((const char *) &n_sides, sizeof(n_sides));

  // save current material properties
  for (unsigned int e = 0; e < n_elems; e++)
  {
    unsigned int elem_id = e;
    out.write((const char *) &elem_id, sizeof(elem_id));

    for (unsigned int s = 0; s < n_sides; s++)
    {
      // write out the properties themselves
      for (unsigned int i = 0; i < n_props; i++)
      {
        unsigned int pid = prop_ids[i];
        bnd_props[e][s][pid]->store(out);
        bnd_propsOld[e][s][pid]->store(out);
        if (_material_props.hasOlderProperties())
          bnd_propsOlder[e][s][pid]->store(out);
      }
    }
  }

  // TODO: end of the loop over blocks

  out.close();
}

void
MaterialPropertyIO::read(const std::string & file_name)
{
  std::ifstream in(file_name.c_str(), std::ios::in | std::ios::binary);

  // header
  MSMPHeader head;
  in.read((char *) &head, sizeof(head));

  // check the header
  if (!(head._id[0] == 'M' && head._id[1] == 'S' && head._id[2] == 'M' && head._id[3] == 'P'))
    mooseError("Corrupted material properties file");
  // check the file version
  if (head._file_version > file_version)
    mooseError("Trying to restart from a newer file version - you need to update MOOSE");

  // grab some references we will need to later
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & props = _material_props.props();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & propsOld = _material_props.propsOld();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & propsOlder = _material_props.propsOlder();

  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_props = _bnd_material_props.props();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_propsOld = _bnd_material_props.propsOld();
  HashMap<unsigned int, HashMap<unsigned int, MaterialProperties> > & bnd_propsOlder = _bnd_material_props.propsOlder();

  std::map<unsigned int, std::string> stateful_prop_names = _material_props.statefulPropNames();
  std::map<std::string, unsigned int> stateful_prop_ids;                                // inverse map of stateful_prop_names
  for (std::map<unsigned int, std::string>::iterator it = stateful_prop_names.begin(); it != stateful_prop_names.end(); ++it)
    stateful_prop_ids[it->second] = it->first;

  // number of blocks
  unsigned int n_blocks = 0;
  in.read((char *) &n_blocks, sizeof(n_blocks));

  // loop over block
  for (unsigned int blk_id = 0; blk_id < n_blocks; blk_id++)
  {
    // number of quadrature points
    unsigned int n_qps = 0;
    in.read((char *) &n_qps, sizeof(n_qps));
    // number of elements
    unsigned int n_elems = props.size();
    in.read((char *) &n_elems, sizeof(n_elems));
    // number of properties in this block
    unsigned int n_props = 0;
    in.read((char *) &n_props, sizeof(n_props));
    // property names
    std::vector<std::string> prop_names;

    for (unsigned int i = 0; i < n_props; i++)
    {
      std::string prop_name;
      char ch = 0;
      do {
        in.read(&ch, 1);
        if (ch != '\0')
          prop_name += ch;
      } while (ch != '\0');
      prop_names.push_back(prop_name);
    }

    for (unsigned int e = 0; e < n_elems; e++)
    {
      unsigned int elem_id = 0;
      in.read((char *) &elem_id, sizeof(elem_id));

      // read in the properties themselves
      for (unsigned int i = 0; i < n_props; i++)
      {
        unsigned int pid = stateful_prop_ids[prop_names[i]];

        props[e][0][pid]->load(in);
        propsOld[e][0][pid]->load(in);
        if (_material_props.hasOlderProperties())               // this should actually check if the value is stored in the file (we do not store it right now)
          propsOlder[e][0][pid]->load(in);
      }
    }

    // load in the material props on sides
    unsigned int n_sides = 0;
    in.read((char *) &n_sides, sizeof(n_sides));

    for (unsigned int e = 0; e < n_elems; e++)
    {
      unsigned int elem_id = 0;
      in.read((char *) &elem_id, sizeof(elem_id));

      for (unsigned int s = 0; s < n_sides; s++)
      {
        // read in the properties themselves
        for (unsigned int i = 0; i < n_props; i++)
        {
          unsigned int pid = stateful_prop_ids[prop_names[i]];

          bnd_props[e][s][pid]->load(in);
          bnd_propsOld[e][s][pid]->load(in);
          if (_material_props.hasOlderProperties())               // this should actually check if the value is stored in the file (we do not store it right now)
            bnd_propsOlder[e][s][pid]->load(in);
        }
      }
    }

  }

  in.close();
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -I %S -Xclang -verify
// XFAIL:*
// Test incompleteType

.rawInput 1
class __attribute__((annotate("Def.h"))) C;
//expected-warning + {{}}
//expected-note + {{}}
.rawInput 0

C c;
//expected-error {{}}

<commit_msg>Improve and reenable test.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -I %S -Xclang -verify
// Test incompleteType

.rawInput 1
class __attribute__((annotate("Def.h"))) C;
//expected-note + {{}}
.rawInput 0

C c; //expected-error {{variable has incomplete type 'C'}}
.q
<|endoftext|>


<commit_before>/*
				Copyright <SWGEmu>
		See file COPYING for copying conditions.*/

#include "server/zone/objects/resource/ResourceContainer.h"
#include "server/zone/objects/resource/ResourceSpawn.h"
#include "server/zone/packets/resource/ResourceContainerObjectDeltaMessage3.h"
#include "server/zone/packets/resource/ResourceContainerObjectMessage3.h"
#include "server/zone/packets/resource/ResourceContainerObjectMessage6.h"
#include "server/zone/ZoneClientSession.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/objects/tangible/TangibleObject.h"
#include "server/zone/objects/creature/CreatureObject.h"

void ResourceContainerImplementation::fillAttributeList(AttributeListMessage* alm, CreatureObject* object) {
	TangibleObjectImplementation::fillAttributeList(alm, object);

	StringBuffer ssQuantity;
	ssQuantity << stackQuantity << "/" << ResourceContainer::MAXSIZE;

	alm->insertAttribute("resource_name", getSpawnName());
	alm->insertAttribute("resource_contents", ssQuantity);

	if (spawnObject != NULL)
		spawnObject->fillAttributeList(alm, object);
	else
		object->sendSystemMessage("error resource container has no spawn object");
}

void ResourceContainerImplementation::sendBaselinesTo(SceneObject* player) {
	info("sending rnco baselines");

	BaseMessage* rnco3 = new ResourceContainerObjectMessage3(_this.get());
	player->sendMessage(rnco3);

	BaseMessage* rnco6 = new ResourceContainerObjectMessage6(_this.get());
	player->sendMessage(rnco6);
}

void ResourceContainerImplementation::setUseCount(uint32 newQuantity, bool notifyClient) {
	setQuantity(newQuantity, notifyClient);
}

void ResourceContainerImplementation::setQuantity(uint32 quantity, bool doNotify, bool ignoreMax) {
	Locker _locker(_this.get());
	ManagedReference<SceneObject*> parent = getParent().get();
	stackQuantity = quantity;

	if(stackQuantity < 1) {

		if(parent != NULL) {
			/*parent->broadcastDestroy(_this.get(), true);
			parent->removeObject(_this.get(), false);*/
			//setParent(NULL);

			destroyObjectFromWorld(true);
		}

		destroyObjectFromDatabase(true);
		return;
	}

	int newStackSize = 0;

	if (!ignoreMax && stackQuantity > ResourceContainer::MAXSIZE) {

		newStackSize = stackQuantity - ResourceContainer::MAXSIZE;
		stackQuantity = ResourceContainer::MAXSIZE;
	}

	if (newStackSize > 0) {
		if (parent != NULL) {

			ResourceContainer* harvestedResource = spawnObject->createResource(newStackSize);

			if (parent->transferObject(harvestedResource, -1, true)) {
				parent->broadcastObject(harvestedResource, true);
			} else {
				harvestedResource->destroyObjectFromDatabase(true);
			}
		}
	}

	if(!doNotify)
		return;

	ResourceContainerObjectDeltaMessage3* rcnod3 =
			new ResourceContainerObjectDeltaMessage3(_this.get());

	rcnod3->updateQuantity();
	rcnod3->close();

	broadcastMessage(rcnod3, true);
}

void ResourceContainerImplementation::split(int newStackSize) {
	if (getQuantity() <= newStackSize)
		return;

	if(newStackSize > getQuantity())
		newStackSize = getQuantity();

	ManagedReference<SceneObject*> sceneParent = cast<SceneObject*>(parent.get().get());

	if (sceneParent == NULL)
		return;

	Locker locker(spawnObject);

	ManagedReference<ResourceContainer*> newResource = spawnObject->createResource(newStackSize);

	locker.release();

	if(newResource == NULL)
		return;

	Locker rlocker(newResource);

	if (newResource->getSpawnObject() == NULL) {
		newResource->destroyObjectFromDatabase(true);
		return;
	}

	if(sceneParent->transferObject(newResource, -1, true)) {
		sceneParent->broadcastObject(newResource, true);

		setQuantity(getQuantity() - newStackSize);
	} else {
		StringBuffer errorMessage;
		errorMessage << "Unable to split resource in container type: " << sceneParent->getGameObjectType() << " " << sceneParent->getDisplayedName();
		error(errorMessage.toString());

		newResource->destroyObjectFromDatabase(true);
	}
}

void ResourceContainerImplementation::split(int newStackSize, CreatureObject* player) {

	ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");

	if (inventory == NULL)
		return;

	Locker locker(spawnObject);

	ManagedReference<ResourceContainer*> newResource = spawnObject->createResource(newStackSize);

	locker.release();

	if (newResource == NULL)
		return;

	Locker rlocker(newResource);

	if (newResource->getSpawnObject() == NULL) {
		newResource->destroyObjectFromDatabase(true);
		return;
	}

	if(inventory->transferObject(newResource, -1, true)) {
		newResource->sendTo(player, true);

		setQuantity(getQuantity() - newStackSize);
	} else {
		error("Unable to split resource to player: " + player->getFirstName());
		newResource->destroyObjectFromDatabase(true);
	}
}

void ResourceContainerImplementation::combine(ResourceContainer* fromContainer) {
	Locker _locker(_this.get());
	Locker clocker(fromContainer, _this.get());

	setQuantity(getQuantity() + fromContainer->getQuantity());
	fromContainer->setQuantity(0);

	fromContainer->destroyObjectFromWorld(true);
	fromContainer->destroyObjectFromDatabase(true);
}

void ResourceContainerImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {
	TangibleObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);

	if (spawnObject != NULL)
		spawnObject->decreaseContainerReferenceCount();
}
<commit_msg>[Fixed] stability issue<commit_after>/*
				Copyright <SWGEmu>
		See file COPYING for copying conditions.*/

#include "server/zone/objects/resource/ResourceContainer.h"
#include "server/zone/objects/resource/ResourceSpawn.h"
#include "server/zone/packets/resource/ResourceContainerObjectDeltaMessage3.h"
#include "server/zone/packets/resource/ResourceContainerObjectMessage3.h"
#include "server/zone/packets/resource/ResourceContainerObjectMessage6.h"
#include "server/zone/ZoneClientSession.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/objects/tangible/TangibleObject.h"
#include "server/zone/objects/creature/CreatureObject.h"

void ResourceContainerImplementation::fillAttributeList(AttributeListMessage* alm, CreatureObject* object) {
	TangibleObjectImplementation::fillAttributeList(alm, object);

	StringBuffer ssQuantity;
	ssQuantity << stackQuantity << "/" << ResourceContainer::MAXSIZE;

	alm->insertAttribute("resource_name", getSpawnName());
	alm->insertAttribute("resource_contents", ssQuantity);

	if (spawnObject != NULL)
		spawnObject->fillAttributeList(alm, object);
	else
		object->sendSystemMessage("error resource container has no spawn object");
}

void ResourceContainerImplementation::sendBaselinesTo(SceneObject* player) {
	info("sending rnco baselines");

	BaseMessage* rnco3 = new ResourceContainerObjectMessage3(_this.get());
	player->sendMessage(rnco3);

	BaseMessage* rnco6 = new ResourceContainerObjectMessage6(_this.get());
	player->sendMessage(rnco6);
}

void ResourceContainerImplementation::setUseCount(uint32 newQuantity, bool notifyClient) {
	setQuantity(newQuantity, notifyClient);
}

void ResourceContainerImplementation::setQuantity(uint32 quantity, bool doNotify, bool ignoreMax) {
	Locker _locker(_this.get());
	ManagedReference<SceneObject*> parent = getParent().get();
	stackQuantity = quantity;

	if(stackQuantity < 1) {

		if(parent != NULL) {
			/*parent->broadcastDestroy(_this.get(), true);
			parent->removeObject(_this.get(), false);*/
			//setParent(NULL);

			destroyObjectFromWorld(true);
		}

		destroyObjectFromDatabase(true);
		return;
	}

	int newStackSize = 0;

	if (!ignoreMax && stackQuantity > ResourceContainer::MAXSIZE) {

		newStackSize = stackQuantity - ResourceContainer::MAXSIZE;
		stackQuantity = ResourceContainer::MAXSIZE;
	}

	if (newStackSize > 0) {
		if (parent != NULL) {

			Locker locker(spawnObject);

			ResourceContainer* harvestedResource = spawnObject->createResource(newStackSize);

			locker.release();

			Locker clocker(harvestedResource, _this.get());

			if (parent->transferObject(harvestedResource, -1, true)) {
				parent->broadcastObject(harvestedResource, true);
			} else {
				harvestedResource->destroyObjectFromDatabase(true);
			}
		}
	}

	if(!doNotify)
		return;

	ResourceContainerObjectDeltaMessage3* rcnod3 =
			new ResourceContainerObjectDeltaMessage3(_this.get());

	rcnod3->updateQuantity();
	rcnod3->close();

	broadcastMessage(rcnod3, true);
}

void ResourceContainerImplementation::split(int newStackSize) {
	if (getQuantity() <= newStackSize)
		return;

	if(newStackSize > getQuantity())
		newStackSize = getQuantity();

	ManagedReference<SceneObject*> sceneParent = cast<SceneObject*>(parent.get().get());

	if (sceneParent == NULL)
		return;

	Locker locker(spawnObject);

	ManagedReference<ResourceContainer*> newResource = spawnObject->createResource(newStackSize);

	locker.release();

	if(newResource == NULL)
		return;

	Locker rlocker(newResource);

	if (newResource->getSpawnObject() == NULL) {
		newResource->destroyObjectFromDatabase(true);
		return;
	}

	if(sceneParent->transferObject(newResource, -1, true)) {
		sceneParent->broadcastObject(newResource, true);

		setQuantity(getQuantity() - newStackSize);
	} else {
		StringBuffer errorMessage;
		errorMessage << "Unable to split resource in container type: " << sceneParent->getGameObjectType() << " " << sceneParent->getDisplayedName();
		error(errorMessage.toString());

		newResource->destroyObjectFromDatabase(true);
	}
}

void ResourceContainerImplementation::split(int newStackSize, CreatureObject* player) {

	ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");

	if (inventory == NULL)
		return;

	Locker locker(spawnObject);

	ManagedReference<ResourceContainer*> newResource = spawnObject->createResource(newStackSize);

	locker.release();

	if (newResource == NULL)
		return;

	Locker rlocker(newResource);

	if (newResource->getSpawnObject() == NULL) {
		newResource->destroyObjectFromDatabase(true);
		return;
	}

	if(inventory->transferObject(newResource, -1, true)) {
		newResource->sendTo(player, true);

		setQuantity(getQuantity() - newStackSize);
	} else {
		error("Unable to split resource to player: " + player->getFirstName());
		newResource->destroyObjectFromDatabase(true);
	}
}

void ResourceContainerImplementation::combine(ResourceContainer* fromContainer) {
	Locker _locker(_this.get());
	Locker clocker(fromContainer, _this.get());

	setQuantity(getQuantity() + fromContainer->getQuantity());
	fromContainer->setQuantity(0);

	fromContainer->destroyObjectFromWorld(true);
	fromContainer->destroyObjectFromDatabase(true);
}

void ResourceContainerImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {
	TangibleObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);

	if (spawnObject != NULL)
		spawnObject->decreaseContainerReferenceCount();
}
<|endoftext|>


<commit_before>#include "fht.h"

#include <vector>

#include "gtest/gtest.h"

#include "test_utils.h"

using lsh::compare_vectors;
using lsh::fht;
using std::vector;

const float eps = 0.0001;

TEST(PolytopeHashTest, FHTTest1) {
  vector<float> data1 = {0.0, 1.0, 0.0, 0.0};
  vector<float> expected_result1 = {1.0, -1.0, 1.0, -1.0};
  int log_dim1 = std::log2(data1.size());
  fht(data1.data(), data1.size(), log_dim1);
  compare_vectors(expected_result1, data1, eps);
}
<commit_msg>removing old FHT test<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <cassert>
#include <ctime>
#include "chtable.hpp"
#include "hash_mixer.hpp"

namespace chtable{
template <>
class Hash<unsigned> {
	HashMixer<unsigned> hashf_;
public:
	Hash(unsigned k, unsigned seed) : hashf_(k, seed){}
	unsigned operator () (unsigned i, unsigned k) const
	{
		return hashf_(i, k);
	}
};
}
static inline unsigned random(unsigned x)
{
	return (x * 16807) % ((2 << 31) - 1);
}

template<unsigned LENGTH>
struct ChtableTester{
	unsigned data [LENGTH];
	unsigned membership[LENGTH];
	Chtable<unsigned, unsigned > t;
	double maxLoad;
	double count;
	double capacity;
	double totalLoad;
	ChtableTester()
		:t(13, 2)
	{
		unsigned seed = 10;
		for(int i = 0; i < LENGTH; i++)
		{
			seed = random(seed);
			data[i] = seed;
			membership[i] = 0;
		}

		maxLoad = 0;
		totalLoad = 0;
	}

	clock_t testInsert()
	{
		clock_t t1 = clock();
		for(unsigned i = 0; i < LENGTH; i++) {
			bool good = t.Set(data[i], i);
			assert(good);

			bool found;
			unsigned val;
			std::tie(val, found) = t.Get(data[i]);
			assert(found);
			assert(val == i);

			count = t.count();
			capacity = t.capacity();
			double load = count / capacity;
			totalLoad += load;
			if(load > maxLoad)
				maxLoad = load;
		}
		clock_t t2 = clock();
		return t2 - t1;
	}
	void testFind()
	{
		for(unsigned i = 0; i < LENGTH; i++)
		{
			bool found;
			unsigned val;
			std::tie(val, found) = t.Get(data[i]);
			if( !found )
				fputs("find error\n", stderr);
			else if( val != i)
				fputs("data error 3\n", stderr);
		}
	}

	void testDelete()
	{
		for(unsigned i = 0; i < LENGTH; i++)
		{
			bool found;
			unsigned val;
			std::tie(val, found) = t.Get(data[i]);
			if( found )
			{
				t.Delete(data[i]);

				std::tie(val, found) = t.Get(data[i]);
				if( found )
					puts("removal error");
			}
		}
	}
	void testIterator()
	{
		for(auto & pair : t)
		{
			unsigned i = pair.val;
			if(data[i] != pair.key)
				fputs("data error\n", stderr);
		}
	}
};
int main(void)
{

	ChtableTester<30000> t;
	clock_t insertTime = t.testInsert();

	std::cout << "count: " << t.count << std::endl <<
		"capacity: " << t.capacity << std::endl <<
		"max load: " << t.maxLoad << std::endl <<
		"current load: " << t.count / t.capacity << std::endl <<
		"average load: " << t.totalLoad / t.count << std::endl <<
		"time: " << insertTime << std::endl;
	t.testFind();
	t.testDelete();
	t.testIterator();
	// test iterator

	// test find

	// test removal

	return 0;
 }
<commit_msg>more detailed test program<commit_after>#include <iostream>
#include <cassert>
#include <ctime>
#include "chtable.hpp"
#include "hash_mixer.hpp"

namespace chtable{
template <>
class Hash<unsigned> {
	HashMixer<unsigned> hashf_;
public:
	Hash(unsigned k, unsigned seed) : hashf_(k, seed){}
	unsigned operator () (unsigned i, unsigned k) const
	{
		return hashf_(i, k);
	}
};
}
static inline unsigned random(unsigned x)
{
	return (x * 16807) % ((2 << 31) - 1);
}

template<unsigned LENGTH>
struct ChtableTester{
	unsigned data [LENGTH];
	unsigned membership[LENGTH];
	Chtable<unsigned, unsigned> t;
	double maxLoad;
	double count;
	double capacity;
	double totalLoad;
	ChtableTester()
		:t(30000, 2)
	{
		unsigned seed = 10;
		for(int i = 0; i < LENGTH; i++)
		{
			seed = random(seed);
			data[i] = seed;
			membership[i] = 0;
		}

		maxLoad = 0;
		totalLoad = 0;
	}

	clock_t testInsert()
	{
		clock_t t1 = clock();
		for(unsigned i = 0; i < LENGTH; i++) {
			t.Set(data[i], i);

			bool found;
			unsigned val;
			std::tie(val, found) = t.Get(data[i]);
			assert(found);
			assert(val == i);

			count = t.count();
			capacity = t.capacity();
			double load = count / capacity;
			totalLoad += load;
			if(load > maxLoad)
				maxLoad = load;
		}
		clock_t t2 = clock();
		return t2 - t1;
	}
	clock_t testFind()
	{
		clock_t t1 = clock();
		for(unsigned i = 0; i < LENGTH; i++)
		{
			bool found;
			unsigned val;
			std::tie(val, found) = t.Get(data[i]);
			if( !found )
				fputs("find error\n", stderr);
			else if( val != i)
				fputs("data error 3\n", stderr);
		}
		clock_t t2 = clock();
		return t2 - t1;
	}

	clock_t testDelete()
	{
		clock_t t1 = clock();
		for(unsigned i = 0; i < LENGTH; i++)
		{
			bool found;
			unsigned val;
			std::tie(val, found) = t.Get(data[i]);
			if( found )
			{
				bool good = t.Delete(data[i]);
				assert(good);
				std::tie(val, found) = t.Get(data[i]);
				if( found )
					puts("removal error");
			}
		}
		clock_t t2 = clock();
		return t2 - t1;
	}
	clock_t testIterator()
	{
		clock_t t1 = clock();
		for(auto pair : t)
		{
			unsigned i = pair.val;
			if(data[i] != pair.key)
				fputs("iterator error\n", stderr);
		}
		clock_t t2 = clock();
		return t2 - t1;
	}
};
int main(void)
{

	ChtableTester<30000> t;
	clock_t insertTime = t.testInsert();

	std::cout << "count: " << t.count << std::endl <<
		"capacity: " << t.capacity << std::endl <<
		"max load: " << t.maxLoad << std::endl <<
		"current load: " << t.count / t.capacity << std::endl <<
		"average load: " << t.totalLoad / t.count << std::endl <<
		"insert time: " << insertTime << std::endl;

	clock_t findTime = t.testFind();
	std::cout << "find time: " << findTime << std::endl;

	clock_t iterTime = t.testIterator();
	std::cout << "iter time: " << iterTime << std::endl;

	clock_t deleteTime = t.testDelete();
	std::cout << "delete time: " << deleteTime << std::endl;

	return 0;
 }
<|endoftext|>


<commit_before>// RUN: %clang_cc1 %s -triple i686-pc-win32 -fsyntax-only -Wmicrosoft -verify -fms-extensions -fexceptions -fcxx-exceptions

// ::type_info is predeclared with forward class declartion
void f(const type_info &a);

// Microsoft doesn't validate exception specification.
void foo(); // expected-note {{previous declaration}}
void foo() throw(); // expected-warning {{exception specification in declaration does not match previous declaration}}

void r6() throw(...); // expected-note {{previous declaration}}
void r6() throw(int); // expected-warning {{exception specification in declaration does not match previous declaration}}

struct Base {
  virtual void f2();
  virtual void f3() throw(...);
};

struct Derived : Base {
  virtual void f2() throw(...);
  virtual void f3();
};

// MSVC allows type definition in anonymous union and struct
struct A
{
  union
  {
    int a;
    struct B  // expected-warning {{types declared in an anonymous union are a Microsoft extension}}
    {
      int c;
    } d;

    union C   // expected-warning {{types declared in an anonymous union are a Microsoft extension}}
    {
      int e;
      int ee;
    } f;

    typedef int D;  // expected-warning {{types declared in an anonymous union are a Microsoft extension}}
    struct F;  // expected-warning {{types declared in an anonymous union are a Microsoft extension}}
  };

  struct
  {
    int a2;

    struct B2  // expected-warning {{types declared in an anonymous struct are a Microsoft extension}}
    {
      int c2;
    } d2;

	union C2  // expected-warning {{types declared in an anonymous struct are a Microsoft extension}}
    {
      int e2;
      int ee2;
    } f2;

    typedef int D2;  // expected-warning {{types declared in an anonymous struct are a Microsoft extension}}
    struct F2;  // expected-warning {{types declared in an anonymous struct are a Microsoft extension}}
  };
};

// __stdcall handling
struct M {
    int __stdcall addP();
    float __stdcall subtractP();
};

template<typename T> void h1(T (__stdcall M::* const )()) { }

void m1() {
  h1<int>(&M::addP);
  h1(&M::subtractP);
}

//MSVC allows forward enum declaration
enum ENUM; // expected-warning {{forward references to 'enum' types are a Microsoft extension}}
ENUM *var = 0;
ENUM var2 = (ENUM)3;
enum ENUM1* var3 = 0;// expected-warning {{forward references to 'enum' types are a Microsoft extension}}

enum ENUM2 {
	ENUM2_a = (enum ENUM2) 4,
	ENUM2_b = 0x9FFFFFFF, // expected-warning {{enumerator value is not representable in the underlying type 'int'}}
	ENUM2_c = 0x100000000 // expected-warning {{enumerator value is not representable in the underlying type 'int'}}
};

void f(long long);
void f(int);

int main()
{
  // This is an ambiguous call in standard C++.
  // This calls f(long long) in Microsoft mode because LL is always signed.
  f(0xffffffffffffffffLL);
  f(0xffffffffffffffffi64);
}

// Enumeration types with a fixed underlying type.
const int seventeen = 17;
typedef int Int;

struct X0 {
  enum E1 : Int { SomeOtherValue } field; // expected-warning{{enumeration types with a fixed underlying type are a Microsoft extension}}
  enum E1 : seventeen;
};

enum : long long {  // expected-warning{{enumeration types with a fixed underlying type are a Microsoft extension}}
  SomeValue = 0x100000000
};

class AAA {
__declspec(dllimport) void f(void) { }
void f2(void);
};

__declspec(dllimport) void AAA::f2(void) { // expected-error {{dllimport attribute can be applied only to symbol}}

}

template <class T>
class BB {
public:
   void f(int g = 10 ); // expected-note {{previous definition is here}}
};

template <class T>
void BB<T>::f(int g = 0) { } // expected-warning {{redefinition of default argument}}

namespace MissingTypename {

template<class T> class A {
public:
	 typedef int TYPE;
};

template<class T> class B {
public:
	 typedef int TYPE;
};

template<class T, class U>
class C : private A<T>, public B<U> {
public:
   typedef A<T> Base1;
   typedef B<U> Base2;
   typedef A<U> Base3;

   A<T>::TYPE a1; // expected-warning {{missing 'typename' prior to dependent type name}}
   Base1::TYPE a2; // expected-warning {{missing 'typename' prior to dependent type name}}

   B<U>::TYPE a3; // expected-warning {{missing 'typename' prior to dependent type name}}
   Base2::TYPE a4; // expected-warning {{missing 'typename' prior to dependent type name}}

   A<U>::TYPE a5; // expected-error {{missing 'typename' prior to dependent type name}}
   Base3::TYPE a6; // expected-error {{missing 'typename' prior to dependent type name}}
 };

}

extern void static_func();
void static_func(); // expected-note {{previous declaration is here}}

static void static_func() // expected-warning {{static declaration of 'static_func' follows non-static declaration}}
{

}

long function_prototype(int a);
long (*function_ptr)(int a);

void function_to_voidptr_conv() {
   void *a1 = function_prototype;
   void *a2 = &function_prototype;
   void *a1 = function_ptr;
   void *a2 = &function_ptr;
}
<commit_msg>Fix test.<commit_after>// RUN: %clang_cc1 %s -triple i686-pc-win32 -fsyntax-only -Wmicrosoft -verify -fms-extensions -fexceptions -fcxx-exceptions

// ::type_info is predeclared with forward class declartion
void f(const type_info &a);

// Microsoft doesn't validate exception specification.
void foo(); // expected-note {{previous declaration}}
void foo() throw(); // expected-warning {{exception specification in declaration does not match previous declaration}}

void r6() throw(...); // expected-note {{previous declaration}}
void r6() throw(int); // expected-warning {{exception specification in declaration does not match previous declaration}}

struct Base {
  virtual void f2();
  virtual void f3() throw(...);
};

struct Derived : Base {
  virtual void f2() throw(...);
  virtual void f3();
};

// MSVC allows type definition in anonymous union and struct
struct A
{
  union
  {
    int a;
    struct B  // expected-warning {{types declared in an anonymous union are a Microsoft extension}}
    {
      int c;
    } d;

    union C   // expected-warning {{types declared in an anonymous union are a Microsoft extension}}
    {
      int e;
      int ee;
    } f;

    typedef int D;  // expected-warning {{types declared in an anonymous union are a Microsoft extension}}
    struct F;  // expected-warning {{types declared in an anonymous union are a Microsoft extension}}
  };

  struct
  {
    int a2;

    struct B2  // expected-warning {{types declared in an anonymous struct are a Microsoft extension}}
    {
      int c2;
    } d2;

	union C2  // expected-warning {{types declared in an anonymous struct are a Microsoft extension}}
    {
      int e2;
      int ee2;
    } f2;

    typedef int D2;  // expected-warning {{types declared in an anonymous struct are a Microsoft extension}}
    struct F2;  // expected-warning {{types declared in an anonymous struct are a Microsoft extension}}
  };
};

// __stdcall handling
struct M {
    int __stdcall addP();
    float __stdcall subtractP();
};

template<typename T> void h1(T (__stdcall M::* const )()) { }

void m1() {
  h1<int>(&M::addP);
  h1(&M::subtractP);
}

//MSVC allows forward enum declaration
enum ENUM; // expected-warning {{forward references to 'enum' types are a Microsoft extension}}
ENUM *var = 0;
ENUM var2 = (ENUM)3;
enum ENUM1* var3 = 0;// expected-warning {{forward references to 'enum' types are a Microsoft extension}}

enum ENUM2 {
	ENUM2_a = (enum ENUM2) 4,
	ENUM2_b = 0x9FFFFFFF, // expected-warning {{enumerator value is not representable in the underlying type 'int'}}
	ENUM2_c = 0x100000000 // expected-warning {{enumerator value is not representable in the underlying type 'int'}}
};

void f(long long);
void f(int);

int main()
{
  // This is an ambiguous call in standard C++.
  // This calls f(long long) in Microsoft mode because LL is always signed.
  f(0xffffffffffffffffLL);
  f(0xffffffffffffffffi64);
}

// Enumeration types with a fixed underlying type.
const int seventeen = 17;
typedef int Int;

struct X0 {
  enum E1 : Int { SomeOtherValue } field; // expected-warning{{enumeration types with a fixed underlying type are a Microsoft extension}}
  enum E1 : seventeen;
};

enum : long long {  // expected-warning{{enumeration types with a fixed underlying type are a Microsoft extension}}
  SomeValue = 0x100000000
};

class AAA {
__declspec(dllimport) void f(void) { }
void f2(void);
};

__declspec(dllimport) void AAA::f2(void) { // expected-error {{dllimport attribute can be applied only to symbol}}

}

template <class T>
class BB {
public:
   void f(int g = 10 ); // expected-note {{previous definition is here}}
};

template <class T>
void BB<T>::f(int g = 0) { } // expected-warning {{redefinition of default argument}}

namespace MissingTypename {

template<class T> class A {
public:
	 typedef int TYPE;
};

template<class T> class B {
public:
	 typedef int TYPE;
};

template<class T, class U>
class C : private A<T>, public B<U> {
public:
   typedef A<T> Base1;
   typedef B<U> Base2;
   typedef A<U> Base3;

   A<T>::TYPE a1; // expected-warning {{missing 'typename' prior to dependent type name}}
   Base1::TYPE a2; // expected-warning {{missing 'typename' prior to dependent type name}}

   B<U>::TYPE a3; // expected-warning {{missing 'typename' prior to dependent type name}}
   Base2::TYPE a4; // expected-warning {{missing 'typename' prior to dependent type name}}

   A<U>::TYPE a5; // expected-error {{missing 'typename' prior to dependent type name}}
   Base3::TYPE a6; // expected-error {{missing 'typename' prior to dependent type name}}
 };

}

extern void static_func();
void static_func(); // expected-note {{previous declaration is here}}

static void static_func() // expected-warning {{static declaration of 'static_func' follows non-static declaration}}
{

}

long function_prototype(int a);
long (*function_ptr)(int a);

void function_to_voidptr_conv() {
   void *a1 = function_prototype;
   void *a2 = &function_prototype;
   void *a3 = function_ptr;
}
<|endoftext|>


<commit_before>
/*
 * benchmark_bwtree_full.cpp - This file contains test suites for command
 *                             benchmark-bwtree-full
 */

#include "test_suite.h"

/*
 * BenchmarkBwTreeRandInsert() - As name suggests
 *
 * Note that for this function we do not pass a bwtree instance for it and
 * instead we make and destroy the object inside the function, since we
 * do not use this function's result to test read (i.e. all read operations
 * are tested upon a sequentially populated BwTree instance)
 */
void BenchmarkBwTreeRandInsert(int key_num, int thread_num) {
  // Get an empty trrr; do not print its construction message
  TreeType *t = GetEmptyTree(true);

  // This is used to record time taken for each individual thread
  double thread_time[thread_num];
  for(int i = 0;i < thread_num;i++) {
    thread_time[i] = 0.0;
  }

  // This generates a permutation on [0, key_num)
  Permutation<long long int> perm{(size_t)key_num, 0};

  auto func = [key_num,
               &thread_time,
               thread_num,
               &perm](uint64_t thread_id, TreeType *t) {
    long int start_key = key_num / thread_num * (long)thread_id;
    long int end_key = start_key + key_num / thread_num;

    // Declare timer and start it immediately
    Timer timer{true};
    CacheMeter cache{true};

    for(int i = start_key;i < end_key;i++) {
      long long int key = perm[i];

      t->Insert(key, key);
    }

    cache.Stop();
    double duration = timer.Stop();

    thread_time[thread_id] = duration;

    std::cout << "[Thread " << thread_id << " Done] @ " \
              << (key_num / thread_num) / (1024.0 * 1024.0) / duration \
              << " million random insert/sec" << "\n";

    // Print L3 total accesses and cache misses
    cache.PrintL3CacheUtilization();
    cache.PrintL1CacheUtilization();

    return;
  };

  LaunchParallelTestID(thread_num, func, t);

  double elapsed_seconds = 0.0;
  for(int i = 0;i < thread_num;i++) {
    elapsed_seconds += thread_time[i];
  }

  std::cout << thread_num << " Threads BwTree: overall "
            << (key_num / (1024.0 * 1024.0) * thread_num) / elapsed_seconds
            << " million random insert/sec" << "\n";

  // Remove the tree instance
  delete t;

  return;
}

/*
 * BenchmarkBwTreeSeqInsert() - As name suggests
 */
void BenchmarkBwTreeSeqInsert(TreeType *t,
                              int key_num,
                              int thread_num) {
  const int num_thread = thread_num;

  // This is used to record time taken for each individual thread
  double thread_time[num_thread];
  for(int i = 0;i < num_thread;i++) {
    thread_time[i] = 0.0;
  }

  auto func = [key_num,
               &thread_time,
               num_thread](uint64_t thread_id, TreeType *t) {
    long int start_key = key_num / num_thread * (long)thread_id;
    long int end_key = start_key + key_num / num_thread;

    // Declare timer and start it immediately
    Timer timer{true};
    CacheMeter cache{true};

    for(int i = start_key;i < end_key;i++) {
      t->Insert(i, i);
    }

    cache.Stop();
    double duration = timer.Stop();

    std::cout << "[Thread " << thread_id << " Done] @ " \
              << (key_num / num_thread) / (1024.0 * 1024.0) / duration \
              << " million insert/sec" << "\n";

    // Print L3 total accesses and cache misses
    cache.PrintL3CacheUtilization();
    cache.PrintL1CacheUtilization();

    thread_time[thread_id] = duration;

    return;
  };

  LaunchParallelTestID(num_thread, func, t);

  double elapsed_seconds = 0.0;
  for(int i = 0;i < num_thread;i++) {
    elapsed_seconds += thread_time[i];
  }

  std::cout << num_thread << " Threads BwTree: overall "
            << (key_num / (1024.0 * 1024.0) * num_thread) / elapsed_seconds
            << " million insert/sec" << "\n";

  return;
}

/*
 * BenchmarkBwTreeSeqRead() - As name suggests
 */
void BenchmarkBwTreeSeqRead(TreeType *t,
                            int key_num,
                            int thread_num) {
  const int num_thread = thread_num;
  int iter = 1;

  // This is used to record time taken for each individual thread
  double thread_time[num_thread];
  for(int i = 0;i < num_thread;i++) {
    thread_time[i] = 0.0;
  }

  auto func = [key_num,
               iter,
               &thread_time,
               num_thread](uint64_t thread_id, TreeType *t) {
    std::vector<long> v{};

    v.reserve(1);

    Timer timer{true};
    CacheMeter cache{true};

    for(int j = 0;j < iter;j++) {
      for(int i = 0;i < key_num;i++) {
        t->GetValue(i, v);

        v.clear();
      }
    }

    cache.Stop();
    double duration = timer.Stop();

    std::cout << "[Thread " << thread_id << " Done] @ " \
              << (iter * key_num / (1024.0 * 1024.0)) / duration \
              << " million read/sec" << "\n";

    cache.PrintL3CacheUtilization();
    cache.PrintL1CacheUtilization();

    thread_time[thread_id] = duration;

    return;
  };

  LaunchParallelTestID(num_thread, func, t);

  double elapsed_seconds = 0.0;
  for(int i = 0;i < num_thread;i++) {
    elapsed_seconds += thread_time[i];
  }

  std::cout << num_thread << " Threads BwTree: overall "
            << (iter * key_num / (1024.0 * 1024.0) * num_thread * num_thread) / elapsed_seconds
            << " million read/sec" << "\n";

  return;
}

/*
 * BenchmarkBwTreeRandRead() - As name suggests
 */
void BenchmarkBwTreeRandRead(TreeType *t,
                             int key_num,
                             int thread_num) {
  const int num_thread = thread_num;
  int iter = 1;

  // This is used to record time taken for each individual thread
  double thread_time[num_thread];
  for(int i = 0;i < num_thread;i++) {
    thread_time[i] = 0.0;
  }

  auto func2 = [key_num,
                iter,
                &thread_time,
                num_thread](uint64_t thread_id, TreeType *t) {
    std::vector<long> v{};

    v.reserve(1);

    // This is the random number generator we use
    SimpleInt64Random<0, 30 * 1024 * 1024> h{};

    Timer timer{true};
    CacheMeter cache{true};

    for(int j = 0;j < iter;j++) {
      for(int i = 0;i < key_num;i++) {
        //int key = uniform_dist(e1);
        long int key = (long int)h((uint64_t)i, thread_id);

        t->GetValue(key, v);

        v.clear();
      }
    }

    cache.Stop();
    double duration = timer.Stop();

    std::cout << "[Thread " << thread_id << " Done] @ " \
              << (iter * key_num / (1024.0 * 1024.0)) / duration \
              << " million read (random)/sec" << "\n";

    cache.PrintL3CacheUtilization();
    cache.PrintL1CacheUtilization();

    thread_time[thread_id] = duration;

    return;
  };

  LaunchParallelTestID(num_thread, func2, t);

  double elapsed_seconds = 0.0;
  for(int i = 0;i < num_thread;i++) {
    elapsed_seconds += thread_time[i];
  }

  std::cout << num_thread << " Threads BwTree: overall "
            << (iter * key_num / (1024.0 * 1024.0) * num_thread * num_thread) / elapsed_seconds
            << " million read (random)/sec" << "\n";

  return;
}

/*
 * BenchmarkBwTreeZipfRead() - As name suggests
 */
void BenchmarkBwTreeZipfRead(TreeType *t,
                             int key_num,
                             int thread_num) {
  const int num_thread = thread_num;
  int iter = 1;

  // This is used to record time taken for each individual thread
  double thread_time[num_thread];
  for(int i = 0;i < num_thread;i++) {
    thread_time[i] = 0.0;
  }

  // Generate zipfian distribution into this list
  std::vector<long> zipfian_key_list{};
  zipfian_key_list.reserve(key_num);

  // Initialize it with time() as the random seed
  Zipfian zipf{(uint64_t)key_num, 0.99, (uint64_t)time(NULL)};

  // Populate the array with random numbers
  for(int i = 0;i < key_num;i++) {
    zipfian_key_list.push_back(zipf.Get());
  }

  auto func2 = [key_num,
                iter,
                &thread_time,
                &zipfian_key_list,
                num_thread](uint64_t thread_id, TreeType *t) {
    // This is the start and end index we read into the zipfian array
    long int start_index = key_num / num_thread * (long)thread_id;
    long int end_index = start_index + key_num / num_thread;

    std::vector<long> v{};

    v.reserve(1);

    Timer timer{true};
    CacheMeter cache{true};

    for(int j = 0;j < iter;j++) {
      for(long i = start_index;i < end_index;i++) {
        long int key = zipfian_key_list[i];

        t->GetValue(key, v);

        v.clear();
      }
    }

    cache.Stop();
    double duration = timer.Stop();

    std::cout << "[Thread " << thread_id << " Done] @ " \
              << (iter * (end_index - start_index) / (1024.0 * 1024.0)) / duration \
              << " million read (zipfian)/sec" << "\n";

    cache.PrintL3CacheUtilization();
    cache.PrintL1CacheUtilization();

    thread_time[thread_id] = duration;

    return;
  };

  LaunchParallelTestID(num_thread, func2, t);

  double elapsed_seconds = 0.0;
  for(int i = 0;i < num_thread;i++) {
    elapsed_seconds += thread_time[i];
  }

  std::cout << num_thread << " Threads BwTree: overall "
            << (iter * key_num / (1024.0 * 1024.0)) / (elapsed_seconds / num_thread)
            << " million read (zipfian)/sec" << "\n";

  return;
}
<commit_msg>Change the order of recording time usage and printing on the screen<commit_after>
/*
 * benchmark_bwtree_full.cpp - This file contains test suites for command
 *                             benchmark-bwtree-full
 */

#include "test_suite.h"

/*
 * BenchmarkBwTreeRandInsert() - As name suggests
 *
 * Note that for this function we do not pass a bwtree instance for it and
 * instead we make and destroy the object inside the function, since we
 * do not use this function's result to test read (i.e. all read operations
 * are tested upon a sequentially populated BwTree instance)
 */
void BenchmarkBwTreeRandInsert(int key_num, int thread_num) {
  // Get an empty trrr; do not print its construction message
  TreeType *t = GetEmptyTree(true);

  // This is used to record time taken for each individual thread
  double thread_time[thread_num];
  for(int i = 0;i < thread_num;i++) {
    thread_time[i] = 0.0;
  }

  // This generates a permutation on [0, key_num)
  Permutation<long long int> perm{(size_t)key_num, 0};

  auto func = [key_num,
               &thread_time,
               thread_num,
               &perm](uint64_t thread_id, TreeType *t) {
    long int start_key = key_num / thread_num * (long)thread_id;
    long int end_key = start_key + key_num / thread_num;

    // Declare timer and start it immediately
    Timer timer{true};
    CacheMeter cache{true};

    for(int i = start_key;i < end_key;i++) {
      long long int key = perm[i];

      t->Insert(key, key);
    }

    cache.Stop();
    double duration = timer.Stop();

    thread_time[thread_id] = duration;

    std::cout << "[Thread " << thread_id << " Done] @ " \
              << (key_num / thread_num) / (1024.0 * 1024.0) / duration \
              << " million random insert/sec" << "\n";

    // Print L3 total accesses and cache misses
    cache.PrintL3CacheUtilization();
    cache.PrintL1CacheUtilization();

    return;
  };

  LaunchParallelTestID(thread_num, func, t);

  double elapsed_seconds = 0.0;
  for(int i = 0;i < thread_num;i++) {
    elapsed_seconds += thread_time[i];
  }

  std::cout << thread_num << " Threads BwTree: overall "
            << (key_num / (1024.0 * 1024.0) * thread_num) / elapsed_seconds
            << " million random insert/sec" << "\n";

  // Remove the tree instance
  delete t;

  return;
}

/*
 * BenchmarkBwTreeSeqInsert() - As name suggests
 */
void BenchmarkBwTreeSeqInsert(TreeType *t,
                              int key_num,
                              int thread_num) {
  const int num_thread = thread_num;

  // This is used to record time taken for each individual thread
  double thread_time[num_thread];
  for(int i = 0;i < num_thread;i++) {
    thread_time[i] = 0.0;
  }

  auto func = [key_num,
               &thread_time,
               num_thread](uint64_t thread_id, TreeType *t) {
    long int start_key = key_num / num_thread * (long)thread_id;
    long int end_key = start_key + key_num / num_thread;

    // Declare timer and start it immediately
    Timer timer{true};
    CacheMeter cache{true};

    for(int i = start_key;i < end_key;i++) {
      t->Insert(i, i);
    }

    cache.Stop();
    double duration = timer.Stop();

    thread_time[thread_id] = duration;

    std::cout << "[Thread " << thread_id << " Done] @ " \
              << (key_num / num_thread) / (1024.0 * 1024.0) / duration \
              << " million insert/sec" << "\n";

    // Print L3 total accesses and cache misses
    cache.PrintL3CacheUtilization();
    cache.PrintL1CacheUtilization();

    return;
  };

  LaunchParallelTestID(num_thread, func, t);

  double elapsed_seconds = 0.0;
  for(int i = 0;i < num_thread;i++) {
    elapsed_seconds += thread_time[i];
  }

  std::cout << num_thread << " Threads BwTree: overall "
            << (key_num / (1024.0 * 1024.0) * num_thread) / elapsed_seconds
            << " million insert/sec" << "\n";

  return;
}

/*
 * BenchmarkBwTreeSeqRead() - As name suggests
 */
void BenchmarkBwTreeSeqRead(TreeType *t,
                            int key_num,
                            int thread_num) {
  const int num_thread = thread_num;
  int iter = 1;

  // This is used to record time taken for each individual thread
  double thread_time[num_thread];
  for(int i = 0;i < num_thread;i++) {
    thread_time[i] = 0.0;
  }

  auto func = [key_num,
               iter,
               &thread_time,
               num_thread](uint64_t thread_id, TreeType *t) {
    std::vector<long> v{};

    v.reserve(1);

    Timer timer{true};
    CacheMeter cache{true};

    for(int j = 0;j < iter;j++) {
      for(int i = 0;i < key_num;i++) {
        t->GetValue(i, v);

        v.clear();
      }
    }

    cache.Stop();
    double duration = timer.Stop();

    thread_time[thread_id] = duration;

    std::cout << "[Thread " << thread_id << " Done] @ " \
              << (iter * key_num / (1024.0 * 1024.0)) / duration \
              << " million read/sec" << "\n";

    cache.PrintL3CacheUtilization();
    cache.PrintL1CacheUtilization();

    return;
  };

  LaunchParallelTestID(num_thread, func, t);

  double elapsed_seconds = 0.0;
  for(int i = 0;i < num_thread;i++) {
    elapsed_seconds += thread_time[i];
  }

  std::cout << num_thread << " Threads BwTree: overall "
            << (iter * key_num / (1024.0 * 1024.0) * num_thread * num_thread) / elapsed_seconds
            << " million read/sec" << "\n";

  return;
}

/*
 * BenchmarkBwTreeRandRead() - As name suggests
 */
void BenchmarkBwTreeRandRead(TreeType *t,
                             int key_num,
                             int thread_num) {
  const int num_thread = thread_num;
  int iter = 1;

  // This is used to record time taken for each individual thread
  double thread_time[num_thread];
  for(int i = 0;i < num_thread;i++) {
    thread_time[i] = 0.0;
  }

  auto func2 = [key_num,
                iter,
                &thread_time,
                num_thread](uint64_t thread_id, TreeType *t) {
    std::vector<long> v{};

    v.reserve(1);

    // This is the random number generator we use
    SimpleInt64Random<0, 30 * 1024 * 1024> h{};

    Timer timer{true};
    CacheMeter cache{true};

    for(int j = 0;j < iter;j++) {
      for(int i = 0;i < key_num;i++) {
        //int key = uniform_dist(e1);
        long int key = (long int)h((uint64_t)i, thread_id);

        t->GetValue(key, v);

        v.clear();
      }
    }

    cache.Stop();
    double duration = timer.Stop();

    thread_time[thread_id] = duration;

    std::cout << "[Thread " << thread_id << " Done] @ " \
              << (iter * key_num / (1024.0 * 1024.0)) / duration \
              << " million read (random)/sec" << "\n";

    cache.PrintL3CacheUtilization();
    cache.PrintL1CacheUtilization();

    return;
  };

  LaunchParallelTestID(num_thread, func2, t);

  double elapsed_seconds = 0.0;
  for(int i = 0;i < num_thread;i++) {
    elapsed_seconds += thread_time[i];
  }

  std::cout << num_thread << " Threads BwTree: overall "
            << (iter * key_num / (1024.0 * 1024.0) * num_thread * num_thread) / elapsed_seconds
            << " million read (random)/sec" << "\n";

  return;
}

/*
 * BenchmarkBwTreeZipfRead() - As name suggests
 */
void BenchmarkBwTreeZipfRead(TreeType *t,
                             int key_num,
                             int thread_num) {
  const int num_thread = thread_num;
  int iter = 1;

  // This is used to record time taken for each individual thread
  double thread_time[num_thread];
  for(int i = 0;i < num_thread;i++) {
    thread_time[i] = 0.0;
  }

  // Generate zipfian distribution into this list
  std::vector<long> zipfian_key_list{};
  zipfian_key_list.reserve(key_num);

  // Initialize it with time() as the random seed
  Zipfian zipf{(uint64_t)key_num, 0.99, (uint64_t)time(NULL)};

  // Populate the array with random numbers
  for(int i = 0;i < key_num;i++) {
    zipfian_key_list.push_back(zipf.Get());
  }

  auto func2 = [key_num,
                iter,
                &thread_time,
                &zipfian_key_list,
                num_thread](uint64_t thread_id, TreeType *t) {
    // This is the start and end index we read into the zipfian array
    long int start_index = key_num / num_thread * (long)thread_id;
    long int end_index = start_index + key_num / num_thread;

    std::vector<long> v{};

    v.reserve(1);

    Timer timer{true};
    CacheMeter cache{true};

    for(int j = 0;j < iter;j++) {
      for(long i = start_index;i < end_index;i++) {
        long int key = zipfian_key_list[i];

        t->GetValue(key, v);

        v.clear();
      }
    }

    cache.Stop();
    double duration = timer.Stop();

    thread_time[thread_id] = duration;

    std::cout << "[Thread " << thread_id << " Done] @ " \
              << (iter * (end_index - start_index) / (1024.0 * 1024.0)) / duration \
              << " million read (zipfian)/sec" << "\n";

    cache.PrintL3CacheUtilization();
    cache.PrintL1CacheUtilization();

    return;
  };

  LaunchParallelTestID(num_thread, func2, t);

  double elapsed_seconds = 0.0;
  for(int i = 0;i < num_thread;i++) {
    elapsed_seconds += thread_time[i];
  }

  std::cout << num_thread << " Threads BwTree: overall "
            << (iter * key_num / (1024.0 * 1024.0)) / (elapsed_seconds / num_thread)
            << " million read (zipfian)/sec" << "\n";

  return;
}
<|endoftext|>