<commit_before>#include "dynet/io.h"
#include "dynet/tensor.h"
#include "dynet/except.h"

using namespace std;
using namespace dynet;

bool valid_key(const std::string & s) {
  if (s == "/") return false;
  auto it = std::find_if(s.begin(), s.end(),
                         [] (char ch) { return ch == ' ' || ch == '#';});
  return it == s.end();
}

TextFileSaver::TextFileSaver(const string & filename, bool append) :
        datastream(filename, append ? ofstream::app : ofstream::out) {
  if(!datastream)
    DYNET_RUNTIME_ERR("Could not write model to " << filename);
}

void TextFileSaver::save(const ParameterCollection & model,
                         const string & key) {
  if (!valid_key(key))
    DYNET_INVALID_ARG("Key could not include ' ' or '#': " << key);
  const ParameterCollectionStorage & storage = model.get_storage();
  if(key.size() == 0) {
    for (auto & p : storage.params) save(*p, key);
    for (auto & p : storage.lookup_params) save(*p, key);
  } else {
    size_t strip_size = model.get_fullname().size();
    for (auto & p : storage.params)
      save(*p, key + p->name.substr(strip_size));
    for (auto & p : storage.lookup_params)
      save(*p, key + p->name.substr(strip_size));
  }
}

void TextFileSaver::save(const Parameter & param,
                         const string & key) {
  if (!valid_key(key))
    DYNET_INVALID_ARG("Key could not include ' ' or '#': " << key);
  save(*param.p, key);
}

void TextFileSaver::save(const LookupParameter & param,
                         const string & key) {
  if (!valid_key(key))
    DYNET_INVALID_ARG("Key could not include ' ' or '#': " << key);
  save(*param.p, key);
}

void TextFileSaver::save(const ParameterStorage & p,
                         const string & key) {
  std::ostringstream buffer;
  buffer << dynet::as_vector(p.values) << endl;
  buffer << dynet::as_vector(p.g) << endl;
  datastream << "#Parameter# " << (key.size() > 0 ? key : p.name) << ' '
    << p.dim << ' ' << buffer.str().size() << endl;
  datastream.write(buffer.str().c_str(), buffer.str().size());
}

void TextFileSaver::save(const LookupParameterStorage & p,
                         const string & key) {
  std::ostringstream buffer;
  buffer << dynet::as_vector(p.all_values) << endl;
  buffer << dynet::as_vector(p.all_grads) << endl;
  datastream << "#LookupParameter# " << (key.size() > 0 ? key : p.name) << ' ' << p.all_dim << ' ' << buffer.str().size() << endl;
  datastream.write(buffer.str().c_str(), buffer.str().size());
}

TextFileLoader::TextFileLoader(const string & filename) :
        dataname(filename) { }

void TextFileLoader::populate(ParameterCollection & model, const string & key) {
  ifstream datastream(dataname);
  if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname);
  string line, type, name;
  Dim dim;
  size_t byte_count = 0;
  vector<float> values;
  Tensor *value_t, *grad_t;
  size_t param_id = 0, lookup_id = 0;
  ParameterCollectionStorage & storage = model.get_storage();
  string key_ = key;
  if (key_.back() != '/') key_ += "/";
  while(getline(datastream, line)) {
    { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }
    // Skip ones that don't match
    if(key.size() != 0 && name.substr(0, key_.size()) != key_) {
      size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;
      datastream.seekg(offset);
      continue;
    // Load a parameter
    } else if(type == "#Parameter#") {
      values.resize(dim.size());
      if(param_id >= storage.params.size())
        DYNET_RUNTIME_ERR("Too many parameters to load in populated model at " << name);
      ParameterStorage & param = *storage.params[param_id++];
      if(param.dim != dim)
        DYNET_RUNTIME_ERR("Dimensions of parameter " << name << " looked up from file (" << dim <<
                            ") do not match parameters to be populated (" << param.dim << ")");
      value_t = &param.values;
      grad_t = &param.g;
    // Load a lookup parameter
    } else if(type == "#LookupParameter#") {
      values.resize(dim.size());
      if(lookup_id >= storage.lookup_params.size())
        DYNET_RUNTIME_ERR("Too many lookup parameters in populated model at " << name);
      LookupParameterStorage & param = *storage.lookup_params[lookup_id++];
      if(param.all_dim != dim)
        DYNET_RUNTIME_ERR("Dimensions of lookup parameter " << name << " lookup up from file (" << dim <<
                            ") do not match parameters to be populated (" << param.all_dim << ")");
      value_t = &param.all_values;
      grad_t = &param.all_grads;
    } else {
      DYNET_RUNTIME_ERR("Bad parameter specification in model: " << line);
    }
    { getline(datastream, line); istringstream iss(line); iss >> values; }
    TensorTools::set_elements(*value_t, values);
    { getline(datastream, line); istringstream iss(line); iss >> values; }
    TensorTools::set_elements(*grad_t, values);
  }
  if(param_id != storage.params.size() || lookup_id != storage.lookup_params.size())
    DYNET_RUNTIME_ERR("Number of parameter/lookup parameter objects loaded from file (" <<
                      param_id << '/' << lookup_id << ") did not match number to be populated (" <<
                      storage.params.size() << '/' << storage.lookup_params.size() << ')');
}

void TextFileLoader::populate(Parameter & param,
                    const string & key) {
  if(key == "")
    DYNET_INVALID_ARG("TextFileLoader.populate() requires non-empty key");
  ifstream datastream(dataname);
  if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname);
  string line, type, name;
  Dim dim;
  size_t byte_count = 0;
  while(getline(datastream, line)) {
    { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }
    if(type == "#Parameter#" && name == key) {
      if(param.p->dim != dim)
        DYNET_RUNTIME_ERR("Attempted to populate parameter where arguments don't match (" << param.p->dim << " != " << dim << ")");
      vector<float> values(dim.size());
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(param.get_storage().values, values);
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(param.get_storage().g, values);
      return;
    } else {
      size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;
      datastream.seekg(offset);
    }
  }
  DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file");
}

void TextFileLoader::populate(LookupParameter & lookup_param,
                              const string & key) {
  if(key == "")
    DYNET_INVALID_ARG("TextFileLoader.populate() requires non-empty key");
  ifstream datastream(dataname);
  if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname);
  string line, type, name;
  Dim dim;
  size_t byte_count = 0;
  while(getline(datastream, line)) {
    { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }
    if(type == "#LookupParameter#" && name == key) {
      if(lookup_param.p->all_dim != dim)
        DYNET_RUNTIME_ERR("Attempted to populate lookup parameter where arguments don't match (" << lookup_param.p->all_dim << " != " << dim << ")");
      vector<float> values(dim.size());
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(lookup_param.get_storage().all_values, values);
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(lookup_param.get_storage().all_grads, values);
      return;
    } else {
      size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;
      datastream.seekg(offset);
    }
  }
  DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file");
}

Parameter TextFileLoader::load_param(ParameterCollection & model,
                                     const string & key) {
  if(key == "")
    DYNET_INVALID_ARG("TextFileLoader.load_param() requires non-empty key");
  ifstream datastream(dataname);
  if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname);
  string line, type, name;
  Dim dim;
  size_t byte_count = 0;
  while(getline(datastream, line)) {
    { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }
    if(type == "#Parameter#" && name == key) {
      Parameter param = model.add_parameters(dim);
      param.get_storage().name = name;
      vector<float> values(dim.size());
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(param.get_storage().values, values);
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(param.get_storage().g, values);
      return param;
    } else {
      size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;
      datastream.seekg(offset);
    }
  }
  DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file");
}

LookupParameter TextFileLoader::load_lookup_param(ParameterCollection & model,
                                                  const string & key) {
  if(key == "")
    DYNET_INVALID_ARG("TextFileLoader.load_lookup_param() requires non-empty key");
  ifstream datastream(dataname);
  if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname);
  string line, type, name;
  Dim dim;
  size_t byte_count = 0;
  while(getline(datastream, line)) {
    { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }
    if(type == "#LookupParameter#" && name == key) {
      vector<float> values(dim.size());
      size_t size = dim[dim.nd-1]; dim.nd--;
      LookupParameter lookup_param = model.add_lookup_parameters(size, dim);
      lookup_param.get_storage().name = name;
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(lookup_param.get_storage().all_values, values);
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(lookup_param.get_storage().all_grads, values);
      return lookup_param;
    } else {
      size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;
      datastream.seekg(offset);
    }
  }
  DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file");
}
<commit_msg>add key check for ParameterCollection<commit_after>#include "dynet/io.h"
#include "dynet/tensor.h"
#include "dynet/except.h"
#include "dynet/str-util.h"

using namespace std;
using namespace dynet;

bool valid_key(const std::string & s) {
  if (s.size() == 0) return true;
  if (s == "/") return false;
  auto it = std::find_if(s.begin(), s.end(),
                         [] (char ch) { return ch == ' ' || ch == '#';});
  return it == s.end();
}

bool valid_pc_key(const std::string & s) {
  if (s.size() == 0) return true;
  if (!(startswith(s, "/") && endswith(s, "/"))) return false;
  return valid_key(s);
}

TextFileSaver::TextFileSaver(const string & filename, bool append) :
        datastream(filename, append ? ofstream::app : ofstream::out) {
  if(!datastream)
    DYNET_RUNTIME_ERR("Could not write model to " << filename);
}

void TextFileSaver::save(const ParameterCollection & model,
                         const string & key) {
  if (!valid_pc_key(key))
    DYNET_INVALID_ARG("Key should start with, end with '/' and could not include ' ' or '#': " << key);
  const ParameterCollectionStorage & storage = model.get_storage();
  if(key.size() == 0) {
    for (auto & p : storage.params) save(*p, key);
    for (auto & p : storage.lookup_params) save(*p, key);
  } else {
    size_t strip_size = model.get_fullname().size();
    for (auto & p : storage.params)
      save(*p, key + p->name.substr(strip_size));
    for (auto & p : storage.lookup_params)
      save(*p, key + p->name.substr(strip_size));
  }
}

void TextFileSaver::save(const Parameter & param,
                         const string & key) {
  if (!valid_key(key))
    DYNET_INVALID_ARG("Key could not include ' ' or '#': " << key);
  save(*param.p, key);
}

void TextFileSaver::save(const LookupParameter & param,
                         const string & key) {
  if (!valid_key(key))
    DYNET_INVALID_ARG("Key could not include ' ' or '#': " << key);
  save(*param.p, key);
}

void TextFileSaver::save(const ParameterStorage & p,
                         const string & key) {
  std::ostringstream buffer;
  buffer << dynet::as_vector(p.values) << endl;
  buffer << dynet::as_vector(p.g) << endl;
  datastream << "#Parameter# " << (key.size() > 0 ? key : p.name) << ' '
    << p.dim << ' ' << buffer.str().size() << endl;
  datastream.write(buffer.str().c_str(), buffer.str().size());
}

void TextFileSaver::save(const LookupParameterStorage & p,
                         const string & key) {
  std::ostringstream buffer;
  buffer << dynet::as_vector(p.all_values) << endl;
  buffer << dynet::as_vector(p.all_grads) << endl;
  datastream << "#LookupParameter# " << (key.size() > 0 ? key : p.name) << ' ' << p.all_dim << ' ' << buffer.str().size() << endl;
  datastream.write(buffer.str().c_str(), buffer.str().size());
}

TextFileLoader::TextFileLoader(const string & filename) :
        dataname(filename) { }

void TextFileLoader::populate(ParameterCollection & model, const string & key) {
  ifstream datastream(dataname);
  if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname);
  string line, type, name;
  Dim dim;
  size_t byte_count = 0;
  vector<float> values;
  Tensor *value_t, *grad_t;
  size_t param_id = 0, lookup_id = 0;
  ParameterCollectionStorage & storage = model.get_storage();
  string key_ = key;
  if (key_.back() != '/') key_ += "/";
  while(getline(datastream, line)) {
    { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }
    // Skip ones that don't match
    if(key.size() != 0 && name.substr(0, key_.size()) != key_) {
      size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;
      datastream.seekg(offset);
      continue;
    // Load a parameter
    } else if(type == "#Parameter#") {
      values.resize(dim.size());
      if(param_id >= storage.params.size())
        DYNET_RUNTIME_ERR("Too many parameters to load in populated model at " << name);
      ParameterStorage & param = *storage.params[param_id++];
      if(param.dim != dim)
        DYNET_RUNTIME_ERR("Dimensions of parameter " << name << " looked up from file (" << dim <<
                            ") do not match parameters to be populated (" << param.dim << ")");
      value_t = &param.values;
      grad_t = &param.g;
    // Load a lookup parameter
    } else if(type == "#LookupParameter#") {
      values.resize(dim.size());
      if(lookup_id >= storage.lookup_params.size())
        DYNET_RUNTIME_ERR("Too many lookup parameters in populated model at " << name);
      LookupParameterStorage & param = *storage.lookup_params[lookup_id++];
      if(param.all_dim != dim)
        DYNET_RUNTIME_ERR("Dimensions of lookup parameter " << name << " lookup up from file (" << dim <<
                            ") do not match parameters to be populated (" << param.all_dim << ")");
      value_t = &param.all_values;
      grad_t = &param.all_grads;
    } else {
      DYNET_RUNTIME_ERR("Bad parameter specification in model: " << line);
    }
    { getline(datastream, line); istringstream iss(line); iss >> values; }
    TensorTools::set_elements(*value_t, values);
    { getline(datastream, line); istringstream iss(line); iss >> values; }
    TensorTools::set_elements(*grad_t, values);
  }
  if(param_id != storage.params.size() || lookup_id != storage.lookup_params.size())
    DYNET_RUNTIME_ERR("Number of parameter/lookup parameter objects loaded from file (" <<
                      param_id << '/' << lookup_id << ") did not match number to be populated (" <<
                      storage.params.size() << '/' << storage.lookup_params.size() << ')');
}

void TextFileLoader::populate(Parameter & param,
                    const string & key) {
  if(key == "")
    DYNET_INVALID_ARG("TextFileLoader.populate() requires non-empty key");
  ifstream datastream(dataname);
  if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname);
  string line, type, name;
  Dim dim;
  size_t byte_count = 0;
  while(getline(datastream, line)) {
    { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }
    if(type == "#Parameter#" && name == key) {
      if(param.p->dim != dim)
        DYNET_RUNTIME_ERR("Attempted to populate parameter where arguments don't match (" << param.p->dim << " != " << dim << ")");
      vector<float> values(dim.size());
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(param.get_storage().values, values);
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(param.get_storage().g, values);
      return;
    } else {
      size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;
      datastream.seekg(offset);
    }
  }
  DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file");
}

void TextFileLoader::populate(LookupParameter & lookup_param,
                              const string & key) {
  if(key == "")
    DYNET_INVALID_ARG("TextFileLoader.populate() requires non-empty key");
  ifstream datastream(dataname);
  if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname);
  string line, type, name;
  Dim dim;
  size_t byte_count = 0;
  while(getline(datastream, line)) {
    { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }
    if(type == "#LookupParameter#" && name == key) {
      if(lookup_param.p->all_dim != dim)
        DYNET_RUNTIME_ERR("Attempted to populate lookup parameter where arguments don't match (" << lookup_param.p->all_dim << " != " << dim << ")");
      vector<float> values(dim.size());
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(lookup_param.get_storage().all_values, values);
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(lookup_param.get_storage().all_grads, values);
      return;
    } else {
      size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;
      datastream.seekg(offset);
    }
  }
  DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file");
}

Parameter TextFileLoader::load_param(ParameterCollection & model,
                                     const string & key) {
  if(key == "")
    DYNET_INVALID_ARG("TextFileLoader.load_param() requires non-empty key");
  ifstream datastream(dataname);
  if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname);
  string line, type, name;
  Dim dim;
  size_t byte_count = 0;
  while(getline(datastream, line)) {
    { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }
    if(type == "#Parameter#" && name == key) {
      Parameter param = model.add_parameters(dim);
      param.get_storage().name = name;
      vector<float> values(dim.size());
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(param.get_storage().values, values);
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(param.get_storage().g, values);
      return param;
    } else {
      size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;
      datastream.seekg(offset);
    }
  }
  DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file");
}

LookupParameter TextFileLoader::load_lookup_param(ParameterCollection & model,
                                                  const string & key) {
  if(key == "")
    DYNET_INVALID_ARG("TextFileLoader.load_lookup_param() requires non-empty key");
  ifstream datastream(dataname);
  if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname);
  string line, type, name;
  Dim dim;
  size_t byte_count = 0;
  while(getline(datastream, line)) {
    { istringstream iss(line); iss >> type >> name >> dim >> byte_count; }
    if(type == "#LookupParameter#" && name == key) {
      vector<float> values(dim.size());
      size_t size = dim[dim.nd-1]; dim.nd--;
      LookupParameter lookup_param = model.add_lookup_parameters(size, dim);
      lookup_param.get_storage().name = name;
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(lookup_param.get_storage().all_values, values);
      { getline(datastream, line); istringstream iss(line); iss >> values; }
      TensorTools::set_elements(lookup_param.get_storage().all_grads, values);
      return lookup_param;
    } else {
      size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count;
      datastream.seekg(offset);
    }
  }
  DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file");
}
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2014 GraphLab Inc.
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license. See the LICENSE file for details.
 */

#ifndef GRAPHLAB_UNITY_GL_GFRAME_HPP
#define GRAPHLAB_UNITY_GL_GFRAME_HPP

#include "gl_sframe.hpp"

namespace graphlab {
class gl_sframe;
class gl_sgraph;
class gl_sarray;

// Possible types of gl_gframe
enum class gframe_type_enum:int {VERTEX_GFRAME, EDGE_GFRAME};

/**
 * \ingroup gl_sdk
 *
 * A proxy for the \ref gl_sframe for the vertex and edge data of the SGRaph
 */
class gl_gframe : public gl_sframe {
 public:
  gl_gframe() = delete;
  gl_gframe(const gl_gframe&) = default;
  gl_gframe(gl_gframe&&) = default;
  gl_gframe& operator=(const gl_gframe&) = default;
  gl_gframe& operator=(gl_gframe&&) = default;

  /*
   * Construct gl_gframe from sgraph, and sframe.
   */
  gl_gframe(gl_sgraph*, gframe_type_enum);

  /*
   * Implicit converters
   */
  operator gl_sframe() const;
  operator std::shared_ptr<unity_sframe>() const;
  operator std::shared_ptr<unity_sframe_base>() const;

  /**
   * Returns number of rows. If type is VERTEX_GFRAME, the value
   * is also the number of vertices (or edges if type is EDGE_GFRAME)
   * in the \ref gl_sgraph.
   *
   * \see gl_sgraph::num_vertices
   * \see gl_sgraph::num_edges
   */
  size_t size() const override;

  /**
   * Returns number of columns. If type is VERTEX_GFRAME, the value
   * is also the number of vertex fields (or edge fields if type is EDGE_GFRAME)
   * in the \ref gl_sgraph.
   */
  size_t num_columns() const override;

  /**
   * Returns a list of column names. If type is VERTEX_GFRAME, the value
   * is also the names of the vertex fields (or edge fields if type is EDGE_GFRAME)
   * in the \ref gl_sgraph.
   *
   * \see gl_sgraph::get_vertex_fields
   * \see gl_sgraph::get_edge_fields
   */
  std::vector<std::string> column_names() const override;

  /**
   * Returns a list of column types. If type is VERTEX_GFRAME, the value
   * is also the names of the vertex fields (or edge fields if type is EDGE_GFRAME)
   * in the \ref gl_sgraph.
   *
   * \see gl_sgraph::get_vertex_field_types
   * \see gl_sgraph::get_edge_field_types
   */
  std::vector<flex_type_enum> column_types() const override;

  /**
   * Add a new column with constant value. If type is VERTEX_GFRAME, the column
   * is added as a new vertex field (or edge field if type is EDGE_GFRAME)
   * in the \ref gl_sgraph.
   *
   * \param data the constant value to fill the column
   * \param name the name of the new column
   *
   * \see gl_sgraph::add_vertex_field(const flexible_type&, const std::string&)
   * \see gl_sgraph::add_edge_field(const flexible_type&, const std::stirng&)
   */
  void add_column(const flexible_type& data, const std::string& name) override;

  /**
   * Add a new column with given column name and data. If type is
   * VERTEX_GFRAME, the column is added as a new vertex field (or edge field if
   * type is EDGE_GFRAME) in the \ref gl_sgraph.
   *
   * \param data the constant value to fill the column
   * \param name the name of the new column
   *
   * \see gl_sgraph::add_vertex_field(const gl_sarray&, const std::string&)
   * \see gl_sgraph::add_edge_field(const gl_sarray&, const std::string&)
   */
  void add_column(const gl_sarray& data, const std::string& name) override;

  /**
   * Batch version of \ref add_column.
   *
   * \param data a map from column name to column data
   */
  void add_columns(const gl_sframe& data) override;

  /**
   * Remove a column with the given name. If type is
   * VERTEX_GFRAME, the column is removed from vertex data (or edge data if
   * type is EDGE_GFRAME) from the \ref gl_sgraph.
   *
   * \param name the column name to be removed
   *
   * \see gl_sgraph::remove_vertex_field
   * \see gl_sgraph::remove_edge_field
   */
  void remove_column(const std::string& name) override;

  /**
   * Rename columns.
   *
   * \param old_to_new_names map from old column name to new column name.
   *
   * \see gl_sgraph::rename_vertex_fields
   * \see gl_sgraph::rename_edge_fields
   */
  void rename(const std::map<std::string, std::string>& old_to_new_names) override;

  /**
   * Swap the order of two columns
   */
  void swap_columns(const std::string& column_1, const std::string& column_2) override;

  virtual std::shared_ptr<unity_sframe> get_proxy() const override;

 private:
  gl_sgraph* m_sgraph;
  gframe_type_enum m_gframe_type;
};

}

#endif
<commit_msg>remove unnecessary implicit converter which cause complication warning<commit_after>/**
 * Copyright (C) 2014 GraphLab Inc.
 * All rights reserved.
 *
 * This software may be modified and distributed under the terms
 * of the BSD license. See the LICENSE file for details.
 */

#ifndef GRAPHLAB_UNITY_GL_GFRAME_HPP
#define GRAPHLAB_UNITY_GL_GFRAME_HPP

#include "gl_sframe.hpp"

namespace graphlab {
class gl_sframe;
class gl_sgraph;
class gl_sarray;

// Possible types of gl_gframe
enum class gframe_type_enum:int {VERTEX_GFRAME, EDGE_GFRAME};

/**
 * \ingroup gl_sdk
 *
 * A proxy for the \ref gl_sframe for the vertex and edge data of the SGRaph
 */
class gl_gframe : public gl_sframe {
 public:
  gl_gframe() = delete;
  gl_gframe(const gl_gframe&) = default;
  gl_gframe(gl_gframe&&) = default;
  gl_gframe& operator=(const gl_gframe&) = default;
  gl_gframe& operator=(gl_gframe&&) = default;

  /*
   * Construct gl_gframe from sgraph, and sframe.
   */
  gl_gframe(gl_sgraph*, gframe_type_enum);

  /*
   * Implicit converters
   */
  operator std::shared_ptr<unity_sframe>() const;
  operator std::shared_ptr<unity_sframe_base>() const;

  /**
   * Returns number of rows. If type is VERTEX_GFRAME, the value
   * is also the number of vertices (or edges if type is EDGE_GFRAME)
   * in the \ref gl_sgraph.
   *
   * \see gl_sgraph::num_vertices
   * \see gl_sgraph::num_edges
   */
  size_t size() const override;

  /**
   * Returns number of columns. If type is VERTEX_GFRAME, the value
   * is also the number of vertex fields (or edge fields if type is EDGE_GFRAME)
   * in the \ref gl_sgraph.
   */
  size_t num_columns() const override;

  /**
   * Returns a list of column names. If type is VERTEX_GFRAME, the value
   * is also the names of the vertex fields (or edge fields if type is EDGE_GFRAME)
   * in the \ref gl_sgraph.
   *
   * \see gl_sgraph::get_vertex_fields
   * \see gl_sgraph::get_edge_fields
   */
  std::vector<std::string> column_names() const override;

  /**
   * Returns a list of column types. If type is VERTEX_GFRAME, the value
   * is also the names of the vertex fields (or edge fields if type is EDGE_GFRAME)
   * in the \ref gl_sgraph.
   *
   * \see gl_sgraph::get_vertex_field_types
   * \see gl_sgraph::get_edge_field_types
   */
  std::vector<flex_type_enum> column_types() const override;

  /**
   * Add a new column with constant value. If type is VERTEX_GFRAME, the column
   * is added as a new vertex field (or edge field if type is EDGE_GFRAME)
   * in the \ref gl_sgraph.
   *
   * \param data the constant value to fill the column
   * \param name the name of the new column
   *
   * \see gl_sgraph::add_vertex_field(const flexible_type&, const std::string&)
   * \see gl_sgraph::add_edge_field(const flexible_type&, const std::stirng&)
   */
  void add_column(const flexible_type& data, const std::string& name) override;

  /**
   * Add a new column with given column name and data. If type is
   * VERTEX_GFRAME, the column is added as a new vertex field (or edge field if
   * type is EDGE_GFRAME) in the \ref gl_sgraph.
   *
   * \param data the constant value to fill the column
   * \param name the name of the new column
   *
   * \see gl_sgraph::add_vertex_field(const gl_sarray&, const std::string&)
   * \see gl_sgraph::add_edge_field(const gl_sarray&, const std::string&)
   */
  void add_column(const gl_sarray& data, const std::string& name) override;

  /**
   * Batch version of \ref add_column.
   *
   * \param data a map from column name to column data
   */
  void add_columns(const gl_sframe& data) override;

  /**
   * Remove a column with the given name. If type is
   * VERTEX_GFRAME, the column is removed from vertex data (or edge data if
   * type is EDGE_GFRAME) from the \ref gl_sgraph.
   *
   * \param name the column name to be removed
   *
   * \see gl_sgraph::remove_vertex_field
   * \see gl_sgraph::remove_edge_field
   */
  void remove_column(const std::string& name) override;

  /**
   * Rename columns.
   *
   * \param old_to_new_names map from old column name to new column name.
   *
   * \see gl_sgraph::rename_vertex_fields
   * \see gl_sgraph::rename_edge_fields
   */
  void rename(const std::map<std::string, std::string>& old_to_new_names) override;

  /**
   * Swap the order of two columns
   */
  void swap_columns(const std::string& column_1, const std::string& column_2) override;

  virtual std::shared_ptr<unity_sframe> get_proxy() const override;

 private:
  gl_sgraph* m_sgraph;
  gframe_type_enum m_gframe_type;
};

}

#endif
<|endoftext|>


<commit_before>/// \file
/// \ingroup tutorial_multicore
/// Fill histograms in parallel with automatic binning.
/// Illustrates use of power-of-two autobin algorithm
///
/// \macro_code
///
/// \author Gerardo Ganis
/// \date November 2017

// The number of workers
const UInt_t nWorkers = 8U;

// Reference boundaries
const Double_t xmiref = -1.;
const Double_t xmaref = 7.;

Int_t mt304_fillHistos(UInt_t nNumbers = 1001)
{

   // The first, fundamental operation to be performed in order to make ROOT
   // thread-aware.
   ROOT::EnableThreadSafety();

   // Histograms to be filled in parallel
   ROOT::TThreadedObject<TH1D> h1d("h1d", "1D test histogram", 64, 0., -1.);
   ROOT::TThreadedObject<TH1D> h1dr("h1dr", "1D test histogram w/ ref boundaries", 64, xmiref, xmaref);

   // We define our work item
   auto workItem = [&](UInt_t workerID) {
      // One generator, file and ntuple per worker
      TRandom3 workerRndm(workerID); // Change the seed

      auto wh1d = h1d.Get();
      wh1d->SetBit(TH1::kAutoBinPTwo);
      auto wh1dr = h1dr.Get();

      Double_t x;
      for (UInt_t i = 0; i < nNumbers; ++i) {
         x = workerRndm.Gaus(3.);
         wh1d->Fill(x);
         wh1dr->Fill(x);
      }
   };

   // Create the collection which will hold the threads, our "pool"
   std::vector<std::thread> workers;

   // Fill the "pool" with workers
   for (auto workerID : ROOT::TSeqI(nWorkers)) {
      workers.emplace_back(workItem, workerID);
   }

   // Now join them
   for (auto &&worker : workers)
      worker.join();

   // Merge
   auto fh1d = h1d.Merge();
   auto fh1dr = h1dr.Merge();

   // Make the canvas
   auto c = new TCanvas("c", "c", 800, 800);
   c->Divide(1, 2);

   gStyle->SetOptStat(111110);
   c->cd(1);
   fh1d->DrawCopy();
   c->cd(2);
   fh1dr->DrawCopy();

   c->Update();

   return 0;
}
<commit_msg>[Doc] Add mt304 tutorial to the online documentation<commit_after>/// \file
/// \ingroup tutorial_multicore
/// \notebook -draw
/// Fill histograms in parallel with automatic binning.
/// Illustrates use of power-of-two autobin algorithm
///
/// \macro_code
/// \macro_image
///
/// \date November 2017
/// \author Gerardo Ganis

// The number of workers
const UInt_t nWorkers = 8U;

// Reference boundaries
const Double_t xmiref = -1.;
const Double_t xmaref = 7.;

Int_t mt304_fillHistos(UInt_t nNumbers = 1001)
{

   // The first, fundamental operation to be performed in order to make ROOT
   // thread-aware.
   ROOT::EnableThreadSafety();

   // Histograms to be filled in parallel
   ROOT::TThreadedObject<TH1D> h1d("h1d", "1D test histogram", 64, 0., -1.);
   ROOT::TThreadedObject<TH1D> h1dr("h1dr", "1D test histogram w/ ref boundaries", 64, xmiref, xmaref);

   // We define our work item
   auto workItem = [&](UInt_t workerID) {
      // One generator, file and ntuple per worker
      TRandom3 workerRndm(workerID); // Change the seed

      auto wh1d = h1d.Get();
      wh1d->SetBit(TH1::kAutoBinPTwo);
      auto wh1dr = h1dr.Get();

      Double_t x;
      for (UInt_t i = 0; i < nNumbers; ++i) {
         x = workerRndm.Gaus(3.);
         wh1d->Fill(x);
         wh1dr->Fill(x);
      }
   };

   // Create the collection which will hold the threads, our "pool"
   std::vector<std::thread> workers;

   // Fill the "pool" with workers
   for (auto workerID : ROOT::TSeqI(nWorkers)) {
      workers.emplace_back(workItem, workerID);
   }

   // Now join them
   for (auto &&worker : workers)
      worker.join();

   // Merge
   auto fh1d = h1d.Merge();
   auto fh1dr = h1dr.Merge();

   // Make the canvas
   auto c = new TCanvas("c", "c", 800, 800);
   c->Divide(1, 2);

   gStyle->SetOptStat(111110);
   c->cd(1);
   fh1d->DrawCopy();
   c->cd(2);
   fh1dr->DrawCopy();

   c->Update();

   return 0;
}
<|endoftext|>


<commit_before>// Copyright 2014 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 "athena/extensions/public/extension_app_model_builder.h"

#include "athena/activity/public/activity_factory.h"
#include "athena/activity/public/activity_manager.h"
#include "athena/extensions/public/extensions_delegate.h"
#include "extensions/browser/extension_icon_image.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/manifest_handlers/icons_handler.h"
#include "extensions/grit/extensions_browser_resources.h"
#include "ui/app_list/app_list_item.h"
#include "ui/app_list/app_list_model.h"
#include "ui/base/resource/resource_bundle.h"

namespace athena {

namespace {

class AppItem : public app_list::AppListItem {
 public:
  AppItem(scoped_refptr<const extensions::Extension> extension,
          content::BrowserContext* browser_context)
      : app_list::AppListItem(extension->id()),
        extension_(extension),
        browser_context_(browser_context),
        icon_image_(browser_context_,
                    extension.get(),
                    extensions::IconsInfo::GetIcons(extension.get()),
                    extension_misc::EXTENSION_ICON_MEDIUM,
                    *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
                        IDR_APP_DEFAULT_ICON),
                    NULL) {
    icon_image_.image_skia().EnsureRepsForSupportedScales();
    SetIcon(icon_image_.image_skia(), false);
    SetName(extension->name());
  }

 private:
  // Overridden from app_list::AppListItem:
  virtual void Activate(int event_flags) override {
    ExtensionsDelegate::Get(browser_context_)->LaunchApp(extension_->id());
  }

  scoped_refptr<const extensions::Extension> extension_;
  content::BrowserContext* browser_context_;
  extensions::IconImage icon_image_;

  DISALLOW_COPY_AND_ASSIGN(AppItem);
};

}  // namespace

ExtensionAppModelBuilder::ExtensionAppModelBuilder(
    content::BrowserContext* browser_context)
    : browser_context_(browser_context) {
}

ExtensionAppModelBuilder::~ExtensionAppModelBuilder() {
}

void ExtensionAppModelBuilder::PopulateApps(app_list::AppListModel* model) {
  ExtensionsDelegate* bridge = ExtensionsDelegate::Get(browser_context_);
  const extensions::ExtensionSet& extensions = bridge->GetInstalledExtensions();
  for (extensions::ExtensionSet::const_iterator iter = extensions.begin();
       iter != extensions.end();
       ++iter) {
    // TODO(mukai): use chrome/browser/extension_ui_util.
    if ((*iter)->ShouldDisplayInAppLauncher()) {
      model->AddItem(scoped_ptr<app_list::AppListItem>(
          new AppItem(*iter, browser_context_)));
    }
  }
}

}  // namespace athena
<commit_msg>Skips Chrome icon in Athena home card.<commit_after>// Copyright 2014 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 "athena/extensions/public/extension_app_model_builder.h"

#include "athena/activity/public/activity_factory.h"
#include "athena/activity/public/activity_manager.h"
#include "athena/extensions/public/extensions_delegate.h"
#include "extensions/browser/extension_icon_image.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/manifest_handlers/icons_handler.h"
#include "extensions/grit/extensions_browser_resources.h"
#include "ui/app_list/app_list_item.h"
#include "ui/app_list/app_list_model.h"
#include "ui/base/resource/resource_bundle.h"

namespace athena {

namespace {

// Copied from chrome/common/extensions/extension_constants.h
// TODO(mukai): move constants to src/extensions
const char kChromeAppId[] = "mgndgikekgjfcpckkfioiadnlibdjbkf";

class AppItem : public app_list::AppListItem {
 public:
  AppItem(scoped_refptr<const extensions::Extension> extension,
          content::BrowserContext* browser_context)
      : app_list::AppListItem(extension->id()),
        extension_(extension),
        browser_context_(browser_context),
        icon_image_(browser_context_,
                    extension.get(),
                    extensions::IconsInfo::GetIcons(extension.get()),
                    extension_misc::EXTENSION_ICON_MEDIUM,
                    *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
                        IDR_APP_DEFAULT_ICON),
                    NULL) {
    icon_image_.image_skia().EnsureRepsForSupportedScales();
    SetIcon(icon_image_.image_skia(), false);
    SetName(extension->name());
  }

 private:
  // Overridden from app_list::AppListItem:
  virtual void Activate(int event_flags) override {
    ExtensionsDelegate::Get(browser_context_)->LaunchApp(extension_->id());
  }

  scoped_refptr<const extensions::Extension> extension_;
  content::BrowserContext* browser_context_;
  extensions::IconImage icon_image_;

  DISALLOW_COPY_AND_ASSIGN(AppItem);
};

}  // namespace

ExtensionAppModelBuilder::ExtensionAppModelBuilder(
    content::BrowserContext* browser_context)
    : browser_context_(browser_context) {
}

ExtensionAppModelBuilder::~ExtensionAppModelBuilder() {
}

void ExtensionAppModelBuilder::PopulateApps(app_list::AppListModel* model) {
  ExtensionsDelegate* bridge = ExtensionsDelegate::Get(browser_context_);
  const extensions::ExtensionSet& extensions = bridge->GetInstalledExtensions();
  for (extensions::ExtensionSet::const_iterator iter = extensions.begin();
       iter != extensions.end();
       ++iter) {
    // Chrome icon is currently disabled for homecard since it's not meaningful.
    // http://crbug.com/421677
    // TODO(mukai): use chrome/browser/extension_ui_util.
    if ((*iter)->ShouldDisplayInAppLauncher() &&
        (*iter)->id() != kChromeAppId) {
      model->AddItem(scoped_ptr<app_list::AppListItem>(
          new AppItem(*iter, browser_context_)));
    }
  }
}

}  // namespace athena
<|endoftext|>


<commit_before><commit_msg>Add return 1<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/crash_reporter/crash_reporter_win.h"

#include <string>

#include "base/file_util.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"

namespace crash_reporter {

namespace {

// Minidump with stacks, PEB, TEB, and unloaded module list.
const MINIDUMP_TYPE kSmallDumpType = static_cast<MINIDUMP_TYPE>(
    MiniDumpWithProcessThreadData |  // Get PEB and TEB.
    MiniDumpWithUnloadedModules);  // Get unloaded modules when available.

const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\$1 Crash Service";

}  // namespace

CrashReporterWin::CrashReporterWin() {
}

CrashReporterWin::~CrashReporterWin() {
}

void CrashReporterWin::InitBreakpad(const std::string& product_name,
                                    const std::string& version,
                                    const std::string& company_name,
                                    const std::string& submit_url,
                                    bool auto_submit,
                                    bool skip_system_crash_handler) {
  skip_system_crash_handler_ = skip_system_crash_handler;

  base::FilePath temp_dir;
  if (!base::GetTempDir(&temp_dir)) {
    LOG(ERROR) << "Cannot get temp directory";
    return;
  }

  base::string16 pipe_name = ReplaceStringPlaceholders(
      kPipeNameFormat, base::UTF8ToUTF16(product_name), NULL);

  // Wait until the crash service is started.
  HANDLE waiting_event =
      ::CreateEventW(NULL, TRUE, FALSE, L"g_atom_shell_crash_service");
  if (waiting_event != INVALID_HANDLE_VALUE)
    WaitForSingleObject(waiting_event, 1000);

  breakpad_.reset(new google_breakpad::ExceptionHandler(
      temp_dir.value(),
      FilterCallback,
      MinidumpCallback,
      this,
      google_breakpad::ExceptionHandler::HANDLER_ALL,
      kSmallDumpType,
      pipe_name.c_str(),
      GetCustomInfo(product_name, version, company_name)));

  if (!breakpad_->IsOutOfProcess())
    LOG(ERROR) << "Cannot initialize out-of-process crash handler";
}

void CrashReporterWin::SetUploadParameters() {
  upload_parameters_["platform"] = "win32";
}

// static
bool CrashReporterWin::FilterCallback(void* context,
                                      EXCEPTION_POINTERS* exinfo,
                                      MDRawAssertionInfo* assertion) {
  return true;
}

// static
bool CrashReporterWin::MinidumpCallback(const wchar_t* dump_path,
                                        const wchar_t* minidump_id,
                                        void* context,
                                        EXCEPTION_POINTERS* exinfo,
                                        MDRawAssertionInfo* assertion,
                                        bool succeeded) {
  CrashReporterWin* self = static_cast<CrashReporterWin*>(context);
  if (succeeded && !self->skip_system_crash_handler_)
    return true;
  else
    return false;
}

google_breakpad::CustomClientInfo* CrashReporterWin::GetCustomInfo(
    const std::string& product_name,
    const std::string& version,
    const std::string& company_name) {
  custom_info_entries_.clear();
  custom_info_entries_.reserve(2 + upload_parameters_.size());

  custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(
      L"prod", L"Atom-Shell"));
  custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(
      L"ver", base::UTF8ToWide(version).c_str()));

  for (StringMap::const_iterator iter = upload_parameters_.begin();
       iter != upload_parameters_.end(); ++iter) {
    custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(
        base::UTF8ToWide(iter->first).c_str(),
        base::UTF8ToWide(iter->second).c_str()));
  }

  custom_info_.entries = &custom_info_entries_.front();
  custom_info_.count = custom_info_entries_.size();
  return &custom_info_;
}

// static
CrashReporterWin* CrashReporterWin::GetInstance() {
  return Singleton<CrashReporterWin>::get();
}

// static
CrashReporter* CrashReporter::GetInstance() {
  return CrashReporterWin::GetInstance();
}

}  // namespace crash_reporter
<commit_msg>win: Don't crash on invalid parameter error.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/crash_reporter/crash_reporter_win.h"

#include <string>

#include "base/file_util.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"

namespace crash_reporter {

namespace {

// Minidump with stacks, PEB, TEB, and unloaded module list.
const MINIDUMP_TYPE kSmallDumpType = static_cast<MINIDUMP_TYPE>(
    MiniDumpWithProcessThreadData |  // Get PEB and TEB.
    MiniDumpWithUnloadedModules);  // Get unloaded modules when available.

const wchar_t kPipeNameFormat[] = L"\\\\.\\pipe\\$1 Crash Service";

}  // namespace

CrashReporterWin::CrashReporterWin() {
}

CrashReporterWin::~CrashReporterWin() {
}

void CrashReporterWin::InitBreakpad(const std::string& product_name,
                                    const std::string& version,
                                    const std::string& company_name,
                                    const std::string& submit_url,
                                    bool auto_submit,
                                    bool skip_system_crash_handler) {
  skip_system_crash_handler_ = skip_system_crash_handler;

  base::FilePath temp_dir;
  if (!base::GetTempDir(&temp_dir)) {
    LOG(ERROR) << "Cannot get temp directory";
    return;
  }

  base::string16 pipe_name = ReplaceStringPlaceholders(
      kPipeNameFormat, base::UTF8ToUTF16(product_name), NULL);

  // Wait until the crash service is started.
  HANDLE waiting_event =
      ::CreateEventW(NULL, TRUE, FALSE, L"g_atom_shell_crash_service");
  if (waiting_event != INVALID_HANDLE_VALUE)
    WaitForSingleObject(waiting_event, 1000);

  int handler_types = google_breakpad::ExceptionHandler::HANDLER_EXCEPTION |
      google_breakpad::ExceptionHandler::HANDLER_PURECALL;
  breakpad_.reset(new google_breakpad::ExceptionHandler(
      temp_dir.value(),
      FilterCallback,
      MinidumpCallback,
      this,
      handler_types,
      kSmallDumpType,
      pipe_name.c_str(),
      GetCustomInfo(product_name, version, company_name)));

  if (!breakpad_->IsOutOfProcess())
    LOG(ERROR) << "Cannot initialize out-of-process crash handler";
}

void CrashReporterWin::SetUploadParameters() {
  upload_parameters_["platform"] = "win32";
}

// static
bool CrashReporterWin::FilterCallback(void* context,
                                      EXCEPTION_POINTERS* exinfo,
                                      MDRawAssertionInfo* assertion) {
  return true;
}

// static
bool CrashReporterWin::MinidumpCallback(const wchar_t* dump_path,
                                        const wchar_t* minidump_id,
                                        void* context,
                                        EXCEPTION_POINTERS* exinfo,
                                        MDRawAssertionInfo* assertion,
                                        bool succeeded) {
  CrashReporterWin* self = static_cast<CrashReporterWin*>(context);
  if (succeeded && !self->skip_system_crash_handler_)
    return true;
  else
    return false;
}

google_breakpad::CustomClientInfo* CrashReporterWin::GetCustomInfo(
    const std::string& product_name,
    const std::string& version,
    const std::string& company_name) {
  custom_info_entries_.clear();
  custom_info_entries_.reserve(2 + upload_parameters_.size());

  custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(
      L"prod", L"Atom-Shell"));
  custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(
      L"ver", base::UTF8ToWide(version).c_str()));

  for (StringMap::const_iterator iter = upload_parameters_.begin();
       iter != upload_parameters_.end(); ++iter) {
    custom_info_entries_.push_back(google_breakpad::CustomInfoEntry(
        base::UTF8ToWide(iter->first).c_str(),
        base::UTF8ToWide(iter->second).c_str()));
  }

  custom_info_.entries = &custom_info_entries_.front();
  custom_info_.count = custom_info_entries_.size();
  return &custom_info_;
}

// static
CrashReporterWin* CrashReporterWin::GetInstance() {
  return Singleton<CrashReporterWin>::get();
}

// static
CrashReporter* CrashReporter::GetInstance() {
  return CrashReporterWin::GetInstance();
}

}  // namespace crash_reporter
<|endoftext|>


<commit_before>/*
 * Copyright 2013 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 "folly/experimental/io/AsyncIO.h"

#include <sys/eventfd.h>
#include <unistd.h>
#include <cerrno>
#include <stdexcept>
#include <string>

#include <boost/intrusive/parent_from_member.hpp>
#include <glog/logging.h>

#include "folly/Exception.h"
#include "folly/Format.h"
#include "folly/Likely.h"
#include "folly/String.h"

namespace folly {

AsyncIOOp::AsyncIOOp(NotificationCallback cb)
  : cb_(std::move(cb)),
    state_(State::UNINITIALIZED),
    result_(-EINVAL) {
  memset(&iocb_, 0, sizeof(iocb_));
}

void AsyncIOOp::reset(NotificationCallback cb) {
  CHECK_NE(state_, State::PENDING);
  cb_ = std::move(cb);
  state_ = State::UNINITIALIZED;
  result_ = -EINVAL;
  memset(&iocb_, 0, sizeof(iocb_));
}

AsyncIOOp::~AsyncIOOp() {
  CHECK_NE(state_, State::PENDING);
}

void AsyncIOOp::start() {
  DCHECK_EQ(state_, State::INITIALIZED);
  state_ = State::PENDING;
}

void AsyncIOOp::complete(ssize_t result) {
  DCHECK_EQ(state_, State::PENDING);
  state_ = State::COMPLETED;
  result_ = result;
  if (cb_) {
    cb_(this);
  }
}

ssize_t AsyncIOOp::result() const {
  CHECK_EQ(state_, State::COMPLETED);
  return result_;
}

void AsyncIOOp::pread(int fd, void* buf, size_t size, off_t start) {
  init();
  io_prep_pread(&iocb_, fd, buf, size, start);
}

void AsyncIOOp::pread(int fd, Range<unsigned char*> range, off_t start) {
  pread(fd, range.begin(), range.size(), start);
}

void AsyncIOOp::preadv(int fd, const iovec* iov, int iovcnt, off_t start) {
  init();
  io_prep_preadv(&iocb_, fd, iov, iovcnt, start);
}

void AsyncIOOp::pwrite(int fd, const void* buf, size_t size, off_t start) {
  init();
  io_prep_pwrite(&iocb_, fd, const_cast<void*>(buf), size, start);
}

void AsyncIOOp::pwrite(int fd, Range<const unsigned char*> range, off_t start) {
  pwrite(fd, range.begin(), range.size(), start);
}

void AsyncIOOp::pwritev(int fd, const iovec* iov, int iovcnt, off_t start) {
  init();
  io_prep_pwritev(&iocb_, fd, iov, iovcnt, start);
}

void AsyncIOOp::init() {
  CHECK_EQ(state_, State::UNINITIALIZED);
  state_ = State::INITIALIZED;
}

AsyncIO::AsyncIO(size_t capacity, PollMode pollMode)
  : ctx_(0),
    ctxSet_(false),
    pending_(0),
    capacity_(capacity),
    pollFd_(-1) {
  CHECK_GT(capacity_, 0);
  completed_.reserve(capacity_);
  if (pollMode == POLLABLE) {
    pollFd_ = eventfd(0, EFD_NONBLOCK);
    checkUnixError(pollFd_, "AsyncIO: eventfd creation failed");
  }
}

AsyncIO::~AsyncIO() {
  CHECK_EQ(pending_, 0);
  if (ctx_) {
    int rc = io_queue_release(ctx_);
    CHECK_EQ(rc, 0) << "io_queue_release: " << errnoStr(-rc);
  }
  if (pollFd_ != -1) {
    CHECK_ERR(close(pollFd_));
  }
}

void AsyncIO::decrementPending() {
  ssize_t p = pending_.fetch_add(-1, std::memory_order_acq_rel);
  DCHECK_GE(p, 1);
}

void AsyncIO::initializeContext() {
  if (!ctxSet_.load(std::memory_order_acquire)) {
    std::lock_guard<std::mutex> lock(initMutex_);
    if (!ctxSet_.load(std::memory_order_relaxed)) {
      int rc = io_queue_init(capacity_, &ctx_);
      // returns negative errno
      checkKernelError(rc, "AsyncIO: io_queue_init failed");
      DCHECK(ctx_);
      ctxSet_.store(true, std::memory_order_release);
    }
  }
}

void AsyncIO::submit(Op* op) {
  CHECK_EQ(op->state(), Op::State::INITIALIZED);
  initializeContext();  // on demand

  // We can increment past capacity, but we'll clean up after ourselves.
  ssize_t p = pending_.fetch_add(1, std::memory_order_acq_rel);
  if (p >= capacity_) {
    decrementPending();
    throw std::range_error("AsyncIO: too many pending requests");
  }
  iocb* cb = &op->iocb_;
  cb->data = nullptr;  // unused
  if (pollFd_ != -1) {
    io_set_eventfd(cb, pollFd_);
  }
  int rc = io_submit(ctx_, 1, &cb);
  if (rc < 0) {
    decrementPending();
    throwSystemErrorExplicit(-rc, "AsyncIO: io_submit failed");
  }
  DCHECK_EQ(rc, 1);
  op->start();
}

Range<AsyncIO::Op**> AsyncIO::wait(size_t minRequests) {
  CHECK(ctx_);
  CHECK_EQ(pollFd_, -1) << "wait() only allowed on non-pollable object";
  ssize_t p = pending_.load(std::memory_order_acquire);
  CHECK_LE(minRequests, p);
  return doWait(minRequests, p);
}

Range<AsyncIO::Op**> AsyncIO::pollCompleted() {
  CHECK(ctx_);
  CHECK_NE(pollFd_, -1) << "pollCompleted() only allowed on pollable object";
  uint64_t numEvents;
  // This sets the eventFd counter to 0, see
  // http://www.kernel.org/doc/man-pages/online/pages/man2/eventfd.2.html
  ssize_t rc;
  do {
    rc = ::read(pollFd_, &numEvents, 8);
  } while (rc == -1 && errno == EINTR);
  if (UNLIKELY(rc == -1 && errno == EAGAIN)) {
    return Range<Op**>();  // nothing completed
  }
  checkUnixError(rc, "AsyncIO: read from event fd failed");
  DCHECK_EQ(rc, 8);

  DCHECK_GT(numEvents, 0);
  DCHECK_LE(numEvents, pending_);

  // Don't reap more than numEvents, as we've just reset the counter to 0.
  return doWait(numEvents, numEvents);
}

Range<AsyncIO::Op**> AsyncIO::doWait(size_t minRequests, size_t maxRequests) {
  io_event events[maxRequests];
  int count;
  do {
    // Wait forever
    count = io_getevents(ctx_, minRequests, maxRequests, events, nullptr);
  } while (count == -EINTR);
  checkKernelError(count, "AsyncIO: io_getevents failed");
  DCHECK_GE(count, minRequests);  // the man page says so
  DCHECK_LE(count, maxRequests);

  completed_.clear();
  if (count == 0) {
    return folly::Range<Op**>();
  }

  for (size_t i = 0; i < count; ++i) {
    DCHECK(events[i].obj);
    Op* op = boost::intrusive::get_parent_from_member(
        events[i].obj, &AsyncIOOp::iocb_);
    decrementPending();
    op->complete(events[i].res);
    completed_.push_back(op);
  }

  return folly::Range<Op**>(&completed_.front(), count);
}

AsyncIOQueue::AsyncIOQueue(AsyncIO* asyncIO)
  : asyncIO_(asyncIO) {
}

AsyncIOQueue::~AsyncIOQueue() {
  CHECK_EQ(asyncIO_->pending(), 0);
}

void AsyncIOQueue::submit(AsyncIOOp* op) {
  submit([op]() { return op; });
}

void AsyncIOQueue::submit(OpFactory op) {
  queue_.push_back(op);
  maybeDequeue();
}

void AsyncIOQueue::onCompleted(AsyncIOOp* op) {
  maybeDequeue();
}

void AsyncIOQueue::maybeDequeue() {
  while (!queue_.empty() && asyncIO_->pending() < asyncIO_->capacity()) {
    auto& opFactory = queue_.front();
    auto op = opFactory();
    queue_.pop_front();

    // Interpose our completion callback
    auto& nextCb = op->notificationCallback();
    op->setNotificationCallback([this, nextCb](AsyncIOOp* op) {
      this->onCompleted(op);
      if (nextCb) nextCb(op);
    });

    asyncIO_->submit(op);
  }
}

// debugging helpers:

namespace {

#define X(c) case c: return #c

const char* asyncIoOpStateToString(AsyncIOOp::State state) {
  switch (state) {
    X(AsyncIOOp::State::UNINITIALIZED);
    X(AsyncIOOp::State::INITIALIZED);
    X(AsyncIOOp::State::PENDING);
    X(AsyncIOOp::State::COMPLETED);
  }
  return "<INVALID AsyncIOOp::State>";
}

const char* iocbCmdToString(short int cmd_short) {
  io_iocb_cmd cmd = static_cast<io_iocb_cmd>(cmd_short);
  switch (cmd) {
    X(IO_CMD_PREAD);
    X(IO_CMD_PWRITE);
    X(IO_CMD_FSYNC);
    X(IO_CMD_FDSYNC);
    X(IO_CMD_POLL);
    X(IO_CMD_NOOP);
    X(IO_CMD_PREADV);
    X(IO_CMD_PWRITEV);
  };
  return "<INVALID io_iocb_cmd>";
}

#undef X

std::string fd2name(int fd) {
  std::string path = folly::to<std::string>("/proc/self/fd/", fd);
  char link[PATH_MAX];
  const ssize_t length =
    std::max<ssize_t>(readlink(path.c_str(), link, PATH_MAX), 0);
  return path.assign(link, length);
}

std::ostream& operator<<(std::ostream& os, const iocb& cb) {
  os << folly::format(
    "data={}, key={}, opcode={}, reqprio={}, fd={}, f={}, ",
    cb.data, cb.key, iocbCmdToString(cb.aio_lio_opcode),
    cb.aio_reqprio, cb.aio_fildes, fd2name(cb.aio_fildes));

  switch (cb.aio_lio_opcode) {
    case IO_CMD_PREAD:
    case IO_CMD_PWRITE:
      os << folly::format("buf={}, off={}, size={}, ",
                          cb.u.c.buf, cb.u.c.nbytes, cb.u.c.offset);
    default:
      os << "[TODO: write debug string for "
         << iocbCmdToString(cb.aio_lio_opcode) << "] ";
  }

  return os;
}

}  // anonymous namespace

std::ostream& operator<<(std::ostream& os, const AsyncIOOp& op) {
  os << "{" << op.state_ << ", ";

  if (op.state_ != AsyncIOOp::State::UNINITIALIZED) {
    os << op.iocb_;
  }

  if (op.state_ == AsyncIOOp::State::COMPLETED) {
    os << "result=" << op.result_ << ", ";
  }

  return os << "}";
}

std::ostream& operator<<(std::ostream& os, AsyncIOOp::State state) {
  return os << asyncIoOpStateToString(state);
}

}  // namespace folly

<commit_msg>AsyncIO::initializeContext() should provide more debug output when io_queue_init fails<commit_after>/*
 * Copyright 2013 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 "folly/experimental/io/AsyncIO.h"

#include <sys/eventfd.h>
#include <unistd.h>
#include <cerrno>
#include <stdexcept>
#include <string>
#include <fstream>

#include <boost/intrusive/parent_from_member.hpp>
#include <glog/logging.h>

#include "folly/Exception.h"
#include "folly/Format.h"
#include "folly/Likely.h"
#include "folly/String.h"

namespace folly {

AsyncIOOp::AsyncIOOp(NotificationCallback cb)
  : cb_(std::move(cb)),
    state_(State::UNINITIALIZED),
    result_(-EINVAL) {
  memset(&iocb_, 0, sizeof(iocb_));
}

void AsyncIOOp::reset(NotificationCallback cb) {
  CHECK_NE(state_, State::PENDING);
  cb_ = std::move(cb);
  state_ = State::UNINITIALIZED;
  result_ = -EINVAL;
  memset(&iocb_, 0, sizeof(iocb_));
}

AsyncIOOp::~AsyncIOOp() {
  CHECK_NE(state_, State::PENDING);
}

void AsyncIOOp::start() {
  DCHECK_EQ(state_, State::INITIALIZED);
  state_ = State::PENDING;
}

void AsyncIOOp::complete(ssize_t result) {
  DCHECK_EQ(state_, State::PENDING);
  state_ = State::COMPLETED;
  result_ = result;
  if (cb_) {
    cb_(this);
  }
}

ssize_t AsyncIOOp::result() const {
  CHECK_EQ(state_, State::COMPLETED);
  return result_;
}

void AsyncIOOp::pread(int fd, void* buf, size_t size, off_t start) {
  init();
  io_prep_pread(&iocb_, fd, buf, size, start);
}

void AsyncIOOp::pread(int fd, Range<unsigned char*> range, off_t start) {
  pread(fd, range.begin(), range.size(), start);
}

void AsyncIOOp::preadv(int fd, const iovec* iov, int iovcnt, off_t start) {
  init();
  io_prep_preadv(&iocb_, fd, iov, iovcnt, start);
}

void AsyncIOOp::pwrite(int fd, const void* buf, size_t size, off_t start) {
  init();
  io_prep_pwrite(&iocb_, fd, const_cast<void*>(buf), size, start);
}

void AsyncIOOp::pwrite(int fd, Range<const unsigned char*> range, off_t start) {
  pwrite(fd, range.begin(), range.size(), start);
}

void AsyncIOOp::pwritev(int fd, const iovec* iov, int iovcnt, off_t start) {
  init();
  io_prep_pwritev(&iocb_, fd, iov, iovcnt, start);
}

void AsyncIOOp::init() {
  CHECK_EQ(state_, State::UNINITIALIZED);
  state_ = State::INITIALIZED;
}

AsyncIO::AsyncIO(size_t capacity, PollMode pollMode)
  : ctx_(0),
    ctxSet_(false),
    pending_(0),
    capacity_(capacity),
    pollFd_(-1) {
  CHECK_GT(capacity_, 0);
  completed_.reserve(capacity_);
  if (pollMode == POLLABLE) {
    pollFd_ = eventfd(0, EFD_NONBLOCK);
    checkUnixError(pollFd_, "AsyncIO: eventfd creation failed");
  }
}

AsyncIO::~AsyncIO() {
  CHECK_EQ(pending_, 0);
  if (ctx_) {
    int rc = io_queue_release(ctx_);
    CHECK_EQ(rc, 0) << "io_queue_release: " << errnoStr(-rc);
  }
  if (pollFd_ != -1) {
    CHECK_ERR(close(pollFd_));
  }
}

void AsyncIO::decrementPending() {
  ssize_t p = pending_.fetch_add(-1, std::memory_order_acq_rel);
  DCHECK_GE(p, 1);
}

void AsyncIO::initializeContext() {
  if (!ctxSet_.load(std::memory_order_acquire)) {
    std::lock_guard<std::mutex> lock(initMutex_);
    if (!ctxSet_.load(std::memory_order_relaxed)) {
      int rc = io_queue_init(capacity_, &ctx_);
      // returns negative errno
      if (rc == -EAGAIN) {
        long aio_nr, aio_max;
        std::unique_ptr<FILE, int(*)(FILE*)>
          fp(fopen("/proc/sys/fs/aio-nr", "r"), fclose);
        PCHECK(fp);
        CHECK_EQ(fscanf(fp.get(), "%ld", &aio_nr), 1);

        std::unique_ptr<FILE, int(*)(FILE*)>
          aio_max_fp(fopen("/proc/sys/fs/aio-max-nr", "r"), fclose);
        PCHECK(aio_max_fp);
        CHECK_EQ(fscanf(aio_max_fp.get(), "%ld", &aio_max), 1);

        LOG(ERROR) << "No resources for requested capacity of " << capacity_;
        LOG(ERROR) << "aio_nr " << aio_nr << ", aio_max_nr " << aio_max;
      }

      checkKernelError(rc, "AsyncIO: io_queue_init failed");
      DCHECK(ctx_);
      ctxSet_.store(true, std::memory_order_release);
    }
  }
}

void AsyncIO::submit(Op* op) {
  CHECK_EQ(op->state(), Op::State::INITIALIZED);
  initializeContext();  // on demand

  // We can increment past capacity, but we'll clean up after ourselves.
  ssize_t p = pending_.fetch_add(1, std::memory_order_acq_rel);
  if (p >= capacity_) {
    decrementPending();
    throw std::range_error("AsyncIO: too many pending requests");
  }
  iocb* cb = &op->iocb_;
  cb->data = nullptr;  // unused
  if (pollFd_ != -1) {
    io_set_eventfd(cb, pollFd_);
  }
  int rc = io_submit(ctx_, 1, &cb);
  if (rc < 0) {
    decrementPending();
    throwSystemErrorExplicit(-rc, "AsyncIO: io_submit failed");
  }
  DCHECK_EQ(rc, 1);
  op->start();
}

Range<AsyncIO::Op**> AsyncIO::wait(size_t minRequests) {
  CHECK(ctx_);
  CHECK_EQ(pollFd_, -1) << "wait() only allowed on non-pollable object";
  ssize_t p = pending_.load(std::memory_order_acquire);
  CHECK_LE(minRequests, p);
  return doWait(minRequests, p);
}

Range<AsyncIO::Op**> AsyncIO::pollCompleted() {
  CHECK(ctx_);
  CHECK_NE(pollFd_, -1) << "pollCompleted() only allowed on pollable object";
  uint64_t numEvents;
  // This sets the eventFd counter to 0, see
  // http://www.kernel.org/doc/man-pages/online/pages/man2/eventfd.2.html
  ssize_t rc;
  do {
    rc = ::read(pollFd_, &numEvents, 8);
  } while (rc == -1 && errno == EINTR);
  if (UNLIKELY(rc == -1 && errno == EAGAIN)) {
    return Range<Op**>();  // nothing completed
  }
  checkUnixError(rc, "AsyncIO: read from event fd failed");
  DCHECK_EQ(rc, 8);

  DCHECK_GT(numEvents, 0);
  DCHECK_LE(numEvents, pending_);

  // Don't reap more than numEvents, as we've just reset the counter to 0.
  return doWait(numEvents, numEvents);
}

Range<AsyncIO::Op**> AsyncIO::doWait(size_t minRequests, size_t maxRequests) {
  io_event events[maxRequests];
  int count;
  do {
    // Wait forever
    count = io_getevents(ctx_, minRequests, maxRequests, events, nullptr);
  } while (count == -EINTR);
  checkKernelError(count, "AsyncIO: io_getevents failed");
  DCHECK_GE(count, minRequests);  // the man page says so
  DCHECK_LE(count, maxRequests);

  completed_.clear();
  if (count == 0) {
    return folly::Range<Op**>();
  }

  for (size_t i = 0; i < count; ++i) {
    DCHECK(events[i].obj);
    Op* op = boost::intrusive::get_parent_from_member(
        events[i].obj, &AsyncIOOp::iocb_);
    decrementPending();
    op->complete(events[i].res);
    completed_.push_back(op);
  }

  return folly::Range<Op**>(&completed_.front(), count);
}

AsyncIOQueue::AsyncIOQueue(AsyncIO* asyncIO)
  : asyncIO_(asyncIO) {
}

AsyncIOQueue::~AsyncIOQueue() {
  CHECK_EQ(asyncIO_->pending(), 0);
}

void AsyncIOQueue::submit(AsyncIOOp* op) {
  submit([op]() { return op; });
}

void AsyncIOQueue::submit(OpFactory op) {
  queue_.push_back(op);
  maybeDequeue();
}

void AsyncIOQueue::onCompleted(AsyncIOOp* op) {
  maybeDequeue();
}

void AsyncIOQueue::maybeDequeue() {
  while (!queue_.empty() && asyncIO_->pending() < asyncIO_->capacity()) {
    auto& opFactory = queue_.front();
    auto op = opFactory();
    queue_.pop_front();

    // Interpose our completion callback
    auto& nextCb = op->notificationCallback();
    op->setNotificationCallback([this, nextCb](AsyncIOOp* op) {
      this->onCompleted(op);
      if (nextCb) nextCb(op);
    });

    asyncIO_->submit(op);
  }
}

// debugging helpers:

namespace {

#define X(c) case c: return #c

const char* asyncIoOpStateToString(AsyncIOOp::State state) {
  switch (state) {
    X(AsyncIOOp::State::UNINITIALIZED);
    X(AsyncIOOp::State::INITIALIZED);
    X(AsyncIOOp::State::PENDING);
    X(AsyncIOOp::State::COMPLETED);
  }
  return "<INVALID AsyncIOOp::State>";
}

const char* iocbCmdToString(short int cmd_short) {
  io_iocb_cmd cmd = static_cast<io_iocb_cmd>(cmd_short);
  switch (cmd) {
    X(IO_CMD_PREAD);
    X(IO_CMD_PWRITE);
    X(IO_CMD_FSYNC);
    X(IO_CMD_FDSYNC);
    X(IO_CMD_POLL);
    X(IO_CMD_NOOP);
    X(IO_CMD_PREADV);
    X(IO_CMD_PWRITEV);
  };
  return "<INVALID io_iocb_cmd>";
}

#undef X

std::string fd2name(int fd) {
  std::string path = folly::to<std::string>("/proc/self/fd/", fd);
  char link[PATH_MAX];
  const ssize_t length =
    std::max<ssize_t>(readlink(path.c_str(), link, PATH_MAX), 0);
  return path.assign(link, length);
}

std::ostream& operator<<(std::ostream& os, const iocb& cb) {
  os << folly::format(
    "data={}, key={}, opcode={}, reqprio={}, fd={}, f={}, ",
    cb.data, cb.key, iocbCmdToString(cb.aio_lio_opcode),
    cb.aio_reqprio, cb.aio_fildes, fd2name(cb.aio_fildes));

  switch (cb.aio_lio_opcode) {
    case IO_CMD_PREAD:
    case IO_CMD_PWRITE:
      os << folly::format("buf={}, off={}, size={}, ",
                          cb.u.c.buf, cb.u.c.nbytes, cb.u.c.offset);
    default:
      os << "[TODO: write debug string for "
         << iocbCmdToString(cb.aio_lio_opcode) << "] ";
  }

  return os;
}

}  // anonymous namespace

std::ostream& operator<<(std::ostream& os, const AsyncIOOp& op) {
  os << "{" << op.state_ << ", ";

  if (op.state_ != AsyncIOOp::State::UNINITIALIZED) {
    os << op.iocb_;
  }

  if (op.state_ == AsyncIOOp::State::COMPLETED) {
    os << "result=" << op.result_ << ", ";
  }

  return os << "}";
}

std::ostream& operator<<(std::ostream& os, AsyncIOOp::State state) {
  return os << asyncIoOpStateToString(state);
}

}  // namespace folly

<|endoftext|>


<commit_before>/**
    @file    max_of_2_solution1.cpp
    @author  Altantur Bayarsaikhan (altantur)
    @purpose Find max of 2 integers
    @version 1.0 26/10/17
*/
#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

int main(){
    ifstream test_file;
    int a = 0, b = 0, max = 0;
    int temp = 0;

    // Read from test files
    test_file.open ("../test/test1.txt");
    test_file >> a;
    test_file >> b;
    test_file.close();

    // Finding max integer without using comparation operator
    max = a + b;
    temp = (a - b);
    temp *= temp;
    temp = sqrt(temp);
    max += temp;
    max /= 2;

    cout << "Max number is : " << max << endl;

    return 0;
}

<commit_msg>commented about abs to simple solution<commit_after>/**
    @file    max_of_2_solution1.cpp
    @author  Altantur Bayarsaikhan (altantur)
    @purpose Find max of 2 integers
    @version 1.0 26/10/17
*/
#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

int main(){
    ifstream test_file;
    int a = 0, b = 0, max = 0;
    int temp = 0;

    // Read from test files
    test_file.open ("../test/test1.txt");
    test_file >> a;
    test_file >> b;
    test_file.close();

    // Finding max integer without using comparation operator
    max = a + b;
    // We can also use cmath lib - abs(a - b)
    temp = (a - b);
    temp *= temp;
    temp = sqrt(temp);
    max += temp;
    max /= 2;

    cout << "Max number is : " << max << endl;

    return 0;
}

<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "FilterHighpass.h"
#include "Filterfill.h"
#include "Pixel8.h"
#include "Bitmap.h"

#include <iostream>
#include <sstream>

using namespace std;

namespace avg {

FilterHighpass::FilterHighpass()
{
}

FilterHighpass::~FilterHighpass()
{
}

BitmapPtr FilterHighpass::apply(BitmapPtr pBmpSrc)
{
    assert(pBmpSrc->getPixelFormat() == I8);
    BitmapPtr pBmpDest = BitmapPtr(new Bitmap(pBmpSrc->getSize(), I8,
            pBmpSrc->getName()));
    int SrcStride = pBmpSrc->getStride();
    int DestStride = pBmpDest->getStride();
    unsigned char * pSrcLine = pBmpSrc->getPixels()+3*SrcStride;
    unsigned char * pDestLine = pBmpDest->getPixels()+3*DestStride;
    IntPoint size = pBmpDest->getSize();
    for (int y = 3; y<size.y-3; ++y) {
        unsigned char * pSrcPixel = pSrcLine+3;
        unsigned char * pDstPixel = pDestLine;
        *pDstPixel++ = 128;
        *pDstPixel++ = 128;
        *pDstPixel++ = 128;
        for (int x = 3; x < size.x-3; ++x) {
            // Convolution Matrix is
            // -1  0  0   0  -1
            //  0 -1  0  -1   0
            //  0  0  8   0   0
            //  0 -1  0  -1   0
            // -1  0  0   0  -1
            // Actually, it's 7x7, but you get the idea.
            *pDstPixel =
                128 - int(*(pSrcPixel-2*SrcStride-2) + *(pSrcPixel-2*SrcStride+2) +
                *(pSrcPixel-SrcStride-1) + *(pSrcPixel-1*SrcStride+1) +
                *(pSrcPixel+SrcStride-1) + *(pSrcPixel+1*SrcStride+1) +
                *(pSrcPixel+2*SrcStride-2) + *(pSrcPixel+2*SrcStride+2))/16 +
                *(pSrcPixel)*3/4;
            *pDstPixel -= int(*(pSrcPixel-3*SrcStride-3) + *(pSrcPixel-3*SrcStride+3) +
                *(pSrcPixel+3*SrcStride-3) + *(pSrcPixel+3*SrcStride+3))/16;
/*
            unsigned char *pSrc = pSrcPixel-3*SrcStride;
            int Dest = *pSrc;
            pSrc += SrcStride;
            Dest += *pSrc;
            pSrc += SrcStride;
            Dest += *pSrc;
            pSrc += SrcStride-3;
            Dest += *pSrc++;
            Dest += *pSrc++;
            Dest += *pSrc++;
            pSrc++;
            Dest += *pSrc++;
            Dest += *pSrc++;
            Dest += *pSrc;
            pSrc += SrcStride-3;
            Dest += *pSrc;
            pSrc += SrcStride;
            Dest += *pSrc;
            pSrc += SrcStride;
            Dest += *pSrc;
            Dest /= 16;
            *pDstPixel = 128-Dest+*(pSrcPixel)*3/4;
/*
            *pDstPixel =
                128 - int(*(pSrcPixel-3*SrcStride) +
                        *(pSrcPixel-2*SrcStride) +
                        *(pSrcPixel-SrcStride) +
                        *(pSrcPixel-3) + *(pSrcPixel-2) + *(pSrcPixel-1) +
                        *(pSrcPixel+3) + *(pSrcPixel+2) + *(pSrcPixel+1) +
                        *(pSrcPixel+1*SrcStride) +
                        *(pSrcPixel+2*SrcStride) +
                        *(pSrcPixel+3*SrcStride))/16 +
                *(pSrcPixel)*3/4;
*/
            ++pSrcPixel;
            ++pDstPixel;
        }
        *pDstPixel++ = 128;
        *pDstPixel++ = 128;
        *pDstPixel++ = 128;
        pSrcLine += SrcStride;
        pDestLine += DestStride;
    }
    // Set top and bottom borders.
    memset(pBmpDest->getPixels(), 128, DestStride*3);
    memset(pBmpDest->getPixels()+DestStride*(size.y-3), 128, DestStride*3);
    return pBmpDest;
}

}
<commit_msg>Added optimized version of highpass (commented out)<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "FilterHighpass.h"
#include "Filterfill.h"
#include "Pixel8.h"
#include "Bitmap.h"

#include <iostream>
#include <sstream>

using namespace std;

namespace avg {

FilterHighpass::FilterHighpass()
{
}

FilterHighpass::~FilterHighpass()
{
}

BitmapPtr FilterHighpass::apply(BitmapPtr pBmpSrc)
{
    assert(pBmpSrc->getPixelFormat() == I8);
    BitmapPtr pBmpDest = BitmapPtr(new Bitmap(pBmpSrc->getSize(), I8,
            pBmpSrc->getName()));
    int SrcStride = pBmpSrc->getStride();
    int DestStride = pBmpDest->getStride();
    unsigned char * pSrcLine = pBmpSrc->getPixels()+3*SrcStride;
    unsigned char * pDestLine = pBmpDest->getPixels()+3*DestStride;
    IntPoint size = pBmpDest->getSize();
    for (int y = 3; y<size.y-3; ++y) {
        unsigned char * pSrcPixel = pSrcLine+3;
        unsigned char * pDstPixel = pDestLine;
        *pDstPixel++ = 128;
        *pDstPixel++ = 128;
        *pDstPixel++ = 128;
        for (int x = 3; x < size.x-3; ++x) {
            // Convolution Matrix is
            // -1  0  0   0  -1
            //  0 -1  0  -1   0
            //  0  0  8   0   0
            //  0 -1  0  -1   0
            // -1  0  0   0  -1
            // Actually, it's 7x7, but you get the idea.
            *pDstPixel =
                128 - int(*(pSrcPixel-2*SrcStride-2) + *(pSrcPixel-2*SrcStride+2) +
                *(pSrcPixel-SrcStride-1) + *(pSrcPixel-1*SrcStride+1) +
                *(pSrcPixel+SrcStride-1) + *(pSrcPixel+1*SrcStride+1) +
                *(pSrcPixel+2*SrcStride-2) + *(pSrcPixel+2*SrcStride+2))/16 +
                *(pSrcPixel)*3/4;
            *pDstPixel -= int(*(pSrcPixel-3*SrcStride-3) + *(pSrcPixel-3*SrcStride+3) +
                *(pSrcPixel+3*SrcStride-3) + *(pSrcPixel+3*SrcStride+3))/16;
/*
            unsigned char *pSrc = pSrcPixel-3*SrcStride-3;
            int Dest = *pSrc;
            pSrc += 6;
            Dest += *pSrc;
            pSrc += SrcStride-5;
            Dest += *pSrc;
            pSrc += 4;
            Dest += *pSrc;
            pSrc += 4*SrcStride-4;
            Dest += *pSrc;
            pSrc += 4;
            Dest += *pSrc;
            pSrc += SrcStride-5;
            Dest += *pSrc;
            pSrc += 6;
            Dest += *pSrc;
            Dest /= 8;
            *pDstPixel = 128+(*pSrcPixel)-Dest;
*/
/*
            unsigned char *pSrc = pSrcPixel-3*SrcStride;
            int Dest = *pSrc;
            pSrc += SrcStride;
            Dest += *pSrc;
            pSrc += SrcStride;
            Dest += *pSrc;
            pSrc += SrcStride-3;
            Dest += *pSrc++;
            Dest += *pSrc++;
            Dest += *pSrc++;
            pSrc++;
            Dest += *pSrc++;
            Dest += *pSrc++;
            Dest += *pSrc;
            pSrc += SrcStride-3;
            Dest += *pSrc;
            pSrc += SrcStride;
            Dest += *pSrc;
            pSrc += SrcStride;
            Dest += *pSrc;
            Dest /= 16;
            *pDstPixel = 128-Dest+*(pSrcPixel)*3/4;
*/
/*
            *pDstPixel =
                128 - int(*(pSrcPixel-3*SrcStride) +
                        *(pSrcPixel-2*SrcStride) +
                        *(pSrcPixel-SrcStride) +
                        *(pSrcPixel-3) + *(pSrcPixel-2) + *(pSrcPixel-1) +
                        *(pSrcPixel+3) + *(pSrcPixel+2) + *(pSrcPixel+1) +
                        *(pSrcPixel+1*SrcStride) +
                        *(pSrcPixel+2*SrcStride) +
                        *(pSrcPixel+3*SrcStride))/16 +
                *(pSrcPixel)*3/4;
*/
            ++pSrcPixel;
            ++pDstPixel;
        }
        *pDstPixel++ = 128;
        *pDstPixel++ = 128;
        *pDstPixel++ = 128;
        pSrcLine += SrcStride;
        pDestLine += DestStride;
    }
    // Set top and bottom borders.
    memset(pBmpDest->getPixels(), 128, DestStride*3);
    memset(pBmpDest->getPixels()+DestStride*(size.y-3), 128, DestStride*3);
    return pBmpDest;
}

}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "precompile.h"

#include "hwplib.h"
#include "hinfo.h"
#include "hwpfile.h"

// Info Block

static bool HWPReadInfoBlock(void *ptr, int len, HWPFile & hwpf)
{
    hwpf.info_block_len = len;
    if (0 == len)
        return true;
    else
        return hwpf.ReadBlock(ptr, len) ? true : false;
}

// Document Information
HWPInfo::HWPInfo()
    : cur_col(0)
    , cur_row(0)
    , readonly(false)
    , encrypted(false)
    , beginpagenum(0)
    , beginfnnum(0)
    , countfn(0)
    , splinetext(0)
    , splinefn(0)
    , spfnfn(0)
    , fnchar(0)
    , fnlinetype(0)
    , borderline(0)
    , empty_line_hide(0)
    , table_move(0)
    , compressed(0)
    , reserved3(0)
    , info_block_len(0)
    , info_block(NULL)
{
    back_info.isset = false;
    memset(reserved1, 0, sizeof(reserved1));
    memset(annotation, 0, sizeof(annotation));
    memset(bordermargin, 0, sizeof(bordermargin));
}

HWPInfo::~HWPInfo(void)
{
    if (info_block)
        delete[]info_block;
    info_block = 0;
}

/**
 * 문서정보를 읽어들이는 함수 ( 128 bytes )
 * 문서정보는 파일인식정보( 30 bytes ) 다음에 위치한 정보이다.
 */
bool HWPInfo::Read(HWPFile & hwpf)
{
    hwpf.Read2b(&cur_col, 1);                     /* 문서를 저장할 당시의 커서가 위치한 문단번호 */
    hwpf.Read2b(&cur_row, 1);                     /* 문단 칸 */

    hwpf.Read1b(&paper.paper_kind, 1);            /* 용지 종류 */
    hwpf.Read1b(&paper.paper_direction, 1);       /* 용지 방향 */

// paper geometry information
    paper.paper_height = (short) hwpf.Read2b();   /* 용지 길이 */
    paper.paper_width = (short) hwpf.Read2b();    /* 용지 너비 */
    paper.top_margin = (short) hwpf.Read2b();     /* 위쪽 여백 */
    paper.bottom_margin = (short) hwpf.Read2b();  /* 아래쪽 여백 */
    paper.left_margin = (short) hwpf.Read2b();    /* 왼쪽 여백 */
    paper.right_margin = (short) hwpf.Read2b();   /* 오른쪽 여백 */
    paper.header_length = (short) hwpf.Read2b();  /* 머리말 길이 */
    paper.footer_length = (short) hwpf.Read2b();  /* 꼬리말 길이 */
    paper.gutter_length = (short) hwpf.Read2b();  /* 제본여백 */
    hwpf.Read2b(&readonly, 1);                    /* 예약 */
    hwpf.Read1b(reserved1, 4);                    /* 예약 */
    hwpf.Read1b(&chain_info.chain_page_no, 1);    /* 쪽 번호 연결 1-연결, 0-새로시작 (연결인쇄에서 사용) */
    hwpf.Read1b(&chain_info.chain_footnote_no, 1);/* 각주번호 연결 1-연결 0-새로시작 */
                                                  /* 연결인쇄할 파일의 이름 */
    hwpf.Read1b(chain_info.chain_filename, CHAIN_MAX_PATH);

    hwpf.Read1b(annotation, ANNOTATION_LEN);      /* 덧붙이는 말 ( 파일 저장할 때 덧붙이는 말에 지정한 내용 ) */
    hwpf.Read2b(&encrypted, 1);                   /* 암호 여부 0-보통파일, 그외-암호걸린 파일 */
//hwpf.Read1b(reserved2, 6);                      /* 아래 3개의값으로 바뀌었다. */
    hwpf.Read2b(&beginpagenum,1);                 /* 페이지시작번호 */

// footnote
    hwpf.Read2b(&beginfnnum,1);                   /* 각주 시작번호 */
    hwpf.Read2b(&countfn,1);                      /* 각주 갯수 */
    splinetext = (short) hwpf.Read2b();
    splinefn = (short) hwpf.Read2b();
    spfnfn = (short) hwpf.Read2b();
    hwpf.Read1b(&fnchar, 1);
    hwpf.Read1b(&fnlinetype, 1);
// border layout
    for (int ii = 0; ii < 4; ++ii)
        bordermargin[ii] = (short) hwpf.Read2b();
    hwpf.Read2b(&borderline, 1);

    hwpf.Read1b(&empty_line_hide, 1);
    hwpf.Read1b(&table_move, 1);
    hwpf.Read1b(&compressed, 1);

    hwpf.Read1b(&reserved3, 1);

    hwpf.Read2b(&info_block_len, 1);
    if (hwpf.State())
        return false;

/* 문서 요약을 읽는다. */
    if (!summary.Read(hwpf))
        return false;
    if (info_block_len > 0)
    {
        info_block = new unsigned char[info_block_len + 1];

        if (0 == info_block ||
            !HWPReadInfoBlock(info_block, info_block_len, hwpf))
            return false;
    }

/* hwpf의 값을 재설정 한다. */
    hwpf.compressed = compressed ? true : false;
    hwpf.encrypted = encrypted ? true : false;
    hwpf.info_block_len = info_block_len;
    hwpf.SetCompressed(hwpf.compressed);

    return (!hwpf.State());
}

// Document Summary

bool HWPSummary::Read(HWPFile & hwpf)
{
    hwpf.Read2b(title, 56);
    hwpf.Read2b(subject, 56);
    hwpf.Read2b(author, 56);
    hwpf.Read2b(date, 56);
    hwpf.Read2b(keyword[0], 56);
    hwpf.Read2b(keyword[1], 56);
    hwpf.Read2b(etc[0], 56);
    hwpf.Read2b(etc[1], 56);
    hwpf.Read2b(etc[2], 56);

    return (!hwpf.State());
}

bool ParaShape::Read(HWPFile & hwpf)
{
     pagebreak = 0;
    left_margin = (short) hwpf.Read2b();
    right_margin = (short) hwpf.Read2b();
    indent = (short) hwpf.Read2b();
    lspacing = (short) hwpf.Read2b();
    pspacing_next = (short) hwpf.Read2b();

    hwpf.Read1b(&condense, 1);
    hwpf.Read1b(&arrange_type, 1);
    for (int ii = 0; ii < MAXTABS; ii++)
    {
        hwpf.Read1b(&tabs[ii].type, 1);
        hwpf.Read1b(&tabs[ii].dot_continue, 1);
        tabs[ii].position = (short) hwpf.Read2b();
    }
    hwpf.Read1b(&coldef.ncols, 1);
    hwpf.Read1b(&coldef.separator, 1);
    coldef.spacing = (short) hwpf.Read2b();
    coldef.columnlen = (short) hwpf.Read2b();
    coldef.columnlen0 = (short) hwpf.Read2b();
    hwpf.Read1b(&shade, 1);
    hwpf.Read1b(&outline, 1);
    hwpf.Read1b(&outline_continue, 1);
    pspacing_prev = (short) hwpf.Read2b();

    hwpf.Read1b(reserved, 2);
    return (!hwpf.State());
}

bool CharShape::Read(HWPFile & hwpf)
{
    size = (short) hwpf.Read2b();
    hwpf.Read1b(font, NLanguage);
    hwpf.Read1b(ratio, NLanguage);
    hwpf.Read1b(space, NLanguage);
    hwpf.Read1b(color, 2);
    hwpf.Read1b(&shade, 1);
    hwpf.Read1b(&attr, 1);
    hwpf.Read1b(reserved, 4);

    return (!hwpf.State());
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: implicit conversion from bool to 'short'<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "precompile.h"

#include "hwplib.h"
#include "hinfo.h"
#include "hwpfile.h"

// Info Block

static bool HWPReadInfoBlock(void *ptr, int len, HWPFile & hwpf)
{
    hwpf.info_block_len = len;
    if (0 == len)
        return true;
    else
        return hwpf.ReadBlock(ptr, len) ? true : false;
}

// Document Information
HWPInfo::HWPInfo()
    : cur_col(0)
    , cur_row(0)
    , readonly(0)
    , encrypted(0)
    , beginpagenum(0)
    , beginfnnum(0)
    , countfn(0)
    , splinetext(0)
    , splinefn(0)
    , spfnfn(0)
    , fnchar(0)
    , fnlinetype(0)
    , borderline(0)
    , empty_line_hide(0)
    , table_move(0)
    , compressed(0)
    , reserved3(0)
    , info_block_len(0)
    , info_block(NULL)
{
    back_info.isset = false;
    memset(reserved1, 0, sizeof(reserved1));
    memset(annotation, 0, sizeof(annotation));
    memset(bordermargin, 0, sizeof(bordermargin));
}

HWPInfo::~HWPInfo(void)
{
    if (info_block)
        delete[]info_block;
    info_block = 0;
}

/**
 * 문서정보를 읽어들이는 함수 ( 128 bytes )
 * 문서정보는 파일인식정보( 30 bytes ) 다음에 위치한 정보이다.
 */
bool HWPInfo::Read(HWPFile & hwpf)
{
    hwpf.Read2b(&cur_col, 1);                     /* 문서를 저장할 당시의 커서가 위치한 문단번호 */
    hwpf.Read2b(&cur_row, 1);                     /* 문단 칸 */

    hwpf.Read1b(&paper.paper_kind, 1);            /* 용지 종류 */
    hwpf.Read1b(&paper.paper_direction, 1);       /* 용지 방향 */

// paper geometry information
    paper.paper_height = (short) hwpf.Read2b();   /* 용지 길이 */
    paper.paper_width = (short) hwpf.Read2b();    /* 용지 너비 */
    paper.top_margin = (short) hwpf.Read2b();     /* 위쪽 여백 */
    paper.bottom_margin = (short) hwpf.Read2b();  /* 아래쪽 여백 */
    paper.left_margin = (short) hwpf.Read2b();    /* 왼쪽 여백 */
    paper.right_margin = (short) hwpf.Read2b();   /* 오른쪽 여백 */
    paper.header_length = (short) hwpf.Read2b();  /* 머리말 길이 */
    paper.footer_length = (short) hwpf.Read2b();  /* 꼬리말 길이 */
    paper.gutter_length = (short) hwpf.Read2b();  /* 제본여백 */
    hwpf.Read2b(&readonly, 1);                    /* 예약 */
    hwpf.Read1b(reserved1, 4);                    /* 예약 */
    hwpf.Read1b(&chain_info.chain_page_no, 1);    /* 쪽 번호 연결 1-연결, 0-새로시작 (연결인쇄에서 사용) */
    hwpf.Read1b(&chain_info.chain_footnote_no, 1);/* 각주번호 연결 1-연결 0-새로시작 */
                                                  /* 연결인쇄할 파일의 이름 */
    hwpf.Read1b(chain_info.chain_filename, CHAIN_MAX_PATH);

    hwpf.Read1b(annotation, ANNOTATION_LEN);      /* 덧붙이는 말 ( 파일 저장할 때 덧붙이는 말에 지정한 내용 ) */
    hwpf.Read2b(&encrypted, 1);                   /* 암호 여부 0-보통파일, 그외-암호걸린 파일 */
//hwpf.Read1b(reserved2, 6);                      /* 아래 3개의값으로 바뀌었다. */
    hwpf.Read2b(&beginpagenum,1);                 /* 페이지시작번호 */

// footnote
    hwpf.Read2b(&beginfnnum,1);                   /* 각주 시작번호 */
    hwpf.Read2b(&countfn,1);                      /* 각주 갯수 */
    splinetext = (short) hwpf.Read2b();
    splinefn = (short) hwpf.Read2b();
    spfnfn = (short) hwpf.Read2b();
    hwpf.Read1b(&fnchar, 1);
    hwpf.Read1b(&fnlinetype, 1);
// border layout
    for (int ii = 0; ii < 4; ++ii)
        bordermargin[ii] = (short) hwpf.Read2b();
    hwpf.Read2b(&borderline, 1);

    hwpf.Read1b(&empty_line_hide, 1);
    hwpf.Read1b(&table_move, 1);
    hwpf.Read1b(&compressed, 1);

    hwpf.Read1b(&reserved3, 1);

    hwpf.Read2b(&info_block_len, 1);
    if (hwpf.State())
        return false;

/* 문서 요약을 읽는다. */
    if (!summary.Read(hwpf))
        return false;
    if (info_block_len > 0)
    {
        info_block = new unsigned char[info_block_len + 1];

        if (0 == info_block ||
            !HWPReadInfoBlock(info_block, info_block_len, hwpf))
            return false;
    }

/* hwpf의 값을 재설정 한다. */
    hwpf.compressed = compressed ? true : false;
    hwpf.encrypted = encrypted ? true : false;
    hwpf.info_block_len = info_block_len;
    hwpf.SetCompressed(hwpf.compressed);

    return (!hwpf.State());
}

// Document Summary

bool HWPSummary::Read(HWPFile & hwpf)
{
    hwpf.Read2b(title, 56);
    hwpf.Read2b(subject, 56);
    hwpf.Read2b(author, 56);
    hwpf.Read2b(date, 56);
    hwpf.Read2b(keyword[0], 56);
    hwpf.Read2b(keyword[1], 56);
    hwpf.Read2b(etc[0], 56);
    hwpf.Read2b(etc[1], 56);
    hwpf.Read2b(etc[2], 56);

    return (!hwpf.State());
}

bool ParaShape::Read(HWPFile & hwpf)
{
     pagebreak = 0;
    left_margin = (short) hwpf.Read2b();
    right_margin = (short) hwpf.Read2b();
    indent = (short) hwpf.Read2b();
    lspacing = (short) hwpf.Read2b();
    pspacing_next = (short) hwpf.Read2b();

    hwpf.Read1b(&condense, 1);
    hwpf.Read1b(&arrange_type, 1);
    for (int ii = 0; ii < MAXTABS; ii++)
    {
        hwpf.Read1b(&tabs[ii].type, 1);
        hwpf.Read1b(&tabs[ii].dot_continue, 1);
        tabs[ii].position = (short) hwpf.Read2b();
    }
    hwpf.Read1b(&coldef.ncols, 1);
    hwpf.Read1b(&coldef.separator, 1);
    coldef.spacing = (short) hwpf.Read2b();
    coldef.columnlen = (short) hwpf.Read2b();
    coldef.columnlen0 = (short) hwpf.Read2b();
    hwpf.Read1b(&shade, 1);
    hwpf.Read1b(&outline, 1);
    hwpf.Read1b(&outline_continue, 1);
    pspacing_prev = (short) hwpf.Read2b();

    hwpf.Read1b(reserved, 2);
    return (!hwpf.State());
}

bool CharShape::Read(HWPFile & hwpf)
{
    size = (short) hwpf.Read2b();
    hwpf.Read1b(font, NLanguage);
    hwpf.Read1b(ratio, NLanguage);
    hwpf.Read1b(space, NLanguage);
    hwpf.Read1b(color, 2);
    hwpf.Read1b(&shade, 1);
    hwpf.Read1b(&attr, 1);
    hwpf.Read1b(reserved, 4);

    return (!hwpf.State());
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int p[2017],dp[2017];
int n;
void Init(){

	memset(p,2017*sizeof(int),0);
	memset(dp,2017*sizeof(int),0);

	REP(i,1,n)
		scanf("%d",p+i);

	sort(p+1,p+1+n);
	return ;
}

void Solve(){

	int Max=p[n];
	int m;
	scanf("%d",&m);

	m-=5;

	REP(i,1,n-1)
	REP(j,m,p[i])
	dp[j]=max(dp[j],dp[j-p[i]]+p[i]);

	print(m+5-dp[m]-Max);

	return ;
}

int main(){

	freopen("hdu2546.in","r",stdin);

	while(scanf("%d",&n)&&n)
	Init(),Solve();
	return 0;
}<commit_msg>update hdu2546<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int p[2017],dp[2017];
int n;
void Init(){

	memset(p,2017*sizeof(int),0);
	memset(dp,2017*sizeof(int),0);

	REP(i,1,n)
		scanf("%d",p+i);

	sort(p+1,p+1+n);
	return ;
}

void Solve(){

	int Max=p[n];
	int m;
	scanf("%d",&m);

	if(m<5){

		print(m);
		return ;
	}
	m-=5;

	REP(i,1,n-1)
	REP(j,m,p[i])
	dp[j]=max(dp[j],dp[j-p[i]]+p[i]);

	print(m+5-dp[m]-Max);

	return ;
}

int main(){

	freopen("hdu2546.in","r",stdin);

	while(scanf("%d",&n)&&n)
	Init(),Solve();
	return 0;
}<|endoftext|>


<commit_before>/*! \file version.hpp
    \brief Macros to detect cereal version

    These macros can assist in determining the version of cereal. Be
    warned that cereal is not guaranteed to be compatible across
    different versions. For more information on releases of cereal,
    see https://github.com/USCiLab/cereal/releases.

    \ingroup utility */
/*
  Copyright (c) 2018, Shane Grant
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of cereal nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifndef CEREAL_VERSION_HPP_
#define CEREAL_VERSION_HPP_

//! The major version
#define CEREAL_VERSION_MAJOR 1
//! The minor version
#define CEREAL_VERSION_MINOR 2
//! The patch version
#define CEREAL_VERSION_PATCH 3

//! The full version as a single number
#define CEREAL_VERSION (CEREAL_VERSION_MAJOR * 10000 \
                        + CEREAL_VERSION_MINOR * 100 \
                        + CEREAL_VERSION_PATCH)

#endif // CEREAL_VERSION_HPP_
<commit_msg>Update version to 1.3.0<commit_after>/*! \file version.hpp
    \brief Macros to detect cereal version

    These macros can assist in determining the version of cereal. Be
    warned that cereal is not guaranteed to be compatible across
    different versions. For more information on releases of cereal,
    see https://github.com/USCiLab/cereal/releases.

    \ingroup utility */
/*
  Copyright (c) 2018, Shane Grant
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:
      * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
      * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
      * Neither the name of cereal nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifndef CEREAL_VERSION_HPP_
#define CEREAL_VERSION_HPP_

//! The major version
#define CEREAL_VERSION_MAJOR 1
//! The minor version
#define CEREAL_VERSION_MINOR 3
//! The patch version
#define CEREAL_VERSION_PATCH 0

//! The full version as a single number
#define CEREAL_VERSION (CEREAL_VERSION_MAJOR * 10000 \
                        + CEREAL_VERSION_MINOR * 100 \
                        + CEREAL_VERSION_PATCH)

#endif // CEREAL_VERSION_HPP_
<|endoftext|>