<commit_before>/*-------------------------------------------------------------------------
 *
 * merge_join.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /peloton/src/executor/merge_join_executor.cpp
 *
 *-------------------------------------------------------------------------
 */

#include <vector>

#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/merge_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor for nested loop join executor.
 * @param node Nested loop join node corresponding to this executor.
 */
MergeJoinExecutor::MergeJoinExecutor(const planner::AbstractPlan *node,
                                     ExecutorContext *executor_context)
    : AbstractJoinExecutor(node, executor_context) {
  join_clauses_ = nullptr;
}

bool MergeJoinExecutor::DInit() {
  auto status = AbstractJoinExecutor::DInit();
  if (status == false)
    return status;

  const planner::MergeJoinPlan &node = GetPlanNode<planner::MergeJoinPlan>();

  join_clauses_ = node.GetJoinClauses();

  if (join_clauses_ == nullptr)
    return false;

  left_end_ = true;
  right_end_ = true;

  return true;
}

/**
 * @brief Creates logical tiles from the two input logical tiles after applying
 * join predicate.
 * @return true on success, false otherwise.
 */
bool MergeJoinExecutor::DExecute() {
  LOG_INFO("********** Merge Join executor :: 2 children \n");

  if (right_end_) {
    // Try to get next tile from RIGHT child
    if (children_[1]->Execute() == false) {
      LOG_INFO("Did not get right tile \n");
      return false;
    }

    std::unique_ptr<LogicalTile> right(children_[1]->GetOutput());
    right_tiles_.push_back(right.release());
    LOG_INFO("size of right tiles: %lu", right_tiles_.size());
  }
  LOG_INFO("Got right tile \n");

  if (left_end_) {
    // Try to get next tile from LEFT child
    if (children_[0]->Execute() == false) {
      LOG_INFO("Did not get left tile \n");
      return false;
    }

    std::unique_ptr<LogicalTile> left(children_[0]->GetOutput());
    left_tiles_.push_back(left.release());
    LOG_INFO("size of right tiles: %lu", left_tiles_.size());
  }
  LOG_INFO("Got left tile \n");

  LogicalTile *left_tile = left_tiles_.back();
  LogicalTile *right_tile = right_tiles_.back();

  // Check the input logical tiles.
  assert(left_tile != nullptr);
  assert(right_tile != nullptr);

  // Construct output logical tile.
  std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile());

  auto left_tile_schema = left_tile->GetSchema();
  auto right_tile_schema = right_tile->GetSchema();

  for (auto &col : right_tile_schema) {
    col.position_list_idx += left_tile->GetPositionLists().size();
  }

  /* build the schema given the projection */
  auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema);

  // Set the output logical tile schema
  output_tile->SetSchema(std::move(output_tile_schema));

  // Get position list from two logical tiles
  auto left_tile_position_lists = left_tile->GetPositionLists();
  auto right_tile_position_lists = right_tile->GetPositionLists();

  // Compute output tile column count
  size_t left_tile_column_count = left_tile_position_lists.size();
  size_t right_tile_column_count = right_tile_position_lists.size();
  size_t output_tile_column_count = left_tile_column_count
      + right_tile_column_count;

  assert(left_tile_column_count > 0);
  assert(right_tile_column_count > 0);

  // Compute output tile row count
  //size_t left_tile_row_count = left_tile_position_lists[0].size();
  //size_t right_tile_row_count = right_tile_position_lists[0].size();

  // Construct position lists for output tile
  std::vector<std::vector<oid_t> > position_lists;
  for (size_t column_itr = 0; column_itr < output_tile_column_count;
      column_itr++)
    position_lists.push_back(std::vector<oid_t>());

  //LOG_INFO("left col count: %lu, right col count: %lu", left_tile_column_count,
  //          right_tile_column_count);
  //LOG_INFO("left col count: %lu, right col count: %lu",
  //          left_tile.get()->GetColumnCount(),
  //          right_tile.get()->GetColumnCount());
  //LOG_INFO("left row count: %lu, right row count: %lu", left_tile_row_count,
  //          right_tile_row_count);

  size_t left_start_row = 0;
  size_t right_start_row = 0;

  size_t left_end_row = Advance(left_tile, left_start_row, true);
  size_t right_end_row = Advance(right_tile, right_start_row, false);

  while (left_end_row > left_start_row && right_end_row > right_start_row) {

    expression::ContainerTuple<executor::LogicalTile> left_tuple(
        left_tile, left_start_row);
    expression::ContainerTuple<executor::LogicalTile> right_tuple(
        right_tile, right_start_row);
    bool diff = false;

    // try to match the join clauses
    for (auto &clause : *join_clauses_) {
      auto left_value = clause.left_->Evaluate(&left_tuple, &right_tuple,
                                               nullptr);
      auto right_value = clause.right_->Evaluate(&left_tuple, &right_tuple,
                                                 nullptr);
      int ret = left_value.Compare(right_value);

      if (ret < 0) {
        // Left key < Right key, advance left
        LOG_INFO("left < right, advance left");
        left_start_row = left_end_row;
        left_end_row = Advance(left_tile, left_start_row, true);
        diff = true;
        break;
      } else if (ret > 0) {
        // Left key > Right key, advance right
        LOG_INFO("left > right, advance right");
        right_start_row = right_end_row;
        right_end_row = Advance(right_tile, right_start_row, false);
        diff = true;
        break;
      }
      // Left key == Right key, go check next join clause
    }

    if (diff) {
      // join clauses are not matched, one of the tile has been advanced
      continue;
    }

    // join clauses are matched, try to match predicate
    LOG_INFO("one pair of tuples matches join clause");

    // Join predicate exists
    if (predicate_ != nullptr) {
      if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
          .IsFalse()) {
        // Join predicate is false. Advance both.
        left_start_row = left_end_row;
        left_end_row = Advance(left_tile, left_start_row, true);
        right_start_row = right_end_row;
        right_end_row = Advance(right_tile, right_start_row, false);
      }
    }

    // sub tile matched, do a Cartesian product
    // Go over every pair of tuples in left and right logical tiles
    for (auto left_tile_row_itr : *left_tile) {
      for (auto right_tile_row_itr : *right_tile) {
        // Insert a tuple into the output logical tile
        // First, copy the elements in left logical tile's tuple
        for (size_t output_tile_column_itr = 0;
            output_tile_column_itr < left_tile_column_count;
            output_tile_column_itr++) {
          position_lists[output_tile_column_itr].push_back(
              left_tile_position_lists[output_tile_column_itr][left_tile_row_itr]);
        }

        // Then, copy the elements in left logical tile's tuple
        for (size_t output_tile_column_itr = 0;
            output_tile_column_itr < right_tile_column_count;
            output_tile_column_itr++) {
          position_lists[left_tile_column_count + output_tile_column_itr]
              .push_back(
              right_tile_position_lists[output_tile_column_itr][right_tile_row_itr]);
        }
      }
    }

    // then Advance both
    left_start_row = left_end_row;
    left_end_row = Advance(left_tile, left_start_row, true);
    right_start_row = right_end_row;
    right_end_row = Advance(right_tile, right_start_row, false);
  }

  // set the corresponding flags if left or right is end
  // so that next execution time, it will be re executed
  if (left_end_row == left_start_row) {
    left_end_ = true;
  }

  if (right_end_row == right_start_row) {
    right_end_ = true;
  }

  // Check if we have any matching tuples.
  if (position_lists[0].size() > 0) {
    output_tile->SetPositionListsAndVisibility(std::move(position_lists));
    SetOutput(output_tile.release());
    return true;
  }
  // Try again
  else {
    // If we are out of any more pairs of child tiles to examine,
    // then we will return false earlier in this function.
    // So, we don't have to return false here.
    DExecute();
  }

  return true;
}

/**
 * @brief Advance the row iterator until value changes in terms of the join clauses
 * @return the end row number, [start_row, end_row) are the rows of the same value
 *         if the end_row == start_row, the subset is empty
 */
size_t MergeJoinExecutor::Advance(LogicalTile *tile, size_t start_row,
bool is_left) {
  size_t end_row = start_row + 1;
  size_t this_row = start_row;
  size_t tuple_count = tile->GetTupleCount();
  if (start_row >= tuple_count)
    return start_row;

  while (end_row < tuple_count) {
    expression::ContainerTuple<executor::LogicalTile> this_tuple(tile,
                                                                 this_row);
    expression::ContainerTuple<executor::LogicalTile> next_tuple(tile, end_row);

    bool diff = false;

    for (auto &clause : *join_clauses_) {
      // Go thru each join clauses
      auto expr = is_left ? clause.left_.get() : clause.right_.get();
      peloton::Value this_value = expr->Evaluate(&this_tuple, &this_tuple,
                                                 nullptr);
      peloton::Value next_value = expr->Evaluate(&next_tuple, &next_tuple,
                                                 nullptr);
      if (0 != this_value.Compare(next_value)) {
        diff = true;
        break;
      }
    }

    if (diff) {
      break;
    }

    // the two tuples are the same, we advance by 1
    end_row++;
    this_row = end_row;
  }

  LOG_INFO("Advanced %s with subset size %lu", is_left ? "left" : "right",
           end_row - start_row);
  return end_row;
}

}  // namespace executor
}  // namespace peloton
<commit_msg>fix over outputting in merge join<commit_after>/*-------------------------------------------------------------------------
 *
 * merge_join.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /peloton/src/executor/merge_join_executor.cpp
 *
 *-------------------------------------------------------------------------
 */

#include <vector>

#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/merge_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor for nested loop join executor.
 * @param node Nested loop join node corresponding to this executor.
 */
MergeJoinExecutor::MergeJoinExecutor(const planner::AbstractPlan *node,
                                     ExecutorContext *executor_context)
    : AbstractJoinExecutor(node, executor_context) {
  join_clauses_ = nullptr;
}

bool MergeJoinExecutor::DInit() {
  auto status = AbstractJoinExecutor::DInit();
  if (status == false)
    return status;

  const planner::MergeJoinPlan &node = GetPlanNode<planner::MergeJoinPlan>();

  join_clauses_ = node.GetJoinClauses();

  if (join_clauses_ == nullptr)
    return false;

  left_end_ = true;
  right_end_ = true;

  return true;
}

/**
 * @brief Creates logical tiles from the two input logical tiles after applying
 * join predicate.
 * @return true on success, false otherwise.
 */
bool MergeJoinExecutor::DExecute() {
  LOG_INFO("********** Merge Join executor :: 2 children \n");

  if (right_end_) {
    // Try to get next tile from RIGHT child
    if (children_[1]->Execute() == false) {
      LOG_INFO("Did not get right tile \n");
      return false;
    }

    std::unique_ptr<LogicalTile> right(children_[1]->GetOutput());
    right_tiles_.push_back(right.release());
    LOG_INFO("size of right tiles: %lu", right_tiles_.size());
  }
  LOG_INFO("Got right tile \n");

  if (left_end_) {
    // Try to get next tile from LEFT child
    if (children_[0]->Execute() == false) {
      LOG_INFO("Did not get left tile \n");
      return false;
    }

    std::unique_ptr<LogicalTile> left(children_[0]->GetOutput());
    left_tiles_.push_back(left.release());
    LOG_INFO("size of right tiles: %lu", left_tiles_.size());
  }
  LOG_INFO("Got left tile \n");

  LogicalTile *left_tile = left_tiles_.back();
  LogicalTile *right_tile = right_tiles_.back();

  // Check the input logical tiles.
  assert(left_tile != nullptr);
  assert(right_tile != nullptr);

  // Construct output logical tile.
  std::unique_ptr<LogicalTile> output_tile(LogicalTileFactory::GetTile());

  auto left_tile_schema = left_tile->GetSchema();
  auto right_tile_schema = right_tile->GetSchema();

  for (auto &col : right_tile_schema) {
    col.position_list_idx += left_tile->GetPositionLists().size();
  }

  /* build the schema given the projection */
  auto output_tile_schema = BuildSchema(left_tile_schema, right_tile_schema);

  // Set the output logical tile schema
  output_tile->SetSchema(std::move(output_tile_schema));

  // Get position list from two logical tiles
  auto left_tile_position_lists = left_tile->GetPositionLists();
  auto right_tile_position_lists = right_tile->GetPositionLists();

  // Compute output tile column count
  size_t left_tile_column_count = left_tile_position_lists.size();
  size_t right_tile_column_count = right_tile_position_lists.size();
  size_t output_tile_column_count = left_tile_column_count
      + right_tile_column_count;

  assert(left_tile_column_count > 0);
  assert(right_tile_column_count > 0);

  // Compute output tile row count
  //size_t left_tile_row_count = left_tile_position_lists[0].size();
  //size_t right_tile_row_count = right_tile_position_lists[0].size();

  // Construct position lists for output tile
  std::vector<std::vector<oid_t> > position_lists;
  for (size_t column_itr = 0; column_itr < output_tile_column_count;
      column_itr++)
    position_lists.push_back(std::vector<oid_t>());

  //LOG_INFO("left col count: %lu, right col count: %lu", left_tile_column_count,
  //          right_tile_column_count);
  //LOG_INFO("left col count: %lu, right col count: %lu",
  //          left_tile.get()->GetColumnCount(),
  //          right_tile.get()->GetColumnCount());
  //LOG_INFO("left row count: %lu, right row count: %lu", left_tile_row_count,
  //          right_tile_row_count);

  size_t left_start_row = 0;
  size_t right_start_row = 0;

  size_t left_end_row = Advance(left_tile, left_start_row, true);
  size_t right_end_row = Advance(right_tile, right_start_row, false);

  while (left_end_row > left_start_row && right_end_row > right_start_row) {

    expression::ContainerTuple<executor::LogicalTile> left_tuple(
        left_tile, left_start_row);
    expression::ContainerTuple<executor::LogicalTile> right_tuple(
        right_tile, right_start_row);
    bool diff = false;

    // try to match the join clauses
    for (auto &clause : *join_clauses_) {
      auto left_value = clause.left_->Evaluate(&left_tuple, &right_tuple,
                                               nullptr);
      auto right_value = clause.right_->Evaluate(&left_tuple, &right_tuple,
                                                 nullptr);
      int ret = left_value.Compare(right_value);

      if (ret < 0) {
        // Left key < Right key, advance left
        LOG_INFO("left < right, advance left");
        left_start_row = left_end_row;
        left_end_row = Advance(left_tile, left_start_row, true);
        diff = true;
        break;
      } else if (ret > 0) {
        // Left key > Right key, advance right
        LOG_INFO("left > right, advance right");
        right_start_row = right_end_row;
        right_end_row = Advance(right_tile, right_start_row, false);
        diff = true;
        break;
      }
      // Left key == Right key, go check next join clause
    }

    if (diff) {
      // join clauses are not matched, one of the tile has been advanced
      continue;
    }

    // join clauses are matched, try to match predicate
    LOG_INFO("one pair of tuples matches join clause");

    // Join predicate exists
    if (predicate_ != nullptr) {
      if (predicate_->Evaluate(&left_tuple, &right_tuple, executor_context_)
          .IsFalse()) {
        // Join predicate is false. Advance both.
        left_start_row = left_end_row;
        left_end_row = Advance(left_tile, left_start_row, true);
        right_start_row = right_end_row;
        right_end_row = Advance(right_tile, right_start_row, false);
      }
    }

    // sub tile matched, do a Cartesian product
    // Go over every pair of tuples in left and right logical tiles
    for (size_t left_tile_row_itr = left_start_row;
            left_tile_row_itr < left_end_row; left_tile_row_itr++) {
          for (size_t right_tile_row_itr = right_start_row;
              right_tile_row_itr < right_end_row; right_tile_row_itr++) {
        // Insert a tuple into the output logical tile
        // First, copy the elements in left logical tile's tuple
        for (size_t output_tile_column_itr = 0;
            output_tile_column_itr < left_tile_column_count;
            output_tile_column_itr++) {
          position_lists[output_tile_column_itr].push_back(
              left_tile_position_lists[output_tile_column_itr][left_tile_row_itr]);
        }

        // Then, copy the elements in left logical tile's tuple
        for (size_t output_tile_column_itr = 0;
            output_tile_column_itr < right_tile_column_count;
            output_tile_column_itr++) {
          position_lists[left_tile_column_count + output_tile_column_itr]
              .push_back(
              right_tile_position_lists[output_tile_column_itr][right_tile_row_itr]);
        }
      }
    }

    // then Advance both
    left_start_row = left_end_row;
    left_end_row = Advance(left_tile, left_start_row, true);
    right_start_row = right_end_row;
    right_end_row = Advance(right_tile, right_start_row, false);
  }

  // set the corresponding flags if left or right is end
  // so that next execution time, it will be re executed
  if (left_end_row == left_start_row) {
    left_end_ = true;
  }

  if (right_end_row == right_start_row) {
    right_end_ = true;
  }

  // Check if we have any matching tuples.
  if (position_lists[0].size() > 0) {
    output_tile->SetPositionListsAndVisibility(std::move(position_lists));
    SetOutput(output_tile.release());
    return true;
  }
  // Try again
  else {
    // If we are out of any more pairs of child tiles to examine,
    // then we will return false earlier in this function.
    // So, we don't have to return false here.
    DExecute();
  }

  return true;
}

/**
 * @brief Advance the row iterator until value changes in terms of the join clauses
 * @return the end row number, [start_row, end_row) are the rows of the same value
 *         if the end_row == start_row, the subset is empty
 */
size_t MergeJoinExecutor::Advance(LogicalTile *tile, size_t start_row,
bool is_left) {
  size_t end_row = start_row + 1;
  size_t this_row = start_row;
  size_t tuple_count = tile->GetTupleCount();
  if (start_row >= tuple_count)
    return start_row;

  while (end_row < tuple_count) {
    expression::ContainerTuple<executor::LogicalTile> this_tuple(tile,
                                                                 this_row);
    expression::ContainerTuple<executor::LogicalTile> next_tuple(tile, end_row);

    bool diff = false;

    for (auto &clause : *join_clauses_) {
      // Go thru each join clauses
      auto expr = is_left ? clause.left_.get() : clause.right_.get();
      peloton::Value this_value = expr->Evaluate(&this_tuple, &this_tuple,
                                                 nullptr);
      peloton::Value next_value = expr->Evaluate(&next_tuple, &next_tuple,
                                                 nullptr);
      if (0 != this_value.Compare(next_value)) {
        diff = true;
        break;
      }
    }

    if (diff) {
      break;
    }

    // the two tuples are the same, we advance by 1
    end_row++;
    this_row = end_row;
  }

  LOG_INFO("Advanced %s with subset size %lu", is_left ? "left" : "right",
           end_row - start_row);
  return end_row;
}

}  // namespace executor
}  // namespace peloton
<|endoftext|>


<commit_before>/*
* Copyright (c) 2013 BlackBerry Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef Keyboard_NDK_HPP_
#define Keyboard_NDK_HPP_

#include <string>
#include <pthread.h>
#include "CallKeyboard.h"
#include <bb/AbstractBpsEventHandler>
#include <bps/bps.h>
#include<bps/netstatus.h>
#include<bps/locale.h>
#include<bps/virtualkeyboard.h>
#include<bps/navigator.h>
#include <bps/event.h>
#include <string>
#include <sstream>

class Keyboard_JS;

namespace webworks {

class Keyboard_NDK  {
public:
	explicit Keyboard_NDK(Keyboard_JS *parent = NULL);
	virtual ~Keyboard_NDK();
    virtual void event(bps_event_t *event);
    void callKeyboardEmail();
    void callKeyboardNumber();
    void cancelKeyboard();

	// The extension methods are defined here
	std::string keyboardTest();

	std::string keyboardTest(const std::string& inputString);

	std::string getKeyboardProperty();

	void setKeyboardProperty(const std::string& inputString);

	void keyboardTestAsync(const std::string& callbackId, const std::string& inputString);

	std::string keyboardStartThread();

	std::string keyboardStopThread();

	bool isThreadHalt();

	void keyboardThreadCallback();

private:

	Keyboard_JS *m_pParent;
	int keyboardProperty;
	int keyboardThreadCount;
	bool threadHalt;
	std::string threadCallbackId;
	pthread_t m_thread;
	pthread_cond_t cond;
	pthread_mutex_t mutex;

};

} // namespace webworks

#endif /* Keyboard_NDK_HPP_ */
<commit_msg>Deleted CallKeyboard<commit_after>/*
* Copyright (c) 2013 BlackBerry Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef Keyboard_NDK_HPP_
#define Keyboard_NDK_HPP_

#include <string>
#include <pthread.h>
#include <bb/AbstractBpsEventHandler>
#include <bps/bps.h>
#include<bps/netstatus.h>
#include<bps/locale.h>
#include<bps/virtualkeyboard.h>
#include<bps/navigator.h>
#include <bps/event.h>
#include <string>
#include <sstream>

class Keyboard_JS;

namespace webworks {

class Keyboard_NDK  {
public:
	explicit Keyboard_NDK(Keyboard_JS *parent = NULL);
	virtual ~Keyboard_NDK();
    virtual void event(bps_event_t *event);
    void callKeyboardEmail();
    void callKeyboardNumber();
    void cancelKeyboard();

	// The extension methods are defined here
	std::string keyboardTest();

	std::string keyboardTest(const std::string& inputString);

	std::string getKeyboardProperty();

	void setKeyboardProperty(const std::string& inputString);

	void keyboardTestAsync(const std::string& callbackId, const std::string& inputString);

	std::string keyboardStartThread();

	std::string keyboardStopThread();

	bool isThreadHalt();

	void keyboardThreadCallback();

private:

	Keyboard_JS *m_pParent;
	int keyboardProperty;
	int keyboardThreadCount;
	bool threadHalt;
	std::string threadCallbackId;
	pthread_t m_thread;
	pthread_cond_t cond;
	pthread_mutex_t mutex;

};

} // namespace webworks

#endif /* Keyboard_NDK_HPP_ */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: servprov.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-18 15:12:55 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "servprov.hxx"
#include "embeddoc.hxx"

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

using namespace com::sun::star;

const GUID* guidList[ SUPPORTED_FACTORIES_NUM ] = {
    &OID_WriterTextServer,
    &OID_WriterOASISTextServer,
    &OID_CalcServer,
    &OID_CalcOASISServer,
    &OID_DrawingServer,
    &OID_DrawingOASISServer,
    &OID_PresentationServer,
    &OID_PresentationOASISServer,
    &OID_MathServer,
    &OID_MathOASISServer
};

class CurThreadData
{
    public:
        CurThreadData();
        virtual ~CurThreadData();

        sal_Bool SAL_CALL setData(void *pData);

        void* SAL_CALL getData();

    protected:
        oslThreadKey m_hKey;
};

CurThreadData::CurThreadData()
{
    m_hKey = osl_createThreadKey( (oslThreadKeyCallbackFunction)NULL );
}

CurThreadData::~CurThreadData()
{
    osl_destroyThreadKey(m_hKey);
}

sal_Bool CurThreadData::setData(void *pData)
{
    OSL_ENSURE( m_hKey, "No thread key!\n" );
    return (osl_setThreadKeyData(m_hKey, pData));
}

void *CurThreadData::getData()
{
    OSL_ENSURE( m_hKey, "No thread key!\n" );
    return (osl_getThreadKeyData(m_hKey));
}

// CoInitializeEx *
typedef DECLSPEC_IMPORT HRESULT (STDAPICALLTYPE *ptrCoInitEx)( LPVOID, DWORD);
// CoInitialize *
typedef DECLSPEC_IMPORT HRESULT (STDAPICALLTYPE *ptrCoInit)( LPVOID);

void o2u_attachCurrentThread()
{
    static CurThreadData oleThreadData;

    if ((sal_Bool)oleThreadData.getData() != sal_True)
    {
        HINSTANCE inst= LoadLibrary( _T("ole32.dll"));
        if( inst )
        {
            HRESULT hr;
            ptrCoInitEx initFuncEx= (ptrCoInitEx)GetProcAddress( inst, _T("CoInitializeEx"));
            if( initFuncEx)
                hr= initFuncEx( NULL, COINIT_MULTITHREADED);
            else
            {
                ptrCoInit initFunc= (ptrCoInit)GetProcAddress( inst,_T("CoInitialize"));
                if( initFunc)
                    hr= initFunc( NULL);
            }
        }
        oleThreadData.setData((void*)sal_True);
    }
}

//===============================================================================
// EmbedServer_Impl

EmbedServer_Impl::EmbedServer_Impl( const uno::Reference<lang::XMultiServiceFactory>& xFactory):
    m_xFactory( xFactory)
{
    for( int nInd = 0; nInd < SUPPORTED_FACTORIES_NUM; nInd++ )
    {
        m_pOLEFactories[nInd] = new EmbedProviderFactory_Impl( m_xFactory, guidList[nInd] );
        m_pOLEFactories[nInd]->registerClass();
    }
}

EmbedServer_Impl::~EmbedServer_Impl()
{
    for( int nInd = 0; nInd < SUPPORTED_FACTORIES_NUM; nInd++ )
    {
        if ( m_pOLEFactories[nInd] )
            m_pOLEFactories[nInd]->deregisterClass();
    }
}

// XInterface --------------------------------------------------
uno::Any SAL_CALL
EmbedServer_Impl::queryInterface(
    const uno::Type& aType )
    throw(
        uno::RuntimeException
    )
{
    uno::Any a=
        ::cppu::queryInterface(
            aType, static_cast<lang::XTypeProvider*>(this));
    if( a == uno::Any())
        return OWeakObject::queryInterface( aType);
    else
        return a;
}

void SAL_CALL EmbedServer_Impl::acquire(  ) throw(uno::RuntimeException)
{
    OWeakObject::acquire();
}

void SAL_CALL EmbedServer_Impl::release(  ) throw (uno::RuntimeException)
{
    OWeakObject::release();
}

// XTypeProvider --------------------------------------------------
uno::Sequence< uno::Type > SAL_CALL
EmbedServer_Impl::getTypes( )
    throw(
        uno::RuntimeException
    )
{
    static ::cppu::OTypeCollection *pCollection = 0;
    if( ! pCollection )
    {
        ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() );
        if( ! pCollection )
        {
            static ::cppu::OTypeCollection collection(
                getCppuType(
                    reinterpret_cast<uno::Reference< uno::XWeak>*>(0)),
                getCppuType(
                    reinterpret_cast<
                    uno::Reference< lang::XTypeProvider>*>(0)));
            pCollection = &collection;
        }
    }
    return (*pCollection).getTypes();
}

uno::Sequence< sal_Int8 > SAL_CALL EmbedServer_Impl::getImplementationId() throw(uno::RuntimeException)
{
    static ::cppu::OImplementationId *pId = 0;
    if( ! pId )
    {
        ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() );
        if( ! pId )
        {
            static ::cppu::OImplementationId id( sal_False );
            pId = &id;
        }
    }
    return (*pId).getImplementationId();
}

//===============================================================================
// EmbedProviderFactory_Impl

EmbedProviderFactory_Impl::EmbedProviderFactory_Impl(const uno::Reference<lang::XMultiServiceFactory>& xFactory, const GUID* pGuid)
    : m_refCount( 0L )
    , m_xFactory( xFactory )
    , m_guid( *pGuid )
{
}

EmbedProviderFactory_Impl::~EmbedProviderFactory_Impl()
{
}

sal_Bool EmbedProviderFactory_Impl::registerClass()
{
    HRESULT hresult;

    o2u_attachCurrentThread();

    hresult = CoRegisterClassObject(
            m_guid,
            this,
            CLSCTX_LOCAL_SERVER,
            REGCLS_MULTIPLEUSE,
            &m_factoryHandle);

    return (hresult == NOERROR);
}

sal_Bool EmbedProviderFactory_Impl::deregisterClass()
{
    HRESULT hresult = CoRevokeClassObject( m_factoryHandle );

    return (hresult == NOERROR);
}

STDMETHODIMP EmbedProviderFactory_Impl::QueryInterface(REFIID riid, void FAR* FAR* ppv)
{
    if(IsEqualIID(riid, IID_IUnknown))
    {
        AddRef();
        *ppv = (IUnknown*) (IClassFactory*) this;
        return NOERROR;
    }
    else if (IsEqualIID(riid, IID_IClassFactory))
    {
        AddRef();
        *ppv = (IClassFactory*) this;
        return NOERROR;
    }

    *ppv = NULL;
    return ResultFromScode(E_NOINTERFACE);
}

STDMETHODIMP_(ULONG) EmbedProviderFactory_Impl::AddRef()
{
    return osl_incrementInterlockedCount( &m_refCount);
}

STDMETHODIMP_(ULONG) EmbedProviderFactory_Impl::Release()
{
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex());
    sal_Int32 nCount = --m_refCount;
    if ( nCount == 0 )
    {
        delete this;
    }

    return nCount;
}

STDMETHODIMP EmbedProviderFactory_Impl::CreateInstance(IUnknown FAR* punkOuter,
                                                     REFIID riid,
                                                     void FAR* FAR* ppv)
{
    punkOuter = NULL;

    IUnknown* pEmbedDocument = (IUnknown*)(IPersistStorage*)( new EmbedDocument_Impl( m_xFactory, &m_guid ) );

    return pEmbedDocument->QueryInterface( riid, ppv );
}

STDMETHODIMP EmbedProviderFactory_Impl::LockServer( int fLock )
{
    return NOERROR;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.6.8); FILE MERGED 2005/09/05 18:46:12 rt 1.6.8.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: servprov.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:54:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "servprov.hxx"
#include "embeddoc.hxx"

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

using namespace com::sun::star;

const GUID* guidList[ SUPPORTED_FACTORIES_NUM ] = {
    &OID_WriterTextServer,
    &OID_WriterOASISTextServer,
    &OID_CalcServer,
    &OID_CalcOASISServer,
    &OID_DrawingServer,
    &OID_DrawingOASISServer,
    &OID_PresentationServer,
    &OID_PresentationOASISServer,
    &OID_MathServer,
    &OID_MathOASISServer
};

class CurThreadData
{
    public:
        CurThreadData();
        virtual ~CurThreadData();

        sal_Bool SAL_CALL setData(void *pData);

        void* SAL_CALL getData();

    protected:
        oslThreadKey m_hKey;
};

CurThreadData::CurThreadData()
{
    m_hKey = osl_createThreadKey( (oslThreadKeyCallbackFunction)NULL );
}

CurThreadData::~CurThreadData()
{
    osl_destroyThreadKey(m_hKey);
}

sal_Bool CurThreadData::setData(void *pData)
{
    OSL_ENSURE( m_hKey, "No thread key!\n" );
    return (osl_setThreadKeyData(m_hKey, pData));
}

void *CurThreadData::getData()
{
    OSL_ENSURE( m_hKey, "No thread key!\n" );
    return (osl_getThreadKeyData(m_hKey));
}

// CoInitializeEx *
typedef DECLSPEC_IMPORT HRESULT (STDAPICALLTYPE *ptrCoInitEx)( LPVOID, DWORD);
// CoInitialize *
typedef DECLSPEC_IMPORT HRESULT (STDAPICALLTYPE *ptrCoInit)( LPVOID);

void o2u_attachCurrentThread()
{
    static CurThreadData oleThreadData;

    if ((sal_Bool)oleThreadData.getData() != sal_True)
    {
        HINSTANCE inst= LoadLibrary( _T("ole32.dll"));
        if( inst )
        {
            HRESULT hr;
            ptrCoInitEx initFuncEx= (ptrCoInitEx)GetProcAddress( inst, _T("CoInitializeEx"));
            if( initFuncEx)
                hr= initFuncEx( NULL, COINIT_MULTITHREADED);
            else
            {
                ptrCoInit initFunc= (ptrCoInit)GetProcAddress( inst,_T("CoInitialize"));
                if( initFunc)
                    hr= initFunc( NULL);
            }
        }
        oleThreadData.setData((void*)sal_True);
    }
}

//===============================================================================
// EmbedServer_Impl

EmbedServer_Impl::EmbedServer_Impl( const uno::Reference<lang::XMultiServiceFactory>& xFactory):
    m_xFactory( xFactory)
{
    for( int nInd = 0; nInd < SUPPORTED_FACTORIES_NUM; nInd++ )
    {
        m_pOLEFactories[nInd] = new EmbedProviderFactory_Impl( m_xFactory, guidList[nInd] );
        m_pOLEFactories[nInd]->registerClass();
    }
}

EmbedServer_Impl::~EmbedServer_Impl()
{
    for( int nInd = 0; nInd < SUPPORTED_FACTORIES_NUM; nInd++ )
    {
        if ( m_pOLEFactories[nInd] )
            m_pOLEFactories[nInd]->deregisterClass();
    }
}

// XInterface --------------------------------------------------
uno::Any SAL_CALL
EmbedServer_Impl::queryInterface(
    const uno::Type& aType )
    throw(
        uno::RuntimeException
    )
{
    uno::Any a=
        ::cppu::queryInterface(
            aType, static_cast<lang::XTypeProvider*>(this));
    if( a == uno::Any())
        return OWeakObject::queryInterface( aType);
    else
        return a;
}

void SAL_CALL EmbedServer_Impl::acquire(  ) throw(uno::RuntimeException)
{
    OWeakObject::acquire();
}

void SAL_CALL EmbedServer_Impl::release(  ) throw (uno::RuntimeException)
{
    OWeakObject::release();
}

// XTypeProvider --------------------------------------------------
uno::Sequence< uno::Type > SAL_CALL
EmbedServer_Impl::getTypes( )
    throw(
        uno::RuntimeException
    )
{
    static ::cppu::OTypeCollection *pCollection = 0;
    if( ! pCollection )
    {
        ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() );
        if( ! pCollection )
        {
            static ::cppu::OTypeCollection collection(
                getCppuType(
                    reinterpret_cast<uno::Reference< uno::XWeak>*>(0)),
                getCppuType(
                    reinterpret_cast<
                    uno::Reference< lang::XTypeProvider>*>(0)));
            pCollection = &collection;
        }
    }
    return (*pCollection).getTypes();
}

uno::Sequence< sal_Int8 > SAL_CALL EmbedServer_Impl::getImplementationId() throw(uno::RuntimeException)
{
    static ::cppu::OImplementationId *pId = 0;
    if( ! pId )
    {
        ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() );
        if( ! pId )
        {
            static ::cppu::OImplementationId id( sal_False );
            pId = &id;
        }
    }
    return (*pId).getImplementationId();
}

//===============================================================================
// EmbedProviderFactory_Impl

EmbedProviderFactory_Impl::EmbedProviderFactory_Impl(const uno::Reference<lang::XMultiServiceFactory>& xFactory, const GUID* pGuid)
    : m_refCount( 0L )
    , m_xFactory( xFactory )
    , m_guid( *pGuid )
{
}

EmbedProviderFactory_Impl::~EmbedProviderFactory_Impl()
{
}

sal_Bool EmbedProviderFactory_Impl::registerClass()
{
    HRESULT hresult;

    o2u_attachCurrentThread();

    hresult = CoRegisterClassObject(
            m_guid,
            this,
            CLSCTX_LOCAL_SERVER,
            REGCLS_MULTIPLEUSE,
            &m_factoryHandle);

    return (hresult == NOERROR);
}

sal_Bool EmbedProviderFactory_Impl::deregisterClass()
{
    HRESULT hresult = CoRevokeClassObject( m_factoryHandle );

    return (hresult == NOERROR);
}

STDMETHODIMP EmbedProviderFactory_Impl::QueryInterface(REFIID riid, void FAR* FAR* ppv)
{
    if(IsEqualIID(riid, IID_IUnknown))
    {
        AddRef();
        *ppv = (IUnknown*) (IClassFactory*) this;
        return NOERROR;
    }
    else if (IsEqualIID(riid, IID_IClassFactory))
    {
        AddRef();
        *ppv = (IClassFactory*) this;
        return NOERROR;
    }

    *ppv = NULL;
    return ResultFromScode(E_NOINTERFACE);
}

STDMETHODIMP_(ULONG) EmbedProviderFactory_Impl::AddRef()
{
    return osl_incrementInterlockedCount( &m_refCount);
}

STDMETHODIMP_(ULONG) EmbedProviderFactory_Impl::Release()
{
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex());
    sal_Int32 nCount = --m_refCount;
    if ( nCount == 0 )
    {
        delete this;
    }

    return nCount;
}

STDMETHODIMP EmbedProviderFactory_Impl::CreateInstance(IUnknown FAR* punkOuter,
                                                     REFIID riid,
                                                     void FAR* FAR* ppv)
{
    punkOuter = NULL;

    IUnknown* pEmbedDocument = (IUnknown*)(IPersistStorage*)( new EmbedDocument_Impl( m_xFactory, &m_guid ) );

    return pEmbedDocument->QueryInterface( riid, ppv );
}

STDMETHODIMP EmbedProviderFactory_Impl::LockServer( int fLock )
{
    return NOERROR;
}

<|endoftext|>


<commit_before>// -*- mode: c++; coding: utf-8 -*-
/*! @file simulation.cpp
    @brief Inplementation of Simulation class
*/
#include "simulation.h"

#include "cxxwtils/iostr.hpp"
#include "cxxwtils/getopt.hpp"
#include "cxxwtils/prandom.hpp"
#include "cxxwtils/os.hpp"
#include "cxxwtils/gz.hpp"
#include "cxxwtils/multiprocessing.hpp"

#include "individual.h"

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// functions

//! Symbols for the program options can be different from those in equations
/*! @ingroup biol_param
    @return Program options description

    Command line option | Symbol   | Variable
    ------------------- | -------- | ------------------------------------------
    `--row,--col`       | -        | Simulation::NUM_COLS, Simulation::NUM_ROWS
    `-T,--time`         | -        | Simulation::ENTIRE_PERIOD
    `-I,--interval`     | -        | Simulation::OBSERVATION_CYCLE
*/
boost::program_options::options_description& Simulation::opt_description() {HERE;
    namespace po = boost::program_options;
    static po::options_description description("Simulation");
    description.add_options()
        ("help,h", po::value<bool>()->default_value(false)->implicit_value(true), "produce help")
        ("verbose,v", po::value<bool>(&VERBOSE)
            ->default_value(VERBOSE)->implicit_value(true), "verbose output")
        ("test", po::value<int>()->default_value(0)->implicit_value(1))
        ("mode", po::value<int>(&MODE)->default_value(MODE))
        ("ppn", po::value<size_t>(&PPN)->default_value(wtl::num_threads()))
        ("label", po::value<std::string>(&LABEL)->default_value("default"))
        ("top_dir", po::value<std::string>()->default_value(OUT_DIR.string()))
        ("row", po::value<size_t>(&NUM_ROWS)->default_value(NUM_ROWS))
        ("col", po::value<size_t>(&NUM_COLS)->default_value(NUM_COLS))
        ("dimensions,D", po::value<size_t>(&DIMENSIONS)->default_value(DIMENSIONS))
        ("time,T", po::value<size_t>(&ENTIRE_PERIOD)->default_value(ENTIRE_PERIOD))
        ("interval,I", po::value<size_t>(&OBSERVATION_CYCLE)->default_value(OBSERVATION_CYCLE))
        ("seed", po::value<unsigned int>(&SEED)->default_value(SEED))
    ;
    return description;
}

//! Unit test for each class
inline void test() {HERE;
    Individual::unit_test();
    Patch::unit_test();
}

Simulation::Simulation(int argc, char* argv[]) {HERE;
    std::vector<std::string> arguments(argv, argv + argc);
    std::cout << wtl::str_join(arguments, " ") << std::endl;
    std::cout << wtl::iso8601datetime() << std::endl;

    namespace po = boost::program_options;
    po::options_description description;
    description.add(opt_description());
    description.add(Individual::opt_description());
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, description), vm);
    po::notify(vm);

    if (vm["help"].as<bool>()) {
        description.print(std::cout);
        exit(0);
    }
    OUT_DIR = fs::path(vm["top_dir"].as<std::string>());
    const std::string CONFIG_STRING = wtl::flags_into_string(description, vm);
    prandom().seed(SEED); // TODO: want to read seed?
    if (VERBOSE) {
        std::cout << CONFIG_STRING << std::endl;
    }
    if (ENTIRE_PERIOD % OBSERVATION_CYCLE > 0) {
        std::cerr << wtl::strprintf(
            "T=%d is not a multiple of I=%d",
            ENTIRE_PERIOD, OBSERVATION_CYCLE) << std::endl;
        exit(1);
    }
    if (DIMENSIONS == 1) {
        std::ostringstream ost;
        ost << "diameter_pref = 0\n"
            << "limb_select = 0\n"
            << "diameter_compe = 0\n"
            << "limb_compe = 0\n"
            << "mutation_mask = 10\n";
        std::istringstream ist(ost.str());
        po::store(po::parse_config_file(ist, description, false), vm);
        vm.notify();
    }
    switch (vm["test"].as<int>()) {
      case 0:
        break;
      case 1:
        test();
        exit(0);
      default:
        exit(1);
    }
    const std::string now(wtl::strftime("%Y%m%d_%H%M%S"));
    std::ostringstream pid_at_host;
    pid_at_host << ::getpid() << "@" << wtl::gethostname();
    WORK_DIR = TMP_DIR / (now + "_" + LABEL + "_" + pid_at_host.str());
    derr("mkdir && cd to " << WORK_DIR << std::endl);
    fs::create_directory(WORK_DIR);
    wtl::cd(WORK_DIR.string());
    fs::create_directory(OUT_DIR);
    OUT_DIR /= (LABEL + "_" + now + "_" + pid_at_host.str());
    wtl::Fout{"program_options.conf"} << CONFIG_STRING;
}

void Simulation::run() {HERE;
    switch (MODE) {
      case 0:
        evolve();
        break;
      case 1:
        Individual::write_resource_abundance();
        break;
      case 2:
        wtl::gzip{wtl::Fout{"possible_geographic.csv.gz"}} << Individual::possible_geographic();
        wtl::gzip{wtl::Fout{"possible_phenotypes.csv.gz"}} << Individual::possible_phenotypes();
        break;
      default:
        exit(1);
    }
    derr("mv results to " << OUT_DIR << std::endl);
    fs::rename(WORK_DIR, OUT_DIR);
    std::cout << wtl::iso8601datetime() << std::endl;
}

void Simulation::evolve() {HERE;
    assert(ENTIRE_PERIOD % OBSERVATION_CYCLE == 0);
    population.assign(NUM_ROWS, std::vector<Patch>(NUM_COLS));
    if (DIMENSIONS == 1) {
        population[0][0] = Patch(INITIAL_PATCH_SIZE, Individual{{15, 0, 15, 0}});
    } else {
        population[0][0] = Patch(INITIAL_PATCH_SIZE);
    }
    std::ostringstream ost;
    for (size_t t=0; t<=ENTIRE_PERIOD; ++t) {
        if (VERBOSE) {
            std::cout << "\nT = " << t << "\n"
                << str_population([](const Patch& p) {return p.size();});
        }
        if (t % OBSERVATION_CYCLE == 0) {
            write_snapshot(t, ost);
        }
        if (t < ENTIRE_PERIOD) {
            life_cycle();
        }
    }
    wtl::gzip{wtl::Fout{"evolution.csv.gz"}} << ost.str();
}

void Simulation::life_cycle() {
    std::vector<std::vector<Patch> > parents(population);
    wtl::Semaphore sem(PPN);
    std::mutex mtx;
    auto patch_task = [&](const size_t row, const size_t col) {
        auto offsprings = parents[row][col].mate_and_reproduce();
        std::lock_guard<std::mutex> lck(mtx);
        for (auto& child: offsprings) {
            size_t dest_row = row;
            size_t dest_col = col;
            choose_patch(&dest_row, &dest_col);
            population[dest_row][dest_col].append(std::move(child));
        }
        sem.unlock();
    };
    std::vector<std::thread> threads;
    for (size_t row=0; row<NUM_ROWS; ++row) {
        for (size_t col=0; col<NUM_COLS; ++col) {
            sem.lock();
            threads.emplace_back(patch_task, row, col);
        }
    }
    for (auto& th: threads) {th.join();}
    threads.clear();
    for (size_t row=0; row<NUM_ROWS; ++row) {
        for (size_t col=0; col<NUM_COLS; ++col) {
            sem.lock();
            threads.emplace_back([row, col, &sem, this] {
                population[row][col].viability_selection();
                sem.unlock();
            });
        }
    }
    for (auto& th: threads) {th.join();}
}

void Simulation::choose_patch(size_t* row, size_t* col) const {
    if (!prandom().bernoulli(Individual::MIGRATION_RATE())) {return;}
    size_t r = *row;
    size_t c = *col;
    switch (prandom().randrange(8)) {
      case 0:      ++c; break;
      case 1: ++r; ++c; break;
      case 2: ++r;      break;
      case 3: ++r; --c; break;
      case 4:      --c; break;
      case 5: --r; --c; break;
      case 6: --r;      break;
      case 7: --r; ++c; break;
    }
    // size_t(-1) also makes true
    if ((r >= NUM_ROWS) | (c >= NUM_COLS)) {return;}
    *row = r; *col = c;
}

void Simulation::write_snapshot(const size_t time, std::ostream& ost) const {
    const std::string sep{","};
    if (time == 0) {
        ost << "time" << sep << "row" << sep << "col" << sep
            << "n" << sep << Individual::header() << "\n";
    }
    std::size_t popsize = 0;
    for (size_t row=0; row<population.size(); ++row) {
        for (size_t col=0; col<population[row].size(); ++col) {
            for (const auto& item: population[row][col].summarize()) {
                ost << time << sep << row << sep << col << sep
                    << item.second << sep << item.first << "\n";
                popsize += item.second;
            }
        }
    }
    derr("N = " << popsize << std::endl);
}

<commit_msg>Minor update for debug print<commit_after>// -*- mode: c++; coding: utf-8 -*-
/*! @file simulation.cpp
    @brief Inplementation of Simulation class
*/
#include "simulation.h"

#include "cxxwtils/iostr.hpp"
#include "cxxwtils/getopt.hpp"
#include "cxxwtils/prandom.hpp"
#include "cxxwtils/os.hpp"
#include "cxxwtils/gz.hpp"
#include "cxxwtils/multiprocessing.hpp"

#include "individual.h"

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
// functions

//! Symbols for the program options can be different from those in equations
/*! @ingroup biol_param
    @return Program options description

    Command line option | Symbol   | Variable
    ------------------- | -------- | ------------------------------------------
    `--row,--col`       | -        | Simulation::NUM_COLS, Simulation::NUM_ROWS
    `-T,--time`         | -        | Simulation::ENTIRE_PERIOD
    `-I,--interval`     | -        | Simulation::OBSERVATION_CYCLE
*/
boost::program_options::options_description& Simulation::opt_description() {HERE;
    namespace po = boost::program_options;
    static po::options_description description("Simulation");
    description.add_options()
        ("help,h", po::value<bool>()->default_value(false)->implicit_value(true), "produce help")
        ("verbose,v", po::value<bool>(&VERBOSE)
            ->default_value(VERBOSE)->implicit_value(true), "verbose output")
        ("test", po::value<int>()->default_value(0)->implicit_value(1))
        ("mode", po::value<int>(&MODE)->default_value(MODE))
        ("ppn", po::value<size_t>(&PPN)->default_value(wtl::num_threads()))
        ("label", po::value<std::string>(&LABEL)->default_value("default"))
        ("top_dir", po::value<std::string>()->default_value(OUT_DIR.string()))
        ("row", po::value<size_t>(&NUM_ROWS)->default_value(NUM_ROWS))
        ("col", po::value<size_t>(&NUM_COLS)->default_value(NUM_COLS))
        ("dimensions,D", po::value<size_t>(&DIMENSIONS)->default_value(DIMENSIONS))
        ("time,T", po::value<size_t>(&ENTIRE_PERIOD)->default_value(ENTIRE_PERIOD))
        ("interval,I", po::value<size_t>(&OBSERVATION_CYCLE)->default_value(OBSERVATION_CYCLE))
        ("seed", po::value<unsigned int>(&SEED)->default_value(SEED))
    ;
    return description;
}

//! Unit test for each class
inline void test() {HERE;
    Individual::unit_test();
    Patch::unit_test();
}

Simulation::Simulation(int argc, char* argv[]) {HERE;
    std::vector<std::string> arguments(argv, argv + argc);
    std::cout << wtl::str_join(arguments, " ") << std::endl;
    std::cout << wtl::iso8601datetime() << std::endl;

    namespace po = boost::program_options;
    po::options_description description;
    description.add(opt_description());
    description.add(Individual::opt_description());
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, description), vm);
    po::notify(vm);

    if (vm["help"].as<bool>()) {
        description.print(std::cout);
        exit(0);
    }
    OUT_DIR = fs::path(vm["top_dir"].as<std::string>());
    prandom().seed(SEED); // TODO: want to read seed?
    if (DIMENSIONS == 1) {
        std::ostringstream ost;
        ost << "diameter_pref = 0\n"
            << "limb_select = 0\n"
            << "diameter_compe = 0\n"
            << "limb_compe = 0\n"
            << "mutation_mask = 10\n";
        std::istringstream ist(ost.str());
        po::store(po::parse_config_file(ist, description, false), vm);
        vm.notify();
    }
    const std::string CONFIG_STRING = wtl::flags_into_string(description, vm);
    if (VERBOSE) {
        std::cout << CONFIG_STRING << std::endl;
    }
    if (ENTIRE_PERIOD % OBSERVATION_CYCLE > 0) {
        std::cerr << wtl::strprintf(
            "T=%d is not a multiple of I=%d",
            ENTIRE_PERIOD, OBSERVATION_CYCLE) << std::endl;
        exit(1);
    }
    switch (vm["test"].as<int>()) {
      case 0:
        break;
      case 1:
        test();
        exit(0);
      default:
        exit(1);
    }
    const std::string now(wtl::strftime("%Y%m%d_%H%M%S"));
    std::ostringstream pid_at_host;
    pid_at_host << ::getpid() << "@" << wtl::gethostname();
    WORK_DIR = TMP_DIR / (now + "_" + LABEL + "_" + pid_at_host.str());
    derr("mkdir && cd to " << WORK_DIR << std::endl);
    fs::create_directory(WORK_DIR);
    wtl::cd(WORK_DIR.string());
    fs::create_directory(OUT_DIR);
    OUT_DIR /= (LABEL + "_" + now + "_" + pid_at_host.str());
    wtl::Fout{"program_options.conf"} << CONFIG_STRING;
}

void Simulation::run() {HERE;
    switch (MODE) {
      case 0:
        evolve();
        break;
      case 1:
        Individual::write_resource_abundance();
        break;
      case 2:
        wtl::gzip{wtl::Fout{"possible_geographic.csv.gz"}} << Individual::possible_geographic();
        wtl::gzip{wtl::Fout{"possible_phenotypes.csv.gz"}} << Individual::possible_phenotypes();
        break;
      default:
        exit(1);
    }
    derr("mv results to " << OUT_DIR << std::endl);
    fs::rename(WORK_DIR, OUT_DIR);
    std::cout << wtl::iso8601datetime() << std::endl;
}

void Simulation::evolve() {HERE;
    assert(ENTIRE_PERIOD % OBSERVATION_CYCLE == 0);
    population.assign(NUM_ROWS, std::vector<Patch>(NUM_COLS));
    if (DIMENSIONS == 1) {
        population[0][0] = Patch(INITIAL_PATCH_SIZE, Individual{{15, 0, 15, 0}});
    } else {
        population[0][0] = Patch(INITIAL_PATCH_SIZE);
    }
    std::ostringstream ost;
    for (size_t t=0; t<=ENTIRE_PERIOD; ++t) {
        if (VERBOSE) {
            std::cout << "\nT = " << t << "\n"
                << str_population([](const Patch& p) {return p.size();})
                << std::flush;
        }
        if (t % OBSERVATION_CYCLE == 0) {
            write_snapshot(t, ost);
        }
        if (t < ENTIRE_PERIOD) {
            life_cycle();
        }
    }
    wtl::gzip{wtl::Fout{"evolution.csv.gz"}} << ost.str();
}

void Simulation::life_cycle() {
    std::vector<std::vector<Patch> > parents(population);
    wtl::Semaphore sem(PPN);
    std::mutex mtx;
    auto patch_task = [&](const size_t row, const size_t col) {
        auto offsprings = parents[row][col].mate_and_reproduce();
        std::lock_guard<std::mutex> lck(mtx);
        for (auto& child: offsprings) {
            size_t dest_row = row;
            size_t dest_col = col;
            choose_patch(&dest_row, &dest_col);
            population[dest_row][dest_col].append(std::move(child));
        }
        sem.unlock();
    };
    std::vector<std::thread> threads;
    for (size_t row=0; row<NUM_ROWS; ++row) {
        for (size_t col=0; col<NUM_COLS; ++col) {
            sem.lock();
            threads.emplace_back(patch_task, row, col);
        }
    }
    for (auto& th: threads) {th.join();}
    threads.clear();
    for (size_t row=0; row<NUM_ROWS; ++row) {
        for (size_t col=0; col<NUM_COLS; ++col) {
            sem.lock();
            threads.emplace_back([row, col, &sem, this] {
                population[row][col].viability_selection();
                sem.unlock();
            });
        }
    }
    for (auto& th: threads) {th.join();}
}

void Simulation::choose_patch(size_t* row, size_t* col) const {
    if (!prandom().bernoulli(Individual::MIGRATION_RATE())) {return;}
    size_t r = *row;
    size_t c = *col;
    switch (prandom().randrange(8)) {
      case 0:      ++c; break;
      case 1: ++r; ++c; break;
      case 2: ++r;      break;
      case 3: ++r; --c; break;
      case 4:      --c; break;
      case 5: --r; --c; break;
      case 6: --r;      break;
      case 7: --r; ++c; break;
    }
    // size_t(-1) also makes true
    if ((r >= NUM_ROWS) | (c >= NUM_COLS)) {return;}
    *row = r; *col = c;
}

void Simulation::write_snapshot(const size_t time, std::ostream& ost) const {
    const std::string sep{","};
    if (time == 0) {
        ost << "time" << sep << "row" << sep << "col" << sep
            << "n" << sep << Individual::header() << "\n";
    }
    std::size_t popsize = 0;
    for (size_t row=0; row<population.size(); ++row) {
        for (size_t col=0; col<population[row].size(); ++col) {
            for (const auto& item: population[row][col].summarize()) {
                ost << time << sep << row << sep << col << sep
                    << item.second << sep << item.first << "\n";
                popsize += item.second;
            }
        }
    }
    derr("N = " << popsize << std::endl);
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017-2018 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#ifndef LIBDNF_TRANSACTION_TRANSACTIONITEM_HPP
#define LIBDNF_TRANSACTION_TRANSACTIONITEM_HPP

#include <memory>
#include <string>

#include "../utils/sqlite3/Sqlite3.hpp"

namespace libdnf {
class TransactionItem;
typedef std::shared_ptr< TransactionItem > TransactionItemPtr;
}

#include "Item.hpp"
#include "CompsEnvironmentItem.hpp"
#include "CompsGroupItem.hpp"
#include "RPMItem.hpp"
#include "private/Repo.hpp"
#include "Transaction.hpp"
#include "Types.hpp"

namespace libdnf {

class TransactionItemBase {
public:
    ItemPtr getItem() const noexcept { return item; }
    void setItem(ItemPtr value) { item = value; }

    // typed items - workaround for lack of shared_ptr<> downcast support in SWIG
    CompsEnvironmentItemPtr getCompsEnvironmentItem() const noexcept
    {
        return std::dynamic_pointer_cast< CompsEnvironmentItem >(item);
    }
    CompsGroupItemPtr getCompsGroupItem() const noexcept
    {
        return std::dynamic_pointer_cast< CompsGroupItem >(item);
    }
    RPMItemPtr getRPMItem() const noexcept { return std::dynamic_pointer_cast< RPMItem >(item); }

    const std::string &getRepoid() const noexcept { return repoid; }
    void setRepoid(const std::string &value) { repoid = value; }

    TransactionItemAction getAction() const noexcept { return action; }
    void setAction(TransactionItemAction value) { action = value; }

    TransactionItemReason getReason() const noexcept { return reason; }
    void setReason(TransactionItemReason value) { reason = value; }

    const std::string &getActionName();
    const std::string &getActionShort();

    TransactionItemState getState() const noexcept { return state; }
    void setState(TransactionItemState value) { state = value; }

protected:
    ItemPtr item;
    std::string repoid;
    TransactionItemAction action = TransactionItemAction::INSTALL;
    TransactionItemReason reason = TransactionItemReason::UNKNOWN;
    TransactionItemState state = TransactionItemState::UNKNOWN;
};

typedef std::shared_ptr< TransactionItemBase > TransactionItemBasePtr;

class TransactionItem : public TransactionItemBase {
public:
    explicit TransactionItem(Transaction *trans);

    TransactionItem(SQLite3Ptr conn, int64_t transID);

    int64_t getId() const noexcept { return id; }
    void setId(int64_t value) { id = value; }

    // int64_t getTransactionId() const noexcept { return trans.getId(); }

    const std::vector< TransactionItemPtr > &getReplacedBy() const noexcept { return replacedBy; }
    void addReplacedBy(TransactionItemPtr value) { replacedBy.push_back(value); }

    void save();
    void saveReplacedBy();
    void saveState();

    std::size_t getHash() { return reinterpret_cast< std::size_t >(this); }
    bool operator==(TransactionItem & other) { return (other.getHash() == getHash()); }
    bool operator==(TransactionItemPtr other) { return (other->getHash() == getHash()); }

protected:
    int64_t id = 0;
    Transaction *trans;

    const int64_t transID;
    SQLite3Ptr conn;

    // TODO: replace with objects? it's just repoid, probably not necessary
    std::vector< TransactionItemPtr > replacedBy;

    void dbInsert();
    void dbUpdate();
};

} // namespace libdnf

#endif // LIBDNF_TRANSACTION_TRANSACTIONITEM_HPP
<commit_msg>Fix sorting a list of transaction items in Python.<commit_after>/*
 * Copyright (C) 2017-2018 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#ifndef LIBDNF_TRANSACTION_TRANSACTIONITEM_HPP
#define LIBDNF_TRANSACTION_TRANSACTIONITEM_HPP

#include <memory>
#include <string>

#include "../utils/sqlite3/Sqlite3.hpp"

namespace libdnf {
class TransactionItem;
typedef std::shared_ptr< TransactionItem > TransactionItemPtr;
}

#include "Item.hpp"
#include "CompsEnvironmentItem.hpp"
#include "CompsGroupItem.hpp"
#include "RPMItem.hpp"
#include "private/Repo.hpp"
#include "Transaction.hpp"
#include "Types.hpp"

namespace libdnf {

class TransactionItemBase {
public:
    ItemPtr getItem() const noexcept { return item; }
    void setItem(ItemPtr value) { item = value; }

    // typed items - workaround for lack of shared_ptr<> downcast support in SWIG
    CompsEnvironmentItemPtr getCompsEnvironmentItem() const noexcept
    {
        return std::dynamic_pointer_cast< CompsEnvironmentItem >(item);
    }
    CompsGroupItemPtr getCompsGroupItem() const noexcept
    {
        return std::dynamic_pointer_cast< CompsGroupItem >(item);
    }
    RPMItemPtr getRPMItem() const noexcept { return std::dynamic_pointer_cast< RPMItem >(item); }

    const std::string &getRepoid() const noexcept { return repoid; }
    void setRepoid(const std::string &value) { repoid = value; }

    TransactionItemAction getAction() const noexcept { return action; }
    void setAction(TransactionItemAction value) { action = value; }

    TransactionItemReason getReason() const noexcept { return reason; }
    void setReason(TransactionItemReason value) { reason = value; }

    const std::string &getActionName();
    const std::string &getActionShort();

    TransactionItemState getState() const noexcept { return state; }
    void setState(TransactionItemState value) { state = value; }

protected:
    ItemPtr item;
    std::string repoid;
    TransactionItemAction action = TransactionItemAction::INSTALL;
    TransactionItemReason reason = TransactionItemReason::UNKNOWN;
    TransactionItemState state = TransactionItemState::UNKNOWN;
};

typedef std::shared_ptr< TransactionItemBase > TransactionItemBasePtr;

class TransactionItem : public TransactionItemBase {
public:
    explicit TransactionItem(Transaction *trans);

    TransactionItem(SQLite3Ptr conn, int64_t transID);

    int64_t getId() const noexcept { return id; }
    void setId(int64_t value) { id = value; }

    // int64_t getTransactionId() const noexcept { return trans.getId(); }

    const std::vector< TransactionItemPtr > &getReplacedBy() const noexcept { return replacedBy; }
    void addReplacedBy(TransactionItemPtr value) { replacedBy.push_back(value); }

    void save();
    void saveReplacedBy();
    void saveState();

    std::size_t getHash() { return reinterpret_cast< std::size_t >(this); }
    bool operator==(TransactionItem & other) { return (other.getHash() == getHash()); }
    bool operator==(TransactionItemPtr other) { return (other->getHash() == getHash()); }

    // needed for sorting a list of transaction items in Python
    // TODO: consider replacing trivial string comparison with something better
    bool operator<(TransactionItem & other) { return (getItem()->toStr() < other.getItem()->toStr()); }
    bool operator<(TransactionItemPtr other) { return (getItem()->toStr() < other->getItem()->toStr()); }

protected:
    int64_t id = 0;
    Transaction *trans;

    const int64_t transID;
    SQLite3Ptr conn;

    // TODO: replace with objects? it's just repoid, probably not necessary
    std::vector< TransactionItemPtr > replacedBy;

    void dbInsert();
    void dbUpdate();
};

} // namespace libdnf

#endif // LIBDNF_TRANSACTION_TRANSACTIONITEM_HPP
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: register.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 00:46:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_embeddedobj.hxx"

#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_
#include <com/sun/star/registry/InvalidRegistryException.hpp>
#endif

#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif

#include "xexecutor.hxx"

using namespace ::com::sun::star;

extern "C" {

void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    void * pRet = 0;

    ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) );
    uno::Reference< lang::XSingleServiceFactory > xFactory;

    if ( pServiceManager && aImplName.equals( UNOMainThreadExecutor::impl_staticGetImplementationName() ) )
    {
        xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>( pServiceManager ),
                                            UNOMainThreadExecutor::impl_staticGetImplementationName(),
                                            UNOMainThreadExecutor::impl_staticCreateSelfInstance,
                                            UNOMainThreadExecutor::impl_staticGetSupportedServiceNames() );
    }

    if ( xFactory.is() )
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }

    return pRet;
}

sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey )
{
    if (pRegistryKey)
    {
        try
        {
            uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) );

            uno::Reference< registry::XRegistryKey >  xNewKey;

            xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) +
                                        UNOMainThreadExecutor::impl_staticGetImplementationName() +
                                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") )  );

            uno::Sequence< ::rtl::OUString > &rServices = UNOMainThreadExecutor::impl_staticGetSupportedServiceNames();
            for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ )
                xNewKey->createKey( rServices.getConstArray()[ind] );

            return sal_True;
        }
        catch (registry::InvalidRegistryException &)
        {
            OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
        }
    }
    return sal_False;
}

} // extern "C"

<commit_msg>INTEGRATION: CWS changefileheader (1.3.68); FILE MERGED 2008/04/01 15:13:51 thb 1.3.68.3: #i85898# Stripping all external header guards 2008/04/01 12:28:54 thb 1.3.68.2: #i85898# Stripping all external header guards 2008/03/31 13:33:23 rt 1.3.68.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: register.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_embeddedobj.hxx"

#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/registry/InvalidRegistryException.hpp>
#include <cppuhelper/factory.hxx>

#include "xexecutor.hxx"

using namespace ::com::sun::star;

extern "C" {

void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )
{
    void * pRet = 0;

    ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) );
    uno::Reference< lang::XSingleServiceFactory > xFactory;

    if ( pServiceManager && aImplName.equals( UNOMainThreadExecutor::impl_staticGetImplementationName() ) )
    {
        xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>( pServiceManager ),
                                            UNOMainThreadExecutor::impl_staticGetImplementationName(),
                                            UNOMainThreadExecutor::impl_staticCreateSelfInstance,
                                            UNOMainThreadExecutor::impl_staticGetSupportedServiceNames() );
    }

    if ( xFactory.is() )
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }

    return pRet;
}

sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey )
{
    if (pRegistryKey)
    {
        try
        {
            uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) );

            uno::Reference< registry::XRegistryKey >  xNewKey;

            xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) +
                                        UNOMainThreadExecutor::impl_staticGetImplementationName() +
                                        ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") )  );

            uno::Sequence< ::rtl::OUString > &rServices = UNOMainThreadExecutor::impl_staticGetSupportedServiceNames();
            for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ )
                xNewKey->createKey( rServices.getConstArray()[ind] );

            return sal_True;
        }
        catch (registry::InvalidRegistryException &)
        {
            OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
        }
    }
    return sal_False;
}

} // extern "C"

<|endoftext|>