<commit_before>/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * 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.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include "Standard.h"

#include <iostream>
#include <sstream>
#include <iomanip>

namespace bm_runtime { namespace standard {

class StandardHandler : virtual public StandardIf {
public:
  StandardHandler() { }

  std::string ToHex(const std::string& s, bool upper_case = false) {
    std::ostringstream ret;

    for (std::string::size_type i = 0; i < s.length(); i++) {
      ret << std::setw(2) << std::setfill('0') << std::hex
	  << (upper_case ? std::uppercase : std::nouppercase)
	  << (int) static_cast<unsigned char>(s[i]);
    }

    return ret.str();
  }

  void print_spec(const std::vector<std::string> &v) {
    for(const auto &e : v)
      std::cout << ToHex(e) << " ";
    std::cout << std::endl;
  }

  void print_match_param(const BmMatchParam &param) {
    switch(param.type) {
    case BmMatchParamType::type::EXACT:
      std::cout << "EXACT: "
		<< ToHex(param.exact.key);
      break;
    case BmMatchParamType::type::LPM:
      std::cout << "LPM: "
		<< ToHex(param.lpm.key) << "/" << param.lpm.prefix_length;
      break;
    case BmMatchParamType::type::TERNARY:
      std::cout << "TERNARY: "
		<<ToHex(param.ternary.key) << "&&&" << ToHex(param.ternary.mask);
      break;
    case BmMatchParamType::type::VALID:
      std::cout << "VALID: "
		<<std::boolalpha << param.valid.key << std::noboolalpha;
      break;
    default:
      assert(0 && "invalid match type");
      break;
    }
    std::cout << std::endl;
  }

  BmEntryHandle bm_mt_add_entry(const std::string& table_name, const BmMatchParams& match_key, const std::string& action_name, const BmActionData& action_data, const BmAddEntryOptions& options) {
    std::cout << "bm_mt_add_entry" << std::endl
	      << table_name << std::endl;
    for(const auto &p : match_key)
      print_match_param(p);
    std::cout << action_name << std::endl;
    print_spec(action_data);
    if(options.__isset.priority)
      std::cout << options.priority << std::endl;
    return 0;
  }

  void bm_mt_set_default_action(const std::string& table_name, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_set_default_action" << std::endl
	      << table_name << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  void bm_mt_delete_entry(const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_mt_delete_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_mt_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const std::string &action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_modify_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  void bm_mt_set_entry_ttl(const std::string& table_name, const BmEntryHandle entry_handle, const int32_t timeout_ms) {
    std::cout << "bm_mt_set_entry_ttl" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << timeout_ms << std::endl;
  }

  BmMemberHandle bm_mt_indirect_add_member(const std::string& table_name, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_indirect_add_member" << std::endl
	      << table_name << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
    return 0;
  }

  void bm_mt_indirect_delete_member(const std::string& table_name, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_delete_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl;
  }

  void bm_mt_indirect_modify_member(const std::string& table_name, const BmMemberHandle mbr_handle, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_indirect_modify_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  BmEntryHandle bm_mt_indirect_add_entry(const std::string& table_name, const BmMatchParams& match_key, const BmMemberHandle mbr_handle, const BmAddEntryOptions& options) {
    std::cout << "bm_mt_indirect_add_entry" << std::endl
	      << table_name << std::endl;
    for(const auto &p : match_key)
      print_match_param(p);
    std::cout << mbr_handle << std::endl;
    if(options.__isset.priority)
      std::cout << options.priority << std::endl;
    return 0;
  }

  void bm_mt_indirect_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_modify_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << mbr_handle << std::endl;
  }

  void bm_mt_indirect_delete_entry(const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_mt_indirect_delete_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_mt_indirect_set_entry_ttl(const std::string& table_name, const BmEntryHandle entry_handle, const int32_t timeout_ms) {
    std::cout << "bm_mt_indirect_set_entry_ttl" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << timeout_ms << std::endl;
  }

  void bm_mt_indirect_set_default_member(const std::string& table_name, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_set_default_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl;
  }

  BmGroupHandle bm_mt_indirect_ws_create_group(const std::string& table_name) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_create_group\n");
    return 0;
  }

  void bm_mt_indirect_ws_delete_group(const std::string& table_name, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_delete_group\n");
  }

  void bm_mt_indirect_ws_add_member_to_group(const std::string& table_name, const BmMemberHandle mbr_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_add_member_to_group\n");
  }

  void bm_mt_indirect_ws_remove_member_from_group(const std::string& table_name, const BmMemberHandle mbr_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_remove_member_from_group\n");
  }

  BmEntryHandle bm_mt_indirect_ws_add_entry(const std::string& table_name, const BmMatchParams& match_key, const BmGroupHandle grp_handle, const BmAddEntryOptions& options) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_add_entry\n");
    return 0;
  }

  void bm_mt_indirect_ws_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_modify_entry\n");
  }

  void bm_mt_indirect_ws_set_default_group(const std::string& table_name, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_set_default_group\n");
  }

  void bm_mt_read_counter(BmCounterValue& _return, const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_mt_read_counter" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_mt_reset_counters(const std::string& table_name) {
    std::cout << "bm_mt_reset_counters" << std::endl
	      << table_name << std::endl;
  }

  void bm_mt_write_counter(const std::string& table_name, const BmEntryHandle entry_handle, const BmCounterValue& value) {
    std::cout << "bm_mt_write_counter" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << value.bytes << " " << value.packets << std::endl;
  }

  void bm_counter_read(BmCounterValue& _return, const std::string& counter_name, const int32_t index) {
    std::cout << "bm_counter_read" << std::endl
	      << counter_name << std::endl
	      << index << std::endl;
  }

  void bm_counter_reset_all(const std::string& counter_name) {
    std::cout << "bm_counter_reset_all" << std::endl
	      << counter_name << std::endl;
  }

  void bm_counter_write(const std::string& counter_name, const int32_t index, const BmCounterValue& value) {
    std::cout << "bm_counter_write" << std::endl
	      << counter_name << std::endl
	      << index << std::endl
	      << value.bytes << " " << value.packets << std::endl;
  }

  void bm_learning_ack(const BmLearningListId list_id, const BmLearningBufferId buffer_id, const std::vector<BmLearningSampleId> & sample_ids) {
    // Your implementation goes here
    printf("bm_learning_ack\n");
  }

  void bm_learning_ack_buffer(const BmLearningListId list_id, const BmLearningBufferId buffer_id) {
    // Your implementation goes here
    printf("bm_learning_ack_buffer\n");
  }

  void bm_load_new_config(const std::string& config_str) {
    // Your implementation goes here
    printf("bm_load_new_config\n");
  }

  void bm_swap_configs() {
    // Your implementation goes here
    printf("bm_swap_configs\n");
  }

  void bm_meter_array_set_rates(const std::string& meter_array_name, const std::vector<BmMeterRateConfig> & rates) {
    // Your implementation goes here
    printf("bm_meter_array_set_rates\n");
  }

  void bm_meter_set_rates(const std::string& meter_array_name, const int32_t index, const std::vector<BmMeterRateConfig> & rates) {
    std::cout << "bm_meter_set_rates" << std::endl
	      << meter_array_name << std::endl
	      << index << std::endl;
    for(const auto &rate : rates) {
      std::cout << rate.units_per_micros << " " << rate.burst_size << std::endl;
    }
  }

  void bm_dev_mgr_add_port(const std::string& iface_name, const int32_t port_num, const std::string& pcap_path) {
    // Your implementation goes here
    printf("bm_dev_mgr_add_port\n");
  }

  void bm_dev_mgr_remove_port(const int32_t port_num) {
    // Your implementation goes here
    printf("bm_dev_mgr_remove_port\n");
  }

  void bm_dump_table(std::string& _return, const std::string& table_name) {
    // Your implementation goes here
    printf("bm_dump_table\n");
  }

  void bm_reset_state() {
    // Your implementation goes here
    printf("bm_reset_state\n");
  }

};

} }
<commit_msg>added missing register functions to stub Thrift server<commit_after>/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * 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.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include "Standard.h"

#include <iostream>
#include <sstream>
#include <iomanip>

namespace bm_runtime { namespace standard {

class StandardHandler : virtual public StandardIf {
public:
  StandardHandler() { }

  std::string ToHex(const std::string& s, bool upper_case = false) {
    std::ostringstream ret;

    for (std::string::size_type i = 0; i < s.length(); i++) {
      ret << std::setw(2) << std::setfill('0') << std::hex
	  << (upper_case ? std::uppercase : std::nouppercase)
	  << (int) static_cast<unsigned char>(s[i]);
    }

    return ret.str();
  }

  void print_spec(const std::vector<std::string> &v) {
    for(const auto &e : v)
      std::cout << ToHex(e) << " ";
    std::cout << std::endl;
  }

  void print_match_param(const BmMatchParam &param) {
    switch(param.type) {
    case BmMatchParamType::type::EXACT:
      std::cout << "EXACT: "
		<< ToHex(param.exact.key);
      break;
    case BmMatchParamType::type::LPM:
      std::cout << "LPM: "
		<< ToHex(param.lpm.key) << "/" << param.lpm.prefix_length;
      break;
    case BmMatchParamType::type::TERNARY:
      std::cout << "TERNARY: "
		<<ToHex(param.ternary.key) << "&&&" << ToHex(param.ternary.mask);
      break;
    case BmMatchParamType::type::VALID:
      std::cout << "VALID: "
		<<std::boolalpha << param.valid.key << std::noboolalpha;
      break;
    default:
      assert(0 && "invalid match type");
      break;
    }
    std::cout << std::endl;
  }

  BmEntryHandle bm_mt_add_entry(const std::string& table_name, const BmMatchParams& match_key, const std::string& action_name, const BmActionData& action_data, const BmAddEntryOptions& options) {
    std::cout << "bm_mt_add_entry" << std::endl
	      << table_name << std::endl;
    for(const auto &p : match_key)
      print_match_param(p);
    std::cout << action_name << std::endl;
    print_spec(action_data);
    if(options.__isset.priority)
      std::cout << options.priority << std::endl;
    return 0;
  }

  void bm_mt_set_default_action(const std::string& table_name, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_set_default_action" << std::endl
	      << table_name << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  void bm_mt_delete_entry(const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_mt_delete_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_mt_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const std::string &action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_modify_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  void bm_mt_set_entry_ttl(const std::string& table_name, const BmEntryHandle entry_handle, const int32_t timeout_ms) {
    std::cout << "bm_mt_set_entry_ttl" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << timeout_ms << std::endl;
  }

  BmMemberHandle bm_mt_indirect_add_member(const std::string& table_name, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_indirect_add_member" << std::endl
	      << table_name << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
    return 0;
  }

  void bm_mt_indirect_delete_member(const std::string& table_name, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_delete_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl;
  }

  void bm_mt_indirect_modify_member(const std::string& table_name, const BmMemberHandle mbr_handle, const std::string& action_name, const BmActionData& action_data) {
    std::cout << "bm_mt_indirect_modify_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl
	      << action_name << std::endl;
    print_spec(action_data);
  }

  BmEntryHandle bm_mt_indirect_add_entry(const std::string& table_name, const BmMatchParams& match_key, const BmMemberHandle mbr_handle, const BmAddEntryOptions& options) {
    std::cout << "bm_mt_indirect_add_entry" << std::endl
	      << table_name << std::endl;
    for(const auto &p : match_key)
      print_match_param(p);
    std::cout << mbr_handle << std::endl;
    if(options.__isset.priority)
      std::cout << options.priority << std::endl;
    return 0;
  }

  void bm_mt_indirect_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_modify_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << mbr_handle << std::endl;
  }

  void bm_mt_indirect_delete_entry(const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_mt_indirect_delete_entry" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_mt_indirect_set_entry_ttl(const std::string& table_name, const BmEntryHandle entry_handle, const int32_t timeout_ms) {
    std::cout << "bm_mt_indirect_set_entry_ttl" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << timeout_ms << std::endl;
  }

  void bm_mt_indirect_set_default_member(const std::string& table_name, const BmMemberHandle mbr_handle) {
    std::cout << "bm_mt_indirect_set_default_member" << std::endl
	      << table_name << std::endl
	      << mbr_handle << std::endl;
  }

  BmGroupHandle bm_mt_indirect_ws_create_group(const std::string& table_name) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_create_group\n");
    return 0;
  }

  void bm_mt_indirect_ws_delete_group(const std::string& table_name, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_delete_group\n");
  }

  void bm_mt_indirect_ws_add_member_to_group(const std::string& table_name, const BmMemberHandle mbr_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_add_member_to_group\n");
  }

  void bm_mt_indirect_ws_remove_member_from_group(const std::string& table_name, const BmMemberHandle mbr_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_remove_member_from_group\n");
  }

  BmEntryHandle bm_mt_indirect_ws_add_entry(const std::string& table_name, const BmMatchParams& match_key, const BmGroupHandle grp_handle, const BmAddEntryOptions& options) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_add_entry\n");
    return 0;
  }

  void bm_mt_indirect_ws_modify_entry(const std::string& table_name, const BmEntryHandle entry_handle, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_modify_entry\n");
  }

  void bm_mt_indirect_ws_set_default_group(const std::string& table_name, const BmGroupHandle grp_handle) {
    // Your implementation goes here
    printf("bm_mt_indirect_ws_set_default_group\n");
  }

  void bm_mt_read_counter(BmCounterValue& _return, const std::string& table_name, const BmEntryHandle entry_handle) {
    std::cout << "bm_mt_read_counter" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl;
  }

  void bm_mt_reset_counters(const std::string& table_name) {
    std::cout << "bm_mt_reset_counters" << std::endl
	      << table_name << std::endl;
  }

  void bm_mt_write_counter(const std::string& table_name, const BmEntryHandle entry_handle, const BmCounterValue& value) {
    std::cout << "bm_mt_write_counter" << std::endl
	      << table_name << std::endl
	      << entry_handle << std::endl
	      << value.bytes << " " << value.packets << std::endl;
  }

  void bm_counter_read(BmCounterValue& _return, const std::string& counter_name, const int32_t index) {
    std::cout << "bm_counter_read" << std::endl
	      << counter_name << std::endl
	      << index << std::endl;
  }

  void bm_counter_reset_all(const std::string& counter_name) {
    std::cout << "bm_counter_reset_all" << std::endl
	      << counter_name << std::endl;
  }

  void bm_counter_write(const std::string& counter_name, const int32_t index, const BmCounterValue& value) {
    std::cout << "bm_counter_write" << std::endl
	      << counter_name << std::endl
	      << index << std::endl
	      << value.bytes << " " << value.packets << std::endl;
  }

  void bm_learning_ack(const BmLearningListId list_id, const BmLearningBufferId buffer_id, const std::vector<BmLearningSampleId> & sample_ids) {
    // Your implementation goes here
    printf("bm_learning_ack\n");
  }

  void bm_learning_ack_buffer(const BmLearningListId list_id, const BmLearningBufferId buffer_id) {
    // Your implementation goes here
    printf("bm_learning_ack_buffer\n");
  }

  void bm_load_new_config(const std::string& config_str) {
    // Your implementation goes here
    printf("bm_load_new_config\n");
  }

  void bm_swap_configs() {
    // Your implementation goes here
    printf("bm_swap_configs\n");
  }

  void bm_meter_array_set_rates(const std::string& meter_array_name, const std::vector<BmMeterRateConfig> & rates) {
    // Your implementation goes here
    printf("bm_meter_array_set_rates\n");
  }

  void bm_meter_set_rates(const std::string& meter_array_name, const int32_t index, const std::vector<BmMeterRateConfig> & rates) {
    std::cout << "bm_meter_set_rates" << std::endl
	      << meter_array_name << std::endl
	      << index << std::endl;
    for(const auto &rate : rates) {
      std::cout << rate.units_per_micros << " " << rate.burst_size << std::endl;
    }
  }

  BmRegisterValue bm_register_read(const std::string& register_name, const int32_t index) {
    // Your implementation goes here
    printf("bm_register_read\n");
  }

  void bm_register_write(const std::string& register_name, const int32_t index, const BmRegisterValue value) {
    // Your implementation goes here
    printf("bm_register_write\n");
  }

  void bm_dev_mgr_add_port(const std::string& iface_name, const int32_t port_num, const std::string& pcap_path) {
    // Your implementation goes here
    printf("bm_dev_mgr_add_port\n");
  }

  void bm_dev_mgr_remove_port(const int32_t port_num) {
    // Your implementation goes here
    printf("bm_dev_mgr_remove_port\n");
  }

  void bm_dump_table(std::string& _return, const std::string& table_name) {
    // Your implementation goes here
    printf("bm_dump_table\n");
  }

  void bm_reset_state() {
    // Your implementation goes here
    printf("bm_reset_state\n");
  }

};

} }
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * 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.
 */

#include "caffe2/core/logging.h"
#include "caffe2/core/flags.h"

#include <algorithm>
#include <cstring>
#include <numeric>

// Common code that we use regardless of whether we use glog or not.

CAFFE2_DEFINE_bool(caffe2_use_fatal_for_enforce, false,
                   "If set true, when CAFFE_ENFORCE is not met, abort instead "
                   "of throwing an exception.");

namespace caffe2 {
std::string StripBasename(const std::string &full_path) {
  const char kSeparator = '/';
  size_t pos = full_path.rfind(kSeparator);
  if (pos != std::string::npos) {
    return full_path.substr(pos + 1, std::string::npos);
  } else {
    return full_path;
  }
}

size_t ReplaceAll(string& s, const char* from, const char* to) {
  CAFFE_ENFORCE(from && *from);
  CAFFE_ENFORCE(to);

  size_t numReplaced = 0;
  string::size_type lenFrom = std::strlen(from);
  string::size_type lenTo = std::strlen(to);
  for (string::size_type pos = s.find(from); pos != string::npos;
       pos = s.find(from, pos + lenTo)) {
    s.replace(pos, lenFrom, to);
    numReplaced++;
  }
  return numReplaced;
}

static std::function<string(void)> FetchStackTrace = []() { return ""; };

void SetStackTraceFetcher(std::function<string(void)> fetcher) {
  FetchStackTrace = fetcher;
}

static std::function<void(const OperatorDef&)> OperatorLogger =
    [](const OperatorDef&) { return; };

void SetOperatorLogger(std::function<void(const OperatorDef&)> tracer) {
  OperatorLogger = tracer;
}

std::function<void(const OperatorDef&)> GetOperatorLogger() {
  return OperatorLogger;
}

EnforceNotMet::EnforceNotMet(
    const char* file,
    const int line,
    const char* condition,
    const string& msg,
    const void* caller)
    : msg_stack_{MakeString(
          "[enforce fail at ",
          StripBasename(std::string(file)),
          ":",
          line,
          "] ",
          condition,
          ". ",
          msg,
          " ")},
      stack_trace_(FetchStackTrace()) {
  if (FLAGS_caffe2_use_fatal_for_enforce) {
    LOG(FATAL) << msg_stack_[0];
  }
  caller_ = caller;
  full_msg_ = this->msg();
}

void EnforceNotMet::AppendMessage(const string& msg) {
  msg_stack_.push_back(msg);
  full_msg_ = this->msg();
}

string EnforceNotMet::msg() const {
  return std::accumulate(msg_stack_.begin(), msg_stack_.end(), string("")) +
      stack_trace_;
}

const char* EnforceNotMet::what() const noexcept {
  return full_msg_.c_str();
}

const void* EnforceNotMet::caller() const noexcept {
  return caller_;
}

}  // namespace caffe2

#ifdef CAFFE2_USE_GOOGLE_GLOG

#ifdef CAFFE2_USE_GFLAGS
// GLOG's minloglevel
CAFFE2_DECLARE_int(minloglevel);
// GLOG's verbose log value.
CAFFE2_DECLARE_int(v);
// GLOG's logtostderr value
CAFFE2_DECLARE_bool(logtostderr);

#else

using fLI::FLAGS_minloglevel;
using fLI::FLAGS_v;
using fLB::FLAGS_logtostderr;

#endif // CAFFE2_USE_GFLAGS

CAFFE2_DEFINE_int(caffe2_log_level, google::ERROR,
                  "The minimum log level that caffe2 will output.");

// Google glog's api does not have an external function that allows one to check
// if glog is initialized or not. It does have an internal function - so we are
// declaring it here. This is a hack but has been used by a bunch of others too
// (e.g. Torch).
namespace google {
namespace glog_internal_namespace_ {
bool IsGoogleLoggingInitialized();
}  // namespace glog_internal_namespace_
}  // namespace google

namespace caffe2 {
bool InitCaffeLogging(int* argc, char** argv) {
  if (*argc == 0) return true;
  if (!::google::glog_internal_namespace_::IsGoogleLoggingInitialized()) {
    ::google::InitGoogleLogging(argv[0]);
    ::google::InstallFailureSignalHandler();
  }
  // If caffe2_log_level is set and is lower than the min log level by glog,
  // we will transfer the caffe2_log_level setting to glog to override that.
  FLAGS_minloglevel = std::min(FLAGS_caffe2_log_level, FLAGS_minloglevel);
  // If caffe2_log_level is explicitly set, let's also turn on logtostderr.
  if (FLAGS_caffe2_log_level < google::ERROR) {
    FLAGS_logtostderr = 1;
  }
  // Also, transfer the caffe2_log_level verbose setting to glog.
  if (FLAGS_caffe2_log_level < 0) {
    FLAGS_v = std::min(FLAGS_v, -FLAGS_caffe2_log_level);
  }
  return true;
}

void ShowLogInfoToStderr() {
  FLAGS_logtostderr = 1;
  FLAGS_minloglevel = std::min(FLAGS_minloglevel, google::INFO);
}
}  // namespace caffe2

#else  // !CAFFE2_USE_GOOGLE_GLOG

#ifdef ANDROID
#include <android/log.h>
#endif // ANDROID

CAFFE2_DEFINE_int(caffe2_log_level, ERROR,
                  "The minimum log level that caffe2 will output.");

namespace caffe2 {
bool InitCaffeLogging(int* argc, char** argv) {
  // When doing InitCaffeLogging, we will assume that caffe's flag paser has
  // already finished.
  if (*argc == 0) return true;
  if (!CommandLineFlagsHasBeenParsed()) {
    std::cerr << "InitCaffeLogging() has to be called after "
                 "ParseCaffeCommandLineFlags. Modify your program to make sure "
                 "of this." << std::endl;
    return false;
  }
  if (FLAGS_caffe2_log_level > FATAL) {
    std::cerr << "The log level of Caffe2 has to be no larger than FATAL("
              << FATAL << "). Capping it to FATAL." << std::endl;
    FLAGS_caffe2_log_level = FATAL;
  }
  return true;
}

void ShowLogInfoToStderr() {
  FLAGS_caffe2_log_level = INFO;
}

MessageLogger::MessageLogger(const char *file, int line, int severity)
  : severity_(severity) {
  if (severity_ < FLAGS_caffe2_log_level) {
    // Nothing needs to be logged.
    return;
  }
#ifdef ANDROID
  tag_ = "native";
#else  // !ANDROID
  tag_ = "";
#endif  // ANDROID
  /*
  time_t rawtime;
  struct tm * timeinfo;
  time(&rawtime);
  timeinfo = localtime(&rawtime);
  std::chrono::nanoseconds ns =
      std::chrono::duration_cast<std::chrono::nanoseconds>(
          std::chrono::high_resolution_clock::now().time_since_epoch());
  */
  stream_ << "[" << CAFFE2_SEVERITY_PREFIX[std::min(4, FATAL - severity_)]
          //<< (timeinfo->tm_mon + 1) * 100 + timeinfo->tm_mday
          //<< std::setfill('0')
          //<< " " << std::setw(2) << timeinfo->tm_hour
          //<< ":" << std::setw(2) << timeinfo->tm_min
          //<< ":" << std::setw(2) << timeinfo->tm_sec
          //<< "." << std::setw(9) << ns.count() % 1000000000
          << " " << StripBasename(std::string(file)) << ":" << line << "] ";
}

// Output the contents of the stream to the proper channel on destruction.
MessageLogger::~MessageLogger() {
  if (severity_ < FLAGS_caffe2_log_level) {
    // Nothing needs to be logged.
    return;
  }
  stream_ << "\n";
#ifdef ANDROID
  static const int android_log_levels[] = {
      ANDROID_LOG_FATAL,    // LOG_FATAL
      ANDROID_LOG_ERROR,    // LOG_ERROR
      ANDROID_LOG_WARN,     // LOG_WARNING
      ANDROID_LOG_INFO,     // LOG_INFO
      ANDROID_LOG_DEBUG,    // VLOG(1)
      ANDROID_LOG_VERBOSE,  // VLOG(2) .. VLOG(N)
  };
  int android_level_index = FATAL - std::min(FATAL, severity_);
  int level = android_log_levels[std::min(android_level_index, 5)];
  // Output the log string the Android log at the appropriate level.
  __android_log_print(level, tag_, "%s", stream_.str().c_str());
  // Indicate termination if needed.
  if (severity_ == FATAL) {
    __android_log_print(ANDROID_LOG_FATAL, tag_, "terminating.\n");
  }
#else  // !ANDROID
  if (severity_ >= FLAGS_caffe2_log_level) {
    // If not building on Android, log all output to std::cerr.
    std::cerr << stream_.str();
  }
#endif  // ANDROID
  if (severity_ == FATAL) {
    DealWithFatal();
  }
}

}  // namespace caffe2

#endif  // !CAFFE2_USE_GOOGLE_GLOG
<commit_msg>Fix for glog on windows<commit_after>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * 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.
 */

#include "caffe2/core/logging.h"
#include "caffe2/core/flags.h"

#include <algorithm>
#include <cstring>
#include <numeric>

// Common code that we use regardless of whether we use glog or not.

CAFFE2_DEFINE_bool(caffe2_use_fatal_for_enforce, false,
                   "If set true, when CAFFE_ENFORCE is not met, abort instead "
                   "of throwing an exception.");

namespace caffe2 {
std::string StripBasename(const std::string &full_path) {
  const char kSeparator = '/';
  size_t pos = full_path.rfind(kSeparator);
  if (pos != std::string::npos) {
    return full_path.substr(pos + 1, std::string::npos);
  } else {
    return full_path;
  }
}

size_t ReplaceAll(string& s, const char* from, const char* to) {
  CAFFE_ENFORCE(from && *from);
  CAFFE_ENFORCE(to);

  size_t numReplaced = 0;
  string::size_type lenFrom = std::strlen(from);
  string::size_type lenTo = std::strlen(to);
  for (string::size_type pos = s.find(from); pos != string::npos;
       pos = s.find(from, pos + lenTo)) {
    s.replace(pos, lenFrom, to);
    numReplaced++;
  }
  return numReplaced;
}

static std::function<string(void)> FetchStackTrace = []() { return ""; };

void SetStackTraceFetcher(std::function<string(void)> fetcher) {
  FetchStackTrace = fetcher;
}

static std::function<void(const OperatorDef&)> OperatorLogger =
    [](const OperatorDef&) { return; };

void SetOperatorLogger(std::function<void(const OperatorDef&)> tracer) {
  OperatorLogger = tracer;
}

std::function<void(const OperatorDef&)> GetOperatorLogger() {
  return OperatorLogger;
}

EnforceNotMet::EnforceNotMet(
    const char* file,
    const int line,
    const char* condition,
    const string& msg,
    const void* caller)
    : msg_stack_{MakeString(
          "[enforce fail at ",
          StripBasename(std::string(file)),
          ":",
          line,
          "] ",
          condition,
          ". ",
          msg,
          " ")},
      stack_trace_(FetchStackTrace()) {
  if (FLAGS_caffe2_use_fatal_for_enforce) {
    LOG(FATAL) << msg_stack_[0];
  }
  caller_ = caller;
  full_msg_ = this->msg();
}

void EnforceNotMet::AppendMessage(const string& msg) {
  msg_stack_.push_back(msg);
  full_msg_ = this->msg();
}

string EnforceNotMet::msg() const {
  return std::accumulate(msg_stack_.begin(), msg_stack_.end(), string("")) +
      stack_trace_;
}

const char* EnforceNotMet::what() const noexcept {
  return full_msg_.c_str();
}

const void* EnforceNotMet::caller() const noexcept {
  return caller_;
}

}  // namespace caffe2

#ifdef CAFFE2_USE_GOOGLE_GLOG

#ifdef CAFFE2_USE_GFLAGS
// GLOG's minloglevel
CAFFE2_DECLARE_int(minloglevel);
// GLOG's verbose log value.
CAFFE2_DECLARE_int(v);
// GLOG's logtostderr value
CAFFE2_DECLARE_bool(logtostderr);

#else

using fLI::FLAGS_minloglevel;
using fLI::FLAGS_v;
using fLB::FLAGS_logtostderr;

#endif // CAFFE2_USE_GFLAGS

CAFFE2_DEFINE_int(caffe2_log_level, google::GLOG_ERROR,
                  "The minimum log level that caffe2 will output.");

// Google glog's api does not have an external function that allows one to check
// if glog is initialized or not. It does have an internal function - so we are
// declaring it here. This is a hack but has been used by a bunch of others too
// (e.g. Torch).
namespace google {
namespace glog_internal_namespace_ {
bool IsGoogleLoggingInitialized();
}  // namespace glog_internal_namespace_
}  // namespace google

namespace caffe2 {
bool InitCaffeLogging(int* argc, char** argv) {
  if (*argc == 0) return true;
#if !defined(_MSC_VER)
  // This trick can only be used on UNIX platforms
  if (!::google::glog_internal_namespace_::IsGoogleLoggingInitialized())
#endif
  {
    ::google::InitGoogleLogging(argv[0]);
#if !defined(_MSC_VER)
  // This is never defined on Windows
    ::google::InstallFailureSignalHandler();
#endif
  }
  // If caffe2_log_level is set and is lower than the min log level by glog,
  // we will transfer the caffe2_log_level setting to glog to override that.
  FLAGS_minloglevel = std::min(FLAGS_caffe2_log_level, FLAGS_minloglevel);
  // If caffe2_log_level is explicitly set, let's also turn on logtostderr.
  if (FLAGS_caffe2_log_level < google::GLOG_ERROR) {
    FLAGS_logtostderr = 1;
  }
  // Also, transfer the caffe2_log_level verbose setting to glog.
  if (FLAGS_caffe2_log_level < 0) {
    FLAGS_v = std::min(FLAGS_v, -FLAGS_caffe2_log_level);
  }
  return true;
}

void ShowLogInfoToStderr() {
  FLAGS_logtostderr = 1;
  FLAGS_minloglevel = std::min(FLAGS_minloglevel, google::GLOG_INFO);
}
}  // namespace caffe2

#else  // !CAFFE2_USE_GOOGLE_GLOG

#ifdef ANDROID
#include <android/log.h>
#endif // ANDROID

CAFFE2_DEFINE_int(caffe2_log_level, ERROR,
                  "The minimum log level that caffe2 will output.");

namespace caffe2 {
bool InitCaffeLogging(int* argc, char** argv) {
  // When doing InitCaffeLogging, we will assume that caffe's flag paser has
  // already finished.
  if (*argc == 0) return true;
  if (!CommandLineFlagsHasBeenParsed()) {
    std::cerr << "InitCaffeLogging() has to be called after "
                 "ParseCaffeCommandLineFlags. Modify your program to make sure "
                 "of this." << std::endl;
    return false;
  }
  if (FLAGS_caffe2_log_level > FATAL) {
    std::cerr << "The log level of Caffe2 has to be no larger than FATAL("
              << FATAL << "). Capping it to FATAL." << std::endl;
    FLAGS_caffe2_log_level = FATAL;
  }
  return true;
}

void ShowLogInfoToStderr() {
  FLAGS_caffe2_log_level = INFO;
}

MessageLogger::MessageLogger(const char *file, int line, int severity)
  : severity_(severity) {
  if (severity_ < FLAGS_caffe2_log_level) {
    // Nothing needs to be logged.
    return;
  }
#ifdef ANDROID
  tag_ = "native";
#else  // !ANDROID
  tag_ = "";
#endif  // ANDROID
  /*
  time_t rawtime;
  struct tm * timeinfo;
  time(&rawtime);
  timeinfo = localtime(&rawtime);
  std::chrono::nanoseconds ns =
      std::chrono::duration_cast<std::chrono::nanoseconds>(
          std::chrono::high_resolution_clock::now().time_since_epoch());
  */
  stream_ << "[" << CAFFE2_SEVERITY_PREFIX[std::min(4, FATAL - severity_)]
          //<< (timeinfo->tm_mon + 1) * 100 + timeinfo->tm_mday
          //<< std::setfill('0')
          //<< " " << std::setw(2) << timeinfo->tm_hour
          //<< ":" << std::setw(2) << timeinfo->tm_min
          //<< ":" << std::setw(2) << timeinfo->tm_sec
          //<< "." << std::setw(9) << ns.count() % 1000000000
          << " " << StripBasename(std::string(file)) << ":" << line << "] ";
}

// Output the contents of the stream to the proper channel on destruction.
MessageLogger::~MessageLogger() {
  if (severity_ < FLAGS_caffe2_log_level) {
    // Nothing needs to be logged.
    return;
  }
  stream_ << "\n";
#ifdef ANDROID
  static const int android_log_levels[] = {
      ANDROID_LOG_FATAL,    // LOG_FATAL
      ANDROID_LOG_ERROR,    // LOG_ERROR
      ANDROID_LOG_WARN,     // LOG_WARNING
      ANDROID_LOG_INFO,     // LOG_INFO
      ANDROID_LOG_DEBUG,    // VLOG(1)
      ANDROID_LOG_VERBOSE,  // VLOG(2) .. VLOG(N)
  };
  int android_level_index = FATAL - std::min(FATAL, severity_);
  int level = android_log_levels[std::min(android_level_index, 5)];
  // Output the log string the Android log at the appropriate level.
  __android_log_print(level, tag_, "%s", stream_.str().c_str());
  // Indicate termination if needed.
  if (severity_ == FATAL) {
    __android_log_print(ANDROID_LOG_FATAL, tag_, "terminating.\n");
  }
#else  // !ANDROID
  if (severity_ >= FLAGS_caffe2_log_level) {
    // If not building on Android, log all output to std::cerr.
    std::cerr << stream_.str();
  }
#endif  // ANDROID
  if (severity_ == FATAL) {
    DealWithFatal();
  }
}

}  // namespace caffe2

#endif  // !CAFFE2_USE_GOOGLE_GLOG
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: typemanager.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-08 16:43:40 $
 *
 *  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    <hash_map>

#ifndef _CODEMAKER_TYPEMANAGER_HXX_
#define _CODEMAKER_TYPEMANAGER_HXX_

#ifndef _CODEMAKER_REGISTRY_HXX_
#include    <codemaker/registry.hxx>
#endif

typedef ::std::list< Registry* >    RegistryList;

#if defined( _MSC_VER ) && ( _MSC_VER < 1200 )
typedef ::std::__hash_map__
<
    ::rtl::OString, // Typename
    RTTypeClass,    // TypeClass
    HashString,
    EqualString,
    NewAlloc
> T2TypeClassMap;
#else
typedef ::std::hash_map
<
    ::rtl::OString, // Typename
    RTTypeClass,    // TypeClass
    HashString,
    EqualString
> T2TypeClassMap;
#endif

struct TypeManagerImpl
{
    TypeManagerImpl()
        : m_refCount(0)
        {}

    sal_Int32       m_refCount;
};

class TypeManager
{
public:
    TypeManager();
    ~TypeManager();

    TypeManager( const TypeManager& value )
        : m_pImpl( value.m_pImpl )
    {
        acquire();
    }

    TypeManager& operator = ( const TypeManager& value )
    {
        release();
        m_pImpl = value.m_pImpl;
        acquire();
        return *this;
    }

    virtual sal_Bool init(sal_Bool bMerge, const StringVector& regFiles)
        { return sal_False; }
    virtual sal_Bool init(const ::rtl::OString& registryName)
        { return sal_False; }

    virtual sal_Bool isValidType(const ::rtl::OString& name)
        { return sal_False; }

    virtual RegistryKey getTypeKey(const ::rtl::OString& name)
        { return RegistryKey(); }
    virtual TypeReader getTypeReader(const ::rtl::OString& name)
        { return TypeReader(); }
    virtual RTTypeClass getTypeClass(const ::rtl::OString& name)
        { return RT_TYPE_INVALID; }

    virtual void setBase(const ::rtl::OString& base) {}
    virtual ::rtl::OString getBase() { return ::rtl::OString(); }

    virtual sal_Int32 getSize() { return 0; }

protected:
    sal_Int32 acquire();
    sal_Int32 release();

protected:
    TypeManagerImpl* m_pImpl;
};

struct RegistryTypeManagerImpl
{
    RegistryTypeManagerImpl()
        : m_pMergedRegistry(NULL)
        , m_isMerged(sal_False)
        , m_base("/")
        {}

    T2TypeClassMap  m_t2TypeClass;
    RegistryList    m_registries;
    Registry*       m_pMergedRegistry;
    ::rtl::OString  m_base;
    sal_Bool        m_isMerged;
};

class RegistryTypeManager : public TypeManager
{
public:
    RegistryTypeManager();
    ~RegistryTypeManager();

    RegistryTypeManager( const RegistryTypeManager& value )
        : TypeManager(value)
        , m_pImpl( value.m_pImpl )
    {
        acquire();
    }
/*
    RegistryTypeManager& operator = ( const RegistryTypeManager& value )
    {
        release();
        m_pImpl = value.m_pImpl;
        acquire();
        return *this;
    }
*/
    sal_Bool init(sal_Bool bMerge, const StringVector& regFiles);

    sal_Bool    isValidType(const ::rtl::OString& name)
        { return searchTypeKey(name).isValid(); }
    RegistryKey getTypeKey(const ::rtl::OString& name)
        { return searchTypeKey(name); }
    TypeReader  getTypeReader(const ::rtl::OString& name);
    RTTypeClass getTypeClass(const ::rtl::OString& name);

    void setBase(const ::rtl::OString& base);
    ::rtl::OString getBase() { return m_pImpl->m_base; }

    sal_Int32 getSize() { return m_pImpl->m_t2TypeClass.size(); }
protected:
    RegistryKey searchTypeKey(const ::rtl::OString& name);
    void        freeRegistries();

    void acquire();
    void release();

protected:
    RegistryTypeManagerImpl* m_pImpl;
};

#endif // _CODEMAKER_TYPEMANAGER_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.8); FILE MERGED 2005/09/05 17:42:11 rt 1.4.8.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: typemanager.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:03:28 $
 *
 *  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    <hash_map>

#ifndef _CODEMAKER_TYPEMANAGER_HXX_
#define _CODEMAKER_TYPEMANAGER_HXX_

#ifndef _CODEMAKER_REGISTRY_HXX_
#include    <codemaker/registry.hxx>
#endif

typedef ::std::list< Registry* >    RegistryList;

#if defined( _MSC_VER ) && ( _MSC_VER < 1200 )
typedef ::std::__hash_map__
<
    ::rtl::OString, // Typename
    RTTypeClass,    // TypeClass
    HashString,
    EqualString,
    NewAlloc
> T2TypeClassMap;
#else
typedef ::std::hash_map
<
    ::rtl::OString, // Typename
    RTTypeClass,    // TypeClass
    HashString,
    EqualString
> T2TypeClassMap;
#endif

struct TypeManagerImpl
{
    TypeManagerImpl()
        : m_refCount(0)
        {}

    sal_Int32       m_refCount;
};

class TypeManager
{
public:
    TypeManager();
    ~TypeManager();

    TypeManager( const TypeManager& value )
        : m_pImpl( value.m_pImpl )
    {
        acquire();
    }

    TypeManager& operator = ( const TypeManager& value )
    {
        release();
        m_pImpl = value.m_pImpl;
        acquire();
        return *this;
    }

    virtual sal_Bool init(sal_Bool bMerge, const StringVector& regFiles)
        { return sal_False; }
    virtual sal_Bool init(const ::rtl::OString& registryName)
        { return sal_False; }

    virtual sal_Bool isValidType(const ::rtl::OString& name)
        { return sal_False; }

    virtual RegistryKey getTypeKey(const ::rtl::OString& name)
        { return RegistryKey(); }
    virtual TypeReader getTypeReader(const ::rtl::OString& name)
        { return TypeReader(); }
    virtual RTTypeClass getTypeClass(const ::rtl::OString& name)
        { return RT_TYPE_INVALID; }

    virtual void setBase(const ::rtl::OString& base) {}
    virtual ::rtl::OString getBase() { return ::rtl::OString(); }

    virtual sal_Int32 getSize() { return 0; }

protected:
    sal_Int32 acquire();
    sal_Int32 release();

protected:
    TypeManagerImpl* m_pImpl;
};

struct RegistryTypeManagerImpl
{
    RegistryTypeManagerImpl()
        : m_pMergedRegistry(NULL)
        , m_isMerged(sal_False)
        , m_base("/")
        {}

    T2TypeClassMap  m_t2TypeClass;
    RegistryList    m_registries;
    Registry*       m_pMergedRegistry;
    ::rtl::OString  m_base;
    sal_Bool        m_isMerged;
};

class RegistryTypeManager : public TypeManager
{
public:
    RegistryTypeManager();
    ~RegistryTypeManager();

    RegistryTypeManager( const RegistryTypeManager& value )
        : TypeManager(value)
        , m_pImpl( value.m_pImpl )
    {
        acquire();
    }
/*
    RegistryTypeManager& operator = ( const RegistryTypeManager& value )
    {
        release();
        m_pImpl = value.m_pImpl;
        acquire();
        return *this;
    }
*/
    sal_Bool init(sal_Bool bMerge, const StringVector& regFiles);

    sal_Bool    isValidType(const ::rtl::OString& name)
        { return searchTypeKey(name).isValid(); }
    RegistryKey getTypeKey(const ::rtl::OString& name)
        { return searchTypeKey(name); }
    TypeReader  getTypeReader(const ::rtl::OString& name);
    RTTypeClass getTypeClass(const ::rtl::OString& name);

    void setBase(const ::rtl::OString& base);
    ::rtl::OString getBase() { return m_pImpl->m_base; }

    sal_Int32 getSize() { return m_pImpl->m_t2TypeClass.size(); }
protected:
    RegistryKey searchTypeKey(const ::rtl::OString& name);
    void        freeRegistries();

    void acquire();
    void release();

protected:
    RegistryTypeManagerImpl* m_pImpl;
};

#endif // _CODEMAKER_TYPEMANAGER_HXX_
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2012
  \file      rdolocale.cpp
  \authors   Пройдаков Евгений (lord.tiran@gmail.com)
  \authors   Урусов Андрей (rdo@rk9.bmstu.ru)
  \date      20.10.2012
  \brief     Настройка локали для РДО
  \indent    4T
*/

// ----------------------------------------------------------------------- PLATFORM
// ----------------------------------------------------------------------- INCLUDES
#include <boost/math/special_functions/nonfinite_num_facets.hpp>
#include <iostream>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdolocale.h"
// --------------------------------------------------------------------------------

namespace rdo
{

void locale::init()
{
	rdo::locale& locale = get();

	std::locale sourceCodeLocale = locale.utf8();
	std::locale::global(sourceCodeLocale);

	std::locale C99_out_locale(sourceCodeLocale, new boost::math::nonfinite_num_put<char>);
	std::locale C99_in_locale (sourceCodeLocale, new boost::math::nonfinite_num_get<char>);

	std::cout.imbue(sourceCodeLocale);
	std::cerr.imbue(sourceCodeLocale);
	std::clog.imbue(sourceCodeLocale);
	std::cin.imbue (sourceCodeLocale);
}

locale& locale::get()
{
	static rdo::locale locale;
	return locale;
}

locale::locale()
{
#ifdef COMPILER_VISUAL_STUDIO
	m_modelLocale = std::locale("Russian_Russia.1251");
#endif

	m_generator.locale_cache_enabled(true);
	system();
	utf8  ();
}

std::locale locale::generate(const std::string& name)
{
	return m_generator.generate(name);
}

std::locale locale::system()
{
	return generate("");
}

std::locale locale::utf8()
{
	return generate("ru_RU.UTF-8");
}

std::string locale::convert(const std::string& txt, const std::locale& to, const std::locale& from)
{
	return convert(txt, std::use_facet<boost::locale::info>(to).encoding(), std::use_facet<boost::locale::info>(from).encoding());
}

std::string locale::convert(const std::string& txt, const std::string& to, const std::string& from)
{
	std::string result;
	try
	{
		result = boost::locale::conv::between(txt, to, from);
	}
	catch (const boost::locale::conv::conversion_error&)
	{}
	catch (const boost::locale::conv::invalid_charset_error&)
	{}
	return result;
}

std::string locale::convertToCLocale(const std::string& txt, const std::locale& from)
{
	return convert(txt, getCLocaleName(), std::use_facet<boost::locale::info>(from).encoding());
}

std::string locale::convertFromCLocale(const std::string& txt, const std::locale& to)
{
	return convert(txt, std::use_facet<boost::locale::info>(to).encoding(), getCLocaleName());
}

std::string locale::getCLocaleName()
{
	return "CP1251";
}

unsigned int locale::length(const std::string& txt, const std::locale& locale)
{
	return convertToWStr(txt, locale).length();
}

std::wstring locale::convertToWStr(const std::string& txt, const std::locale& locale)
{
	return boost::locale::conv::to_utf<wchar_t>(txt, locale);
}

std::string locale::convertFromWStr(const std::wstring& txt, const std::locale& locale)
{
	return boost::locale::conv::from_utf(txt, locale);
}

} // namespace rdo
<commit_msg> - исправлена инициализация локали<commit_after>/*!
  \copyright (c) RDO-Team, 2012
  \file      rdolocale.cpp
  \authors   Пройдаков Евгений (lord.tiran@gmail.com)
  \authors   Урусов Андрей (rdo@rk9.bmstu.ru)
  \date      20.10.2012
  \brief     Настройка локали для РДО
  \indent    4T
*/

// ----------------------------------------------------------------------- PLATFORM
// ----------------------------------------------------------------------- INCLUDES
#include <boost/math/special_functions/nonfinite_num_facets.hpp>
#include <iostream>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdolocale.h"
// --------------------------------------------------------------------------------

namespace rdo
{

void locale::init()
{
	rdo::locale& locale = get();

	std::locale sourceCodeLocale = locale.utf8();
	std::locale globalLocale(sourceCodeLocale, new boost::math::nonfinite_num_put<char>);
	std::locale::global(globalLocale);

	std::cout.imbue(globalLocale);
	std::cerr.imbue(globalLocale);
	std::clog.imbue(globalLocale);
	std::cin.imbue (globalLocale);
}

locale& locale::get()
{
	static rdo::locale locale;
	return locale;
}

locale::locale()
{
#ifdef COMPILER_VISUAL_STUDIO
	m_modelLocale = std::locale("Russian_Russia.1251");
#endif

	m_generator.locale_cache_enabled(true);
	system();
	utf8  ();
}

std::locale locale::generate(const std::string& name)
{
	return m_generator.generate(name);
}

std::locale locale::system()
{
	return generate("");
}

std::locale locale::utf8()
{
	return generate("ru_RU.UTF-8");
}

std::string locale::convert(const std::string& txt, const std::locale& to, const std::locale& from)
{
	return convert(txt, std::use_facet<boost::locale::info>(to).encoding(), std::use_facet<boost::locale::info>(from).encoding());
}

std::string locale::convert(const std::string& txt, const std::string& to, const std::string& from)
{
	std::string result;
	try
	{
		result = boost::locale::conv::between(txt, to, from);
	}
	catch (const boost::locale::conv::conversion_error&)
	{}
	catch (const boost::locale::conv::invalid_charset_error&)
	{}
	return result;
}

std::string locale::convertToCLocale(const std::string& txt, const std::locale& from)
{
	return convert(txt, getCLocaleName(), std::use_facet<boost::locale::info>(from).encoding());
}

std::string locale::convertFromCLocale(const std::string& txt, const std::locale& to)
{
	return convert(txt, std::use_facet<boost::locale::info>(to).encoding(), getCLocaleName());
}

std::string locale::getCLocaleName()
{
	return "CP1251";
}

unsigned int locale::length(const std::string& txt, const std::locale& locale)
{
	return convertToWStr(txt, locale).length();
}

std::wstring locale::convertToWStr(const std::string& txt, const std::locale& locale)
{
	return boost::locale::conv::to_utf<wchar_t>(txt, locale);
}

std::string locale::convertFromWStr(const std::wstring& txt, const std::locale& locale)
{
	return boost::locale::conv::from_utf(txt, locale);
}

} // namespace rdo
<|endoftext|>


<commit_before>// https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
namespace BestTimeToBuyAndSellStock {
    class Solution {
    public:
        int maxProfit(vector<int> &prices) {

            int min = INT_MAX;
            int max = INT_MIN;
            int maxProfit = 0;
            for (int i = 0; i < prices.size(); i++) {
                if (prices[i] < min) {
                    min = prices[i];
                    max = min; // when update min price, always reset max price
                }

                if (prices[i] > max) {
                    max = prices[i];
                }

                int profit = max - min;
                if (profit > maxProfit) {
                    maxProfit = profit;
                }

            }

            return maxProfit;

        }
    };
}
<commit_msg>Update BestTimeToBuyAndSellStock.cc<commit_after>// https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
//
// Say you have an array for which the ith element is the price of a given stock on day i.
//
// If you were only permitted to complete at most one transaction (ie, buy one and sell
// one share of the stock), design an algorithm to find the maximum profit.

namespace BestTimeToBuyAndSellStock {
    class Solution {
    public:
        int maxProfit(vector<int> &prices) {

            int min = INT_MAX;
            int max = INT_MIN;
            int maxProfit = 0;
            for (int i = 0; i < prices.size(); i++) {
                if (prices[i] < min) {
                    min = prices[i];
                    max = min; // when update min price, always reset max price
                }

                if (prices[i] > max) {
                    max = prices[i];
                }

                int profit = max - min;
                if (profit > maxProfit) {
                    maxProfit = profit;
                }

            }

            return maxProfit;

        }
    };
}
<|endoftext|>


<commit_before>/** \file    patch_up_ppns_for_k10plus.cc
 *  \brief   Swaps out all persistent old PPN's with new PPN's.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2019, Library of the University of Tübingen

    This program 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.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <unordered_map>
#include <cstdlib>
#include <cstring>
#include "Compiler.h"
#include "DbConnection.h"
#include "ControlNumberGuesser.h"
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
#include "VuFind.h"

namespace {

void LoadMapping(MARC::Reader * const marc_reader, std::unordered_map<std::string, std::string> * const old_to_new_map) {
    while (const auto record = marc_reader->read()) {
        for (const auto &field : record.getTagRange("035")) {
            const auto subfield_a(field.getFirstSubfieldWithCode('a'));
            if (StringUtil::StartsWith(subfield_a, "(DE-576)"))
                old_to_new_map->emplace(subfield_a.substr(__builtin_strlen("(DE-576)")), record.getControlNumber());
        }
    }

    LOG_INFO("Found " + std::to_string(old_to_new_map->size()) + " mappings of old PPN's to new PPN's in \"" + marc_reader->getPath()
             + "\".\n");
}

} // unnamed namespace

int Main(int argc, char **argv) {
    ::progname = argv[0];

    if (argc < 2)
        ::Usage("marc_input1 [marc_input2 .. marc_inputN]");

    std::unordered_map<std::string, std::string> old_to_new_map;
    for (int arg_no(1); arg_no < argc; ++arg_no) {
        const auto marc_reader(MARC::Reader::Factory(argv[arg_no]));
        LoadMapping(marc_reader.get(), &old_to_new_map);
    }

    ControlNumberGuesser control_number_guesser;
    control_number_guesser.swapControlNumbers(old_to_new_map);

    std::string mysql_url;
    VuFind::GetMysqlURL(&mysql_url);
    DbConnection db_connection(mysql_url);

    return EXIT_SUCCESS;
}
<commit_msg>Added support for patching PPN's in the ixtheo database.<commit_after>/** \file    patch_up_ppns_for_k10plus.cc
 *  \brief   Swaps out all persistent old PPN's with new PPN's.
 *  \author  Dr. Johannes Ruscheinski
 */

/*
    Copyright (C) 2019, Library of the University of Tübingen

    This program 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.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <unordered_map>
#include <cstdlib>
#include <cstring>
#include "Compiler.h"
#include "DbConnection.h"
#include "DbResultSet.h"
#include "DbRow.h"
#include "ControlNumberGuesser.h"
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
#include "VuFind.h"

namespace {

void LoadMapping(MARC::Reader * const marc_reader, std::unordered_map<std::string, std::string> * const old_to_new_map) {
    while (const auto record = marc_reader->read()) {
        for (const auto &field : record.getTagRange("035")) {
            const auto subfield_a(field.getFirstSubfieldWithCode('a'));
            if (StringUtil::StartsWith(subfield_a, "(DE-576)"))
                old_to_new_map->emplace(subfield_a.substr(__builtin_strlen("(DE-576)")), record.getControlNumber());
        }
    }

    LOG_INFO("Found " + std::to_string(old_to_new_map->size()) + " mappings of old PPN's to new PPN's in \"" + marc_reader->getPath()
             + "\".\n");
}

void PatchKeywordTranslations(DbConnection * const db_connection, const std::unordered_map<std::string, std::string> &old_to_new_map) {
    db_connection->queryOrDie("SELECT DISTINCT ppn FROM ixtheo.keyword_translations");
    auto result_set(db_connection->getLastResultSet());
    unsigned replacement_count(0);
    while (const DbRow row = result_set.getNextRow()) {
        const auto old_and_new(old_to_new_map.find(row["ppn"]));
        if (old_and_new != old_to_new_map.cend()) {
            db_connection->queryOrDie("UPDATE IGNORE ixtheo.keyword_translations SET ppn='" + old_and_new->second
                                      + "' WHERE ppn='" + old_and_new->first + "'");
            ++replacement_count;
        }
    }

    LOG_INFO("Replaced " + std::to_string(replacement_count) + " PPN's in ixtheo.keyword_translations.");
}

} // unnamed namespace

int Main(int argc, char **argv) {
    ::progname = argv[0];

    if (argc < 2)
        ::Usage("marc_input1 [marc_input2 .. marc_inputN]");

    std::unordered_map<std::string, std::string> old_to_new_map;
    for (int arg_no(1); arg_no < argc; ++arg_no) {
        const auto marc_reader(MARC::Reader::Factory(argv[arg_no]));
        LoadMapping(marc_reader.get(), &old_to_new_map);
    }

    ControlNumberGuesser control_number_guesser;
    control_number_guesser.swapControlNumbers(old_to_new_map);

    std::string mysql_url;
    VuFind::GetMysqlURL(&mysql_url);
    DbConnection db_connection(mysql_url);

    PatchKeywordTranslations(&db_connection, old_to_new_map);

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tools.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 15:00:54 $
 *
 *  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_cppcanvas.hxx"

#include <tools.hxx>

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

namespace cppcanvas
{
    namespace tools
    {
        uno::Sequence< double > intSRGBAToDoubleSequence( const uno::Reference< rendering::XGraphicDevice >&,
                                                          Color::IntSRGBA                                   aColor  )
        {
            uno::Sequence< double > aRes( 4 );

            aRes[0] = getRed(aColor) / 255.0;
            aRes[1] = getGreen(aColor) / 255.0;
            aRes[2] = getBlue(aColor) / 255.0;
            aRes[3] = getAlpha(aColor) / 255.0;

            return aRes;
        }

        Color::IntSRGBA doubleSequenceToIntSRGBA( const uno::Reference< rendering::XGraphicDevice >&,
                                                  const uno::Sequence< double >&                    rColor  )
        {
            return makeColor( static_cast<sal_uInt8>( 255*rColor[0] + .5 ),
                              static_cast<sal_uInt8>( 255*rColor[1] + .5 ),
                              static_cast<sal_uInt8>( 255*rColor[2] + .5 ),
                              static_cast<sal_uInt8>( 255*rColor[3] + .5 ) );
        }
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.46); FILE MERGED 2008/03/31 13:07:08 rt 1.7.46.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: tools.cxx,v $
 * $Revision: 1.8 $
 *
 * 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_cppcanvas.hxx"

#include <tools.hxx>

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

namespace cppcanvas
{
    namespace tools
    {
        uno::Sequence< double > intSRGBAToDoubleSequence( const uno::Reference< rendering::XGraphicDevice >&,
                                                          Color::IntSRGBA                                   aColor  )
        {
            uno::Sequence< double > aRes( 4 );

            aRes[0] = getRed(aColor) / 255.0;
            aRes[1] = getGreen(aColor) / 255.0;
            aRes[2] = getBlue(aColor) / 255.0;
            aRes[3] = getAlpha(aColor) / 255.0;

            return aRes;
        }

        Color::IntSRGBA doubleSequenceToIntSRGBA( const uno::Reference< rendering::XGraphicDevice >&,
                                                  const uno::Sequence< double >&                    rColor  )
        {
            return makeColor( static_cast<sal_uInt8>( 255*rColor[0] + .5 ),
                              static_cast<sal_uInt8>( 255*rColor[1] + .5 ),
                              static_cast<sal_uInt8>( 255*rColor[2] + .5 ),
                              static_cast<sal_uInt8>( 255*rColor[3] + .5 ) );
        }
    }
}
<|endoftext|>


<commit_before>//
// Created by dar on 11/27/15.
//

#include <stdio.h>
#include <stdlib.h>
#include <gui/GuiText.h>
#include <gui/GuiButton.h>
#include "Game.h"
#include "../core/Core.h"
#include "../core/map/TiledTxtMapLoader.h"
#include "render/RenderManager.h"
#include "InputManager.h"
#include <core/map/entity/EntityBullet.h>
#include <gui/GuiTextBubble.h>
#include <core/map/entity/EntityDoor.h>
#include "../logging.h"

Game::Game(const std::function<bool(Window *window)> &switchWindow) : Window(switchWindow) {
    initShapeDefinitions();
    MapLoader *mapLoader = new TiledTxtMapLoader("test_map");
    Map *bmap = mapLoader->loadMap();
    this->core = new Core(bmap);
    delete mapLoader;

    double ringScale = 2 * this->core->getBlockSize();
    this->entityRotationRing = new GuiElement(GUI_TOP_LEFT, 0, 0, ringScale, ringScale, 6);
    this->entityRotationRing->setVisible(false);
    this->entityRotationRing->setAngle(2);
    this->guiElements.push_back(this->entityRotationRing);

    GuiElement *character = new GuiElement(GUI_TOP_RIGHT, 0, 50, 150, 150, 7);
    this->guiElements.push_back(character);
    GuiElement *window = new GuiTextBubble(GUI_TOP_RIGHT, 160, 60, 400, 170);
    this->guiElements.push_back(window);
    GuiText *text = new GuiText(string("Hey, I am Willy. I will \nguide you around this \nplace. I am the \nghost from the blah \nblah blah blah..."), -500, 73, GUI_TOP_LEFT, 24, 0x666666FF, 0);
    this->guiElements.push_back(text);
    this->popup[0] = character;
    this->popup[1] = window;
    this->popup[2] = text;

    GuiText *t = new GuiText(string("Dev Build: ") + __DATE__ + " " + __TIME__, 15, 15, GUI_BOTTOM_LEFT, 32, 0xFFFFFFFF, 0);
    this->guiElements.push_back(t);
}

void Game::reload(unsigned int windowWidth, unsigned int windowHeight) {
    for (GuiElement *e : this->guiElements) {
        e->reinit(windowWidth, windowHeight);
    }

    this->windowWidth = windowWidth;
    this->windowHeight = windowHeight;
    SDL_StartTextInput();
}

void Game::tick(double deltaTime) {
    this->core->getMap()->update();
    this->core->getMap()->getWorld()->Step(deltaTime, 8, 3);
    for (int i = 0; i < this->core->getMap()->getEntities().size(); i++) {
        Entity *entity = this->core->getMap()->getEntities().at(i);
        if (entity->isToBeDeleted()) {
            this->core->getMap()->removeEntity(entity);
            i--;
        }
    }

    bool popupVisible = ((GuiText *) this->popup[2])->getString().size() > 0;
    static float alpha = 0.0f;
    alpha += deltaTime * 0.75;
    if (alpha > 1) alpha = 1;
    for (int i = 0; i < 3; i++) {
        this->popup[i]->setVisible(popupVisible);
        int color = this->popup[i]->getColor() & 0xFFFFFF00;
        color |= (int) (alpha * 255);
        this->popup[i]->setColor(color);
    }
    this->popup[2]->setX(this->popup[1]->getX() + 10);

    double dx = (this->core->getPlayer()->getX() + this->core->getPlayer()->getWidth() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamX();
    double dy = (this->core->getPlayer()->getY() + this->core->getPlayer()->getHeight() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamY();
    if (abs(dx) > 2) this->core->setCamX(-this->core->getCamX() + (dx) * 0.05);
    if (abs(dy) > 2) this->core->setCamY(-this->core->getCamY() + (dy) * 0.05);

    double camX = this->core->getCamX(), camY = this->core->getCamY();
    if (-camX < this->windowWidth / 2 - this->core->getBlockSize() * this->core->getGeneralScale()) {
        this->core->setCamX(this->windowWidth / 2 - this->core->getBlockSize() * this->core->getGeneralScale());
    }
    if (-camY < this->windowHeight / 2 - this->core->getBlockSize() * this->core->getGeneralScale()) {
        this->core->setCamY(this->windowHeight / 2 - this->core->getBlockSize() * this->core->getGeneralScale());
    }
    if (-camX > -(signed) this->windowWidth / 2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) {
        this->core->setCamX(-(signed) this->windowWidth / 2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale());
    }
    if (-camY > -(signed) this->windowHeight / 2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) {
        this->core->setCamY(-(signed) this->windowHeight / 2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale());
    }
}

void Game::handleKeyboard(const Keypress *const keypress) {
    if (keypress[SDLK_c].isPressed()) {
        double angle = atan2(0, 0) + M_PI; //TODO
        EntityBullet *p = new EntityBullet(this->core->getMap(), angle, 1);
        p->setX(this->core->getPlayer()->getX() - (p->getWidth()) + 0.5 * cos(angle));
        p->setY(this->core->getPlayer()->getY() - (p->getHeight()) + 0.5 * sin(angle));
        this->core->getMap()->addEntity(p);
    }
    if (keypress[SDLK_n].isPressed()) {
        EntityDoor *p = new EntityDoor(this->core->getMap(), 0);
        p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() / 2);
        p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() / 2);
        this->core->getMap()->addEntity(p);
    }
    if (keypress[SDLK_m].isPressed()) {
        SimpleShape *p = new SimpleShape(this->core->getMap(), (unsigned int) (rand() % 3));
        p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() / 2);
        p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() / 2);
        this->core->getMap()->addEntity(p);
    }
    if (keypress[SDLK_k].isPressed()) {
        if (this->core->getPlayer()->getToy() == nullptr) {
            this->core->getPlayer()->setToy();
        } else {
            this->core->getPlayer()->eject();
        }
    }
    double playerSpeed = this->core->getPlayer()->getSpeed();
    if (keypress[SDLK_w].isDown()) {
        this->core->getPlayer()->applyImpulse(0, -playerSpeed);
    }
    if (keypress[SDLK_s].isDown()) {
        this->core->getPlayer()->applyImpulse(0, playerSpeed);
    }
    if (keypress[SDLK_a].isDown()) {
        this->core->getPlayer()->applyImpulse(-playerSpeed, 0);
    }
    if (keypress[SDLK_d].isDown()) {
        this->core->getPlayer()->applyImpulse(playerSpeed, 0);
    }
    if (keypress[SDLK_q].isPressed()) {
        this->core->stop();
    }
    if (keypress[SDLK_p].isPressed()) {
        this->core->getMap()->saveEntities();
    }
    if (keypress[SDLK_MINUS].isDown()) {
        this->core->setBlockSize(this->core->getBlockSize() - 0.15);
    }
    if (keypress[SDLK_EQUALS].isDown()) {
        this->core->setBlockSize(this->core->getBlockSize() + 0.15);
    }
}

void Game::handleClick(const TouchPoint *const p) {
    float x = (float) ((-this->core->getCamX() - (double) this->windowWidth / 2 + p->x) / this->core->getGeneralScale() / this->core->getBlockSize() + 0.5);
    float y = (float) ((-this->core->getCamY() - (double) this->windowHeight / 2 + p->y) / this->core->getGeneralScale() / this->core->getBlockSize() + 0.5);
    if (p->id == SDL_BUTTON_LEFT) {
        if (p->state == 0) {
            this->heldEntity = this->getEntityAt(x, y);
            int i = 0;
        } else if (p->state == 2) {
            if (this->heldEntity != nullptr && !this->entityRotationRing->isVisible()) {
                Entity *e = this->heldEntity;
                e->setX(x + e->getWidth() / 2);
                e->setY(y + e->getHeight() / 2);
            }
        } else if (p->state == 1) {
            if (this->heldEntity == nullptr) {
                SimpleShape *s = new SimpleShape(this->core->getMap(), (unsigned int) (rand() % 3));
                s->setX(x + s->getWidth() / 2);
                s->setY(y + s->getWidth() / 2);
                this->core->getMap()->addEntity(s);
            } else {
                this->heldEntity = nullptr;
                if (this->entityRotationRing->isVisible()) {
                    this->entityRotationRing->setVisible(false);
                    SDL_ShowCursor(true);
                    SDL_WarpMouseGlobal(this->mouseLockX, this->mouseLockY);
                }
            }
        }
    } else if (p->id == SDL_BUTTON_MIDDLE) {
        if (p->state == 0) {
            this->heldEntity = this->getEntityAt(x, y);
        } else if (p->state == 1) {
            if (this->heldEntity != nullptr && this->getEntityAt(x, y) == this->heldEntity) {
                this->heldEntity->remove();
            }
        }
    } else if (p->id == SDL_BUTTON_RIGHT) {
        if (p->state == 0) {
            if (this->heldEntity != nullptr) {
                this->entityRotationRing->setX(p->x - this->entityRotationRing->getWidth() / 2);
                this->entityRotationRing->setY(p->y - this->entityRotationRing->getHeight() / 2);
                this->entityRotationRing->setAngle(this->heldEntity->getAngle());
                this->entityRotationRing->setVisible(true);
                SDL_GetGlobalMouseState(&this->mouseLockX, &this->mouseLockY);
                SDL_ShowCursor(false);
            }
        } else if (p->state == 2) {
            if (this->heldEntity != nullptr) {
                int x, y;
                SDL_GetGlobalMouseState(&x, &y);
                double angle = 10.0 * (x - this->mouseLockX) / this->windowWidth;
                this->entityRotationRing->setAngle(angle);
                this->heldEntity->setAngle(angle);
            }
        } else if (p->state == 1) {
            if (this->entityRotationRing->isVisible()) {
                this->entityRotationRing->setVisible(false);
                SDL_ShowCursor(true);
                SDL_WarpMouseGlobal(this->mouseLockX, this->mouseLockY);
            }
        }
    }
}

Entity *Game::getEntityAt(float x, float y) {
    for (Entity *e : this->core->getMap()->getEntities()) {
        if (x >= e->getX() - e->getWidth() - 0.25 && x <= e->getX() + 0.25 &&
            y >= e->getY() - e->getHeight() - 0.25 && y <= e->getY() + 0.25) {
            return e;
        }
    }
    return nullptr;
}

Game::~Game() {
    SDL_StopTextInput();
    delete this->core;
}
<commit_msg>Added random switch for entity spawning.<commit_after>//
// Created by dar on 11/27/15.
//

#include <stdio.h>
#include <stdlib.h>
#include <gui/GuiText.h>
#include <gui/GuiButton.h>
#include "Game.h"
#include "../core/Core.h"
#include "../core/map/TiledTxtMapLoader.h"
#include "render/RenderManager.h"
#include "InputManager.h"
#include <core/map/entity/EntityBullet.h>
#include <gui/GuiTextBubble.h>
#include <core/map/entity/EntityDoor.h>
#include <core/map/entity/EntityFurniture.h>
#include "../logging.h"

Game::Game(const std::function<bool(Window *window)> &switchWindow) : Window(switchWindow) {
    initShapeDefinitions();
    MapLoader *mapLoader = new TiledTxtMapLoader("test_map");
    Map *bmap = mapLoader->loadMap();
    this->core = new Core(bmap);
    delete mapLoader;

    double ringScale = 2 * this->core->getBlockSize();
    this->entityRotationRing = new GuiElement(GUI_TOP_LEFT, 0, 0, ringScale, ringScale, 6);
    this->entityRotationRing->setVisible(false);
    this->entityRotationRing->setAngle(2);
    this->guiElements.push_back(this->entityRotationRing);

    GuiElement *character = new GuiElement(GUI_TOP_RIGHT, 0, 50, 150, 150, 7);
    this->guiElements.push_back(character);
    GuiElement *window = new GuiTextBubble(GUI_TOP_RIGHT, 160, 60, 400, 170);
    this->guiElements.push_back(window);
    GuiText *text = new GuiText(string("Hey, I am Willy. I will \nguide you around this \nplace. I am the \nghost from the blah \nblah blah blah..."), -500, 73, GUI_TOP_LEFT, 24, 0x666666FF, 0);
    this->guiElements.push_back(text);
    this->popup[0] = character;
    this->popup[1] = window;
    this->popup[2] = text;

    GuiText *t = new GuiText(string("Dev Build: ") + __DATE__ + " " + __TIME__, 15, 15, GUI_BOTTOM_LEFT, 32, 0xFFFFFFFF, 0);
    this->guiElements.push_back(t);
}

void Game::reload(unsigned int windowWidth, unsigned int windowHeight) {
    for (GuiElement *e : this->guiElements) {
        e->reinit(windowWidth, windowHeight);
    }

    this->windowWidth = windowWidth;
    this->windowHeight = windowHeight;
    SDL_StartTextInput();
}

void Game::tick(double deltaTime) {
    this->core->getMap()->update();
    this->core->getMap()->getWorld()->Step(deltaTime, 8, 3);
    for (int i = 0; i < this->core->getMap()->getEntities().size(); i++) {
        Entity *entity = this->core->getMap()->getEntities().at(i);
        if (entity->isToBeDeleted()) {
            this->core->getMap()->removeEntity(entity);
            i--;
        }
    }

    bool popupVisible = ((GuiText *) this->popup[2])->getString().size() > 0;
    static float alpha = 0.0f;
    alpha += deltaTime * 0.75;
    if (alpha > 1) alpha = 1;
    for (int i = 0; i < 3; i++) {
        this->popup[i]->setVisible(popupVisible);
        int color = this->popup[i]->getColor() & 0xFFFFFF00;
        color |= (int) (alpha * 255);
        this->popup[i]->setColor(color);
    }
    this->popup[2]->setX(this->popup[1]->getX() + 10);

    double dx = (this->core->getPlayer()->getX() + this->core->getPlayer()->getWidth() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamX();
    double dy = (this->core->getPlayer()->getY() + this->core->getPlayer()->getHeight() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamY();
    if (abs(dx) > 2) this->core->setCamX(-this->core->getCamX() + (dx) * 0.05);
    if (abs(dy) > 2) this->core->setCamY(-this->core->getCamY() + (dy) * 0.05);

    double camX = this->core->getCamX(), camY = this->core->getCamY();
    if (-camX < this->windowWidth / 2 - this->core->getBlockSize() * this->core->getGeneralScale()) {
        this->core->setCamX(this->windowWidth / 2 - this->core->getBlockSize() * this->core->getGeneralScale());
    }
    if (-camY < this->windowHeight / 2 - this->core->getBlockSize() * this->core->getGeneralScale()) {
        this->core->setCamY(this->windowHeight / 2 - this->core->getBlockSize() * this->core->getGeneralScale());
    }
    if (-camX > -(signed) this->windowWidth / 2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) {
        this->core->setCamX(-(signed) this->windowWidth / 2 + (this->core->getMap()->getWidth() - 1) * this->core->getBlockSize() * this->core->getGeneralScale());
    }
    if (-camY > -(signed) this->windowHeight / 2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale()) {
        this->core->setCamY(-(signed) this->windowHeight / 2 + (this->core->getMap()->getHeight() - 1) * this->core->getBlockSize() * this->core->getGeneralScale());
    }
}

void Game::handleKeyboard(const Keypress *const keypress) {
    if (keypress[SDLK_c].isPressed()) {
        double angle = atan2(0, 0) + M_PI; //TODO
        EntityBullet *p = new EntityBullet(this->core->getMap(), angle, 1);
        p->setX(this->core->getPlayer()->getX() - (p->getWidth()) + 0.5 * cos(angle));
        p->setY(this->core->getPlayer()->getY() - (p->getHeight()) + 0.5 * sin(angle));
        this->core->getMap()->addEntity(p);
    }
    if (keypress[SDLK_n].isPressed()) {
        Entity *p;
        switch (rand() % 3) {
            case 0:
                p = new EntityFridge(this->core->getMap());
                break;
            case 1:
                p = new EntityTruck(this->core->getMap());
                break;
            case 2:
                p = new EntityBulldozer(this->core->getMap());
                break;
            default:
                p = new EntityDoor(this->core->getMap(), 0);
                break;
        }
        p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() / 2);
        p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() / 2);
        this->core->getMap()->addEntity(p);
    }
    if (keypress[SDLK_m].isPressed()) {
        SimpleShape *p = new SimpleShape(this->core->getMap(), (unsigned int) (rand() % 3));
        p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() / 2);
        p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() / 2);
        this->core->getMap()->addEntity(p);
    }
    if (keypress[SDLK_k].isPressed()) {
        if (this->core->getPlayer()->getToy() == nullptr) {
            this->core->getPlayer()->setToy();
        } else {
            this->core->getPlayer()->eject();
        }
    }
    double playerSpeed = this->core->getPlayer()->getSpeed();
    if (keypress[SDLK_w].isDown()) {
        this->core->getPlayer()->applyImpulse(0, -playerSpeed);
    }
    if (keypress[SDLK_s].isDown()) {
        this->core->getPlayer()->applyImpulse(0, playerSpeed);
    }
    if (keypress[SDLK_a].isDown()) {
        this->core->getPlayer()->applyImpulse(-playerSpeed, 0);
    }
    if (keypress[SDLK_d].isDown()) {
        this->core->getPlayer()->applyImpulse(playerSpeed, 0);
    }
    if (keypress[SDLK_q].isPressed()) {
        this->core->stop();
    }
    if (keypress[SDLK_p].isPressed()) {
        this->core->getMap()->saveEntities();
    }
    if (keypress[SDLK_MINUS].isDown()) {
        this->core->setBlockSize(this->core->getBlockSize() - 0.15);
    }
    if (keypress[SDLK_EQUALS].isDown()) {
        this->core->setBlockSize(this->core->getBlockSize() + 0.15);
    }
}

void Game::handleClick(const TouchPoint *const p) {
    float x = (float) ((-this->core->getCamX() - (double) this->windowWidth / 2 + p->x) / this->core->getGeneralScale() / this->core->getBlockSize() + 0.5);
    float y = (float) ((-this->core->getCamY() - (double) this->windowHeight / 2 + p->y) / this->core->getGeneralScale() / this->core->getBlockSize() + 0.5);
    if (p->id == SDL_BUTTON_LEFT) {
        if (p->state == 0) {
            this->heldEntity = this->getEntityAt(x, y);
            int i = 0;
        } else if (p->state == 2) {
            if (this->heldEntity != nullptr && !this->entityRotationRing->isVisible()) {
                Entity *e = this->heldEntity;
                e->setX(x + e->getWidth() / 2);
                e->setY(y + e->getHeight() / 2);
            }
        } else if (p->state == 1) {
            if (this->heldEntity == nullptr) {
                SimpleShape *s = new SimpleShape(this->core->getMap(), (unsigned int) (rand() % 3));
                s->setX(x + s->getWidth() / 2);
                s->setY(y + s->getWidth() / 2);
                this->core->getMap()->addEntity(s);
            } else {
                this->heldEntity = nullptr;
                if (this->entityRotationRing->isVisible()) {
                    this->entityRotationRing->setVisible(false);
                    SDL_ShowCursor(true);
                    SDL_WarpMouseGlobal(this->mouseLockX, this->mouseLockY);
                }
            }
        }
    } else if (p->id == SDL_BUTTON_MIDDLE) {
        if (p->state == 0) {
            this->heldEntity = this->getEntityAt(x, y);
        } else if (p->state == 1) {
            if (this->heldEntity != nullptr && this->getEntityAt(x, y) == this->heldEntity) {
                this->heldEntity->remove();
            }
        }
    } else if (p->id == SDL_BUTTON_RIGHT) {
        if (p->state == 0) {
            if (this->heldEntity != nullptr) {
                this->entityRotationRing->setX(p->x - this->entityRotationRing->getWidth() / 2);
                this->entityRotationRing->setY(p->y - this->entityRotationRing->getHeight() / 2);
                this->entityRotationRing->setAngle(this->heldEntity->getAngle());
                this->entityRotationRing->setVisible(true);
                SDL_GetGlobalMouseState(&this->mouseLockX, &this->mouseLockY);
                SDL_ShowCursor(false);
            }
        } else if (p->state == 2) {
            if (this->heldEntity != nullptr) {
                int x, y;
                SDL_GetGlobalMouseState(&x, &y);
                double angle = 10.0 * (x - this->mouseLockX) / this->windowWidth;
                this->entityRotationRing->setAngle(angle);
                this->heldEntity->setAngle(angle);
            }
        } else if (p->state == 1) {
            if (this->entityRotationRing->isVisible()) {
                this->entityRotationRing->setVisible(false);
                SDL_ShowCursor(true);
                SDL_WarpMouseGlobal(this->mouseLockX, this->mouseLockY);
            }
        }
    }
}

Entity *Game::getEntityAt(float x, float y) {
    for (Entity *e : this->core->getMap()->getEntities()) {
        if (x >= e->getX() - e->getWidth() - 0.25 && x <= e->getX() + 0.25 &&
            y >= e->getY() - e->getHeight() - 0.25 && y <= e->getY() + 0.25) {
            return e;
        }
    }
    return nullptr;
}

Game::~Game() {
    SDL_StopTextInput();
    delete this->core;
}
<|endoftext|>