<commit_before>#include "SysConfig.h"
#if(HAS_MPL3115A2)

#include <CI2C.h>
#include "CMPL3115A2.h"
#include "CTimer.h"
#include "NDataManager.h"

namespace
{
    CTimer mpl3115a2_report_timer;
    CTimer mpl3115a2_sample_timer;

    bool isInitialized = false;
}

CMPL3115A2::CMPL3115A2( CI2C *i2cInterfaceIn )
    : m_mpl( i2cInterfaceIn )
{

}

void CMPL3115A2::Initialize()
{
    Serial.println( "MPL3115A2.Status:INIT;" );

    //init process
    mpl3115a2_sample_timer.Reset();
    mpl3115a2_report_timer.Reset();

    Serial.println( "MPL3115A2.Status:POST_INIT; ");
}

void CMPL3115A2::InitializeSensor()
{
    //Attempt to init the sensor
    auto ret = m_mpl.Initialize();
    if( ret != mpl3115a2::ERetCode::SUCCESS )
    {
        Serial.println( "MPL3115A2_INIT_STATUS:FAILED;" );
    }
    else
    {
        Serial.println( "MPL3115A2_INIT_STATUS:SUCCESS;" );

        //Set the mode
        m_mpl.SetMode( mpl3115a2::EMode::BAROMETER );

        //Set the over sample rate_div
        m_mpl.SetOversampleRatio( mpl3115a2::EOversampleRatio::OSR_128 );

        //Enable event flags
        m_mpl.EnableEventFlags();

        isInitialized = true;
    }
}

void CMPL3115A2::Update( CCommand &commandIn )
{
    //
    if( mpl3115a2_sample_timer.HasElapsed( 2000 ) )
    {
        if( !isInitialized )
        {
            if( mpl3115a2_report_timer.HasElapsed( 1000 ) )
            {
                Serial.println( "MPL3115A2.Status:TRYING;" );
                InitializeSensor();
            }
            return;
        }
        float pressure;

        auto ret = m_mpl.ReadPressure(pressure);
        Serial.println(pressure);
        Serial.println(ret);
    }
}

#endif<commit_msg>Added module functionality at 1hz<commit_after>#include "SysConfig.h"
#if(HAS_MPL3115A2)

#include <CI2C.h>
#include "CMPL3115A2.h"
#include "CTimer.h"
#include "NDataManager.h"

namespace
{
    CTimer mpl3115a2_report_timer;
    CTimer mpl3115a2_sample_timer;

    bool isInitialized = false;
}

CMPL3115A2::CMPL3115A2( CI2C *i2cInterfaceIn )
    : m_mpl( i2cInterfaceIn )
{

}

void CMPL3115A2::Initialize()
{
    Serial.println( "MPL3115A2.Status:INIT;" );

    //init process
    mpl3115a2_sample_timer.Reset();
    mpl3115a2_report_timer.Reset();

    Serial.println( "MPL3115A2.Status:POST_INIT; ");
}

void CMPL3115A2::InitializeSensor()
{
    //Attempt to init the sensor
    auto ret = m_mpl.Initialize();
    if( ret != mpl3115a2::ERetCode::SUCCESS )
    {
        Serial.println( "MPL3115A2_INIT_STATUS:FAILED;" );
    }
    else
    {
        Serial.println( "MPL3115A2_INIT_STATUS:SUCCESS;" );

        //Set the mode
        m_mpl.SetMode( mpl3115a2::EMode::BAROMETER );

        //Set the over sample rate_div
        m_mpl.SetOversampleRatio( mpl3115a2::EOversampleRatio::OSR_128 );

        //Enable event flags
        m_mpl.EnableEventFlags();

        isInitialized = true;
    }
}

void CMPL3115A2::Update( CCommand &commandIn )
{
    //1 Hz
    if( mpl3115a2_sample_timer.HasElapsed( 1000 ) )
    {
        if( !isInitialized )
        {
            if( mpl3115a2_report_timer.HasElapsed( 5000 ) )
            {
                Serial.println( "MPL3115A2.Status:TRYING;" );
                InitializeSensor();
            }
            return;
        }

        //Attempt to read the pressue
        float pressure;
        auto ret = m_mpl.ReadPressure(pressure);
        if( ret != mpl3115a2::ERetCode::SUCCESS )
        {
            Serial.print( "MPL3115A2.Status:ERROR: " );
            Serial.print( ret );
            Serial.println( ";" );
            return;
        }

        Serial.print( "MPL3115A2.Value.Pressure: " );
        Serial.print( pressure );
        Serial.println( " kPa;" );
    }
}

#endif<|endoftext|>


<commit_before>/*
 * Copyright (C) 2019 pengjian.uestc @ gmail.com
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is seastar::sharded 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "redis/options.hh"
#include "redis/protocol_parser.hh"
#include "redis/query_processor.hh"
#include "redis/reply.hh"
#include "redis/request.hh"
#include "redis/request.hh"
#include "redis/stats.hh"

#include "auth/authenticator.hh"
#include "auth/service.hh"
#include "cql3/values.hh"
#include "service/client_state.hh"
#include "service/storage_proxy.hh"
#include "service_permit.hh"
#include "timeout_config.hh"
#include "utils/estimated_histogram.hh"
#include "utils/fragmented_temporary_buffer.hh"

#include <seastar/core/seastar.hh>
#include <seastar/core/semaphore.hh>
#include <seastar/core/sharded.hh>
#include <seastar/net/tls.hh>

#include <memory>

db::consistency_level make_consistency_level(const sstring&);

namespace db {
class config;
};
class redis_exception;

namespace redis_transport {

struct redis_server_config {
    ::timeout_config _timeout_config;
    size_t _max_request_size;
    db::consistency_level _read_consistency_level;
    db::consistency_level _write_consistency_level;
    size_t _total_redis_db_count;
};

class redis_server {
    std::vector<server_socket> _listeners;
    seastar::sharded<service::storage_proxy>& _proxy;
    seastar::sharded<redis::query_processor>& _query_processor;
    redis_server_config _config;
    size_t _max_request_size;
    semaphore _memory_available;
    redis::stats _stats;
    uint64_t _requests_blocked_memory = 0;
    auth::service& _auth_service;
    size_t _total_redis_db_count;

public:
    redis_server(seastar::sharded<service::storage_proxy>& proxy, seastar::sharded<redis::query_processor>& qp, auth::service& auth_service, redis_server_config config);
    future<> listen(socket_address addr, std::shared_ptr<seastar::tls::credentials_builder> = {}, bool keepalive = false);
    future<> do_accepts(int which, bool keepalive, socket_address server_addr);
    future<> stop();

    struct result {
        result(redis::redis_message&& m) : _data(make_foreign(std::make_unique<redis::redis_message>(std::move(m)))) {}
        foreign_ptr<std::unique_ptr<redis::redis_message>> _data;
        inline lw_shared_ptr<scattered_message<char>> make_message()  {
            return _data->message();
        }
    };
    using response_type = result;

private:
    friend class connection;
    class connection : public boost::intrusive::list_base_hook<> {
       // using result = redis_server::result;
        redis_server& _server;
        socket_address _server_addr;
        connected_socket _fd;
        input_stream<char> _read_buf;
        output_stream<char> _write_buf;
        redis_protocol_parser _parser;
        seastar::gate _pending_requests_gate;
        //service::client_state _client_state;
        redis::redis_options _options;
        future<> _ready_to_respond = make_ready_future<>();
        unsigned _request_cpu = 0;
    private:
        enum class tracing_request_type : uint8_t {
            not_requested,
            no_write_on_close,
            write_on_close
        };

        using execution_stage_type = inheriting_concrete_execution_stage<
                future<redis_server::result>,
                redis_server::connection*,
                redis::request&&,
                redis::redis_options&,
                service_permit
        >;
        static thread_local execution_stage_type _process_request_stage;
    public:
        connection(redis_server& server, socket_address server_addr, connected_socket&& fd, socket_address addr);
        ~connection();
        future<> process();
        future<> process_request();
        void write_reply(const redis_exception&);
        void write_reply(redis_server::result result);
        future<> shutdown();
    private:
        const ::timeout_config& timeout_config() { return _server.timeout_config(); }
        friend class process_request_executor;
        future<result> process_request_one(redis::request&& request, redis::redis_options&, service_permit permit);
        future<result> process_request_internal();
    };

    bool _stopping = false;
    promise<> _all_connections_stopped;
    future<> _stopped = _all_connections_stopped.get_future();
    boost::intrusive::list<connection> _connections_list;

    void maybe_idle() {
        if (_stopping && !_stats._connections_being_accepted && !_stats._current_connections) {
            _all_connections_stopped.set_value();
        }
    }
    const ::timeout_config& timeout_config() { return _config._timeout_config; }
};
}
<commit_msg>redis: Remove unused db::config forward declaration<commit_after>/*
 * Copyright (C) 2019 pengjian.uestc @ gmail.com
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is seastar::sharded 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "redis/options.hh"
#include "redis/protocol_parser.hh"
#include "redis/query_processor.hh"
#include "redis/reply.hh"
#include "redis/request.hh"
#include "redis/request.hh"
#include "redis/stats.hh"

#include "auth/authenticator.hh"
#include "auth/service.hh"
#include "cql3/values.hh"
#include "service/client_state.hh"
#include "service/storage_proxy.hh"
#include "service_permit.hh"
#include "timeout_config.hh"
#include "utils/estimated_histogram.hh"
#include "utils/fragmented_temporary_buffer.hh"

#include <seastar/core/seastar.hh>
#include <seastar/core/semaphore.hh>
#include <seastar/core/sharded.hh>
#include <seastar/net/tls.hh>

#include <memory>

db::consistency_level make_consistency_level(const sstring&);

class redis_exception;

namespace redis_transport {

struct redis_server_config {
    ::timeout_config _timeout_config;
    size_t _max_request_size;
    db::consistency_level _read_consistency_level;
    db::consistency_level _write_consistency_level;
    size_t _total_redis_db_count;
};

class redis_server {
    std::vector<server_socket> _listeners;
    seastar::sharded<service::storage_proxy>& _proxy;
    seastar::sharded<redis::query_processor>& _query_processor;
    redis_server_config _config;
    size_t _max_request_size;
    semaphore _memory_available;
    redis::stats _stats;
    uint64_t _requests_blocked_memory = 0;
    auth::service& _auth_service;
    size_t _total_redis_db_count;

public:
    redis_server(seastar::sharded<service::storage_proxy>& proxy, seastar::sharded<redis::query_processor>& qp, auth::service& auth_service, redis_server_config config);
    future<> listen(socket_address addr, std::shared_ptr<seastar::tls::credentials_builder> = {}, bool keepalive = false);
    future<> do_accepts(int which, bool keepalive, socket_address server_addr);
    future<> stop();

    struct result {
        result(redis::redis_message&& m) : _data(make_foreign(std::make_unique<redis::redis_message>(std::move(m)))) {}
        foreign_ptr<std::unique_ptr<redis::redis_message>> _data;
        inline lw_shared_ptr<scattered_message<char>> make_message()  {
            return _data->message();
        }
    };
    using response_type = result;

private:
    friend class connection;
    class connection : public boost::intrusive::list_base_hook<> {
       // using result = redis_server::result;
        redis_server& _server;
        socket_address _server_addr;
        connected_socket _fd;
        input_stream<char> _read_buf;
        output_stream<char> _write_buf;
        redis_protocol_parser _parser;
        seastar::gate _pending_requests_gate;
        //service::client_state _client_state;
        redis::redis_options _options;
        future<> _ready_to_respond = make_ready_future<>();
        unsigned _request_cpu = 0;
    private:
        enum class tracing_request_type : uint8_t {
            not_requested,
            no_write_on_close,
            write_on_close
        };

        using execution_stage_type = inheriting_concrete_execution_stage<
                future<redis_server::result>,
                redis_server::connection*,
                redis::request&&,
                redis::redis_options&,
                service_permit
        >;
        static thread_local execution_stage_type _process_request_stage;
    public:
        connection(redis_server& server, socket_address server_addr, connected_socket&& fd, socket_address addr);
        ~connection();
        future<> process();
        future<> process_request();
        void write_reply(const redis_exception&);
        void write_reply(redis_server::result result);
        future<> shutdown();
    private:
        const ::timeout_config& timeout_config() { return _server.timeout_config(); }
        friend class process_request_executor;
        future<result> process_request_one(redis::request&& request, redis::redis_options&, service_permit permit);
        future<result> process_request_internal();
    };

    bool _stopping = false;
    promise<> _all_connections_stopped;
    future<> _stopped = _all_connections_stopped.get_future();
    boost::intrusive::list<connection> _connections_list;

    void maybe_idle() {
        if (_stopping && !_stats._connections_being_accepted && !_stats._current_connections) {
            _all_connections_stopped.set_value();
        }
    }
    const ::timeout_config& timeout_config() { return _config._timeout_config; }
};
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/slide_animation.h"

#include <math.h>

// How many frames per second to target.
static const int kDefaultFramerateHz = 50;

// How long animations should take by default.
static const int kDefaultDurationMs = 120;

SlideAnimation::SlideAnimation(AnimationDelegate* target)
    : Animation(kDefaultFramerateHz, target),
      target_(target),
      tween_type_(EASE_OUT),
      showing_(false),
      value_start_(0),
      value_end_(0),
      value_current_(0),
      slide_duration_(kDefaultDurationMs) {
}

SlideAnimation::~SlideAnimation() {
}

void SlideAnimation::Reset() {
  Reset(0);
}

void SlideAnimation::Reset(double value) {
  Stop();
  showing_ = static_cast<bool>(value == 1);
  value_current_ = value;
}

void SlideAnimation::Show() {
  // If we're already showing (or fully shown), we have nothing to do.
  if (showing_)
    return;

  showing_ = true;
  value_start_ = value_current_;
  value_end_ = 1.0;

  // Make sure we actually have something to do.
  if (slide_duration_ == 0) {
    AnimateToState(1.0);  // Skip to the end of the animation.
    return;
  } else if (value_current_ == value_end_)  {
    return;
  }

  // This will also reset the currently-occuring animation.
  SetDuration(static_cast<int>(slide_duration_ * (1 - value_current_)));
  Start();
}

void SlideAnimation::Hide() {
  // If we're already hiding (or hidden), we have nothing to do.
  if (!showing_)
    return;

  showing_ = false;
  value_start_ = value_current_;
  value_end_ = 0.0;

  // Make sure we actually have something to do.
  if (slide_duration_ == 0) {
    AnimateToState(0.0);  // Skip to the end of the animation.
    return;
  } else if (value_current_ == value_end_) {
    return;
  }

  // This will also reset the currently-occuring animation.
  SetDuration(static_cast<int>(slide_duration_ * value_current_));
  Start();
}

void SlideAnimation::AnimateToState(double state) {
  if (state > 1.0)
    state = 1.0;

  // Make our animation ease-out.
  switch (tween_type_) {
    case EASE_IN:
      state = pow(state, 2);
      break;
    case EASE_IN_OUT:
      if (state < 0.5)
        state = pow(state * 2, 2) / 2.0;
      else
        state = 1.0 - (pow((state - 1.0) * 2, 2) / 2.0);
      break;
    case FAST_IN_OUT:
      state = (pow(state - 0.5, 3) + 0.125) / 0.25;
      break;
    case NONE:
      // state remains linear.
      break;
    case EASE_OUT_SNAP:
      state = 0.95 * (1.0 - pow(1.0 - state, 2));
      break;
    case EASE_OUT:
    default:
      state = 1.0 - pow(1.0 - state, 2);
      break;
  }

  value_current_ = value_start_ + (value_end_ - value_start_) * state;

  // Implement snapping.
  if (tween_type_ == EASE_OUT_SNAP && abs(value_current_ - value_end_) <= 0.06)
    value_current_ = value_end_;

  // Correct for any overshoot (while state may be capped at 1.0, let's not
  // take any rounding error chances.
  if ((value_end_ >= value_start_ && value_current_ > value_end_) ||
      (value_end_ < value_start_ && value_current_ < value_end_)) {
    value_current_ = value_end_;
  }
}

<commit_msg>Submit Issue 2965 patch by vega.james@gmail.com (jamessan)<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/slide_animation.h"

#include <math.h>

// How many frames per second to target.
static const int kDefaultFramerateHz = 50;

// How long animations should take by default.
static const int kDefaultDurationMs = 120;

SlideAnimation::SlideAnimation(AnimationDelegate* target)
    : Animation(kDefaultFramerateHz, target),
      target_(target),
      tween_type_(EASE_OUT),
      showing_(false),
      value_start_(0),
      value_end_(0),
      value_current_(0),
      slide_duration_(kDefaultDurationMs) {
}

SlideAnimation::~SlideAnimation() {
}

void SlideAnimation::Reset() {
  Reset(0);
}

void SlideAnimation::Reset(double value) {
  Stop();
  showing_ = static_cast<bool>(value == 1);
  value_current_ = value;
}

void SlideAnimation::Show() {
  // If we're already showing (or fully shown), we have nothing to do.
  if (showing_)
    return;

  showing_ = true;
  value_start_ = value_current_;
  value_end_ = 1.0;

  // Make sure we actually have something to do.
  if (slide_duration_ == 0) {
    AnimateToState(1.0);  // Skip to the end of the animation.
    return;
  } else if (value_current_ == value_end_)  {
    return;
  }

  // This will also reset the currently-occuring animation.
  SetDuration(static_cast<int>(slide_duration_ * (1 - value_current_)));
  Start();
}

void SlideAnimation::Hide() {
  // If we're already hiding (or hidden), we have nothing to do.
  if (!showing_)
    return;

  showing_ = false;
  value_start_ = value_current_;
  value_end_ = 0.0;

  // Make sure we actually have something to do.
  if (slide_duration_ == 0) {
    AnimateToState(0.0);  // Skip to the end of the animation.
    return;
  } else if (value_current_ == value_end_) {
    return;
  }

  // This will also reset the currently-occuring animation.
  SetDuration(static_cast<int>(slide_duration_ * value_current_));
  Start();
}

void SlideAnimation::AnimateToState(double state) {
  if (state > 1.0)
    state = 1.0;

  // Make our animation ease-out.
  switch (tween_type_) {
    case EASE_IN:
      state = pow(state, 2);
      break;
    case EASE_IN_OUT:
      if (state < 0.5)
        state = pow(state * 2, 2) / 2.0;
      else
        state = 1.0 - (pow((state - 1.0) * 2, 2) / 2.0);
      break;
    case FAST_IN_OUT:
      state = (pow(state - 0.5, 3) + 0.125) / 0.25;
      break;
    case NONE:
      // state remains linear.
      break;
    case EASE_OUT_SNAP:
      state = 0.95 * (1.0 - pow(1.0 - state, 2));
      break;
    case EASE_OUT:
    default:
      state = 1.0 - pow(1.0 - state, 2);
      break;
  }

  value_current_ = value_start_ + (value_end_ - value_start_) * state;

  // Implement snapping.
  if (tween_type_ == EASE_OUT_SNAP && fabs(value_current_ - value_end_) <= 0.06)
    value_current_ = value_end_;

  // Correct for any overshoot (while state may be capped at 1.0, let's not
  // take any rounding error chances.
  if ((value_end_ >= value_start_ && value_current_ > value_end_) ||
      (value_end_ < value_start_ && value_current_ < value_end_)) {
    value_current_ = value_end_;
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/nacl/nacl_ui_test.h"

// TODO(jvoung) see what includes we really need.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "chrome/common/chrome_paths.h"

namespace {
// NOTE: The base URL of each HTML file is specified in nacl_test.
const FilePath::CharType kPPAPIHwHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_hw_ppapi.html");
const FilePath::CharType kSrpcBasicHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_basic.html");
const FilePath::CharType kSrpcSockAddrHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_sockaddr.html");
const FilePath::CharType kSrpcShmHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_shm.html");
const FilePath::CharType kSrpcPluginHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_plugin.html");
const FilePath::CharType kSrpcNrdXferHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_nrd_xfer.html");
const FilePath::CharType kServerHtmlFileName[] =
  FILE_PATH_LITERAL("server_test.html");
const FilePath::CharType kNpapiHwHtmlFileName[] =
  FILE_PATH_LITERAL("npapi_hw.html");
}  // namespace

NaClUITest::NaClUITest() {
}

NaClUITest::~NaClUITest() {
}

TEST_F(NaClUITest, ServerTest) {
  FilePath test_file(kServerHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, PPAPIHelloWorld) {
  FilePath test_file(kPPAPIHwHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

// http://crbug.com/64973
TEST_F(NaClUITest, DISABLED_SrpcBasicTest) {
  FilePath test_file(kSrpcBasicHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, DISABLED_SrpcSockAddrTest) {
  FilePath test_file(kSrpcSockAddrHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, DISABLED_SrpcShmTest) {
  FilePath test_file(kSrpcShmHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, DISABLED_SrpcPluginTest) {
  FilePath test_file(kSrpcPluginHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, DISABLED_SrpcNrdXferTest) {
  FilePath test_file(kSrpcNrdXferHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, DISABLED_NpapiHwTest) {
  FilePath test_file(kNpapiHwHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

// TEST_F(NaClUITest, DISABLED_MultiarchTest) {
//   FilePath test_file(kSrpcHwHtmlFileName);
//   RunMultiarchTest(test_file, TestTimeouts::action_max_timeout_ms());
// }

<commit_msg>Disabling PPAPI hello world test in nacl_ui_tests. This mis-named test uses a now deprecated interface. It's making the nacl-chrome integration builder red.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/nacl/nacl_ui_test.h"

// TODO(jvoung) see what includes we really need.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "chrome/common/chrome_paths.h"

namespace {
// NOTE: The base URL of each HTML file is specified in nacl_test.
const FilePath::CharType kPPAPIHwHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_hw_ppapi.html");
const FilePath::CharType kSrpcBasicHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_basic.html");
const FilePath::CharType kSrpcSockAddrHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_sockaddr.html");
const FilePath::CharType kSrpcShmHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_shm.html");
const FilePath::CharType kSrpcPluginHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_plugin.html");
const FilePath::CharType kSrpcNrdXferHtmlFileName[] =
  FILE_PATH_LITERAL("srpc_nrd_xfer.html");
const FilePath::CharType kServerHtmlFileName[] =
  FILE_PATH_LITERAL("server_test.html");
const FilePath::CharType kNpapiHwHtmlFileName[] =
  FILE_PATH_LITERAL("npapi_hw.html");
}  // namespace

NaClUITest::NaClUITest() {
}

NaClUITest::~NaClUITest() {
}

TEST_F(NaClUITest, ServerTest) {
  FilePath test_file(kServerHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

// Uses obsolete srpc interface.
TEST_F(NaClUITest, DISABLED_PPAPIHelloWorld) {
  FilePath test_file(kPPAPIHwHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

// http://crbug.com/64973
TEST_F(NaClUITest, DISABLED_SrpcBasicTest) {
  FilePath test_file(kSrpcBasicHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, DISABLED_SrpcSockAddrTest) {
  FilePath test_file(kSrpcSockAddrHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, DISABLED_SrpcShmTest) {
  FilePath test_file(kSrpcShmHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, DISABLED_SrpcPluginTest) {
  FilePath test_file(kSrpcPluginHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, DISABLED_SrpcNrdXferTest) {
  FilePath test_file(kSrpcNrdXferHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

TEST_F(NaClUITest, DISABLED_NpapiHwTest) {
  FilePath test_file(kNpapiHwHtmlFileName);
  RunTest(test_file, TestTimeouts::action_max_timeout_ms());
}

// TEST_F(NaClUITest, DISABLED_MultiarchTest) {
//   FilePath test_file(kSrpcHwHtmlFileName);
//   RunMultiarchTest(test_file, TestTimeouts::action_max_timeout_ms());
// }

<|endoftext|>


<commit_before>//
// replace.cpp
//
// Perform search-and-replace using pcre++ on file names matching file_regex.
//
// Created by Daniel Kozitza
//

#include <csignal>
#include <cstdlib>
#include <dirent.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include "options.hpp"
#include "tools.hpp"

using namespace tools;

void help(string prog_name);
void more_info();

int main(int argc, char *argv[]) {
   string file_regex, match_regex, replacement;
   string dir_path     = ".";
   string prog_name    = string(argv[0]);
   string m[10];
   options opt;
   bool all            = false;
   bool recursive      = false;
   bool quiet          = false;
   bool test           = false;
   bool file_list      = false;
   bool show_help      = false;
   long total_replaced = 0;
   vector<string> args;
   vector<string> files;
   vector<string> new_files;
   Error e;

   signal(SIGINT, signals_callback_handler);

   opt.handle('a', all);
   opt.handle('r', recursive);
   opt.handle('q', quiet);
   opt.handle('f', file_list);
   opt.handle('h', show_help);
   opt.handle('t', test);

   for (size_t i = 1; i < argc; ++i)
      args.push_back(argv[i]);

   if (pmatches(m, prog_name, "^.*/([^/]+)$"))
      prog_name = m[1];

   e = opt.evaluate(args);
   if (e != NULL) {
      help(prog_name);
      cout << prog_name << "::" << e << "\n";
      return 0;
   }

   if (show_help) {
      help(prog_name);
      more_info();
      return 0;
   }

   if (!file_list && args.size() != 3 || file_list && args.size() < 3) {
      cout << prog_name << ": Invalid argument sequence.\n";
      help(prog_name);
      return 0;
   }

   // get arguments
   match_regex = args[args.size() - 2];
   replacement = args[args.size() - 1];
   if (!file_list) {
      file_regex = args[args.size() - 3];
   }
   else {
      for (size_t i = 0; i < args.size() - 2; ++i)
         files.push_back(args[i]);
   }

   // get dir_path by searching for the last / in file_regex
   // get the new file_regex by removing dir_path from the original file_regex
   if (!file_list && pmatches(m, file_regex, "^(.*/)")) {
      dir_path = m[1];
      file_regex = file_regex.substr(dir_path.size());
   }

   if (!quiet) {
      if (test || !file_list)
         cout << "\n";
      if (test)
         cout << prog_name << ": test mode: No files will be modified.\n";
      if (!file_list) {
         cout << prog_name << ": searching directory: " << dir_path;
         cout << " for file_regex: " << file_regex << endl;
      }
   }

   if (!file_list) {
      if (recursive) {
         if (!list_dir_r(dir_path, files)) {
            cerr << prog_name << ": Error! exiting.\n\n";
            return 1;
         }
      }
      else if (!list_dir(dir_path, files)) {
         cerr << prog_name << ": Error! exiting.\n\n";
         return 1;
      }

      // remove non-matching file names
      new_files.clear();
      for (size_t i = 0; i < files.size(); ++i) {
         string tmp = files[i];
         // remove directory path
         if (pmatches(m, tmp, "^.*/([^/]+)$"))
            tmp = m[1];
         if (pmatches(tmp, file_regex))
            new_files.push_back(files[i]);
      }
      files = new_files;

      // TODO: ignore binary files
      // loop through files removing directories and prefixing dir_path to file
      // names in files.
      new_files.clear();
      for (size_t i = 0; i < files.size(); ++i) {
         if (dir_path != ".") {
            if (!dir_exists(dir_path + files[i]))
               new_files.push_back(dir_path + files[i]);
         }
         else {
            if (!dir_exists(files[i]))
               new_files.push_back(files[i]);
         }
      }
      files = new_files;
   }

   // loop through files finding match_regex matches and replacing them with
   // replacement on each line of each file.
   bool wrote_col_names = false;
   for (size_t i = 0; i < files.size(); ++i) {
      vector<string> contents; // used to store replacement contents of files
      long replaced = 0; // number of lines replaced

      // open files[i] for reading
      ifstream ifh;
      ifh.open(files[i].c_str());
      if (!ifh.is_open()) {
         cerr << prog_name << ": Error! Could not open `" << files[i];
         cerr << "` for reading.\n\n";
         return 1;
      }

      // replace all of the matches on each line or replace the first match
      // in the file
      while (ifh.peek() != EOF) {
         string line;
         getline(ifh, line);

         if (all) {
            replaced += replace_all(line, match_regex, replacement);
         }
         else if (replaced == 0) {
            if (replace_first(line, match_regex, replacement))
               replaced++;
         }

         contents.push_back(line);
      }
      ifh.close();

      if (!quiet && !wrote_col_names) {
         cout << "\n                  file name";
         cout << "                          matches replaced\n";
         wrote_col_names = true;
      }
      if (!quiet) {
         cout << left << setw(60) << files[i];
         cout << " " << replaced << "\n";
      }

      total_replaced += replaced;

      // skip writing over files[i] if there are no changes or if in test mode
      if (replaced == 0 || test)
         continue;

      // open files[i] for writing
      ofstream ofh;
      ofh.open(files[i].c_str());
      if (!ofh.is_open()) {
         cerr << prog_name << ": Could not open `" << files[i];
         cerr << "` for writing.\n\n";
         continue;
      }
      for (size_t i = 0; i < contents.size(); ++i) {
         contents[i] += "\n";
         ofh.write(contents[i].c_str(), contents[i].size());
      }
      ofh.close();
   } // end of files loop

   if (!quiet) {
      if (wrote_col_names) {
         cout << "\n" << prog_name << ": Total matches replaced: ";
         cout << "                            " << total_replaced << "\n\n";
      }
      else {
         cout << prog_name << ": No files match!\n\n";
      }
   }
   return 0;
}

void help(string p_name) {
   cout << "\n";
   cout << fold(0, 80, p_name +
      " is a tool that performs search-and-replace using pcre++ on file "
      "names matching file_regex.");
   cout << "\n\nUsage:\n\n   " << p_name;
   cout << " [-option] file_regex match_regex replacement\n\n";
   cout << "Options:\n\n";
   cout << "   a - Replace all matches in the files that match file_regex.\n";
   cout << "   r - Search recursively for files that match file_regex.\n";
   cout << "   q - Quiet mode. Nothing will be printed to stdout.\n";
   cout << "   t - Test mode. No files will be modified.\n";
   cout << "   f - The file(s) will be input as a list.\n";
   cout << "   h - Print more information.\n\n";
}

void more_info() {
   cout << "Arguments:\n\n";
   cout << "   file";
   cout << fold(
         7,
         80,
         "_regex  - A Perl regular expression to match a file in the current "
         "working directory. A directory path can be prepended to the regular "
         "expression. the / character is not allowed in the regular expression "
         "part.");
   cout << "\n\n   ma";
   cout << fold(
         7,
         80,
         "tch_regex - A Perl regular expression to be used for search and "
         "replace.");

   cout << "\n\n   rep";
   cout << fold(
         7,
         80,
         "lacement - A string that will replace whatever matches match_regex. "
         "This string can contain the special variables #1, #2, #3, etc. These "
         "contain the backreferences.");
   cout << "\n\n";
}
<commit_msg>help text<commit_after>//
// replace.cpp
//
// Perform search-and-replace using pcre++ on file names matching file_regex.
//
// Created by Daniel Kozitza
//

#include <csignal>
#include <cstdlib>
#include <dirent.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include "options.hpp"
#include "tools.hpp"

using namespace tools;

void help(string prog_name);
void more_info();

int main(int argc, char *argv[]) {
   string file_regex, match_regex, replacement;
   string dir_path     = ".";
   string prog_name    = string(argv[0]);
   string m[10];
   options opt;
   bool all            = false;
   bool recursive      = false;
   bool quiet          = false;
   bool test           = false;
   bool file_list      = false;
   bool show_help      = false;
   long total_replaced = 0;
   vector<string> args;
   vector<string> files;
   vector<string> new_files;
   Error e;

   signal(SIGINT, signals_callback_handler);

   opt.handle('a', all);
   opt.handle('r', recursive);
   opt.handle('q', quiet);
   opt.handle('f', file_list);
   opt.handle('h', show_help);
   opt.handle('t', test);

   for (size_t i = 1; i < argc; ++i)
      args.push_back(argv[i]);

   if (pmatches(m, prog_name, "^.*/([^/]+)$"))
      prog_name = m[1];

   e = opt.evaluate(args);
   if (e != NULL) {
      help(prog_name);
      cout << prog_name << "::" << e << "\n";
      return 0;
   }

   if (show_help) {
      help(prog_name);
      more_info();
      return 0;
   }

   if (!file_list && args.size() != 3 || file_list && args.size() < 3) {
      cout << prog_name << ": Invalid argument sequence.\n";
      help(prog_name);
      return 0;
   }

   // get arguments
   match_regex = args[args.size() - 2];
   replacement = args[args.size() - 1];
   if (!file_list) {
      file_regex = args[args.size() - 3];
   }
   else {
      for (size_t i = 0; i < args.size() - 2; ++i)
         files.push_back(args[i]);
   }

   // get dir_path by searching for the last / in file_regex
   // get the new file_regex by removing dir_path from the original file_regex
   if (!file_list && pmatches(m, file_regex, "^(.*/)")) {
      dir_path = m[1];
      file_regex = file_regex.substr(dir_path.size());
   }

   if (!quiet) {
      if (test || !file_list)
         cout << "\n";
      if (test)
         cout << prog_name << ": test mode: No files will be modified.\n";
      if (!file_list) {
         cout << prog_name << ": searching directory: " << dir_path;
         cout << " for file_regex: " << file_regex << endl;
      }
   }

   if (!file_list) {
      if (recursive) {
         if (!list_dir_r(dir_path, files)) {
            cerr << prog_name << ": Error! exiting.\n\n";
            return 1;
         }
      }
      else if (!list_dir(dir_path, files)) {
         cerr << prog_name << ": Error! exiting.\n\n";
         return 1;
      }

      // remove non-matching file names
      new_files.clear();
      for (size_t i = 0; i < files.size(); ++i) {
         string tmp = files[i];
         // remove directory path
         if (pmatches(m, tmp, "^.*/([^/]+)$"))
            tmp = m[1];
         if (pmatches(tmp, file_regex))
            new_files.push_back(files[i]);
      }
      files = new_files;

      // TODO: ignore binary files
      // loop through files removing directories and prefixing dir_path to file
      // names in files.
      new_files.clear();
      for (size_t i = 0; i < files.size(); ++i) {
         if (dir_path != ".") {
            if (!dir_exists(dir_path + files[i]))
               new_files.push_back(dir_path + files[i]);
         }
         else {
            if (!dir_exists(files[i]))
               new_files.push_back(files[i]);
         }
      }
      files = new_files;
   }

   // loop through files finding match_regex matches and replacing them with
   // replacement on each line of each file.
   bool wrote_col_names = false;
   for (size_t i = 0; i < files.size(); ++i) {
      vector<string> contents; // used to store replacement contents of files
      long replaced = 0; // number of lines replaced

      // open files[i] for reading
      ifstream ifh;
      ifh.open(files[i].c_str());
      if (!ifh.is_open()) {
         cerr << prog_name << ": Error! Could not open `" << files[i];
         cerr << "` for reading.\n\n";
         return 1;
      }

      // replace all of the matches on each line or replace the first match
      // in the file
      while (ifh.peek() != EOF) {
         string line;
         getline(ifh, line);

         if (all) {
            replaced += replace_all(line, match_regex, replacement);
         }
         else if (replaced == 0) {
            if (replace_first(line, match_regex, replacement))
               replaced++;
         }

         contents.push_back(line);
      }
      ifh.close();

      if (!quiet && !wrote_col_names) {
         cout << "\n                  file name";
         cout << "                          matches replaced\n";
         wrote_col_names = true;
      }
      if (!quiet) {
         cout << left << setw(60) << files[i];
         cout << " " << replaced << "\n";
      }

      total_replaced += replaced;

      // skip writing over files[i] if there are no changes or if in test mode
      if (replaced == 0 || test)
         continue;

      // open files[i] for writing
      ofstream ofh;
      ofh.open(files[i].c_str());
      if (!ofh.is_open()) {
         cerr << prog_name << ": Could not open `" << files[i];
         cerr << "` for writing.\n\n";
         continue;
      }
      for (size_t i = 0; i < contents.size(); ++i) {
         contents[i] += "\n";
         ofh.write(contents[i].c_str(), contents[i].size());
      }
      ofh.close();
   } // end of files loop

   if (!quiet) {
      if (wrote_col_names) {
         cout << "\n" << prog_name << ": Total matches replaced: ";
         cout << "                            " << total_replaced << "\n\n";
      }
      else {
         cout << prog_name << ": No files match!\n\n";
      }
   }
   return 0;
}

void help(string p_name) {
   cout << "\n";
   cout << fold(0, 80, p_name +
      " is a tool that performs search-and-replace using std::regex on file "
      "names matching file_regex.");
   cout << "\n\nUsage:\n\n   " << p_name;
   cout << " [-option] file_regex match_regex replacement\n\n";
   cout << "Options:\n\n";
   cout << "   a - Replace all matches in the files that match file_regex.\n";
   cout << "   r - Search recursively for files that match file_regex.\n";
   cout << "   q - Quiet mode. Nothing will be printed to stdout.\n";
   cout << "   t - Test mode. No files will be modified.\n";
   cout << "   f - The file(s) will be input as a list.\n";
   cout << "   h - Print more information.\n\n";
}

void more_info() {
   cout << "Arguments:\n\n";
   cout << "   file";
   cout << fold(
         7,
         80,
         "_regex  - A Perl regular expression to match a file in the current "
         "working directory. A directory path can be prepended to the regular "
         "expression. the / character is not allowed in the regular expression "
         "part.");
   cout << "\n\n   ma";
   cout << fold(
         7,
         80,
         "tch_regex - A Perl regular expression to be used for search and "
         "replace.");

   cout << "\n\n   rep";
   cout << fold(
         7,
         80,
         "lacement - A string that will replace whatever matches match_regex. "
         "This string can contain the special variables #1, #2, #3, etc. These "
         "contain the backreferences.");
   cout << "\n\n";
}
<|endoftext|>


<commit_before>// @(#)root/reflex:$Id$
// Author: Stefan Roiser 2004

// Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#ifndef REFLEX_BUILD
#define REFLEX_BUILD
#endif

#include "Reflex/Builder/ClassBuilder.h"

#include "Reflex/Type.h"
#include "Reflex/Member.h"

#include "Class.h"
#include "ClassTemplateInstance.h"
#include "Reflex/Tools.h"
#include "Typedef.h"
#include "Enum.h"
#include "DataMember.h"
#include "FunctionMemberTemplateInstance.h"

//______________________________________________________________________________
//______________________________________________________________________________
//
//
//  ClassBuilderImpl
//
//

//______________________________________________________________________________
Reflex::ClassBuilderImpl::ClassBuilderImpl(const char* nam, const std::type_info& ti, size_t size, unsigned int modifiers, TYPE typ)
: fClass(0)
, fLastMember()
, fNewClass(true)
, fCallbackEnabled(true)
{
   // -- Construct a class information (internal).
   std::string nam2(nam);
   Type c = Type::ByName(nam2);
   if (c) {
      // We found a typedef to a class with the same name
      if (c.IsTypedef()) {
         nam2 += " @HIDDEN@";
         c = Dummy::Type();
      }
      // Class already exists. Check if it was a class.
      else if (!c.IsClass()) {
         throw RuntimeError("Attempt to replace a non-class type with a class");
      }
   }
   if (!c) {
      if (Tools::IsTemplated(nam)) {
         fClass = new ClassTemplateInstance(nam2.c_str(), size, ti, modifiers);
      }
      else {
         fClass = new Class(nam2.c_str(), size, ti, modifiers, typ);
      }
   } else {
      fNewClass = false;
      fClass = const_cast<Class*>(dynamic_cast<const Class*>( c.ToTypeBase() ));
      if (!fClass) {
         throw RuntimeError("Attempt to replace a non-class type with a class");
      }
      if (fClass->SizeOf() == 0) {
         fClass->SetSize(size);
      } else if (fClass->SizeOf() != size) {
         throw RuntimeError(std::string("Attempt to change the size of the class ")+std::string(nam));
      }
      if (!strcmp(fClass->TypeInfo().name(), typeid(Reflex::UnknownType).name())) {
         fClass->SetTypeInfo(ti);
      } else if (strcmp(fClass->TypeInfo().name(), ti.name())) {
         throw RuntimeError(std::string("Attempt to change the type_info of the class ") + std::string(nam));
      }
      if (modifiers != 0) {
         if ( 0==fClass->Modifiers() ) {
            fClass->SetModifiers(modifiers);
         } else if ( fClass->Modifiers() != modifiers ) {
            throw RuntimeError(std::string("Attempt to change the modifiers of the class ")+std::string(nam));
         }
      }
   }
}

//______________________________________________________________________________
Reflex::ClassBuilderImpl::~ClassBuilderImpl()
{
   // -- ClassBuilderImpl destructor. Used for call back functions (e.g. Cintex).
   if (fCallbackEnabled) {
      FireClassCallback(fClass->ThisType());
   }
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddBase(const Type& bas, OffsetFunction offsFP, unsigned int modifiers)
{
   // -- Add base class information (internal).
   if (!fNewClass) {
      for(Reflex::Base_Iterator iter = fClass->Base_Begin(); iter != fClass->Base_End() ; ++iter ) {
         if ( iter->Name() == bas.Name() ) {
            // Already entered, ignore.
            return;
//            if ( offsFP != iter->Offset() ) {
//               throw RuntimeError(std::string("Attempt to change the offset of a base class (")+bas.Name()+" of the class \"")+fClass.Name());
//            }
         }
      }
   }
   fClass->AddBase(bas, offsFP, modifiers);
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddDataMember(const char* nam, const Type& typ, size_t offs, unsigned int modifiers)
{
   // -- Add data member info (internal).
   if (!fNewClass) {
      for(Reflex::Member_Iterator iter = fClass->DataMember_Begin(); iter != fClass->DataMember_End() ; ++iter ) {
         if ( iter->Name() == nam ) {
            if (offs!=0 && iter->Offset() != offs) {
               throw RuntimeError(std::string("Attempt to change the offset of a data member (")+nam+") of the class "+fClass->Name());
            }
            if (typ && typ != iter->TypeOf()) {
               throw RuntimeError(std::string("Attempt to change the type of a data member (")+nam+") of the class "+fClass->Name());
            }
            return;
         }
      }
   }
   fLastMember = Member(new DataMember(nam, typ, offs, modifiers));
   fClass->AddDataMember(fLastMember);
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddFunctionMember(const char* nam, const Type& typ, StubFunction stubFP, void* stubCtx, const char* params, unsigned int modifiers)
{
   // -- Add function member info (internal).
   if (!fNewClass) {
      for(Reflex::Member_Iterator iter = fClass->DataMember_Begin(); iter != fClass->DataMember_End() ; ++iter ) {
         if ( iter->Name() == nam && typ && typ == iter->TypeOf()) {
            return;
         }
      }
   }
   if (Tools::IsTemplated(nam)) {
      fLastMember = Member(new FunctionMemberTemplateInstance(nam, typ, stubFP, stubCtx, params, modifiers, *(dynamic_cast<ScopeBase*>(fClass))));
   }
   else {
      fLastMember = Member(new FunctionMember(nam, typ, stubFP, stubCtx, params, modifiers));
   }
   fClass->AddFunctionMember(fLastMember);
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddTypedef(const Type& typ, const char* def)
{
   // -- Add typedef info (internal).
   Type ret = Type::ByName(def);
   // Check for typedef AA AA;
   if (ret == typ && ! typ.IsTypedef()) {
      if (typ) {
         typ.ToTypeBase()->HideName();
      }
      else {
         ((TypeName*)typ.Id())->HideName();
      }
   }
   // We found the typedef type
   else if (ret) {
      fClass->AddSubType(ret);
   }
   // Create a new typedef
   else {
      new Typedef(def , typ);
   }
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddEnum(const char* nam, const char* values, const std::type_info* ti, unsigned int modifiers)
{
   // -- Add enum info (internal).

   // This does not work because the EnumTypeBuilder does a definition of the enum
   // not only a declaration. (It is called in the dictionary header already)
   //   EnumTypeBuilder(nam, values, *ti, modifiers);

   Enum* e = new Enum(nam, *ti, modifiers);

   std::vector<std::string> valVec = std::vector<std::string>();
   Tools::StringSplit(valVec, values, ";");

   for (
      std::vector<std::string>::const_iterator it = valVec.begin();
      it != valVec.end();
      ++it
   ) {
      std::string name;
      std::string value;
      Tools::StringSplitPair(name, value, *it, "=");
      unsigned long int valInt = atol(value.c_str());
      e->AddDataMember(Member(new DataMember(name.c_str(), Type::ByName("int"), valInt, 0)));
   }
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddProperty(const char* key, const char* value)
{
   // -- Add property info (internal).
   AddProperty(key, Any(value));
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddProperty(const char* key, Any value)
{
   // -- Add property info (internal).
   if (fLastMember) {
      fLastMember.Properties().AddProperty(key, value);
   }
   else {
      fClass->Properties().AddProperty(key, value);
   }
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::EnableCallback(bool enable /*= true*/)
{
   // Enable (or disable) the calling of the callback when this object is
   // destructed.

   fCallbackEnabled = enable;
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::SetSizeOf(size_t size)
{
   // -- Set the size of the class (internal).
   fClass->SetSize(size);
}

//______________________________________________________________________________
Reflex::Type Reflex::ClassBuilderImpl::ToType()
{
   // -- Return the type currently being built.
   return fClass->ThisType();
}

//______________________________________________________________________________
//______________________________________________________________________________
//
//
//  ClassBuilder
//
//

//______________________________________________________________________________
Reflex::ClassBuilder::ClassBuilder(const char* nam, const std::type_info& ti, size_t size, unsigned int modifiers, TYPE typ)
: fClassBuilderImpl(nam, ti, size, modifiers, typ)
{
   // -- Constructor
}

//______________________________________________________________________________
Reflex::ClassBuilder::~ClassBuilder()
{
   // -- Destructor
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddBase(const Type& bas, OffsetFunction offsFP, unsigned int modifiers)
{
   // -- Add base class information to this class.
   fClassBuilderImpl.AddBase(bas, offsFP, modifiers);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddDataMember(const Type&  typ, const char*  nam, size_t offs, unsigned int modifiers)
{
   // -- Add data member info to this class.
   fClassBuilderImpl.AddDataMember(nam, typ, offs, modifiers);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddFunctionMember(const Type& typ, const char* nam, StubFunction stubFP, void* stubCtx, const char* params, unsigned int modifiers)
{
   // -- Add function member info to this class.
   fClassBuilderImpl.AddFunctionMember(nam, typ, stubFP, stubCtx, params, modifiers);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddTypedef(const char* typ, const char* def)
{
   // -- Add typedef info to this class.
   fClassBuilderImpl.AddTypedef(TypeBuilder(typ), def);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddTypedef(const Type& typ, const char* def)
{
   // -- Add typedef info to this class.
   fClassBuilderImpl.AddTypedef(typ, def);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddEnum(const char* nam, const char* values, const std::type_info* ti, unsigned int modifiers)
{
   // -- Add enum info to this class.
   fClassBuilderImpl.AddEnum(nam, values, ti, modifiers);
   return *this;
}

/*
//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::addUnion(const char* nam, const char* values, unsigned int modifiers)
{
  fClassBuilderImpl.addUnion(nam, values, modifiers);
  return *this;
}
*/

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::EnableCallback(bool enable /*=true*/)
{
   // Enable (or disable) the calling of the callback when this object is
   // destructed.

   fClassBuilderImpl.EnableCallback(enable);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::SetSizeOf(size_t size)
{
// Set the class's size.
   fClassBuilderImpl.SetSizeOf(size);
   return *this;
}

//______________________________________________________________________________
Reflex::Type Reflex::ClassBuilder::ToType()
{
   // -- Return the type currently being built.
   return fClassBuilderImpl.ToType();
}

<commit_msg>Do not complain if a redefinition that 'change' the size is a forward declaration<commit_after>// @(#)root/reflex:$Id$
// Author: Stefan Roiser 2004

// Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#ifndef REFLEX_BUILD
#define REFLEX_BUILD
#endif

#include "Reflex/Builder/ClassBuilder.h"

#include "Reflex/Type.h"
#include "Reflex/Member.h"

#include "Class.h"
#include "ClassTemplateInstance.h"
#include "Reflex/Tools.h"
#include "Typedef.h"
#include "Enum.h"
#include "DataMember.h"
#include "FunctionMemberTemplateInstance.h"

//______________________________________________________________________________
//______________________________________________________________________________
//
//
//  ClassBuilderImpl
//
//

//______________________________________________________________________________
Reflex::ClassBuilderImpl::ClassBuilderImpl(const char* nam, const std::type_info& ti, size_t size, unsigned int modifiers, TYPE typ)
: fClass(0)
, fLastMember()
, fNewClass(true)
, fCallbackEnabled(true)
{
   // -- Construct a class information (internal).
   std::string nam2(nam);
   Type c = Type::ByName(nam2);
   if (c) {
      // We found a typedef to a class with the same name
      if (c.IsTypedef()) {
         nam2 += " @HIDDEN@";
         c = Dummy::Type();
      }
      // Class already exists. Check if it was a class.
      else if (!c.IsClass()) {
         throw RuntimeError("Attempt to replace a non-class type with a class");
      }
   }
   if (!c) {
      if (Tools::IsTemplated(nam)) {
         fClass = new ClassTemplateInstance(nam2.c_str(), size, ti, modifiers);
      }
      else {
         fClass = new Class(nam2.c_str(), size, ti, modifiers, typ);
      }
   } else {
      fNewClass = false;
      fClass = const_cast<Class*>(dynamic_cast<const Class*>( c.ToTypeBase() ));
      if (!fClass) {
         throw RuntimeError("Attempt to replace a non-class type with a class");
      }
      if (fClass->SizeOf() == 0) {
         fClass->SetSize(size);
      } else if (size !=0 && fClass->SizeOf() != size) {
         throw RuntimeError(std::string("Attempt to change the size of the class ")+std::string(nam));
      }
      if (!strcmp(fClass->TypeInfo().name(), typeid(Reflex::UnknownType).name())) {
         fClass->SetTypeInfo(ti);
      } else if (strcmp(fClass->TypeInfo().name(), ti.name())) {
         throw RuntimeError(std::string("Attempt to change the type_info of the class ") + std::string(nam));
      }
      if (modifiers != 0) {
         if ( 0==fClass->Modifiers() ) {
            fClass->SetModifiers(modifiers);
         } else if ( fClass->Modifiers() != modifiers ) {
            throw RuntimeError(std::string("Attempt to change the modifiers of the class ")+std::string(nam));
         }
      }
   }
}

//______________________________________________________________________________
Reflex::ClassBuilderImpl::~ClassBuilderImpl()
{
   // -- ClassBuilderImpl destructor. Used for call back functions (e.g. Cintex).
   if (fCallbackEnabled) {
      FireClassCallback(fClass->ThisType());
   }
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddBase(const Type& bas, OffsetFunction offsFP, unsigned int modifiers)
{
   // -- Add base class information (internal).
   if (!fNewClass) {
      for(Reflex::Base_Iterator iter = fClass->Base_Begin(); iter != fClass->Base_End() ; ++iter ) {
         if ( iter->Name() == bas.Name() ) {
            // Already entered, ignore.
            return;
//            if ( offsFP != iter->Offset() ) {
//               throw RuntimeError(std::string("Attempt to change the offset of a base class (")+bas.Name()+" of the class \"")+fClass.Name());
//            }
         }
      }
   }
   fClass->AddBase(bas, offsFP, modifiers);
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddDataMember(const char* nam, const Type& typ, size_t offs, unsigned int modifiers)
{
   // -- Add data member info (internal).
   if (!fNewClass) {
      for(Reflex::Member_Iterator iter = fClass->DataMember_Begin(); iter != fClass->DataMember_End() ; ++iter ) {
         if ( iter->Name() == nam ) {
            if (offs!=0 && iter->Offset() != offs) {
               throw RuntimeError(std::string("Attempt to change the offset of a data member (")+nam+") of the class "+fClass->Name());
            }
            if (typ && typ != iter->TypeOf()) {
               throw RuntimeError(std::string("Attempt to change the type of a data member (")+nam+") of the class "+fClass->Name());
            }
            return;
         }
      }
   }
   fLastMember = Member(new DataMember(nam, typ, offs, modifiers));
   fClass->AddDataMember(fLastMember);
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddFunctionMember(const char* nam, const Type& typ, StubFunction stubFP, void* stubCtx, const char* params, unsigned int modifiers)
{
   // -- Add function member info (internal).
   if (!fNewClass) {
      for(Reflex::Member_Iterator iter = fClass->DataMember_Begin(); iter != fClass->DataMember_End() ; ++iter ) {
         if ( iter->Name() == nam && typ && typ == iter->TypeOf()) {
            return;
         }
      }
   }
   if (Tools::IsTemplated(nam)) {
      fLastMember = Member(new FunctionMemberTemplateInstance(nam, typ, stubFP, stubCtx, params, modifiers, *(dynamic_cast<ScopeBase*>(fClass))));
   }
   else {
      fLastMember = Member(new FunctionMember(nam, typ, stubFP, stubCtx, params, modifiers));
   }
   fClass->AddFunctionMember(fLastMember);
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddTypedef(const Type& typ, const char* def)
{
   // -- Add typedef info (internal).
   Type ret = Type::ByName(def);
   // Check for typedef AA AA;
   if (ret == typ && ! typ.IsTypedef()) {
      if (typ) {
         typ.ToTypeBase()->HideName();
      }
      else {
         ((TypeName*)typ.Id())->HideName();
      }
   }
   // We found the typedef type
   else if (ret) {
      fClass->AddSubType(ret);
   }
   // Create a new typedef
   else {
      new Typedef(def , typ);
   }
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddEnum(const char* nam, const char* values, const std::type_info* ti, unsigned int modifiers)
{
   // -- Add enum info (internal).

   // This does not work because the EnumTypeBuilder does a definition of the enum
   // not only a declaration. (It is called in the dictionary header already)
   //   EnumTypeBuilder(nam, values, *ti, modifiers);

   Enum* e = new Enum(nam, *ti, modifiers);

   std::vector<std::string> valVec = std::vector<std::string>();
   Tools::StringSplit(valVec, values, ";");

   for (
      std::vector<std::string>::const_iterator it = valVec.begin();
      it != valVec.end();
      ++it
   ) {
      std::string name;
      std::string value;
      Tools::StringSplitPair(name, value, *it, "=");
      unsigned long int valInt = atol(value.c_str());
      e->AddDataMember(Member(new DataMember(name.c_str(), Type::ByName("int"), valInt, 0)));
   }
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddProperty(const char* key, const char* value)
{
   // -- Add property info (internal).
   AddProperty(key, Any(value));
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::AddProperty(const char* key, Any value)
{
   // -- Add property info (internal).
   if (fLastMember) {
      fLastMember.Properties().AddProperty(key, value);
   }
   else {
      fClass->Properties().AddProperty(key, value);
   }
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::EnableCallback(bool enable /*= true*/)
{
   // Enable (or disable) the calling of the callback when this object is
   // destructed.

   fCallbackEnabled = enable;
}

//______________________________________________________________________________
void Reflex::ClassBuilderImpl::SetSizeOf(size_t size)
{
   // -- Set the size of the class (internal).
   fClass->SetSize(size);
}

//______________________________________________________________________________
Reflex::Type Reflex::ClassBuilderImpl::ToType()
{
   // -- Return the type currently being built.
   return fClass->ThisType();
}

//______________________________________________________________________________
//______________________________________________________________________________
//
//
//  ClassBuilder
//
//

//______________________________________________________________________________
Reflex::ClassBuilder::ClassBuilder(const char* nam, const std::type_info& ti, size_t size, unsigned int modifiers, TYPE typ)
: fClassBuilderImpl(nam, ti, size, modifiers, typ)
{
   // -- Constructor
}

//______________________________________________________________________________
Reflex::ClassBuilder::~ClassBuilder()
{
   // -- Destructor
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddBase(const Type& bas, OffsetFunction offsFP, unsigned int modifiers)
{
   // -- Add base class information to this class.
   fClassBuilderImpl.AddBase(bas, offsFP, modifiers);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddDataMember(const Type&  typ, const char*  nam, size_t offs, unsigned int modifiers)
{
   // -- Add data member info to this class.
   fClassBuilderImpl.AddDataMember(nam, typ, offs, modifiers);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddFunctionMember(const Type& typ, const char* nam, StubFunction stubFP, void* stubCtx, const char* params, unsigned int modifiers)
{
   // -- Add function member info to this class.
   fClassBuilderImpl.AddFunctionMember(nam, typ, stubFP, stubCtx, params, modifiers);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddTypedef(const char* typ, const char* def)
{
   // -- Add typedef info to this class.
   fClassBuilderImpl.AddTypedef(TypeBuilder(typ), def);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddTypedef(const Type& typ, const char* def)
{
   // -- Add typedef info to this class.
   fClassBuilderImpl.AddTypedef(typ, def);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::AddEnum(const char* nam, const char* values, const std::type_info* ti, unsigned int modifiers)
{
   // -- Add enum info to this class.
   fClassBuilderImpl.AddEnum(nam, values, ti, modifiers);
   return *this;
}

/*
//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::addUnion(const char* nam, const char* values, unsigned int modifiers)
{
  fClassBuilderImpl.addUnion(nam, values, modifiers);
  return *this;
}
*/

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::EnableCallback(bool enable /*=true*/)
{
   // Enable (or disable) the calling of the callback when this object is
   // destructed.

   fClassBuilderImpl.EnableCallback(enable);
   return *this;
}

//______________________________________________________________________________
Reflex::ClassBuilder& Reflex::ClassBuilder::SetSizeOf(size_t size)
{
// Set the class's size.
   fClassBuilderImpl.SetSizeOf(size);
   return *this;
}

//______________________________________________________________________________
Reflex::Type Reflex::ClassBuilder::ToType()
{
   // -- Return the type currently being built.
   return fClassBuilderImpl.ToType();
}

<|endoftext|>


<commit_before>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;
    MTL M;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);

    init_time_at(time,"# read target, SS, SF files",t);
    MTL Targ=read_MTLfile(F.Targfile,F,0,0);
    MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
    MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
    print_time(time,"# ... took :");
    //combine the three input files
    M=Targ;
    printf(" Target size %d \n",M.size());
    M.insert(M.end(),SStars.begin(),SStars.end());
    printf(" Standard Star size %d \n",M.size());
    M.insert(M.end(),SkyF.begin(),SkyF.end());
    printf(" Sky Fiber size %d \n",M.size());

    F.Ngal = M.size();
    assign_priority_class(M);
    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        if(!M[i].SS&&!M[i].SF){
            count_class[M[i].priority_class]+=1;
        }
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }
    print_time(time,"# ... took :");

    // fiber positioners
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F);
    pp.compute_fibsofsp(F);

    //P is original list of plates
	Plates P = read_plate_centers(F);
	F.Nplate=P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct target> T(M,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect galaxies at ",t);

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(M,T,P,pp,F);
    print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect available tile-fibers at",t);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(M,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
	Assignment A(M,F);
    // Make a plan ----------------------------------------------------
	print_time(t,"# Start assignment at : ");
    simple_assign(M,P,pp,F,A);

    //check to see if there are tiles with no galaxies
    //need to keep mapping of old tile list to new tile list
    //and inverse map
    A.inv_order=initList(F.Nplate,-1);
    int inv_count=0;
    for (int j=0;j<F.Nplate ;++j){

        bool not_done=true;
        for(int k=0;k<F.Nfiber && not_done;++k){
            if(A.TF[j][k]!=-1){
                A.suborder.push_back(j);//suborder[jused] is jused-th used plate
                not_done=false;
                A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
                inv_count++;
            }
        }
    }
    F.NUsedplate=A.suborder.size();
    printf(" Plates actually used %d \n",F.NUsedplate);
    //for(int i=0;i<F.NUsedplate;i++)printf(" jused  %d  j  %d\n",i,A.suborder[i]);

    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs

    // Smooth out distribution of free fibers, and increase the number of assignments

    for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
    for (int i=0; i<3; i++) {
        improve(M,P,pp,F,A,0);
        redistribute_tf(M,P,pp,F,A,0);
    }
    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
    //try assigning SF and SS before real time assignment
    for (int jused=0;jused<F.NUsedplate;++jused){

        int j=A.suborder[jused];
        assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
        assign_unused(j,M,P,pp,F,A);
    }

	// Results -------------------------------------------------------*/
    std::vector <int> total_used_by_class(M.priority_list.size(),0);
    int total_used_SS=0;
    int total_used_SF=0;
    for (int jused=0;jused<F.NUsedplate;++jused){
        std::vector <int> used_by_class(M.priority_list.size(),0);
        int used_SS=0;
        int used_SF=0;
        int j=A.suborder[jused];
        for(int k=0;k<F.Nfiber;++k){
            int g=A.TF[j][k];
            if(g!=-1){
                if(M[g].SS){
                    total_used_SS++;
                    used_SS++;
                    }
                    else if(M[g].SF){
                        used_SF++;
                        total_used_SF++;
                    }
                    else{
                        used_by_class[M[g].priority_class]++;
                        total_used_by_class[M[g].priority_class]++;
                    }
            }
        }
       /* printf(" plate jused %5d j %5d  SS   %4d    SF   %4d",jused,j,used_SS,used_SF);
        for (int pr=0;pr<M.priority_list.size();++pr){
            printf(" class %2d   %5d",pr,used_by_class[pr]);
        }
        printf("\n");
        */
    }
    printf(" Totals SS   %4d    SF   %4d",total_used_SS,total_used_SF);
    for (int pr=0;pr<M.priority_list.size();++pr){
        printf(" class %2d   %5d",pr,total_used_by_class[pr]);
    }
    printf("\n");

    if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
        }

    if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        fa_write(j,F.outDir,M,P,pp,F,A); // Write output
    }
    /*
	display_results("doc/figs/",G,M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
     */

    print_time(t,"# Finished !... in");

    return(0);
}
<commit_msg>print more times<commit_after>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;
    MTL M;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);

    init_time_at(time,"# read target, SS, SF files",t);
    MTL Targ=read_MTLfile(F.Targfile,F,0,0);
    MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
    MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
    print_time(time,"# ... took :");
    //combine the three input files
    M=Targ;
    printf(" Target size %d \n",M.size());
    M.insert(M.end(),SStars.begin(),SStars.end());
    printf(" Standard Star size %d \n",M.size());
    M.insert(M.end(),SkyF.begin(),SkyF.end());
    printf(" Sky Fiber size %d \n",M.size());

    F.Ngal = M.size();
    assign_priority_class(M);
    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        if(!M[i].SS&&!M[i].SF){
            count_class[M[i].priority_class]+=1;
        }
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }
    print_time(time,"# ... took :");

    // fiber positioners
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F);
    pp.compute_fibsofsp(F);

    //P is original list of plates
	Plates P = read_plate_centers(F);
	F.Nplate=P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct target> T(M,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect galaxies at ",t);

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(M,T,P,pp,F);
    print_time(time,"# ... took :");//T.stats();
    init_time_at(time,"# collect available tile-fibers at",t);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(M,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
	Assignment A(M,F);
    // Make a plan ----------------------------------------------------
	print_time(t,"# Start assignment at : ");
    simple_assign(M,P,pp,F,A);

    //check to see if there are tiles with no galaxies
    //need to keep mapping of old tile list to new tile list
    //and inverse map
    A.inv_order=initList(F.Nplate,-1);
    int inv_count=0;
    for (int j=0;j<F.Nplate ;++j){

        bool not_done=true;
        for(int k=0;k<F.Nfiber && not_done;++k){
            if(A.TF[j][k]!=-1){
                A.suborder.push_back(j);//suborder[jused] is jused-th used plate
                not_done=false;
                A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
                inv_count++;
            }
        }
    }
    F.NUsedplate=A.suborder.size();
    printf(" Plates actually used %d \n",F.NUsedplate);
    //for(int i=0;i<F.NUsedplate;i++)printf(" jused  %d  j  %d\n",i,A.suborder[i]);

    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs

    // Smooth out distribution of free fibers, and increase the number of assignments

    for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
    for (int i=0; i<3; i++) {
        improve(M,P,pp,F,A,0);
        redistribute_tf(M,P,pp,F,A,0);
    }
    init_time_at(time,"# assign SS and SF ",t);
    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
    //try assigning SF and SS before real time assignment
    for (int jused=0;jused<F.NUsedplate;++jused){

        int j=A.suborder[jused];
        assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
        assign_unused(j,M,P,pp,F,A);
    }

	// Results -------------------------------------------------------*/
    std::vector <int> total_used_by_class(M.priority_list.size(),0);
    int total_used_SS=0;
    int total_used_SF=0;
    for (int jused=0;jused<F.NUsedplate;++jused){
        std::vector <int> used_by_class(M.priority_list.size(),0);
        int used_SS=0;
        int used_SF=0;
        int j=A.suborder[jused];
        for(int k=0;k<F.Nfiber;++k){
            int g=A.TF[j][k];
            if(g!=-1){
                if(M[g].SS){
                    total_used_SS++;
                    used_SS++;
                    }
                    else if(M[g].SF){
                        used_SF++;
                        total_used_SF++;
                    }
                    else{
                        used_by_class[M[g].priority_class]++;
                        total_used_by_class[M[g].priority_class]++;
                    }
            }
        }
       /* printf(" plate jused %5d j %5d  SS   %4d    SF   %4d",jused,j,used_SS,used_SF);
        for (int pr=0;pr<M.priority_list.size();++pr){
            printf(" class %2d   %5d",pr,used_by_class[pr]);
        }
        printf("\n");
        */
    }
    init_time_at(time,"# count SS and SF ",t);
    printf(" Totals SS   %4d    SF   %4d",total_used_SS,total_used_SF);
    std::cout.flush();
    for (int pr=0;pr<M.priority_list.size();++pr){
        printf(" class %2d   %5d",pr,total_used_by_class[pr]);
        std::cout>flush();
    }
    printf("\n");
    init_time_at(time,"# print txt files ",t);
    if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        write_FAtile_ascii(j,F.outDir,M,P,pp,F,A);
        }
    init_time_at(time,"# print fits files ",t);
    if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
        int j=A.suborder[jused];
        fa_write(j,F.outDir,M,P,pp,F,A); // Write output
    }
    /*
	display_results("doc/figs/",G,M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
     */

    print_time(t,"# Finished !... in");

    return(0);
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////
//
//                             Pixie
//
// Copyright  1999 - 2003, Okan Arikan
//
// Contact: okan@cs.berkeley.edu
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation; either
// version 2 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
// General Public License for more details.
//
// You should have received a copy of the GNU 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
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
//  File				:	show.cpp
//  Classes				:	-
//  Description			:	The hardware visualizer
//
////////////////////////////////////////////////////////////////////////
#include "show.h"
#include "cache.h"
#include "renderer.h"
#include "error.h"
#include "fileResource.h"
#include "photonMap.h"
#include "opengl/opengl.h"

// The static members of the CView class that visualizable classes derive from
void					*CView::handle			=	NULL;
TGlTrianglesFunction	CView::drawTriangles	=	NULL;
TGlPointsFunction		CView::drawPoints		=	NULL;

///////////////////////////////////////////////////////////////////////
// Class				:	CShow
// Method				:	CShow
// Description			:	Ctor
// Return Value			:	-
// Comments				:
// Date last edited		:	9/21/2006
CShow::CShow(COptions *o,CXform *x,SOCKET s) : CShadingContext(o,x,s,HIDER_NODISPLAY) {
	const char	*pixieHome	=	osEnvironment("PIXIEHOME");
	char		tmp[OS_MAX_PATH_LENGTH];

	// First, try to load the dynamic library
//TODO: load from displays directory
#ifdef WIN32
	if (pixieHome != NULL)	sprintf(tmp,"%s\\opengl.dll",pixieHome);
	else					strcpy(tmp,"opengl.dll");
#else
	if (pixieHome != NULL)	sprintf(tmp,"%s/opengl.so",pixieHome);
	else					strcpy(tmp,"opengl.so");
#endif

	CView::handle	=	osLoadModule(tmp);

	if (CView::handle != NULL) {

		// Is this the library we were expecting ?
		TGlVisualizeFunction	visualize	=	(TGlVisualizeFunction) osResolve(CView::handle,"pglVisualize");
		CView					*view		=	NULL;

		if (visualize != NULL) {

			// Try to load the file
			const char	*fileName	=	hider + 5;
			FILE		*in			=	fopen(fileName,"rb");

			CView::drawTriangles	=	(TGlTrianglesFunction)	osResolve(CView::handle,"pglTriangles");
			CView::drawPoints		=	(TGlPointsFunction)		osResolve(CView::handle,"pglPoints");

			assert(CView::drawTriangles != NULL);
			assert(CView::drawPoints != NULL);

			if (in != NULL)	{
				unsigned int	magic	=	0;
				int				version[3],i;
				char			*t;

				fread(&magic,1,sizeof(int),in);

				if (magic == magicNumber) {
					fread(version,3,sizeof(int),in);

					if (!((version[0] == VERSION_RELEASE) || (version[1] == VERSION_BETA))) {
						error(CODE_VERSION,"File %s is from an incompatible version\n",fileName);
					} else {
						fread(&i,1,sizeof(int),in);
						t	=	(char *) alloca((i+1)*sizeof(char));
						fread(t,i+1,sizeof(char),in);

						info(CODE_LOG,"File:    %s\n",fileName);
						info(CODE_LOG,"Version: %d.%d.%d\n",version[0],version[1],version[2]);
						info(CODE_LOG,"Type:    %s\n",t);
						fclose(in);

						if (strcmp(t,filePhotonMap) == 0) {
							view	=	getPhotonMap(fileName);
						} else if (strcmp(t,fileIrradianceCache) == 0) {
							view	=	getCache(fileName,"R");
						} else if (strcmp(t,fileGatherCache) == 0) {
							view	=	getCache(fileName,"R");
						} else if (strcmp(t,filePointCloud) == 0) {

						} else if (strcmp(t,fileBrickMap) == 0) {

						}

						// Create / display the window
						if (view != NULL)	visualize(view);
					}
				} else {
					error(CODE_BADFILE,"File %s doesn't seem to be a Pixie file\n",fileName);
				}
			}
		}
	} else {
		error(CODE_SYSTEM,"Opengl wrapper not found...");
	}
}

///////////////////////////////////////////////////////////////////////
// Class				:	CShow
// Method				:	~CShow
// Description			:	Dtor
// Return Value			:	-
// Comments				:
// Date last edited		:	9/21/2006
CShow::~CShow() {
}
<commit_msg>removed odd char<commit_after>//////////////////////////////////////////////////////////////////////
//
//                             Pixie
//
// Copyright  1999 - 2003, Okan Arikan
//
// Contact: okan@cs.berkeley.edu
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation; either
// version 2 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
// General Public License for more details.
//
// You should have received a copy of the GNU 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
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
//  File				:	show.cpp
//  Classes				:	-
//  Description			:	The hardware visualizer
//
////////////////////////////////////////////////////////////////////////
#include "show.h"
#include "cache.h"
#include "renderer.h"
#include "error.h"
#include "fileResource.h"
#include "photonMap.h"
#include "opengl/opengl.h"

// The static members of the CView class that visualizable classes derive from
void					*CView::handle			=	NULL;
TGlTrianglesFunction	CView::drawTriangles	=	NULL;
TGlPointsFunction		CView::drawPoints		=	NULL;

///////////////////////////////////////////////////////////////////////
// Class				:	CShow
// Method				:	CShow
// Description			:	Ctor
// Return Value			:	-
// Comments				:
// Date last edited		:	9/21/2006
CShow::CShow(COptions *o,CXform *x,SOCKET s) : CShadingContext(o,x,s,HIDER_NODISPLAY) {
	const char	*pixieHome	=	osEnvironment("PIXIEHOME");
	char		tmp[OS_MAX_PATH_LENGTH];

	// First, try to load the dynamic library
//TODO: load from displays directory
#ifdef WIN32
	if (pixieHome != NULL)	sprintf(tmp,"%s\\opengl.dll",pixieHome);
	else					strcpy(tmp,"opengl.dll");
#else
	if (pixieHome != NULL)	sprintf(tmp,"%s/opengl.so",pixieHome);
	else					strcpy(tmp,"opengl.so");
#endif

	CView::handle	=	osLoadModule(tmp);

	if (CView::handle != NULL) {

		// Is this the library we were expecting ?
		TGlVisualizeFunction	visualize	=	(TGlVisualizeFunction) osResolve(CView::handle,"pglVisualize");
		CView					*view		=	NULL;

		if (visualize != NULL) {

			// Try to load the file
			const char	*fileName	=	hider + 5;
			FILE		*in			=	fopen(fileName,"rb");

			CView::drawTriangles	=	(TGlTrianglesFunction)	osResolve(CView::handle,"pglTriangles");
			CView::drawPoints		=	(TGlPointsFunction)		osResolve(CView::handle,"pglPoints");

			assert(CView::drawTriangles != NULL);
			assert(CView::drawPoints != NULL);

			if (in != NULL)	{
				unsigned int	magic	=	0;
				int				version[3],i;
				char			*t;

				fread(&magic,1,sizeof(int),in);

				if (magic == magicNumber) {
					fread(version,3,sizeof(int),in);

					if (!((version[0] == VERSION_RELEASE) || (version[1] == VERSION_BETA))) {
						error(CODE_VERSION,"File %s is from an incompatible version\n",fileName);
					} else {
						fread(&i,1,sizeof(int),in);
						t	=	(char *) alloca((i+1)*sizeof(char));
						fread(t,i+1,sizeof(char),in);

						info(CODE_LOG,"File:    %s\n",fileName);
						info(CODE_LOG,"Version: %d.%d.%d\n",version[0],version[1],version[2]);
						info(CODE_LOG,"Type:    %s\n",t);
						fclose(in);

						if (strcmp(t,filePhotonMap) == 0) {
							view	=	getPhotonMap(fileName);
						} else if (strcmp(t,fileIrradianceCache) == 0) {
							view	=	getCache(fileName,"R");
						} else if (strcmp(t,fileGatherCache) == 0) {
							view	=	getCache(fileName,"R");
						} else if (strcmp(t,filePointCloud) == 0) {

						} else if (strcmp(t,fileBrickMap) == 0) {

						}

						// Create / display the window
						if (view != NULL)	visualize(view);
					}
				} else {
					error(CODE_BADFILE,"File %s doesn't seem to be a Pixie file\n",fileName);
				}
			}
		}
	} else {
		error(CODE_SYSTEM,"Opengl wrapper not found...");
	}
}

///////////////////////////////////////////////////////////////////////
// Class				:	CShow
// Method				:	~CShow
// Description			:	Dtor
// Return Value			:	-
// Comments				:
// Date last edited		:	9/21/2006
CShow::~CShow() {
}
<|endoftext|>