<commit_before>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include <unordered_map>
#include <boost/range/iterator_range.hpp>
#include <boost/range/join.hpp>
#include <boost/range/algorithm/transform.hpp>

#include "cql3/column_specification.hh"
#include "core/shared_ptr.hh"
#include "types.hh"
#include "tuple.hh"
#include "gc_clock.hh"
#include "unimplemented.hh"
#include "utils/UUID.hh"

using column_id = uint32_t;

class column_definition final {
public:
    template<typename ColumnRange>
    static std::vector<const column_definition*> vectorize(ColumnRange&& columns) {
        std::vector<const column_definition*> r;
        boost::transform(std::forward<ColumnRange>(columns), std::back_inserter(r), [] (auto& def) { return &def; });
        return r;
    }
private:
    bytes _name;
public:
    enum class column_kind { PARTITION, CLUSTERING, REGULAR, STATIC };
    column_definition(bytes name, data_type type, column_id id, column_kind kind);
    data_type type;

    // Unique within (kind, schema instance).
    // schema::position() and component_index() depend on the fact that for PK columns this is
    // equivalent to component index.
    column_id id;

    column_kind kind;
    ::shared_ptr<cql3::column_specification> column_specification;
    bool is_static() const { return kind == column_kind::STATIC; }
    bool is_regular() const { return kind == column_kind::REGULAR; }
    bool is_partition_key() const { return kind == column_kind::PARTITION; }
    bool is_clustering_key() const { return kind == column_kind::CLUSTERING; }
    bool is_primary_key() const { return kind == column_kind::PARTITION || kind == column_kind::CLUSTERING; }
    bool is_atomic() const { return !type->is_multi_cell(); }
    bool is_compact_value() const;
    const sstring& name_as_text() const;
    const bytes& name() const;
    friend std::ostream& operator<<(std::ostream& os, const column_definition& cd) {
        return os << cd.name_as_text();
    }
    uint32_t component_index() const {
        assert(is_primary_key());
        return id;
    }
};

struct thrift_schema {
    shared_ptr<abstract_type> partition_key_type;
};

/*
 * Effectively immutable.
 * Not safe to access across cores because of shared_ptr's.
 */
class schema final {
private:
    // More complex fields are derived from these inside rebuild().
    // Contains only fields which can be safely default-copied.
    struct raw_schema {
        raw_schema(utils::UUID id);
        utils::UUID _id;
        sstring _ks_name;
        sstring _cf_name;
        std::vector<column_definition> _partition_key;
        std::vector<column_definition> _clustering_key;
        std::vector<column_definition> _regular_columns; // sorted by name
        std::vector<column_definition> _static_columns; // sorted by name, present only when there's any clustering column
        sstring _comment;
        gc_clock::duration _default_time_to_live = gc_clock::duration::zero();
        data_type _regular_column_name_type;
    };
    raw_schema _raw;
private:
    std::unordered_map<bytes, const column_definition*> _columns_by_name;
    std::map<bytes, const column_definition*, serialized_compare> _regular_columns_by_name;
    lw_shared_ptr<tuple_type<allow_prefixes::no>> _partition_key_type;
    lw_shared_ptr<tuple_type<allow_prefixes::no>> _clustering_key_type;
    lw_shared_ptr<tuple_type<allow_prefixes::yes>> _clustering_key_prefix_type;
    thrift_schema _thrift;
public:
    struct column {
        bytes name;
        data_type type;
        struct name_compare {
            shared_ptr<abstract_type> type;
            name_compare(shared_ptr<abstract_type> type) : type(type) {}
            bool operator()(const column& cd1, const column& cd2) const {
                return type->less(cd1.name, cd2.name);
            }
        };
    };
private:
    void build_columns(const std::vector<column>& columns, column_definition::column_kind kind, std::vector<column_definition>& dst);
    ::shared_ptr<cql3::column_specification> make_column_specification(const column_definition& def);
    void rebuild();
public:
    schema(std::experimental::optional<utils::UUID> id,
        sstring ks_name,
        sstring cf_name,
        std::vector<column> partition_key,
        std::vector<column> clustering_key,
        std::vector<column> regular_columns,
        std::vector<column> static_columns,
        shared_ptr<abstract_type> regular_column_name_type,
        sstring comment = {});
    schema(const schema&);
    const utils::UUID& id() const {
        return _raw._id;
    }
    void set_comment(const sstring& comment) {
        _raw._comment = comment;
    }
    void set_id(utils::UUID new_id) {
        _raw._id = new_id;
    }
    bool is_dense() const {
        return false;
    }
    bool is_counter() const {
        return false;
    }
    const column_definition* get_column_definition(const bytes& name);
    auto regular_begin() {
        return _raw._regular_columns.begin();
    }
    auto regular_end() {
        return _raw._regular_columns.end();
    }
    auto regular_lower_bound(const bytes& name) {
        // TODO: use regular_columns and a version of std::lower_bound() with heterogeneous comparator
        auto i = _regular_columns_by_name.lower_bound(name);
        if (i == _regular_columns_by_name.end()) {
            return regular_end();
        } else {
            return _raw._regular_columns.begin() + i->second->id;
        }
    }
    auto regular_upper_bound(const bytes& name) {
        // TODO: use regular_columns and a version of std::upper_bound() with heterogeneous comparator
        auto i = _regular_columns_by_name.upper_bound(name);
        if (i == _regular_columns_by_name.end()) {
            return regular_end();
        } else {
            return _raw._regular_columns.begin() + i->second->id;
        }
    }
    data_type column_name_type(const column_definition& def) {
        return def.kind == column_definition::column_kind::REGULAR ? _raw._regular_column_name_type : utf8_type;
    }
    const column_definition& regular_column_at(column_id id) const {
        return _raw._regular_columns.at(id);
    }
    const column_definition& static_column_at(column_id id) const {
        return _raw._static_columns.at(id);
    }
    bool is_last_partition_key(const column_definition& def) {
        return &_raw._partition_key[_raw._partition_key.size() - 1] == &def;
    }
    bool has_collections() {
        warn(unimplemented::cause::COLLECTIONS);
        return false; // FIXME
    }
    bool has_static_columns() {
        return !_raw._static_columns.empty();
    }
    size_t partition_key_size() const { return _raw._partition_key.size(); }
    size_t clustering_key_size() const { return _raw._clustering_key.size(); }
    size_t static_columns_count() const { return _raw._static_columns.size(); }
    size_t regular_columns_count() const { return _raw._regular_columns.size(); }
    // Returns a range of column definitions
    auto partition_key_columns() const {
        return boost::make_iterator_range(_raw._partition_key.begin(), _raw._partition_key.end());
    }
    // Returns a range of column definitions
    auto clustering_key_columns() const {
        return boost::make_iterator_range(_raw._clustering_key.begin(), _raw._clustering_key.end());
    }
    // Returns a range of column definitions
    auto static_columns() const {
        return boost::make_iterator_range(_raw._static_columns.begin(), _raw._static_columns.end());
    }
    // Returns a range of column definitions
    auto regular_columns() const {
        return boost::make_iterator_range(_raw._regular_columns.begin(), _raw._regular_columns.end());
    }
    // Returns a range of column definitions
    auto all_columns_in_select_order() const {
        return boost::range::join(partition_key_columns(),
            boost::range::join(clustering_key_columns(),
            boost::range::join(static_columns(), regular_columns())));
    }
    uint32_t position(const column_definition& column) const {
        if (column.is_primary_key()) {
            return column.id;
        }
        return _raw._clustering_key.size();
    }
    gc_clock::duration default_time_to_live() const {
        return _raw._default_time_to_live;
    }
    const sstring& ks_name() const {
        return _raw._ks_name;
    }
    const sstring& cf_name() const {
        return _raw._cf_name;
    }
    const lw_shared_ptr<tuple_type<allow_prefixes::no>>& partition_key_type() const {
        return _partition_key_type;
    }
    const lw_shared_ptr<tuple_type<allow_prefixes::no>>& clustering_key_type() const {
        return _clustering_key_type;
    }
    const lw_shared_ptr<tuple_type<allow_prefixes::yes>>& clustering_key_prefix_type() const {
        return _clustering_key_prefix_type;
    }
    const data_type& regular_column_name_type() const {
        return _raw._regular_column_name_type;
    }
};

using schema_ptr = lw_shared_ptr<schema>;

utils::UUID generate_legacy_id(const sstring& ks_name, const sstring& cf_name);
<commit_msg>schema.hh: Add schema::comment() accessor<commit_after>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include <unordered_map>
#include <boost/range/iterator_range.hpp>
#include <boost/range/join.hpp>
#include <boost/range/algorithm/transform.hpp>

#include "cql3/column_specification.hh"
#include "core/shared_ptr.hh"
#include "types.hh"
#include "tuple.hh"
#include "gc_clock.hh"
#include "unimplemented.hh"
#include "utils/UUID.hh"

using column_id = uint32_t;

class column_definition final {
public:
    template<typename ColumnRange>
    static std::vector<const column_definition*> vectorize(ColumnRange&& columns) {
        std::vector<const column_definition*> r;
        boost::transform(std::forward<ColumnRange>(columns), std::back_inserter(r), [] (auto& def) { return &def; });
        return r;
    }
private:
    bytes _name;
public:
    enum class column_kind { PARTITION, CLUSTERING, REGULAR, STATIC };
    column_definition(bytes name, data_type type, column_id id, column_kind kind);
    data_type type;

    // Unique within (kind, schema instance).
    // schema::position() and component_index() depend on the fact that for PK columns this is
    // equivalent to component index.
    column_id id;

    column_kind kind;
    ::shared_ptr<cql3::column_specification> column_specification;
    bool is_static() const { return kind == column_kind::STATIC; }
    bool is_regular() const { return kind == column_kind::REGULAR; }
    bool is_partition_key() const { return kind == column_kind::PARTITION; }
    bool is_clustering_key() const { return kind == column_kind::CLUSTERING; }
    bool is_primary_key() const { return kind == column_kind::PARTITION || kind == column_kind::CLUSTERING; }
    bool is_atomic() const { return !type->is_multi_cell(); }
    bool is_compact_value() const;
    const sstring& name_as_text() const;
    const bytes& name() const;
    friend std::ostream& operator<<(std::ostream& os, const column_definition& cd) {
        return os << cd.name_as_text();
    }
    uint32_t component_index() const {
        assert(is_primary_key());
        return id;
    }
};

struct thrift_schema {
    shared_ptr<abstract_type> partition_key_type;
};

/*
 * Effectively immutable.
 * Not safe to access across cores because of shared_ptr's.
 */
class schema final {
private:
    // More complex fields are derived from these inside rebuild().
    // Contains only fields which can be safely default-copied.
    struct raw_schema {
        raw_schema(utils::UUID id);
        utils::UUID _id;
        sstring _ks_name;
        sstring _cf_name;
        std::vector<column_definition> _partition_key;
        std::vector<column_definition> _clustering_key;
        std::vector<column_definition> _regular_columns; // sorted by name
        std::vector<column_definition> _static_columns; // sorted by name, present only when there's any clustering column
        sstring _comment;
        gc_clock::duration _default_time_to_live = gc_clock::duration::zero();
        data_type _regular_column_name_type;
    };
    raw_schema _raw;
private:
    std::unordered_map<bytes, const column_definition*> _columns_by_name;
    std::map<bytes, const column_definition*, serialized_compare> _regular_columns_by_name;
    lw_shared_ptr<tuple_type<allow_prefixes::no>> _partition_key_type;
    lw_shared_ptr<tuple_type<allow_prefixes::no>> _clustering_key_type;
    lw_shared_ptr<tuple_type<allow_prefixes::yes>> _clustering_key_prefix_type;
    thrift_schema _thrift;
public:
    struct column {
        bytes name;
        data_type type;
        struct name_compare {
            shared_ptr<abstract_type> type;
            name_compare(shared_ptr<abstract_type> type) : type(type) {}
            bool operator()(const column& cd1, const column& cd2) const {
                return type->less(cd1.name, cd2.name);
            }
        };
    };
private:
    void build_columns(const std::vector<column>& columns, column_definition::column_kind kind, std::vector<column_definition>& dst);
    ::shared_ptr<cql3::column_specification> make_column_specification(const column_definition& def);
    void rebuild();
public:
    schema(std::experimental::optional<utils::UUID> id,
        sstring ks_name,
        sstring cf_name,
        std::vector<column> partition_key,
        std::vector<column> clustering_key,
        std::vector<column> regular_columns,
        std::vector<column> static_columns,
        shared_ptr<abstract_type> regular_column_name_type,
        sstring comment = {});
    schema(const schema&);
    const utils::UUID& id() const {
        return _raw._id;
    }
    const sstring& comment() const {
        return _raw._comment;
    }
    void set_comment(const sstring& comment) {
        _raw._comment = comment;
    }
    void set_id(utils::UUID new_id) {
        _raw._id = new_id;
    }
    bool is_dense() const {
        return false;
    }
    bool is_counter() const {
        return false;
    }
    const column_definition* get_column_definition(const bytes& name);
    auto regular_begin() {
        return _raw._regular_columns.begin();
    }
    auto regular_end() {
        return _raw._regular_columns.end();
    }
    auto regular_lower_bound(const bytes& name) {
        // TODO: use regular_columns and a version of std::lower_bound() with heterogeneous comparator
        auto i = _regular_columns_by_name.lower_bound(name);
        if (i == _regular_columns_by_name.end()) {
            return regular_end();
        } else {
            return _raw._regular_columns.begin() + i->second->id;
        }
    }
    auto regular_upper_bound(const bytes& name) {
        // TODO: use regular_columns and a version of std::upper_bound() with heterogeneous comparator
        auto i = _regular_columns_by_name.upper_bound(name);
        if (i == _regular_columns_by_name.end()) {
            return regular_end();
        } else {
            return _raw._regular_columns.begin() + i->second->id;
        }
    }
    data_type column_name_type(const column_definition& def) {
        return def.kind == column_definition::column_kind::REGULAR ? _raw._regular_column_name_type : utf8_type;
    }
    const column_definition& regular_column_at(column_id id) const {
        return _raw._regular_columns.at(id);
    }
    const column_definition& static_column_at(column_id id) const {
        return _raw._static_columns.at(id);
    }
    bool is_last_partition_key(const column_definition& def) {
        return &_raw._partition_key[_raw._partition_key.size() - 1] == &def;
    }
    bool has_collections() {
        warn(unimplemented::cause::COLLECTIONS);
        return false; // FIXME
    }
    bool has_static_columns() {
        return !_raw._static_columns.empty();
    }
    size_t partition_key_size() const { return _raw._partition_key.size(); }
    size_t clustering_key_size() const { return _raw._clustering_key.size(); }
    size_t static_columns_count() const { return _raw._static_columns.size(); }
    size_t regular_columns_count() const { return _raw._regular_columns.size(); }
    // Returns a range of column definitions
    auto partition_key_columns() const {
        return boost::make_iterator_range(_raw._partition_key.begin(), _raw._partition_key.end());
    }
    // Returns a range of column definitions
    auto clustering_key_columns() const {
        return boost::make_iterator_range(_raw._clustering_key.begin(), _raw._clustering_key.end());
    }
    // Returns a range of column definitions
    auto static_columns() const {
        return boost::make_iterator_range(_raw._static_columns.begin(), _raw._static_columns.end());
    }
    // Returns a range of column definitions
    auto regular_columns() const {
        return boost::make_iterator_range(_raw._regular_columns.begin(), _raw._regular_columns.end());
    }
    // Returns a range of column definitions
    auto all_columns_in_select_order() const {
        return boost::range::join(partition_key_columns(),
            boost::range::join(clustering_key_columns(),
            boost::range::join(static_columns(), regular_columns())));
    }
    uint32_t position(const column_definition& column) const {
        if (column.is_primary_key()) {
            return column.id;
        }
        return _raw._clustering_key.size();
    }
    gc_clock::duration default_time_to_live() const {
        return _raw._default_time_to_live;
    }
    const sstring& ks_name() const {
        return _raw._ks_name;
    }
    const sstring& cf_name() const {
        return _raw._cf_name;
    }
    const lw_shared_ptr<tuple_type<allow_prefixes::no>>& partition_key_type() const {
        return _partition_key_type;
    }
    const lw_shared_ptr<tuple_type<allow_prefixes::no>>& clustering_key_type() const {
        return _clustering_key_type;
    }
    const lw_shared_ptr<tuple_type<allow_prefixes::yes>>& clustering_key_prefix_type() const {
        return _clustering_key_prefix_type;
    }
    const data_type& regular_column_name_type() const {
        return _raw._regular_column_name_type;
    }
};

using schema_ptr = lw_shared_ptr<schema>;

utils::UUID generate_legacy_id(const sstring& ks_name, const sstring& cf_name);
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "net/http/http_auth.h"

#include <algorithm>

#include "base/basictypes.h"
#include "base/string_util.h"
#include "net/base/net_errors.h"
#include "net/http/http_auth_handler_basic.h"
#include "net/http/http_auth_handler_digest.h"
#include "net/http/http_auth_handler_negotiate.h"
#include "net/http/http_auth_handler_ntlm.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"

namespace net {

// static
void HttpAuth::ChooseBestChallenge(
    HttpAuthHandlerFactory* http_auth_handler_factory,
    const HttpResponseHeaders* headers,
    Target target,
    const GURL& origin,
    const std::set<std::string>& disabled_schemes,
    const BoundNetLog& net_log,
    scoped_ptr<HttpAuthHandler>* handler) {
  DCHECK(http_auth_handler_factory);

  // A connection-based authentication scheme must continue to use the
  // existing handler object in |*handler|.
  if (handler->get() && (*handler)->is_connection_based()) {
    const std::string header_name = GetChallengeHeaderName(target);
    std::string challenge;
    void* iter = NULL;
    while (headers->EnumerateHeader(&iter, header_name, &challenge)) {
      ChallengeTokenizer props(challenge.begin(), challenge.end());
      if (LowerCaseEqualsASCII(props.scheme(), (*handler)->scheme().c_str()) &&
          (*handler)->InitFromChallenge(&props, target, origin, net_log))
        return;
    }
  }

  // Choose the challenge whose authentication handler gives the maximum score.
  scoped_ptr<HttpAuthHandler> best;
  const std::string header_name = GetChallengeHeaderName(target);
  std::string cur_challenge;
  void* iter = NULL;
  while (headers->EnumerateHeader(&iter, header_name, &cur_challenge)) {
    scoped_ptr<HttpAuthHandler> cur;
    int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
        cur_challenge, target, origin, net_log, &cur);
    if (rv != OK) {
      LOG(WARNING) << "Unable to create AuthHandler. Status: "
                   << ErrorToString(rv) << " Challenge: " << cur_challenge;
      continue;
    }
    if (cur.get() && (!best.get() || best->score() < cur->score())) {
      if (disabled_schemes.find(cur->scheme()) == disabled_schemes.end())
        best.swap(cur);
    }
  }
  handler->swap(best);
}

void HttpAuth::ChallengeTokenizer::Init(std::string::const_iterator begin,
                                        std::string::const_iterator end) {
  // The first space-separated token is the auth-scheme.
  // NOTE: we are more permissive than RFC 2617 which says auth-scheme
  // is separated by 1*SP.
  StringTokenizer tok(begin, end, HTTP_LWS);
  if (!tok.GetNext()) {
    valid_ = false;
    return;
  }

  // Save the scheme's position.
  scheme_begin_ = tok.token_begin();
  scheme_end_ = tok.token_end();

  // Everything past scheme_end_ is a (comma separated) value list.
  props_ = HttpUtil::ValuesIterator(scheme_end_, end, ',');
}

// We expect properties to be formatted as one of:
//   name="value"
//   name=value
//   name=
// Due to buggy implementations found in some embedded devices, we also
// accept values with missing close quotemark (http://crbug.com/39836):
//   name="value
bool HttpAuth::ChallengeTokenizer::GetNext() {
  if (!props_.GetNext())
    return false;

  // Set the value as everything. Next we will split out the name.
  value_begin_ = props_.value_begin();
  value_end_ = props_.value_end();
  name_begin_ = name_end_ = value_end_;

  if (expect_base64_token_) {
    expect_base64_token_ = false;
    // Strip off any padding.
    // (See https://bugzilla.mozilla.org/show_bug.cgi?id=230351.)
    //
    // Our base64 decoder requires that the length be a multiple of 4.
    int encoded_length = value_end_ - value_begin_;
    while (encoded_length > 0 && encoded_length % 4 != 0 &&
           value_begin_[encoded_length - 1] == '=') {
      --encoded_length;
      --value_end_;
    }
    return true;
  }

  // Scan for the equals sign.
  std::string::const_iterator equals = std::find(value_begin_, value_end_, '=');
  if (equals == value_end_ || equals == value_begin_)
    return valid_ = false;  // Malformed

  // Verify that the equals sign we found wasn't inside of quote marks.
  for (std::string::const_iterator it = value_begin_; it != equals; ++it) {
    if (HttpUtil::IsQuote(*it))
      return valid_ = false;  // Malformed
  }

  name_begin_ = value_begin_;
  name_end_ = equals;
  value_begin_ = equals + 1;

  value_is_quoted_ = false;
  if (value_begin_ != value_end_ && HttpUtil::IsQuote(*value_begin_)) {
    // Trim surrounding quotemarks off the value
    if (*value_begin_ != *(value_end_ - 1) || value_begin_ + 1 == value_end_)
      value_begin_ = equals + 2;  // Gracefully recover from mismatching quotes.
    else
      value_is_quoted_ = true;
  }
  return true;
}

// If value() has quotemarks, unquote it.
std::string HttpAuth::ChallengeTokenizer::unquoted_value() const {
  return HttpUtil::Unquote(value_begin_, value_end_);
}

// static
std::string HttpAuth::GetChallengeHeaderName(Target target) {
  switch (target) {
    case AUTH_PROXY:
      return "Proxy-Authenticate";
    case AUTH_SERVER:
      return "WWW-Authenticate";
    default:
      NOTREACHED();
      return "";
  }
}

// static
std::string HttpAuth::GetAuthorizationHeaderName(Target target) {
  switch (target) {
    case AUTH_PROXY:
      return "Proxy-Authorization";
    case AUTH_SERVER:
      return "Authorization";
    default:
      NOTREACHED();
      return "";
  }
}

// static
std::string HttpAuth::GetAuthTargetString(
    HttpAuth::Target target) {
  return target == HttpAuth::AUTH_PROXY ? "proxy" : "server";
}

}  // namespace net
<commit_msg>Fix for Proxy server authentication without credentials available.<commit_after>// Copyright (c) 2010 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 "net/http/http_auth.h"

#include <algorithm>

#include "base/basictypes.h"
#include "base/string_util.h"
#include "net/base/net_errors.h"
#include "net/http/http_auth_handler_basic.h"
#include "net/http/http_auth_handler_digest.h"
#include "net/http/http_auth_handler_negotiate.h"
#include "net/http/http_auth_handler_ntlm.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_util.h"

namespace net {

// static
void HttpAuth::ChooseBestChallenge(
    HttpAuthHandlerFactory* http_auth_handler_factory,
    const HttpResponseHeaders* headers,
    Target target,
    const GURL& origin,
    const std::set<std::string>& disabled_schemes,
    const BoundNetLog& net_log,
    scoped_ptr<HttpAuthHandler>* handler) {
  DCHECK(http_auth_handler_factory);

  // A connection-based authentication scheme must continue to use the
  // existing handler object in |*handler|.
  if (handler->get() && (*handler)->is_connection_based() &&
      (disabled_schemes.find((*handler)->scheme()) == disabled_schemes.end())) {
    const std::string header_name = GetChallengeHeaderName(target);
    std::string challenge;
    void* iter = NULL;
    while (headers->EnumerateHeader(&iter, header_name, &challenge)) {
      ChallengeTokenizer props(challenge.begin(), challenge.end());
      if (LowerCaseEqualsASCII(props.scheme(), (*handler)->scheme().c_str()) &&
          (*handler)->InitFromChallenge(&props, target, origin, net_log))
        return;
    }
  }

  // Choose the challenge whose authentication handler gives the maximum score.
  scoped_ptr<HttpAuthHandler> best;
  const std::string header_name = GetChallengeHeaderName(target);
  std::string cur_challenge;
  void* iter = NULL;
  while (headers->EnumerateHeader(&iter, header_name, &cur_challenge)) {
    scoped_ptr<HttpAuthHandler> cur;
    int rv = http_auth_handler_factory->CreateAuthHandlerFromString(
        cur_challenge, target, origin, net_log, &cur);
    if (rv != OK) {
      LOG(WARNING) << "Unable to create AuthHandler. Status: "
                   << ErrorToString(rv) << " Challenge: " << cur_challenge;
      continue;
    }
    if (cur.get() && (!best.get() || best->score() < cur->score()) &&
        (disabled_schemes.find(cur->scheme()) == disabled_schemes.end()))
      best.swap(cur);
  }
  handler->swap(best);
}

void HttpAuth::ChallengeTokenizer::Init(std::string::const_iterator begin,
                                        std::string::const_iterator end) {
  // The first space-separated token is the auth-scheme.
  // NOTE: we are more permissive than RFC 2617 which says auth-scheme
  // is separated by 1*SP.
  StringTokenizer tok(begin, end, HTTP_LWS);
  if (!tok.GetNext()) {
    valid_ = false;
    return;
  }

  // Save the scheme's position.
  scheme_begin_ = tok.token_begin();
  scheme_end_ = tok.token_end();

  // Everything past scheme_end_ is a (comma separated) value list.
  props_ = HttpUtil::ValuesIterator(scheme_end_, end, ',');
}

// We expect properties to be formatted as one of:
//   name="value"
//   name=value
//   name=
// Due to buggy implementations found in some embedded devices, we also
// accept values with missing close quotemark (http://crbug.com/39836):
//   name="value
bool HttpAuth::ChallengeTokenizer::GetNext() {
  if (!props_.GetNext())
    return false;

  // Set the value as everything. Next we will split out the name.
  value_begin_ = props_.value_begin();
  value_end_ = props_.value_end();
  name_begin_ = name_end_ = value_end_;

  if (expect_base64_token_) {
    expect_base64_token_ = false;
    // Strip off any padding.
    // (See https://bugzilla.mozilla.org/show_bug.cgi?id=230351.)
    //
    // Our base64 decoder requires that the length be a multiple of 4.
    int encoded_length = value_end_ - value_begin_;
    while (encoded_length > 0 && encoded_length % 4 != 0 &&
           value_begin_[encoded_length - 1] == '=') {
      --encoded_length;
      --value_end_;
    }
    return true;
  }

  // Scan for the equals sign.
  std::string::const_iterator equals = std::find(value_begin_, value_end_, '=');
  if (equals == value_end_ || equals == value_begin_)
    return valid_ = false;  // Malformed

  // Verify that the equals sign we found wasn't inside of quote marks.
  for (std::string::const_iterator it = value_begin_; it != equals; ++it) {
    if (HttpUtil::IsQuote(*it))
      return valid_ = false;  // Malformed
  }

  name_begin_ = value_begin_;
  name_end_ = equals;
  value_begin_ = equals + 1;

  value_is_quoted_ = false;
  if (value_begin_ != value_end_ && HttpUtil::IsQuote(*value_begin_)) {
    // Trim surrounding quotemarks off the value
    if (*value_begin_ != *(value_end_ - 1) || value_begin_ + 1 == value_end_)
      value_begin_ = equals + 2;  // Gracefully recover from mismatching quotes.
    else
      value_is_quoted_ = true;
  }
  return true;
}

// If value() has quotemarks, unquote it.
std::string HttpAuth::ChallengeTokenizer::unquoted_value() const {
  return HttpUtil::Unquote(value_begin_, value_end_);
}

// static
std::string HttpAuth::GetChallengeHeaderName(Target target) {
  switch (target) {
    case AUTH_PROXY:
      return "Proxy-Authenticate";
    case AUTH_SERVER:
      return "WWW-Authenticate";
    default:
      NOTREACHED();
      return "";
  }
}

// static
std::string HttpAuth::GetAuthorizationHeaderName(Target target) {
  switch (target) {
    case AUTH_PROXY:
      return "Proxy-Authorization";
    case AUTH_SERVER:
      return "Authorization";
    default:
      NOTREACHED();
      return "";
  }
}

// static
std::string HttpAuth::GetAuthTargetString(
    HttpAuth::Target target) {
  return target == HttpAuth::AUTH_PROXY ? "proxy" : "server";
}

}  // namespace net
<|endoftext|>


<commit_before>#ifndef ATL_PRINT_HH
#define ATL_PRINT_HH
/**
 * @file /home/ryan/programming/atl/print.hpp
 * @author Ryan Domigan <ryan_domigan@sutdents@uml.edu>
 * Created on Aug 10, 2013
 */
#include <functional>
#include <iostream>
#include <utility>

#include "./utility.hpp"
#include "./helpers.hpp"

namespace atl
{
	namespace printer
	{
		struct Printer
		{
			virtual std::ostream& print(std::ostream&) const = 0;
		};

		typedef ::Range<typename Ast::const_iterator> Range;

		struct PrintRange : public Printer
		{
			Range _range;
			char _delim_open, _delim_close;

			PrintRange(Range const& range, char delim_open, char delim_close)
				: _range(range),
				  _delim_open(delim_open),
				  _delim_close(delim_close)
			{}

			virtual std::ostream& print(std::ostream&) const;
		};

		struct PrintAny : public Printer
		{
			const Any &a;
			PrintAny(const Any &a_) : a(a_) {}
			virtual std::ostream& print(std::ostream&) const;
		};

		PrintRange range(Range const& rr, char open='(', char close=')')
		{ return PrintRange(rr, open, close); }

		PrintAny any(Any const& aa) { return PrintAny(aa); }

		std::ostream& operator<<(std::ostream& out, const printer::Printer& p) { return p.print(out); }

		std::ostream& PrintRange::print(std::ostream& out) const
		{
			if(_range.empty())
				return out << _delim_open << _delim_close << endl;
			else {
				out << _delim_open << printer::any(_range[0]) << flush;
				for(auto& vv : slice(_range, 1)) out << " " << printer::any(vv);
				return out << _delim_close;
			}
		}

		std::ostream& PrintAny::print(std::ostream& out) const
		{
			auto trim_addr = [](void *pntr)
				{ return reinterpret_cast<long>(pntr) & (256 - 1); };

			using namespace std;
			switch(a._tag)
				{
				case tag<Undefined>::value:
					{
						out << "#<Undefined ";
						return out << ":" << hex << trim_addr(a.value) << ">";
					}

				case tag<Symbol>::value:
					return out << "'" << unwrap<string>(a);
				case tag<Type>::value:
					return out << "#{" << unwrap<Type>(a).value << "}";
				case tag<Fixnum>::value:
					return out << value<Fixnum>(a);
				case tag<Bool>::value:
					{
						if(value<bool>(a))
							return out << "True";
						else
							return out << "False";
					}
				case tag<String>::value:
					return out << '"' << *reinterpret_cast<string*>(a.value) << '"';
				case tag<CxxFunctor>::value:
					return out << unwrap<CxxFunctor>(a)._name;
				case tag<Pointer>::value:
					{
						if(a.value)
							return out << "#<Pointer-" << hex << (reinterpret_cast<long>(a.value) & (256 - 1)) << ">";
						else
							return out << "#<Pointer-NULL>";
					}
				case tag<Ast>::value:
					return out << range(make_range(unwrap<Ast>(a)));
				case tag<AstData>::value:
					return out << range(make_range(unwrap<AstData>(a)));
				case tag<Slice>::value:
					return out << range(make_range(unwrap<Slice>(a)), '[', ']');
				case tag<DefProcedure>::value:
					{
						out << "#<DefProcedure" << flush;
						auto closure = unwrap<DefProcedure>(a).closure;
						if(!closure.empty())
							{
								out << " (" << closure.size() << " free vars)";
							}
						return out << ">" << flush;;
					}
				default:
					return out << "#<" << type_name(a._tag) << ">";
				}
		}
	}

	void dbg_any(Any vv)
	{ cout << printer::any(vv) << endl; }

	void dbg_pbv(PassByValue value)
	{ return dbg_any(value.as_Any()); }

	void dbg_ast(Ast const& vv)
	{ cout << printer::range(make_range(vv)) << endl; }

	std::ostream& print_type(PassByValue const& value, std::ostream& out)
	{
		switch(value._tag)
			{
			case tag<Ast>::value:
				{
					auto ast = unwrap<Ast>(value);
					out << "(";
					if(!ast.empty())
						{
							print_type(ast[0], out);
							for(auto& vv : slice(ast, 1))
								{
									out << ' ';
									print_type(vv, out);
								}
						}
					return out << ")";
				}
			case tag<Type>::value:
				{ return out << "#<Type: " << unwrap<Type>(value).value << ">"; }
			default:
				return out << type_name(value._tag);
			}
	}
	void dbg_type(PassByValue const& value)
	{ print_type(value, std::cout) << std::endl; }
}

#endif
<commit_msg>Print type information for symbols<commit_after>#ifndef ATL_PRINT_HH
#define ATL_PRINT_HH
/**
 * @file /home/ryan/programming/atl/print.hpp
 * @author Ryan Domigan <ryan_domigan@sutdents@uml.edu>
 * Created on Aug 10, 2013
 */
#include <functional>
#include <iostream>
#include <utility>

#include "./utility.hpp"
#include "./helpers.hpp"

namespace atl
{
	namespace printer
	{
		struct Printer
		{
			virtual std::ostream& print(std::ostream&) const = 0;
		};

		typedef ::Range<typename Ast::const_iterator> Range;

		struct PrintRange : public Printer
		{
			Range _range;
			char _delim_open, _delim_close;

			PrintRange(Range const& range, char delim_open, char delim_close)
				: _range(range),
				  _delim_open(delim_open),
				  _delim_close(delim_close)
			{}

			virtual std::ostream& print(std::ostream&) const;
		};

		struct PrintAny : public Printer
		{
			const Any &a;
			PrintAny(const Any &a_) : a(a_) {}
			virtual std::ostream& print(std::ostream&) const;
		};

		PrintRange range(Range const& rr, char open='(', char close=')')
		{ return PrintRange(rr, open, close); }

		PrintAny any(Any const& aa) { return PrintAny(aa); }

		std::ostream& operator<<(std::ostream& out, const printer::Printer& p) { return p.print(out); }

		std::ostream& PrintRange::print(std::ostream& out) const
		{
			if(_range.empty())
				return out << _delim_open << _delim_close << endl;
			else {
				out << _delim_open << printer::any(_range[0]) << flush;
				for(auto& vv : slice(_range, 1)) out << " " << printer::any(vv);
				return out << _delim_close;
			}
		}

		std::ostream& print_atom(Any any, std::ostream& out)
		{
			using namespace std;
			auto trim_addr = [](void *pntr)
				{ return reinterpret_cast<long>(pntr) & (256 - 1); };

			switch(any._tag)
				{
				case tag<Undefined>::value:
					{
						out << "#<Undefined ";
						return out << ":" << hex << trim_addr(any.value) << ">";
					}

				case tag<Symbol>::value:
					return out << "'" << unwrap<string>(a);
				case tag<Type>::value:
					return out << "#{" << unwrap<Type>(any).value << "}";
				case tag<Fixnum>::value:
					return out << value<Fixnum>(any);
				case tag<Bool>::value:
					{
						if(value<bool>(any))
							return out << "True";
						else
							return out << "False";
					}
				case tag<String>::value:
					return out << '"' << *reinterpret_cast<string*>(any.value) << '"';
				case tag<CxxFunctor>::value:
					return out << unwrap<CxxFunctor>(any)._name;
				case tag<Pointer>::value:
					{
						if(any.value)
							return out << "#<Pointer-" << hex << (reinterpret_cast<long>(any.value) & (256 - 1)) << ">";
						else
							return out << "#<Pointer-NULL>";
					}
				case tag<DefProcedure>::value:
					{
						out << "#<DefProcedure" << flush;
						auto closure = unwrap<DefProcedure>(any).closure;
						if(!closure.empty())
							{
								out << " (" << closure.size() << " free vars)";
							}
						return out << ">" << flush;;
					}
				default:
					return out << "#<" << type_name(any._tag) << ">";
				}
		}

		std::ostream& PrintAny::print(std::ostream& out) const
		{
			using namespace std;
			switch(a._tag)
				{
				case tag<Ast>::value:
					return out << range(make_range(unwrap<Ast>(a)));
				case tag<AstData>::value:
					return out << range(make_range(unwrap<AstData>(a)));
				case tag<Slice>::value:
					return out << range(make_range(unwrap<Slice>(a)), '[', ']');
				case tag<DefProcedure>::value:
					{
						out << "#<DefProcedure" << flush;
						auto closure = unwrap<DefProcedure>(a).closure;
						if(!closure.empty())
							{
								out << " (" << closure.size() << " free vars)";
							}
						return out << ">" << flush;;
					}
				default:
					return print_atom(a, out);
				}
		}
	}

	void dbg_any(Any vv)
	{ cout << printer::any(vv) << endl; }

	void dbg_pbv(PassByValue value)
	{ return dbg_any(value.as_Any()); }

	void dbg_ast(Ast const& vv)
	{ cout << printer::range(make_range(vv)) << endl; }

	std::ostream& print_type(PassByValue const& value, std::ostream& out)
	{
		switch(value._tag)
			{
			case tag<Ast>::value:
				{
					auto ast = unwrap<Ast>(value);
					out << "(";
					if(!ast.empty())
						{
							print_type(ast[0], out);
							for(auto& vv : slice(ast, 1))
								{
									out << ' ';
									print_type(vv, out);
								}
						}
					return out << ")";
				}
			case tag<Type>::value:
				{ return out << "#<Type: " << unwrap<Type>(value).value << ">"; }
			default:
				return out << type_name(value._tag);
			}
	}
	void dbg_type(PassByValue const& value)
	{ print_type(value, std::cout) << std::endl; }

	std::ostream& print_with_type(PassByValue value, std::ostream& out)
	{
		auto print_sym = [&](Symbol& sym) -> std::ostream&
			{
				out << "['" << sym.name << ": ";
				print_type(pass_value(sym.type), out);
				return out << "]";
			};

		switch(value._tag)
			{
			case tag<Ast>::value:
				{
					auto ast = unwrap<Ast>(value);
					out << "(";
					if(!ast.empty())
						{
							print_with_type(ast[0], out);
							for(auto& vv : slice(ast, 1))
								{
									out << ' ';
									print_with_type(vv, out);
								}
						}
					return out << ")";
				}
			case tag<Bound>::value:
				{
					cout << "[Bound";
					print_sym(*unwrap<Bound>(value).value);
					return cout << "]";
				}
			case tag<Symbol>::value:
				{
					return print_sym(unwrap<Symbol>(value));
				}
			default:
				return printer::print_atom(value.as_Any(), out);
			}
	}
	void dbg_with_type(PassByValue const& value)
	{ print_with_type(value, std::cout) << std::endl; }
}

#endif
<|endoftext|>


<commit_before><commit_msg>Take intensity into account when culling lights<commit_after><|endoftext|>


<commit_before>#include <variant>
#include <cassert>

void test_constexpr()
{
    using variant = std::variant<bool,int,double>;

    constexpr variant v1{};
    static_assert(std::get<0>(v1)    == false);
    static_assert(std::get<bool>(v1) == false);

    constexpr variant v2{true};
    static_assert(std::get<0>(v2)   == true);
    static_assert(std::get<bool>(v2) == true);

    constexpr variant v3{11};
    static_assert(std::get<1>(v3)   == 11);
    static_assert(std::get<int>(v3) == 11);

    constexpr variant v4{22.22};
    static_assert(std::get<2>(v4)      == 22.22);
    static_assert(std::get<double>(v4) == 22.22);
}

int main()
{
    test_constexpr();
}
<commit_msg>more get tests<commit_after>#include <variant>
#include <string>
#include <cassert>

void test_constexpr_get()
{
    using variant = std::variant<bool,int,double>;

    constexpr variant v1{};
    static_assert(std::get<0>(v1)    == false);
    static_assert(std::get<bool>(v1) == false);

    constexpr variant v2{true};
    static_assert(std::get<0>(v2)   == true);
    static_assert(std::get<bool>(v2) == true);

    constexpr variant v3{11};
    static_assert(std::get<1>(v3)   == 11);
    static_assert(std::get<int>(v3) == 11);

    constexpr variant v4{22.22};
    static_assert(std::get<2>(v4)      == 22.22);
    static_assert(std::get<double>(v4) == 22.22);

    static_assert(std::get<2>(variant{3.3}) == 3.3);
}

void test_constexpr_get_if()
{
    using variant = std::variant<bool,int,double>;

    constexpr variant v1{};
    static_assert(std::get_if<0>(&v1)      != nullptr);
    static_assert(std::get_if<bool>(&v1)   != nullptr);
    static_assert(std::get_if<1>(&v1)      == nullptr);
    static_assert(std::get_if<int>(&v1)    == nullptr);
    static_assert(std::get_if<2>(&v1)      == nullptr);
    static_assert(std::get_if<double>(&v1) == nullptr);

    constexpr variant v2{true};
    static_assert(*std::get_if<0>(&v2)      == true);
    static_assert(std::get_if<0>(&v2)      != nullptr);
    static_assert(std::get_if<bool>(&v2)   != nullptr);
    static_assert(std::get_if<1>(&v2)      == nullptr);
    static_assert(std::get_if<int>(&v2)    == nullptr);
    static_assert(std::get_if<2>(&v2)      == nullptr);
    static_assert(std::get_if<double>(&v2) == nullptr);

    constexpr variant v3{11};
    static_assert(*std::get_if<1>(&v3)     == 11);
    static_assert(std::get_if<0>(&v3)      == nullptr);
    static_assert(std::get_if<bool>(&v3)   == nullptr);
    static_assert(std::get_if<1>(&v3)      != nullptr);
    static_assert(std::get_if<int>(&v3)    != nullptr);
    static_assert(std::get_if<2>(&v3)      == nullptr);
    static_assert(std::get_if<double>(&v3) == nullptr);

    constexpr variant v4{22.22};
    static_assert(*std::get_if<2>(&v4)     == 22.22);
    static_assert(std::get_if<0>(&v4)      == nullptr);
    static_assert(std::get_if<bool>(&v4)   == nullptr);
    static_assert(std::get_if<1>(&v4)      == nullptr);
    static_assert(std::get_if<int>(&v4)    == nullptr);
    static_assert(std::get_if<2>(&v4)      != nullptr);
    static_assert(std::get_if<double>(&v4) != nullptr);
}

void test_get()
{
    using variant = std::variant<bool,int,double,std::string>;

    variant v1{false};
    std::get<0>(v1) = true;
    assert(std::get<0>(v1) == true);

    variant v2{};
    std::get<3>(v2) = "ABCDEFG";
    assert(std::get<3>(v2) == "ABCDEFG");

    const variant v3{1};
    assert(std::get<1>(v3) == 3);
}

void test_get_if()
{
    using variant = std::variant<bool,int,double,std::string>;

    variant v1{false};
    *std::get_if<0>(&v1) = true;
    assert(*std::get_if<0>(&v1) == true);

    variant v2{};
    *std::get_if<3>(&v2) = "ABCDEFG";
    assert(*std::get_if<3>(&v2) == "ABCDEFG");

    const variant v3{1};
    assert(*std::get_if<1>(&v3) == 3);
}

int main()
{
    test_constexpr_get();
    test_constexpr_get_if();
    test_get();
    test_get_if();
}
<|endoftext|>


<commit_before>/*! \file
 *
 * \brief Python exports for module storage and database
 * \author Benjamin Pritchard (ben@bennyp.org)
 */

#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/dict.hpp>

// Various components
#include "bpmodule/modulebase/ModuleBase.hpp"
#include "bpmodule/modulelocator/CModuleLoader.hpp"
#include "bpmodule/modulelocator/PyModuleLoader.hpp"

using bpmodule::modulebase::ModuleBase;
using namespace boost::python;

namespace bpmodule {
namespace modulelocator {
namespace export_python {

////////////////////////////
// Main boost python part
////////////////////////////

BOOST_PYTHON_MODULE(modulelocator)
{
    //////////////////////
    // ModuleInfo
    //////////////////////
    // for now, we won't allow initialization from python
    class_<ModuleInfo>("ModuleInfo", no_init)
    .def("Print", &ModuleInfo::Print)
    .def_readonly("key", &ModuleInfo::key)
    .def_readonly("name", &ModuleInfo::name)
    .def_readonly("type", &ModuleInfo::type)
    .def_readonly("path", &ModuleInfo::path)
    .def_readonly("soname", &ModuleInfo::soname)
    .def_readonly("version", &ModuleInfo::version)
    .def_readonly("description", &ModuleInfo::description)
    .add_property("authors", boost::python::make_getter(&ModuleInfo::authors, return_value_policy<return_by_value>()))
    .add_property("refs", boost::python::make_getter(&ModuleInfo::refs, return_value_policy<return_by_value>()))
    .add_property("options", boost::python::make_getter(&ModuleInfo::options, return_value_policy<return_by_value>()))
    ;

    //////////////////////////
    // Main ModuleLocator and
    // module loaders
    //////////////////////////
    class_<ModuleLocator, boost::noncopyable>("ModuleLocator")
    .def("Size", &ModuleLocator::Size)
    .def("GetKeys", &ModuleLocator::GetKeys)
    .def("KeyInfo", &ModuleLocator::KeyInfo)
    .def("PrintInfo", &ModuleLocator::PrintInfo)
    .def("Has", &ModuleLocator::Has)
    .def("SetOptions", static_cast<void(ModuleLocator::*)(const std::string &, const boost::python::dict &)>(&ModuleLocator::SetOptions))
    .def("TestAll", &ModuleLocator::TestAll)
    .def("GetModule", &ModuleLocator::GetModulePy)
    ;

    class_<CModuleLoader, boost::noncopyable>("CModuleLoader", init<ModuleLocator *>())
    .def("LoadSO", static_cast<void(CModuleLoader::*)(const std::string &, const boost::python::dict &)>(&CModuleLoader::LoadSO));

    class_<PyModuleLoader, boost::noncopyable>("PyModuleLoader", init<ModuleLocator *>())
    .def("LoadPyModule", static_cast<void(PyModuleLoader::*)(const std::string &, boost::python::object, const boost::python::dict &)>(&PyModuleLoader::LoadPyModule));

}

} // close namespace export_python
} // close namespace modulelocator
} // close namespace bpmodule

<commit_msg>Remove namespace resolution<commit_after>/*! \file
 *
 * \brief Python exports for module storage and database
 * \author Benjamin Pritchard (ben@bennyp.org)
 */

#include <boost/python/module.hpp>
#include <boost/python/class.hpp>
#include <boost/python/dict.hpp>

// Various components
#include "bpmodule/modulebase/ModuleBase.hpp"
#include "bpmodule/modulelocator/CModuleLoader.hpp"
#include "bpmodule/modulelocator/PyModuleLoader.hpp"

using bpmodule::modulebase::ModuleBase;
using namespace boost::python;

namespace bpmodule {
namespace modulelocator {
namespace export_python {

////////////////////////////
// Main boost python part
////////////////////////////

BOOST_PYTHON_MODULE(modulelocator)
{
    //////////////////////
    // ModuleInfo
    //////////////////////
    // for now, we won't allow initialization from python
    class_<ModuleInfo>("ModuleInfo", no_init)
    .def("Print", &ModuleInfo::Print)
    .def_readonly("key", &ModuleInfo::key)
    .def_readonly("name", &ModuleInfo::name)
    .def_readonly("type", &ModuleInfo::type)
    .def_readonly("path", &ModuleInfo::path)
    .def_readonly("soname", &ModuleInfo::soname)
    .def_readonly("version", &ModuleInfo::version)
    .def_readonly("description", &ModuleInfo::description)
    .add_property("authors", make_getter(&ModuleInfo::authors, return_value_policy<return_by_value>()))
    .add_property("refs", make_getter(&ModuleInfo::refs, return_value_policy<return_by_value>()))
    .add_property("options", make_getter(&ModuleInfo::options, return_value_policy<return_by_value>()))
    ;

    //////////////////////////
    // Main ModuleLocator and
    // module loaders
    //////////////////////////
    class_<ModuleLocator, boost::noncopyable>("ModuleLocator")
    .def("Size", &ModuleLocator::Size)
    .def("GetKeys", &ModuleLocator::GetKeys)
    .def("KeyInfo", &ModuleLocator::KeyInfo)
    .def("PrintInfo", &ModuleLocator::PrintInfo)
    .def("Has", &ModuleLocator::Has)
    .def("SetOptions", static_cast<void(ModuleLocator::*)(const std::string &, const boost::python::dict &)>(&ModuleLocator::SetOptions))
    .def("TestAll", &ModuleLocator::TestAll)
    .def("GetModule", &ModuleLocator::GetModulePy)
    ;

    class_<CModuleLoader, boost::noncopyable>("CModuleLoader", init<ModuleLocator *>())
    .def("LoadSO", static_cast<void(CModuleLoader::*)(const std::string &, const boost::python::dict &)>(&CModuleLoader::LoadSO));

    class_<PyModuleLoader, boost::noncopyable>("PyModuleLoader", init<ModuleLocator *>())
    .def("LoadPyModule", static_cast<void(PyModuleLoader::*)(const std::string &, boost::python::object, const boost::python::dict &)>(&PyModuleLoader::LoadPyModule));

}

} // close namespace export_python
} // close namespace modulelocator
} // close namespace bpmodule

<|endoftext|>


<commit_before>/** @addtogroup FMI
 *  @{
 *  \copyright TU Dresden ZIH. All rights reserved.
 *  \authors Martin Flehmig, Marc Hartung, Marcus Walther
 *  \date Oct 2015
 */
#ifdef USE_FMILIB

#ifndef INCLUDE_FMI_FMILIBFMU_HPP_
#define INCLUDE_FMI_FMILIBFMU_HPP_

extern "C"
{
#include <fmilib.h>
}

#include "Stdafx.hpp"
#include "fmi/AbstractFmu.hpp"

namespace FMI
{
    class FmiLibFmu : public AbstractFmu
    {
     public:
        using AbstractFmu::getValuesInternal;
        using AbstractFmu::setValuesInternal;

        FmiLibFmu(const Initialization::FmuPlan & in);
        virtual ~FmiLibFmu();

        void load(const bool & alsoInit = true) override;
        void unload() override;
        void initialize() override;

        AbstractFmu * duplicate() override;

        void stepCompleted() override;
        FmuEventInfo eventUpdate() override;

        void setTime(const double & time) override;
        double getDefaultStart() const override;
        double getDefaultStop() const override;

     protected:

        void getStatesInternal(real_type * states) const override;
        void setStatesInternal(const real_type * states) override;
        void getStateDerivativesInternal(real_type * stateDerivatives) override;
        void getEventIndicatorsInternal(real_type * eventIndicators) override;

        void getValuesInternal(vector<real_type> & out, const vector<size_type> & references) const override;
        void getValuesInternal(vector<int_type> & out, const vector<size_type> & references) const override;
        void getValuesInternal(vector<bool_type> & out, const vector<size_type> & references) const override;
        void getValuesInternal(vector<string_type> & out, const vector<size_type> & references) const override;

        void setValuesInternal(const vector<real_type> & in, const vector<size_type> & references) override;
        void setValuesInternal(const vector<int_type> & in, const vector<size_type> & references) override;
        void setValuesInternal(const vector<bool_type> & in, const vector<size_type> & references) override;
        void setValuesInternal(const vector<string_type> & in, const vector<size_type> & references) override;

        fmi1_boolean_t toFmi1Boolean(bool_type value) const;
        size_type toSizeT(fmi1_value_reference_t value) const;

     private:

        static set<string_type> _loadedFmuObjects;
        set<string_type>::iterator _posPath;
        std::shared_ptr<fmi_import_context_t> _context;

        jm_callbacks _callbacks;
        std::shared_ptr<fmi1_import_t> _fmu;
        fmi1_event_info_t _fmuEventInfo;

        template<typename T>
        void addVariable(fmi1_import_variable_t * variable)
        {
            string_type varName = string_type(fmi1_import_get_variable_name(variable));
            size_type valueReference = fmi1_import_get_variable_vr(variable);
            _valueInfo.addNameReferencePair<T>(varName, valueReference);
            fmi1_causality_enu_t varCausality = fmi1_import_get_causality(variable);

            if (fmi1_import_get_variable_has_start(variable))
            {
                _startValues.getValues<T>().push_back(getStartValue<T>(variable));
                _startValueReferences.getValues<T>().push_back(valueReference);
            }
            _valueInfo.addNameReferencePair<T>(varName, valueReference);
            _allValueReferences.getValues<T>().push_back(valueReference);

            switch (varCausality)
            {
                case fmi1_causality_enu_t::fmi1_causality_enu_input:
                    _inputValueReferences.getValues<T>().push_back(valueReference);
                    //_startValues.getValues<T>().push_back(std::numeric_limits<T>::max());
                    //_startValueReferences.getValues<T>().push_back(valueReference);
                    break;
                case fmi1_causality_enu_t::fmi1_causality_enu_output:
                    _outputValueReferences.getValues<T>().push_back(valueReference);
                    break;
                default:
                    ;
            }
        }

        template<typename T>
        T getStartValue(fmi1_import_variable_t * variable)
        {
            throw std::runtime_error("FmiLibFmu: Unkown type for start value.");
        }
    };

    template<typename T>
    T getStartValue(fmi1_import_variable_t * variable)
    {
        throw std::runtime_error("FmiLibFmu: Unkown type for start value.");
    }
    template<>
    real_type FmiLibFmu::getStartValue<real_type>(fmi1_import_variable_t * variable);
    template<>
    int_type FmiLibFmu::getStartValue<int_type>(fmi1_import_variable_t * variable);
    template<>
    bool_type FmiLibFmu::getStartValue<bool_type>(fmi1_import_variable_t * variable);
    template<>
    string_type FmiLibFmu::getStartValue<string_type>(fmi1_import_variable_t * variable);

} /* namespace FMI */

#endif /* INCLUDE_FMI_FMILIBFMU_HPP_ */
/**
 * @}
 */

#endif
<commit_msg>Fix typo<commit_after>/** @addtogroup FMI
 *  @{
 *  \copyright TU Dresden ZIH. All rights reserved.
 *  \authors Martin Flehmig, Marc Hartung, Marcus Walther
 *  \date Oct 2015
 */
#ifdef USE_FMILIB

#ifndef INCLUDE_FMI_FMILIBFMU_HPP_
#define INCLUDE_FMI_FMILIBFMU_HPP_

extern "C"
{
#include <fmilib.h>
}

#include "Stdafx.hpp"
#include "fmi/AbstractFmu.hpp"

namespace FMI
{
    class FmiLibFmu : public AbstractFmu
    {
     public:
        using AbstractFmu::getValuesInternal;
        using AbstractFmu::setValuesInternal;

        FmiLibFmu(const Initialization::FmuPlan & in);
        virtual ~FmiLibFmu();

        void load(const bool & alsoInit = true) override;
        void unload() override;
        void initialize() override;

        AbstractFmu * duplicate() override;

        void stepCompleted() override;
        FmuEventInfo eventUpdate() override;

        void setTime(const double & time) override;
        double getDefaultStart() const override;
        double getDefaultStop() const override;

     protected:

        void getStatesInternal(real_type * states) const override;
        void setStatesInternal(const real_type * states) override;
        void getStateDerivativesInternal(real_type * stateDerivatives) override;
        void getEventIndicatorsInternal(real_type * eventIndicators) override;

        void getValuesInternal(vector<real_type> & out, const vector<size_type> & references) const override;
        void getValuesInternal(vector<int_type> & out, const vector<size_type> & references) const override;
        void getValuesInternal(vector<bool_type> & out, const vector<size_type> & references) const override;
        void getValuesInternal(vector<string_type> & out, const vector<size_type> & references) const override;

        void setValuesInternal(const vector<real_type> & in, const vector<size_type> & references) override;
        void setValuesInternal(const vector<int_type> & in, const vector<size_type> & references) override;
        void setValuesInternal(const vector<bool_type> & in, const vector<size_type> & references) override;
        void setValuesInternal(const vector<string_type> & in, const vector<size_type> & references) override;

        fmi1_boolean_t toFmi1Boolean(bool_type value) const;
        size_type toSizeT(fmi1_value_reference_t value) const;

     private:

        static set<string_type> _loadedFmuObjects;
        set<string_type>::iterator _posPath;
        std::shared_ptr<fmi_import_context_t> _context;

        jm_callbacks _callbacks;
        std::shared_ptr<fmi1_import_t> _fmu;
        fmi1_event_info_t _fmuEventInfo;

        template<typename T>
        void addVariable(fmi1_import_variable_t * variable)
        {
            string_type varName = string_type(fmi1_import_get_variable_name(variable));
            size_type valueReference = fmi1_import_get_variable_vr(variable);
            _valueInfo.addNameReferencePair<T>(varName, valueReference);
            fmi1_causality_enu_t varCausality = fmi1_import_get_causality(variable);

            if (fmi1_import_get_variable_has_start(variable))
            {
                _startValues.getValues<T>().push_back(getStartValue<T>(variable));
                _startValueReferences.getValues<T>().push_back(valueReference);
            }
            _valueInfo.addNameReferencePair<T>(varName, valueReference);
            _allValueReferences.getValues<T>().push_back(valueReference);

            switch (varCausality)
            {
                case fmi1_causality_enu_t::fmi1_causality_enu_input:
                    _inputValueReferences.getValues<T>().push_back(valueReference);
                    //_startValues.getValues<T>().push_back(std::numeric_limits<T>::max());
                    //_startValueReferences.getValues<T>().push_back(valueReference);
                    break;
                case fmi1_causality_enu_t::fmi1_causality_enu_output:
                    _outputValueReferences.getValues<T>().push_back(valueReference);
                    break;
                default:
                    ;
            }
        }

        template<typename T>
        T getStartValue(fmi1_import_variable_t * variable)
        {
            throw std::runtime_error("FmiLibFmu: Unknown type for start value.");
        }
    };

    template<typename T>
    T getStartValue(fmi1_import_variable_t * variable)
    {
        throw std::runtime_error("FmiLibFmu: Unknown type for start value.");
    }
    template<>
    real_type FmiLibFmu::getStartValue<real_type>(fmi1_import_variable_t * variable);
    template<>
    int_type FmiLibFmu::getStartValue<int_type>(fmi1_import_variable_t * variable);
    template<>
    bool_type FmiLibFmu::getStartValue<bool_type>(fmi1_import_variable_t * variable);
    template<>
    string_type FmiLibFmu::getStartValue<string_type>(fmi1_import_variable_t * variable);

} /* namespace FMI */

#endif /* INCLUDE_FMI_FMILIBFMU_HPP_ */
/**
 * @}
 */

#endif
<|endoftext|>


<commit_before>#include "root_path.hpp"
#include "../content_format.hpp"

#include <cthun-agent/modules/status.hpp>
#include <cthun-agent/configuration.hpp>

#include <cthun-client/protocol/chunks.hpp>       // ParsedChunks

#include <leatherman/json_container/json_container.hpp>
#include <leatherman/file_util/file.hpp>
#include <leatherman/util/strings.hpp>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

#include <catch.hpp>

#include <cstdio>

namespace CthunAgent {

namespace lth_jc = leatherman::json_container;
namespace lth_util = leatherman::util;

static const std::string QUERY_ACTION { "query" };

boost::format STATUS_FORMAT {
    "{  \"transaction_id\" : \"2345236346\","
    "    \"module\" : \"status\","
    "    \"action\" : \"query\","
    "    \"params\" : {\"job_id\" : \"%1%\"}"
    "}"
};

static const std::string STATUS_TXT { (STATUS_FORMAT % "the-uuid-string").str() };

static const std::vector<lth_jc::JsonContainer> NO_DEBUG {};

static const CthunClient::ParsedChunks PARSED_CHUNKS {
                    lth_jc::JsonContainer(ENVELOPE_TXT),
                    lth_jc::JsonContainer(STATUS_TXT),
                    NO_DEBUG,
                    0 };

TEST_CASE("Modules::Status::executeAction", "[modules]") {
    Modules::Status status_module {};

    SECTION("the status module is correctly named") {
        REQUIRE(status_module.module_name == "status");
    }

    SECTION("the inventory module has the 'query' action") {
        auto found = std::find(status_module.actions.begin(),
                               status_module.actions.end(),
                               QUERY_ACTION);
        REQUIRE(found != status_module.actions.end());
    }

    SECTION("it can call the 'query' action") {
        ActionRequest request { RequestType::Blocking, PARSED_CHUNKS };
        REQUIRE_NOTHROW(status_module.executeAction(request));
    }

    SECTION("it works properly when an unknown job id is provided") {
        auto job_id = lth_util::get_UUID();
        std::string other_status_txt { (STATUS_FORMAT % job_id).str() };
        CthunClient::ParsedChunks other_chunks {
                lth_jc::JsonContainer(ENVELOPE_TXT),
                lth_jc::JsonContainer(other_status_txt),
                NO_DEBUG,
                0 };
        ActionRequest request { RequestType::Blocking, other_chunks };

        SECTION("it doesn't throw") {
            REQUIRE_NOTHROW(status_module.executeAction(request));
        }

        SECTION("it returns status 'Unknown'") {
            auto outcome = status_module.executeAction(request);
            REQUIRE(outcome.results.get<std::string>("status") == "Unknown");
        }
    }

    SECTION("it correctly retrieves the file content of a known job") {
        std::string result_path { std::string { CTHUN_AGENT_ROOT_PATH }
                                  + "/lib/tests/resources/delayed_result" };
        boost::filesystem::path to { result_path };

        if (!boost::filesystem::exists(DEFAULT_ACTION_RESULTS_DIR)
            && !boost::filesystem::create_directory(DEFAULT_ACTION_RESULTS_DIR)) {
            FAIL("Failed to create the results directory");
        }

        auto symlink_name = lth_util::get_UUID();
        std::string symlink_path { DEFAULT_ACTION_RESULTS_DIR + symlink_name };
        boost::filesystem::path symlink { symlink_path };

        std::string other_status_txt { (STATUS_FORMAT % symlink_name).str() };
        CthunClient::ParsedChunks other_chunks {
                lth_jc::JsonContainer(ENVELOPE_TXT),
                lth_jc::JsonContainer(other_status_txt),
                NO_DEBUG,
                0 };
        ActionRequest request { RequestType::Blocking, other_chunks };

        try {
            boost::filesystem::create_symlink(to, symlink);
        } catch (boost::filesystem::filesystem_error) {
            FAIL("Failed to create the symlink");
        }

        SECTION("it doesn't throw") {
            REQUIRE_NOTHROW(status_module.executeAction(request));
        }

        SECTION("it returns the action status") {
            auto outcome = status_module.executeAction(request);
            REQUIRE(outcome.results.get<std::string>("status") == "Completed");
        }

        SECTION("it returns the action output") {
            auto outcome = status_module.executeAction(request);
            REQUIRE(outcome.results.get<std::string>("stdout") == "***OUTPUT\n");
        }

        SECTION("it returns the action error string") {
            auto outcome = status_module.executeAction(request);
            REQUIRE(outcome.results.get<std::string>("stderr") == "***ERROR\n");
        }

        boost::filesystem::remove(symlink_path);
    }
}

}  // namespace CthunAgent
<commit_msg>(maint) Fix typo in status module test<commit_after>#include "root_path.hpp"
#include "../content_format.hpp"

#include <cthun-agent/modules/status.hpp>
#include <cthun-agent/configuration.hpp>

#include <cthun-client/protocol/chunks.hpp>       // ParsedChunks

#include <leatherman/json_container/json_container.hpp>
#include <leatherman/file_util/file.hpp>
#include <leatherman/util/strings.hpp>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

#include <catch.hpp>

#include <cstdio>

namespace CthunAgent {

namespace lth_jc = leatherman::json_container;
namespace lth_util = leatherman::util;

static const std::string QUERY_ACTION { "query" };

boost::format STATUS_FORMAT {
    "{  \"transaction_id\" : \"2345236346\","
    "    \"module\" : \"status\","
    "    \"action\" : \"query\","
    "    \"params\" : {\"job_id\" : \"%1%\"}"
    "}"
};

static const std::string STATUS_TXT { (STATUS_FORMAT % "the-uuid-string").str() };

static const std::vector<lth_jc::JsonContainer> NO_DEBUG {};

static const CthunClient::ParsedChunks PARSED_CHUNKS {
                    lth_jc::JsonContainer(ENVELOPE_TXT),
                    lth_jc::JsonContainer(STATUS_TXT),
                    NO_DEBUG,
                    0 };

TEST_CASE("Modules::Status::executeAction", "[modules]") {
    Modules::Status status_module {};

    SECTION("the status module is correctly named") {
        REQUIRE(status_module.module_name == "status");
    }

    SECTION("the status module has the 'query' action") {
        auto found = std::find(status_module.actions.begin(),
                               status_module.actions.end(),
                               QUERY_ACTION);
        REQUIRE(found != status_module.actions.end());
    }

    SECTION("it can call the 'query' action") {
        ActionRequest request { RequestType::Blocking, PARSED_CHUNKS };
        REQUIRE_NOTHROW(status_module.executeAction(request));
    }

    SECTION("it works properly when an unknown job id is provided") {
        auto job_id = lth_util::get_UUID();
        std::string other_status_txt { (STATUS_FORMAT % job_id).str() };
        CthunClient::ParsedChunks other_chunks {
                lth_jc::JsonContainer(ENVELOPE_TXT),
                lth_jc::JsonContainer(other_status_txt),
                NO_DEBUG,
                0 };
        ActionRequest request { RequestType::Blocking, other_chunks };

        SECTION("it doesn't throw") {
            REQUIRE_NOTHROW(status_module.executeAction(request));
        }

        SECTION("it returns status 'Unknown'") {
            auto outcome = status_module.executeAction(request);
            REQUIRE(outcome.results.get<std::string>("status") == "Unknown");
        }
    }

    SECTION("it correctly retrieves the file content of a known job") {
        std::string result_path { std::string { CTHUN_AGENT_ROOT_PATH }
                                  + "/lib/tests/resources/delayed_result" };
        boost::filesystem::path to { result_path };

        if (!boost::filesystem::exists(DEFAULT_ACTION_RESULTS_DIR)
            && !boost::filesystem::create_directory(DEFAULT_ACTION_RESULTS_DIR)) {
            FAIL("Failed to create the results directory");
        }

        auto symlink_name = lth_util::get_UUID();
        std::string symlink_path { DEFAULT_ACTION_RESULTS_DIR + symlink_name };
        boost::filesystem::path symlink { symlink_path };

        std::string other_status_txt { (STATUS_FORMAT % symlink_name).str() };
        CthunClient::ParsedChunks other_chunks {
                lth_jc::JsonContainer(ENVELOPE_TXT),
                lth_jc::JsonContainer(other_status_txt),
                NO_DEBUG,
                0 };
        ActionRequest request { RequestType::Blocking, other_chunks };

        try {
            boost::filesystem::create_symlink(to, symlink);
        } catch (boost::filesystem::filesystem_error) {
            FAIL("Failed to create the symlink");
        }

        SECTION("it doesn't throw") {
            REQUIRE_NOTHROW(status_module.executeAction(request));
        }

        SECTION("it returns the action status") {
            auto outcome = status_module.executeAction(request);
            REQUIRE(outcome.results.get<std::string>("status") == "Completed");
        }

        SECTION("it returns the action output") {
            auto outcome = status_module.executeAction(request);
            REQUIRE(outcome.results.get<std::string>("stdout") == "***OUTPUT\n");
        }

        SECTION("it returns the action error string") {
            auto outcome = status_module.executeAction(request);
            REQUIRE(outcome.results.get<std::string>("stderr") == "***ERROR\n");
        }

        boost::filesystem::remove(symlink_path);
    }
}

}  // namespace CthunAgent
<|endoftext|>


<commit_before>/*
 * EepromManager.cpp
 *
 * Created: 23/04/2013 03:15:44
 *  Author: mat
 */

#include "Brewpi.h"
#include <stddef.h>

#include "EepromManager.h"
#include "TempControl.h"
#include "EepromFormat.h"
#include "PiLink.h"

EepromManager eepromManager;
EepromAccess eepromAccess;

#define pointerOffset(x) offsetof(EepromFormat, x)

EepromManager::EepromManager()
{
	eepromSizeCheck();
}

bool EepromManager::hasSettings()
{
	uint8_t version = eepromAccess.readByte(pointerOffset(version));
	return (version==EEPROM_FORMAT_VERSION);
}

void EepromManager::zapEeprom()
{
	for (uint16_t offset=0; offset<EepromFormat::MAX_EEPROM_SIZE; offset++)
		eepromAccess.writeByte(offset, 0xFF);
}

void EepromManager::initializeEeprom()
{
	deviceManager.setupUnconfiguredDevices();

	// fetch the default values
	tempControl.loadDefaultConstants();
	tempControl.loadDefaultSettings();

	// write the default constants
	for (uint8_t c=0; c<EepromFormat::MAX_CHAMBERS; c++) {
		eptr_t pv = pointerOffset(chambers)+(c*sizeof(ChamberBlock)) ;
		tempControl.storeConstants(pv+offsetof(ChamberBlock, chamberSettings.cc));
		pv += offsetof(ChamberBlock, beer)+offsetof(BeerBlock, cs);
		for (uint8_t b=0; b<ChamberBlock::MAX_BEERS; b++) {
//			logDeveloper(PSTR("EepromManager - saving settings for beer %d at %d"), b, (uint16_t)pv);
			tempControl.storeSettings(pv);
			pv += sizeof(BeerBlock);		// advance to next beer
		}
	}

	// clear the rest of eeprom
	for (uint16_t offset=pointerOffset(devices); offset<EepromFormat::MAX_EEPROM_SIZE; offset++)
		eepromAccess.writeByte(offset, 0);

	// set the version flag - so that storeDevice will work
	eepromAccess.writeByte(0, EEPROM_FORMAT_VERSION);

	saveDefaultDevices();
}

uint8_t EepromManager::saveDefaultDevices()
{
	DeviceConfig config;
	clear((uint8_t*)&config, sizeof(config));

#if BREWPI_STATIC_CONFIG==BREWPI_SHIELD_REV_A
	// single-chamber single beer config from original shield

	config.chamber = 1;			// all devices are in chamber 1
	config.hw.invert = 1;		// all pin devices inverted

	config.deviceHardware = DEVICE_HARDWARE_PIN;

	config.deviceFunction = DEVICE_CHAMBER_DOOR;
	config.hw.pinNr = doorPin;
	eepromManager.storeDevice(config, 0);

	config.deviceFunction = DEVICE_CHAMBER_HEAT;
	config.hw.pinNr = heatingPin;
	eepromManager.storeDevice(config, 1);

	config.deviceFunction = DEVICE_CHAMBER_COOL;
	config.hw.pinNr = heatingPin;
	eepromManager.storeDevice(config, 2);

	config.deviceHardware = DEVICE_HARDWARE_ONEWIRE_TEMP;
	config.hw.pinNr = fridgeSensorPin;
	config.deviceFunction = DEVICE_CHAMBER_TEMP;
	eepromManager.storeDevice(config, 3);

	config.beer = 1;
	config.hw.pinNr = beerSensorPin;
	config.deviceFunction = DEVICE_BEER_TEMP;
	eepromManager.storeDevice(config, 4);

	return 5;

#elif BREWPI_STATIC_CONFIG==BREWPI_SHIELD_REV_C
	// the only component that's not dynamic is the door
	return 0;
#else
	return 0;
#endif
}

#define arraySize(x) (sizeof(x)/sizeof(x[0]))

bool EepromManager::applySettings()
{
	if (!hasSettings())
		return false;

	// start from a clean state
	deviceManager.setupUnconfiguredDevices();

	logDeveloper("Applying settings");

	// load the one chamber and one beer for now
	eptr_t pv = pointerOffset(chambers);
	tempControl.loadConstants(pv+offsetof(ChamberBlock, chamberSettings.cc));
	tempControl.loadSettings(pv+offsetof(ChamberBlock, beer[0].cs));

	logDeveloper("Applied settings");

	if (!BREWPI_SIMULATE) {
		DeviceConfig deviceConfig;
		for (uint8_t index = 0; fetchDevice(deviceConfig, index); index++)
		{
			if (deviceManager.isDeviceValid(deviceConfig, deviceConfig, index))
				deviceManager.installDevice(deviceConfig);
			else {
				clear((uint8_t*)&deviceConfig, sizeof(deviceConfig));
				eepromManager.storeDevice(deviceConfig, index);
			}
		}
	}
	return true;
}

void EepromManager::storeTempConstantsAndSettings()
{
	uint8_t chamber = 0;
	eptr_t pv = pointerOffset(chambers);
	pv += sizeof(ChamberBlock)*chamber;
	tempControl.storeConstants(pv+offsetof(ChamberBlock, chamberSettings.cc));

	storeTempSettings();
}

void EepromManager::storeTempSettings()
{
	uint8_t chamber = 0;
	eptr_t pv = pointerOffset(chambers);
	pv += sizeof(ChamberBlock)*chamber;
	// for now assume just one beer.
	tempControl.storeSettings(pv+offsetof(ChamberBlock, beer[0].cs));
}

#if !BREWPI_SIMULATE

bool EepromManager::fetchDevice(DeviceConfig& config, uint8_t deviceIndex)
{
	bool ok = (hasSettings() && deviceIndex<EepromFormat::MAX_DEVICES);
	if (ok)
		eepromAccess.readBlock(&config, pointerOffset(devices)+sizeof(DeviceConfig)*deviceIndex, sizeof(DeviceConfig));
	return ok;
}

bool EepromManager::storeDevice(const DeviceConfig& config, uint8_t deviceIndex)
{
	bool ok = (hasSettings() && deviceIndex<EepromFormat::MAX_DEVICES);
	if (ok)
		eepromAccess.writeBlock(pointerOffset(devices)+sizeof(DeviceConfig)*deviceIndex, &config, sizeof(DeviceConfig));
	return ok;
}

#endif // !BREWPI_SIMULATE

void fill(int8_t* p, uint8_t size) {
	while (size-->0) *p++ = -1;
}
void clear(uint8_t* p, uint8_t size) {
	while (size-->0) *p++ = 0;
}

<commit_msg>clear all of eeprom<commit_after>/*
 * EepromManager.cpp
 *
 * Created: 23/04/2013 03:15:44
 *  Author: mat
 */

#include "Brewpi.h"
#include <stddef.h>

#include "EepromManager.h"
#include "TempControl.h"
#include "EepromFormat.h"
#include "PiLink.h"

EepromManager eepromManager;
EepromAccess eepromAccess;

#define pointerOffset(x) offsetof(EepromFormat, x)

EepromManager::EepromManager()
{
	eepromSizeCheck();
}

bool EepromManager::hasSettings()
{
	uint8_t version = eepromAccess.readByte(pointerOffset(version));
	return (version==EEPROM_FORMAT_VERSION);
}

void EepromManager::zapEeprom()
{
	for (uint16_t offset=0; offset<EepromFormat::MAX_EEPROM_SIZE; offset++)
		eepromAccess.writeByte(offset, 0xFF);
}

void EepromManager::initializeEeprom()
{
	// clear all eeprom
	for (uint16_t offset=0; offset<EepromFormat::MAX_EEPROM_SIZE; offset++)
		eepromAccess.writeByte(offset, 0);

	deviceManager.setupUnconfiguredDevices();

	// fetch the default values
	tempControl.loadDefaultConstants();
	tempControl.loadDefaultSettings();

	// write the default constants
	for (uint8_t c=0; c<EepromFormat::MAX_CHAMBERS; c++) {
		eptr_t pv = pointerOffset(chambers)+(c*sizeof(ChamberBlock)) ;
		tempControl.storeConstants(pv+offsetof(ChamberBlock, chamberSettings.cc));
		pv += offsetof(ChamberBlock, beer)+offsetof(BeerBlock, cs);
		for (uint8_t b=0; b<ChamberBlock::MAX_BEERS; b++) {
//			logDeveloper(PSTR("EepromManager - saving settings for beer %d at %d"), b, (uint16_t)pv);
			tempControl.storeSettings(pv);
			pv += sizeof(BeerBlock);		// advance to next beer
		}
	}

	// set the version flag - so that storeDevice will work
	eepromAccess.writeByte(0, EEPROM_FORMAT_VERSION);

	saveDefaultDevices();
}

uint8_t EepromManager::saveDefaultDevices()
{
	DeviceConfig config;
	clear((uint8_t*)&config, sizeof(config));

#if BREWPI_STATIC_CONFIG==BREWPI_SHIELD_REV_A
	// single-chamber single beer config from original shield

	config.chamber = 1;			// all devices are in chamber 1
	config.hw.invert = 1;		// all pin devices inverted

	config.deviceHardware = DEVICE_HARDWARE_PIN;

	config.deviceFunction = DEVICE_CHAMBER_DOOR;
	config.hw.pinNr = doorPin;
	eepromManager.storeDevice(config, 0);

	config.deviceFunction = DEVICE_CHAMBER_HEAT;
	config.hw.pinNr = heatingPin;
	eepromManager.storeDevice(config, 1);

	config.deviceFunction = DEVICE_CHAMBER_COOL;
	config.hw.pinNr = heatingPin;
	eepromManager.storeDevice(config, 2);

	config.deviceHardware = DEVICE_HARDWARE_ONEWIRE_TEMP;
	config.hw.pinNr = fridgeSensorPin;
	config.deviceFunction = DEVICE_CHAMBER_TEMP;
	eepromManager.storeDevice(config, 3);

	config.beer = 1;
	config.hw.pinNr = beerSensorPin;
	config.deviceFunction = DEVICE_BEER_TEMP;
	eepromManager.storeDevice(config, 4);

	return 5;

#elif BREWPI_STATIC_CONFIG==BREWPI_SHIELD_REV_C
	// the only component that's not dynamic is the door
	return 0;
#else
	return 0;
#endif
}

#define arraySize(x) (sizeof(x)/sizeof(x[0]))

bool EepromManager::applySettings()
{
	if (!hasSettings())
		return false;

	// start from a clean state
	deviceManager.setupUnconfiguredDevices();

	logDeveloper("Applying settings");

	// load the one chamber and one beer for now
	eptr_t pv = pointerOffset(chambers);
	tempControl.loadConstants(pv+offsetof(ChamberBlock, chamberSettings.cc));
	tempControl.loadSettings(pv+offsetof(ChamberBlock, beer[0].cs));

	logDeveloper("Applied settings");

	if (!BREWPI_SIMULATE) {
		DeviceConfig deviceConfig;
		for (uint8_t index = 0; fetchDevice(deviceConfig, index); index++)
		{
			if (deviceManager.isDeviceValid(deviceConfig, deviceConfig, index))
				deviceManager.installDevice(deviceConfig);
			else {
				clear((uint8_t*)&deviceConfig, sizeof(deviceConfig));
				eepromManager.storeDevice(deviceConfig, index);
			}
		}
	}
	return true;
}

void EepromManager::storeTempConstantsAndSettings()
{
	uint8_t chamber = 0;
	eptr_t pv = pointerOffset(chambers);
	pv += sizeof(ChamberBlock)*chamber;
	tempControl.storeConstants(pv+offsetof(ChamberBlock, chamberSettings.cc));

	storeTempSettings();
}

void EepromManager::storeTempSettings()
{
	uint8_t chamber = 0;
	eptr_t pv = pointerOffset(chambers);
	pv += sizeof(ChamberBlock)*chamber;
	// for now assume just one beer.
	tempControl.storeSettings(pv+offsetof(ChamberBlock, beer[0].cs));
}

#if !BREWPI_SIMULATE

bool EepromManager::fetchDevice(DeviceConfig& config, uint8_t deviceIndex)
{
	bool ok = (hasSettings() && deviceIndex<EepromFormat::MAX_DEVICES);
	if (ok)
		eepromAccess.readBlock(&config, pointerOffset(devices)+sizeof(DeviceConfig)*deviceIndex, sizeof(DeviceConfig));
	return ok;
}

bool EepromManager::storeDevice(const DeviceConfig& config, uint8_t deviceIndex)
{
	bool ok = (hasSettings() && deviceIndex<EepromFormat::MAX_DEVICES);
	if (ok)
		eepromAccess.writeBlock(pointerOffset(devices)+sizeof(DeviceConfig)*deviceIndex, &config, sizeof(DeviceConfig));
	return ok;
}

#endif // !BREWPI_SIMULATE

void fill(int8_t* p, uint8_t size) {
	while (size-->0) *p++ = -1;
}
void clear(uint8_t* p, uint8_t size) {
	while (size-->0) *p++ = 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2013, Cloudera, inc.
#include "common/scan_spec.h"
#include "common/schema.h"
#include "common/row.h"
#include "tablet/tablet.h"
#include "tablet/transaction_context.h"
#include "benchmarks/tpch/local_line_item_dao.h"
#include "benchmarks/tpch/tpch-schemas.h"

namespace kudu {

using metadata::TabletMasterBlockPB;
using metadata::TabletMetadata;

void LocalLineItemDAO::Init() {
  // Hard-coded master block
  TabletMasterBlockPB master_block;
  master_block.set_tablet_id("tpch1");
  master_block.set_block_a("9865b0f142ed4d1aaa7dac6eddf281e4");
  master_block.set_block_b("b0f65c47c2a84dcf9ec4e95dd63f4393");

  // Try to load it. If it was not found, create a new one.
  gscoped_ptr<kudu::metadata::TabletMetadata> metadata;
  CHECK_OK(TabletMetadata::LoadOrCreate(&fs_manager_, master_block,
                                        tpch::CreateLineItemSchema(), "", "", &metadata));

  tablet_.reset(new tablet::Tablet(metadata.Pass()));
  CHECK_OK(tablet_->Open());
}

void LocalLineItemDAO::WriteLine(const ConstContiguousRow &row) {
  CHECK_OK(tablet_->Insert(&tx_ctx_, row));
  tx_ctx_.Reset();
}

void LocalLineItemDAO::MutateLine(const ConstContiguousRow &row, const faststring &mutations) {
  // Call MutateRow with context, rb, schema and a list of changes such as:
  // RowChangeListEncoder(schema_, &update_buf).AddColumnUpdate(col_idx, &new_val);
  // CHECK_OK(tablet_->MutateRow(&dummy, rb.row(), schema_, RowChangeList(update_buf)));
}

void LocalLineItemDAO::FinishWriting() {
  CHECK_OK(tablet_->Flush());
}

void LocalLineItemDAO::OpenScanner(const Schema &query_schema, ScanSpec *spec) {
  CHECK_OK(tablet_->NewRowIterator(query_schema, &current_iter_));
  CHECK_OK(current_iter_->Init(spec));
}

bool LocalLineItemDAO::HasMore() {
  return current_iter_->HasNext();
}

void LocalLineItemDAO::GetNext(RowBlock *block) {
  CHECK_OK(RowwiseIterator::CopyBlock(current_iter_.get(), block));
}

bool LocalLineItemDAO::IsTableEmpty() {
  return tablet_->num_rowsets() == 0;
}

LocalLineItemDAO::~LocalLineItemDAO() {

}

} // namespace kudu
<commit_msg>tpch: add column IDs to tpch schema when creating on disk<commit_after>// Copyright (c) 2013, Cloudera, inc.
#include "common/scan_spec.h"
#include "common/schema.h"
#include "common/row.h"
#include "tablet/tablet.h"
#include "tablet/transaction_context.h"
#include "benchmarks/tpch/local_line_item_dao.h"
#include "benchmarks/tpch/tpch-schemas.h"

namespace kudu {

using metadata::TabletMasterBlockPB;
using metadata::TabletMetadata;

void LocalLineItemDAO::Init() {
  // Hard-coded master block
  TabletMasterBlockPB master_block;
  master_block.set_tablet_id("tpch1");
  master_block.set_block_a("9865b0f142ed4d1aaa7dac6eddf281e4");
  master_block.set_block_b("b0f65c47c2a84dcf9ec4e95dd63f4393");

  // Try to load it. If it was not found, create a new one.
  Schema s = SchemaBuilder(tpch::CreateLineItemSchema()).Build();
  gscoped_ptr<kudu::metadata::TabletMetadata> metadata;
  CHECK_OK(TabletMetadata::LoadOrCreate(&fs_manager_, master_block, s,
                                        "", "", &metadata));

  tablet_.reset(new tablet::Tablet(metadata.Pass()));
  CHECK_OK(tablet_->Open());
}

void LocalLineItemDAO::WriteLine(const ConstContiguousRow &row) {
  CHECK_OK(tablet_->Insert(&tx_ctx_, row));
  tx_ctx_.Reset();
}

void LocalLineItemDAO::MutateLine(const ConstContiguousRow &row, const faststring &mutations) {
  // Call MutateRow with context, rb, schema and a list of changes such as:
  // RowChangeListEncoder(schema_, &update_buf).AddColumnUpdate(col_idx, &new_val);
  // CHECK_OK(tablet_->MutateRow(&dummy, rb.row(), schema_, RowChangeList(update_buf)));
}

void LocalLineItemDAO::FinishWriting() {
  CHECK_OK(tablet_->Flush());
}

void LocalLineItemDAO::OpenScanner(const Schema &query_schema, ScanSpec *spec) {
  CHECK_OK(tablet_->NewRowIterator(query_schema, &current_iter_));
  CHECK_OK(current_iter_->Init(spec));
}

bool LocalLineItemDAO::HasMore() {
  return current_iter_->HasNext();
}

void LocalLineItemDAO::GetNext(RowBlock *block) {
  CHECK_OK(RowwiseIterator::CopyBlock(current_iter_.get(), block));
}

bool LocalLineItemDAO::IsTableEmpty() {
  return tablet_->num_rowsets() == 0;
}

LocalLineItemDAO::~LocalLineItemDAO() {

}

} // namespace kudu
<|endoftext|>


<commit_before>/**
 * @file radical_main.cpp
 * @author Nishant Mehta
 *
 * Executable for RADICAL.
 */

#include <mlpack/core.hpp>
#include <armadillo>
#include "radical.hpp"

PROGRAM_INFO("RADICAL", "An implementation of RADICAL, a method for independent"
    "component analysis (ICA).  Assuming that we have an input matrix X, the"
    "goal is to find a square unmixing matrix W such that Y = W * X and the "
    "dimensions of Y are independent components.\n"
    "\n"
    "For more details, see the following paper:\n"
    "\n"
    "@article{\n"
    "  title = {ICA Using Spacings Estimates of Entropy},\n"
    "  author = {Learned-Miller, E.G. and Fisher III, J.W.},\n"
    "  journal = {Journal of Machine Learning Research},\n"
    "  volume = {4},\n"
    "  pages = {1271--1295},\n"
    "  year = {2003}\n"
    "}");

PARAM_STRING_REQ("input_file", "Input dataset filename for ICA.", "");

PARAM_STRING("output_ic", "File to save independent components to.", "o",
    "output_ic.csv");
PARAM_STRING("output_unmixing", "File to save unmixing matrix to.", "u",
    "output_unmixing.csv");

PARAM_DOUBLE("noise_std_dev", "Standard deviation of Gaussian noise", "",
    0.175);
PARAM_INT("replicates", "Number of Gaussian-perturbed replicates to use "
    "(per point) in Radical2D.", "", 30);
PARAM_INT("angles", "Number of angles to consider in brute-force search "
    "during Radical2D.", "", 150);
PARAM_INT("sweeps", "Number of sweeps (each sweep calls Radical2D once for "
    "each pair of dimensions", "", 0);

using namespace mlpack;
using namespace mlpack::radical;
using namespace std;
using namespace arma;

int main(int argc, char* argv[])
{
  // Handle parameters.
  CLI::ParseCommandLine(argc, argv);

  // Load the data.
  const string matXFilename = CLI::GetParam<string>("input_file");
  mat matX;
  data::Load(matXFilename, matX);

  // Load parameters.
  double noiseStdDev = CLI::GetParam<double>("noise_std_dev");
  size_t nReplicates = CLI::GetParam<int>("replicates");
  size_t nAngles = CLI::GetParam<int>("angles");
  size_t nSweeps = CLI::GetParam<int>("sweeps");

  if (nSweeps == 0)
  {
    nSweeps = matX.n_rows - 1;
  }

  // Run RADICAL.
  Radical rad(noiseStdDev, nReplicates, nAngles, nSweeps);
  mat matY;
  mat matW;
  rad.DoRadical(matX, matY, matW);

  // save results
  const string matYFilename = CLI::GetParam<string>("output_ic");
  data::Save(matYFilename, matY);

  const string matWFilename = CLI::GetParam<string>("output_unmixing");
  data::Save(matWFilename, matW);

  /*
  // compute and print objective
  mat matYT = trans(matY);
  double valEst = 0;
  for(size_t i = 0; i < matYT.n_cols; i++)
  {
    vec Yi = vec(matYT.col(i));
    valEst += rad.Vasicek(Yi);
  }
  Log::Info << "Objective (estimate): " << valEst << "." << endl;
  */
}
<commit_msg>Allow setting of random seed for RADICAL.<commit_after>/**
 * @file radical_main.cpp
 * @author Nishant Mehta
 *
 * Executable for RADICAL.
 */

#include <mlpack/core.hpp>
#include <armadillo>
#include "radical.hpp"

PROGRAM_INFO("RADICAL", "An implementation of RADICAL, a method for independent"
    "component analysis (ICA).  Assuming that we have an input matrix X, the"
    "goal is to find a square unmixing matrix W such that Y = W * X and the "
    "dimensions of Y are independent components.\n"
    "\n"
    "For more details, see the following paper:\n"
    "\n"
    "@article{\n"
    "  title = {ICA Using Spacings Estimates of Entropy},\n"
    "  author = {Learned-Miller, E.G. and Fisher III, J.W.},\n"
    "  journal = {Journal of Machine Learning Research},\n"
    "  volume = {4},\n"
    "  pages = {1271--1295},\n"
    "  year = {2003}\n"
    "}");

PARAM_STRING_REQ("input_file", "Input dataset filename for ICA.", "i");

PARAM_STRING("output_ic", "File to save independent components to.", "o",
    "output_ic.csv");
PARAM_STRING("output_unmixing", "File to save unmixing matrix to.", "u",
    "output_unmixing.csv");

PARAM_DOUBLE("noise_std_dev", "Standard deviation of Gaussian noise.", "n",
    0.175);
PARAM_INT("replicates", "Number of Gaussian-perturbed replicates to use "
    "(per point) in Radical2D.", "r", 30);
PARAM_INT("angles", "Number of angles to consider in brute-force search "
    "during Radical2D.", "a", 150);
PARAM_INT("sweeps", "Number of sweeps (each sweep calls Radical2D once for "
    "each pair of dimensions", "S", 0);
PARAM_INT("seed", "Random seed.  If 0, 'std::time(NULL)' is used.", "s", 0);

using namespace mlpack;
using namespace mlpack::radical;
using namespace std;
using namespace arma;

int main(int argc, char* argv[])
{
  // Handle parameters.
  CLI::ParseCommandLine(argc, argv);

  // Set random seed.
  if (CLI::GetParam<int>("seed") != 0)
    math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
  else
    math::RandomSeed((size_t) std::time(NULL));

  // Load the data.
  const string matXFilename = CLI::GetParam<string>("input_file");
  mat matX;
  data::Load(matXFilename, matX);

  // Load parameters.
  double noiseStdDev = CLI::GetParam<double>("noise_std_dev");
  size_t nReplicates = CLI::GetParam<int>("replicates");
  size_t nAngles = CLI::GetParam<int>("angles");
  size_t nSweeps = CLI::GetParam<int>("sweeps");

  if (nSweeps == 0)
  {
    nSweeps = matX.n_rows - 1;
  }

  // Run RADICAL.
  Radical rad(noiseStdDev, nReplicates, nAngles, nSweeps);
  mat matY;
  mat matW;
  rad.DoRadical(matX, matY, matW);

  // save results
  const string matYFilename = CLI::GetParam<string>("output_ic");
  data::Save(matYFilename, matY);

  const string matWFilename = CLI::GetParam<string>("output_unmixing");
  data::Save(matWFilename, matW);

  /*
  // compute and print objective
  mat matYT = trans(matY);
  double valEst = 0;
  for(size_t i = 0; i < matYT.n_cols; i++)
  {
    vec Yi = vec(matYT.col(i));
    valEst += rad.Vasicek(Yi);
  }
  Log::Info << "Objective (estimate): " << valEst << "." << endl;
  */
}
<|endoftext|>