<commit_before>#include "RDom.h"
#include "Util.h"
#include "IROperator.h"
#include "IRPrinter.h"

namespace Halide {

using namespace Internal;

using std::string;
using std::vector;

RVar::operator Expr() const {
    if (!min().defined() || !extent().defined()) {
        user_error << "Use of undefined RDom dimension: " <<
            (name().empty() ? "<unknown>" : name()) << "\n";
    }
    return Variable::make(Int(32), name(), domain());
}

Expr RVar::min() const {
    if (_domain.defined()) {
        return _var().min;
    } else {
        return Expr();
    }
}

Expr RVar::extent() const {
    if (_domain.defined()) {
        return _var().extent;
    } else {
        return Expr();
    }
}

const std::string &RVar::name() const {
    if (_domain.defined()) {
        return _var().var;
    } else {
        return _name;
    }
}

template <int N>
ReductionDomain build_domain(ReductionVariable (&vars)[N]) {
    vector<ReductionVariable> d(&vars[0], &vars[N]);
    ReductionDomain dom(d);
    return dom;
}

// This just initializes the predefined x, y, z, w members of RDom.
void RDom::init_vars(string name) {
    static string var_names[] = { "x", "y", "z", "w" };

    const std::vector<ReductionVariable> &dom_vars = dom.domain();
    RVar *vars[] = { &x, &y, &z, &w };

    for (size_t i = 0; i < sizeof(vars)/sizeof(vars[0]); i++) {
        if (i < dom_vars.size()) {
            *(vars[i]) = RVar(dom, i);
        } else {
            *(vars[i]) = RVar(name + "." + var_names[i]);
        }
    }
}

RDom::RDom(ReductionDomain d) : dom(d) {
    if (d.defined()) {
        init_vars("");
    }
}

void RDom::initialize_from_ranges(const std::vector<std::pair<Expr, Expr>> &ranges, string name) {
    if (name.empty()) {
        name = make_entity_name(this, "Halide::RDom", 'r');
    }

    std::vector<ReductionVariable> vars;
    for (size_t i = 0; i < ranges.size(); i++) {
        std::string rvar_uniquifier;
        switch (i) {
            case 0: rvar_uniquifier = "x"; break;
            case 1: rvar_uniquifier = "y"; break;
            case 2: rvar_uniquifier = "z"; break;
            case 3: rvar_uniquifier = "w"; break;
            default: rvar_uniquifier = std::to_string(i); break;
        }
        ReductionVariable rv;
        rv.var = name + "." + rvar_uniquifier + "$r";
        rv.min = cast<int32_t>(ranges[i].first);
        rv.extent = cast<int32_t>(ranges[i].second);
        vars.push_back(rv);
    }
    dom = ReductionDomain(vars);
    init_vars(name);
}

RDom::RDom(Buffer b) {
    static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
    std::vector<ReductionVariable> vars;
    for (int i = 0; i < b.dimensions(); i++) {
        ReductionVariable var = {
            b.name() + "." + var_names[i],
            b.min(i),
            b.extent(i)
        };
        vars.push_back(var);
    }

    dom = ReductionDomain(vars);
    init_vars(b.name());
}

RDom::RDom(ImageParam p) {
    static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
    std::vector<ReductionVariable> vars;
    for (int i = 0; i < p.dimensions(); i++) {
        ReductionVariable var = {
            p.name() + "." + var_names[i],
            p.min(i),
            p.extent(i)
        };
        vars.push_back(var);
    }

    dom = ReductionDomain(vars);
    init_vars(p.name());
}

int RDom::dimensions() const {
    return (int)dom.domain().size();
}

RVar RDom::operator[](int i) const {
    if (i == 0) return x;
    if (i == 1) return y;
    if (i == 2) return z;
    if (i == 3) return w;
    if (i < dimensions()) {
        return RVar(dom, i);
    }
    user_error << "Reduction domain index out of bounds: " << i << "\n";
    return x; // Keep the compiler happy
}

RDom::operator Expr() const {
    if (dimensions() != 1) {
        user_error << "Error: Can't treat this multidimensional RDom as an Expr:\n"
                   << (*this) << "\n"
                   << "Only single-dimensional RDoms can be cast to Expr.\n";
    }
    return Expr(x);
}

RDom::operator RVar() const {
    if (dimensions() != 1) {
        user_error << "Error: Can't treat this multidimensional RDom as an RVar:\n"
                   << (*this) << "\n"
                   << "Only single-dimensional RDoms can be cast to RVar.\n";
    }
    return x;
}

/** Emit an RVar in a human-readable form */
std::ostream &operator<<(std::ostream &stream, RVar v) {
    stream << v.name() << "(" << v.min() << ", " << v.extent() << ")";
    return stream;
}

/** Emit an RDom in a human-readable form. */
std::ostream &operator<<(std::ostream &stream, RDom dom) {
    stream << "RDom(\n";
    for (int i = 0; i < dom.dimensions(); i++) {
        stream << "  " << dom[i] << "\n";
    }
    stream << ")\n";
    return stream;
}

}
<commit_msg>Better error messages when RDoms depend on Funcs or Vars<commit_after>#include "RDom.h"
#include "Util.h"
#include "IROperator.h"
#include "IRPrinter.h"

namespace Halide {

using namespace Internal;

using std::string;
using std::vector;

RVar::operator Expr() const {
    if (!min().defined() || !extent().defined()) {
        user_error << "Use of undefined RDom dimension: " <<
            (name().empty() ? "<unknown>" : name()) << "\n";
    }
    return Variable::make(Int(32), name(), domain());
}

Expr RVar::min() const {
    if (_domain.defined()) {
        return _var().min;
    } else {
        return Expr();
    }
}

Expr RVar::extent() const {
    if (_domain.defined()) {
        return _var().extent;
    } else {
        return Expr();
    }
}

const std::string &RVar::name() const {
    if (_domain.defined()) {
        return _var().var;
    } else {
        return _name;
    }
}

template <int N>
ReductionDomain build_domain(ReductionVariable (&vars)[N]) {
    vector<ReductionVariable> d(&vars[0], &vars[N]);
    ReductionDomain dom(d);
    return dom;
}

// This just initializes the predefined x, y, z, w members of RDom.
void RDom::init_vars(string name) {
    static string var_names[] = { "x", "y", "z", "w" };

    const std::vector<ReductionVariable> &dom_vars = dom.domain();
    RVar *vars[] = { &x, &y, &z, &w };

    for (size_t i = 0; i < sizeof(vars)/sizeof(vars[0]); i++) {
        if (i < dom_vars.size()) {
            *(vars[i]) = RVar(dom, i);
        } else {
            *(vars[i]) = RVar(name + "." + var_names[i]);
        }
    }
}

RDom::RDom(ReductionDomain d) : dom(d) {
    if (d.defined()) {
        init_vars("");
    }
}

namespace {
class CheckRDomBounds : public IRGraphVisitor {

    using IRGraphVisitor::visit;

    void visit(const Call *op) {
        IRGraphVisitor::visit(op);
        if (op->call_type == Call::Halide) {
            offending_func = op->name;
        }
    }

    void visit(const Variable *op) {
        if (!op->param.defined() && !op->image.defined()) {
            offending_free_var = op->name;
        }
    }
public:
    string offending_func;
    string offending_free_var;
};
}

void RDom::initialize_from_ranges(const std::vector<std::pair<Expr, Expr>> &ranges, string name) {
    if (name.empty()) {
        name = make_entity_name(this, "Halide::RDom", 'r');
    }

    std::vector<ReductionVariable> vars;
    for (size_t i = 0; i < ranges.size(); i++) {
        CheckRDomBounds checker;
        ranges[i].first.accept(&checker);
        ranges[i].second.accept(&checker);
        user_assert(checker.offending_func.empty())
            << "The bounds of the RDom " << name
            << " in dimension " << i
            << " are:\n"
            << "  " << ranges[i].first << " ... " << ranges[i].second << "\n"
            << "These depend on a call to the Func " << checker.offending_func << ".\n"
            << "The bounds of an RDom may not depend on a call to a Func.\n";
        user_assert(checker.offending_free_var.empty())
            << "The bounds of the RDom " << name
            << " in dimension " << i
            << " are:\n"
            << "  " << ranges[i].first << " ... " << ranges[i].second << "\n"
            << "These depend on the variable " << checker.offending_free_var << ".\n"
            << "The bounds of an RDom may not depend on a free variable.\n";

        std::string rvar_uniquifier;
        switch (i) {
            case 0: rvar_uniquifier = "x"; break;
            case 1: rvar_uniquifier = "y"; break;
            case 2: rvar_uniquifier = "z"; break;
            case 3: rvar_uniquifier = "w"; break;
            default: rvar_uniquifier = std::to_string(i); break;
        }
        ReductionVariable rv;
        rv.var = name + "." + rvar_uniquifier + "$r";
        rv.min = cast<int32_t>(ranges[i].first);
        rv.extent = cast<int32_t>(ranges[i].second);
        vars.push_back(rv);
    }
    dom = ReductionDomain(vars);
    init_vars(name);
}

RDom::RDom(Buffer b) {
    static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
    std::vector<ReductionVariable> vars;
    for (int i = 0; i < b.dimensions(); i++) {
        ReductionVariable var = {
            b.name() + "." + var_names[i],
            b.min(i),
            b.extent(i)
        };
        vars.push_back(var);
    }

    dom = ReductionDomain(vars);
    init_vars(b.name());
}

RDom::RDom(ImageParam p) {
    static string var_names[] = {"x$r", "y$r", "z$r", "w$r"};
    std::vector<ReductionVariable> vars;
    for (int i = 0; i < p.dimensions(); i++) {
        ReductionVariable var = {
            p.name() + "." + var_names[i],
            p.min(i),
            p.extent(i)
        };
        vars.push_back(var);
    }

    dom = ReductionDomain(vars);
    init_vars(p.name());
}

int RDom::dimensions() const {
    return (int)dom.domain().size();
}

RVar RDom::operator[](int i) const {
    if (i == 0) return x;
    if (i == 1) return y;
    if (i == 2) return z;
    if (i == 3) return w;
    if (i < dimensions()) {
        return RVar(dom, i);
    }
    user_error << "Reduction domain index out of bounds: " << i << "\n";
    return x; // Keep the compiler happy
}

RDom::operator Expr() const {
    if (dimensions() != 1) {
        user_error << "Error: Can't treat this multidimensional RDom as an Expr:\n"
                   << (*this) << "\n"
                   << "Only single-dimensional RDoms can be cast to Expr.\n";
    }
    return Expr(x);
}

RDom::operator RVar() const {
    if (dimensions() != 1) {
        user_error << "Error: Can't treat this multidimensional RDom as an RVar:\n"
                   << (*this) << "\n"
                   << "Only single-dimensional RDoms can be cast to RVar.\n";
    }
    return x;
}

/** Emit an RVar in a human-readable form */
std::ostream &operator<<(std::ostream &stream, RVar v) {
    stream << v.name() << "(" << v.min() << ", " << v.extent() << ")";
    return stream;
}

/** Emit an RDom in a human-readable form. */
std::ostream &operator<<(std::ostream &stream, RDom dom) {
    stream << "RDom(\n";
    for (int i = 0; i < dom.dimensions(); i++) {
        stream << "  " << dom[i] << "\n";
    }
    stream << ")\n";
    return stream;
}

}
<|endoftext|>


<commit_before>/*
Copyright 2014-2015 Adam Grandquist

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.
 */
/**
 * @author Adam Grandquist
 * @copyright Apache
 */

#ifndef REQL_HPP_
#define REQL_HPP_

#include "./cpp/connection.hpp"
#include "./cpp/cursor.hpp"
#include "./cpp/error.hpp"
#include "./cpp/query.hpp"

#endif  // REQL_H_
<commit_msg>Fix bad end comment.<commit_after>/*
Copyright 2014-2015 Adam Grandquist

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.
 */
/**
 * @author Adam Grandquist
 * @copyright Apache
 */

#ifndef REQL_HPP_
#define REQL_HPP_

#include "./cpp/connection.hpp"
#include "./cpp/cursor.hpp"
#include "./cpp/error.hpp"
#include "./cpp/query.hpp"

#endif  // REQL_HPP_
<|endoftext|>


<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces.
 * Copyright (C) 2005, 2006, 2007 Roman Schindlauer
 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner
 * Copyright (C) 2009, 2010 Peter Schüller
 * Copyright (C) 2011, 2012, 2013 Christoph Redl
 *
 * This file is part of dlvhex.
 *
 * dlvhex is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * dlvhex 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 dlvhex; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */

/**
 * @file Term.cpp
 * @author Christoph Redl
 *
 * @brief Implementation of Term.h
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

#include "dlvhex2/Term.h"
#include "dlvhex2/Logger.h"
#include "dlvhex2/Printhelpers.h"
#include "dlvhex2/Interpretation.h"
#include "dlvhex2/Registry.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/PluginInterface.h"
#include "dlvhex2/OrdinaryAtomTable.h"

#include <boost/foreach.hpp>
#include <map>

DLVHEX_NAMESPACE_BEGIN

Term::Term(IDKind kind, const std::vector<ID>& arguments, RegistryPtr reg): kind(kind), arguments(arguments) {
	assert(ID(kind,0).isTerm());
	assert(arguments.size() > 0);

	updateSymbolOfNestedTerm(reg.get());
}

void Term::updateSymbolOfNestedTerm(Registry* reg){
	std::stringstream ss;
	ss << reg->terms.getByID(arguments[0]).symbol;
	if (arguments.size() > 1){
		ss << "(";
		for (uint32_t i = 1; i < arguments.size(); ++i){
			ss << (i > 1 ? "," : "");
			if (arguments[i].isIntegerTerm()){
				ss << arguments[i].address;
			}else{
				ss << reg->terms.getByID(arguments[i]).symbol;
			}
		}
		ss << ")";
	}

	symbol = ss.str();
}

// restores the hierarchical structure of a term from a string representation
void Term::analyzeTerm(RegistryPtr reg){

	// get token: function name and arguments
	bool quoted = false;
	bool primitive = true;
	int nestedcount = 0;
	int start = 0;
	int end = symbol.length();
	std::vector<std::string> tuple;
	//DBGLOG(DBG,"Analyzing Term '" << symbol << "'");
	for (int pos = 0; pos < end; ++pos){
		if (symbol[pos] == '\"' &&
				(pos == 0 || symbol[pos-1] != '\\')) quoted = !quoted;
		if (symbol[pos] == '(' && !quoted ) {
			if (nestedcount == 0) {
				primitive = false;
				tuple.push_back(symbol.substr(start, pos - start));
				start = pos + 1;
				// eliminate closing bracket
				assert(symbol[end-1] == ')');
				end--;
			}
			nestedcount++;
		}
		if (symbol[pos] == ')' && !quoted){
			nestedcount--;
		}
		if (symbol[pos] == ',' && !quoted && nestedcount == 1){
			tuple.push_back(symbol.substr(start, pos - start));
			start = pos + 1;
		}
		if (pos == end - 1){
			tuple.push_back(symbol.substr(start, pos - start + 1));
		}
	}
	// we did not find a ( -> it is primitive, or
	// we came into (, increased by one, and eliminated the closing )
	// therefore if it is not primitive we must leave the loop at 1
	assert(primitive || nestedcount == 1);
#ifndef NDEBUG
	{
		std::stringstream ss;
		ss << "Term tuple: ";
		bool first = true;
		BOOST_FOREACH (std::string str, tuple){
			if (!first) ss << ", ";
			first = false;
			ss << str;
		}
		DBGLOG(DBG, ss.str());
	}
#endif

	// convert tuple of strings to terms
	arguments.clear();
	if (primitive){
		arguments.push_back(ID_FAIL);
		if (islower(symbol[0]) || symbol[0] == '\"') kind |= ID::SUBKIND_TERM_CONSTANT;
		if (isupper(symbol[0])) kind |= ID::SUBKIND_TERM_VARIABLE;
	}else{
		BOOST_FOREACH (std::string str, tuple){
			Term t(ID::MAINKIND_TERM, str);
			t.analyzeTerm(reg);
			if (t.arguments[0] == ID_FAIL){
				if (islower(t.symbol[0]) || t.symbol[0] == '\"') t.kind |= ID::SUBKIND_TERM_CONSTANT;
				if (isupper(t.symbol[0])) t.kind |= ID::SUBKIND_TERM_VARIABLE;
			}else{
				t.kind |= ID::SUBKIND_TERM_NESTED;
			}
			ID tid = reg->storeTerm(t);
			arguments.push_back(tid);
		}
		kind |= ID::SUBKIND_TERM_NESTED;
	}
}

DLVHEX_NAMESPACE_END
<commit_msg>not putting "dummy ID" for non-nested terms<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces.
 * Copyright (C) 2005, 2006, 2007 Roman Schindlauer
 * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner
 * Copyright (C) 2009, 2010 Peter Schüller
 * Copyright (C) 2011, 2012, 2013 Christoph Redl
 *
 * This file is part of dlvhex.
 *
 * dlvhex is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * dlvhex 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 dlvhex; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 */

/**
 * @file Term.cpp
 * @author Christoph Redl
 *
 * @brief Implementation of Term.h
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

#include "dlvhex2/Term.h"
#include "dlvhex2/Logger.h"
#include "dlvhex2/Printhelpers.h"
#include "dlvhex2/Interpretation.h"
#include "dlvhex2/Registry.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/PluginInterface.h"
#include "dlvhex2/OrdinaryAtomTable.h"

#include <boost/foreach.hpp>
#include <map>

DLVHEX_NAMESPACE_BEGIN

Term::Term(IDKind kind, const std::vector<ID>& arguments, RegistryPtr reg): kind(kind), arguments(arguments) {
	assert(ID(kind,0).isTerm());
	assert(arguments.size() > 0);

	updateSymbolOfNestedTerm(reg.get());
}

void Term::updateSymbolOfNestedTerm(Registry* reg){
	std::stringstream ss;
	ss << reg->terms.getByID(arguments[0]).symbol;
	if (arguments.size() > 1){
		ss << "(";
		for (uint32_t i = 1; i < arguments.size(); ++i){
			ss << (i > 1 ? "," : "");
			if (arguments[i].isIntegerTerm()){
				ss << arguments[i].address;
			}else{
				ss << reg->terms.getByID(arguments[i]).symbol;
			}
		}
		ss << ")";
	}

	symbol = ss.str();
}

// restores the hierarchical structure of a term from a string representation
void Term::analyzeTerm(RegistryPtr reg){

	// get token: function name and arguments
	bool quoted = false;
	bool primitive = true;
	int nestedcount = 0;
	int start = 0;
	int end = symbol.length();
	std::vector<std::string> tuple;
	//DBGLOG(DBG,"Analyzing Term '" << symbol << "'");
	for (int pos = 0; pos < end; ++pos){
		if (symbol[pos] == '\"' &&
				(pos == 0 || symbol[pos-1] != '\\')) quoted = !quoted;
		if (symbol[pos] == '(' && !quoted ) {
			if (nestedcount == 0) {
				primitive = false;
				tuple.push_back(symbol.substr(start, pos - start));
				start = pos + 1;
				// eliminate closing bracket
				assert(symbol[end-1] == ')');
				end--;
			}
			nestedcount++;
		}
		if (symbol[pos] == ')' && !quoted){
			nestedcount--;
		}
		if (symbol[pos] == ',' && !quoted && nestedcount == 1){
			tuple.push_back(symbol.substr(start, pos - start));
			start = pos + 1;
		}
		if (pos == end - 1){
			tuple.push_back(symbol.substr(start, pos - start + 1));
		}
	}
	// we did not find a ( -> it is primitive, or
	// we came into (, increased by one, and eliminated the closing )
	// therefore if it is not primitive we must leave the loop at 1
	assert(primitive || nestedcount == 1);
#ifndef NDEBUG
	{
		std::stringstream ss;
		ss << "Term tuple: ";
		bool first = true;
		BOOST_FOREACH (std::string str, tuple){
			if (!first) ss << ", ";
			first = false;
			ss << str;
		}
		DBGLOG(DBG, ss.str());
	}
#endif

	// convert tuple of strings to terms
	arguments.clear();
	if (primitive){
		// no arguments
		if (islower(symbol[0]) || symbol[0] == '\"') kind |= ID::SUBKIND_TERM_CONSTANT;
		if (isupper(symbol[0])) kind |= ID::SUBKIND_TERM_VARIABLE;
	}else{
		BOOST_FOREACH (std::string str, tuple){
			Term t(ID::MAINKIND_TERM, str);
			t.analyzeTerm(reg);
			if (t.arguments[0] == ID_FAIL){
				if (islower(t.symbol[0]) || t.symbol[0] == '\"') t.kind |= ID::SUBKIND_TERM_CONSTANT;
				if (isupper(t.symbol[0])) t.kind |= ID::SUBKIND_TERM_VARIABLE;
			}else{
				t.kind |= ID::SUBKIND_TERM_NESTED;
			}
			ID tid = reg->storeTerm(t);
			arguments.push_back(tid);
		}
		kind |= ID::SUBKIND_TERM_NESTED;
	}
}

DLVHEX_NAMESPACE_END
<|endoftext|>


<commit_before>//2014.04.01 - 2014.04.02 - 2014.04.03 Gustaf - CTG.

/* OBJECTIVE :

=== PLAN ===

- Function to identify the start and end positions of the target inside the source string.
 ok- Convert to a function and Test functionality.

 - Return a list with the positions.
 For each target string, just the initial position is needed.
 The final can be calculated easily with the length of the target string.

*/

#include <iostream>

using namespace std;

typedef char *arrayString;
typedef int  *arrayInt;

struct posIniNode
{
  int posInitial;

  posIniNode *next; // Pointer to the same struct.
};

typedef posIniNode *posList; // type reserved for the head pointer.

int lengthFunction(arrayString s)
{
  // Determine the length of a string array.
  int count = 0;
  while (s[count] != 0) // not includes the "null terminator".
  {
    count++;
  }
  return count;
}

// void identifyLimits (arrayString sourceStr, arrayString targetStr, arrayInt &arrayLimitsResult)
void identifyLimits (arrayString sourceStr, arrayString targetStr, posList &positionsResult)
{

  int posIni = -1, posFinal = -1;

  /*
    const int RESULT_SIZE = 2;
    arrayInt newArrayLimits = new int[RESULT_SIZE]; // At the end it is going to point to: arrayLimitsResult.

  */

  int SOURCE_SIZE = lengthFunction(sourceStr);
  int TARGET_SIZE = lengthFunction(targetStr);

  // --- Linked list

  // Head pointer
  posList newPositionsResult;

  // Nodes
  posIniNode *node1 = new posIniNode;
  node1 -> posInitial = -1;

  //Linking the list, just one node.
  newPositionsResult = node1;
  node1 -> next = NULL;

  // Cleaning things up to avoid cross-linking.
  node1 = NULL;

  // ---

  // -----------------------------------
  // -----------------------------------

  posIni = -1, posFinal = -1;
  for (int i = 0; i < SOURCE_SIZE; ++i)
  {

    // Find first character.
    if ( (posIni == -1) && (posFinal == -1) && (sourceStr[i] == targetStr[0]) )
    {
      posIni = i;
      newPositionsResult -> posInitial = posIni; //New node????

      // Handles special case of one character.
      if (TARGET_SIZE == 1)
      {
        cout << "Target initial/final - index: " << targetStr[0] << " - " << posIni << endl;
        cout << endl;

        posIni = -1, posFinal = -1; // Reset.
      }

      // Handles cases from two characters until ...
      for (int j = 1; j < TARGET_SIZE; ++j)
      {

        // Check second adjacent character.
        if ( (posFinal == -1) && ( (i + j) == (posIni + j)) )
        {
          if (sourceStr[i + j] == targetStr[j])
          {
            posFinal = i + j;
          }

          if (sourceStr[i + j] != targetStr[j])
          {
            posIni = -1, posFinal = -1; // Reset.
          }
        }

        // Check next adjacent character. BUT not the last.
        if ( (posFinal != -1) && ((i + j) == (posIni + j)) && (j <= (TARGET_SIZE - 2)) )
        {
          if (sourceStr[i + j] == targetStr[j])
          {
            posFinal = i + j;
          }

          if (sourceStr[i + j] != targetStr[j])
          {
            posIni = -1, posFinal = -1; // Reset.
          }
        }

        // Check last adjacent character.
        if ( (posFinal != -1) && ((i + j) == (posIni + j)) && (j == (TARGET_SIZE - 1)) )
        {
          if (sourceStr[i + j] == targetStr[j])
          {
            posFinal = i + j;

            cout << "Target initial - index: " << targetStr[0] << " - " << posIni << endl;
            cout << "Target final   - index: " << targetStr[j] << " - " << posFinal << endl;
            cout << endl;
          }

          posIni = -1, posFinal = -1; // Reset.
        }

      } // internal for
    } // if that check the first character.

  } // external for

  // -----------------------------------
  // -----------------------------------

  // -- To avoid a memory leak.

  /*
    delete[] arrayLimitsResult;
    arrayLimitsResult = newArrayLimits;
  */

  delete[] positionsResult;
  positionsResult = newPositionsResult;

}

void identifyLimitsTester ()
{

  const int ARRAY_SIZE = 9;
  arrayString a = new char[ARRAY_SIZE];

  a[0] = 'a'; a[1] = 'b'; a[2] = 'c'; a[3] = 'd';
  a[4] = 'a'; a[5] = 'b'; a[6] = 'c'; a[7] = 'e'; a[8] = 0;

  // -- Different tests for the TARGET STRING

  // const int TARGET_SIZE = 9;
  // arrayString t = new char[TARGET_SIZE];
  // t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 'd';
  // t[4] = 'a'; t[5] = 'b'; t[6] = 'c'; t[7] = 'e'; t[8] = 'f'; t[9] = 0;

  // const int TARGET_SIZE = 8;
  // arrayString t = new char[TARGET_SIZE];
  // t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 'd';
  // t[4] = 'a'; t[5] = 'b'; t[6] = 'c'; t[7] = 'e'; t[8] = 0;

  // const int TARGET_SIZE = 4;
  // arrayString t = new char[TARGET_SIZE];
  // t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 0;

  // const int TARGET_SIZE = 3;
  // arrayString t = new char[TARGET_SIZE];
  // t[0] = 'a'; t[1] = 'b'; t[2] = 0;

  const int TARGET_SIZE = 2; arrayString t = new char[TARGET_SIZE];
  t[0] = 'a'; t[1] = 0;

  /// ---

  //--------------------------

  // const int RESULT_SIZE = 1;
  // arrayInt resultLimits = new int[RESULT_SIZE];

  /*=================

  struct posIniNode
  {
    int posInitial;

    posIniNode *next; // Pointer to the same struct.
  };

  typedef posIniNode *posList;
  ==========================

  */

  // -- Linked list

  // Head pointer
  posList resultLimits;

  // Nodes
  posIniNode *node1 = new posIniNode;
  node1 -> posInitial = -1;

  //Linking the list, just one node.
  resultLimits = node1;
  node1 -> next = NULL;

  // Cleaning things up to avoid cross-linking.
  node1 = NULL;

  //-------------------------------------------------

  cout << "Initial string : " << a << endl;
  cout << "Target string  : " << t << endl;
  cout << endl;
  identifyLimits(a, t, resultLimits);

  cout << "Positions: " << resultLimits -> posInitial << endl;
  cout << endl;

  // Free dynamic memory.
  delete[] a;
  delete[] t;
  delete[] resultLimits;

}

int main()
{
  cout << "Variable-Length String Manipulation. Function to identify limits." << endl;
  identifyLimitsTester();

  cout << endl;
  return 0;
}
<commit_msg>Chapter 04 exercice 4-3 partial progress. Now return a linked list of initial positions. Work in progress.<commit_after>//2014.04.01 - 2014.04.02 - 2014.04.03 - 2014.04.05 Gustaf - CTG.

/* OBJECTIVE :

=== PLAN ===

- Function to identify the start and end positions of the target inside the source string.
 ok- Convert to a function and Test functionality.

 - Return a list with the positions.
 For each target string, just the initial position is needed.
 The final can be calculated easily with the length of the target string.

*/

#include <iostream>

using namespace std;

typedef char *arrayString;
typedef int  *arrayInt;

struct posIniNode
{
  int posInitial;

  posIniNode *next; // Pointer to the same struct.
};

typedef posIniNode *posList; // type reserved for the head pointer.

void addPosition(posList &posResult, int posIni)
{
  // After the new node is created, it is linked into the list at the beginning.

  // New node
  posIniNode *newNode = new posIniNode;
  newNode -> posInitial = posIni;

  newNode -> next = posResult; // linked at the beginning of the list.
  posResult = newNode; // new head pointer.
}

int lengthFunction(arrayString s)
{
  // Determine the length of a string array.
  int count = 0;
  while (s[count] != 0) // not includes the "null terminator".
  {
    count++;
  }
  return count;
}

// void identifyLimits (arrayString sourceStr, arrayString targetStr, arrayInt &arrayLimitsResult)
void identifyLimits (arrayString sourceStr, arrayString targetStr, posList &positionsResult)
{

  int posIni = -1, posFinal = -1;

  /*
    const int RESULT_SIZE = 2;
    arrayInt newArrayLimits = new int[RESULT_SIZE]; // At the end it is going to point to: arrayLimitsResult.

  */

  int SOURCE_SIZE = lengthFunction(sourceStr);
  int TARGET_SIZE = lengthFunction(targetStr);

  // --- Linked list

  // Head pointer
  posList newPositionsResult;

  /*  // Nodes
    posIniNode *node1 = new posIniNode;
    node1 -> posInitial = -1;

    //Linking the list, just one node.
    newPositionsResult = node1;
    node1 -> next = NULL;

    // Cleaning things up to avoid cross-linking.
    node1 = NULL;
  */
  // ---

  // -----------------------------------
  // -----------------------------------

  posIni = -1, posFinal = -1;
  for (int i = 0; i < SOURCE_SIZE; ++i)
  {

    // Find first character.
    if ( (posIni == -1) && (posFinal == -1) && (sourceStr[i] == targetStr[0]) )
    {
      posIni = i;

      // Handles special case of one character.
      if (TARGET_SIZE == 1)
      {
        addPosition(newPositionsResult, posIni); // A new node for every new initial position.

        cout << "Target initial/final - index: " << targetStr[0] << " - " << posIni << endl;
        cout << endl;

        posIni = -1, posFinal = -1; // Reset.
      }

      // Handles cases from two characters until ...
      for (int j = 1; j < TARGET_SIZE; ++j)
      {

        // Check second adjacent character.
        if ( (posFinal == -1) && ( (i + j) == (posIni + j)) )
        {
          if (sourceStr[i + j] == targetStr[j])
          {
            posFinal = i + j;
          }

          if (sourceStr[i + j] != targetStr[j])
          {
            posIni = -1, posFinal = -1; // Reset.
          }
        }

        // Check next adjacent character. BUT not the last.
        if ( (posFinal != -1) && ((i + j) == (posIni + j)) && (j <= (TARGET_SIZE - 2)) )
        {
          if (sourceStr[i + j] == targetStr[j])
          {
            posFinal = i + j;
          }

          if (sourceStr[i + j] != targetStr[j])
          {
            posIni = -1, posFinal = -1; // Reset.
          }
        }

        // Check last adjacent character.
        if ( (posFinal != -1) && ((i + j) == (posIni + j)) && (j == (TARGET_SIZE - 1)) )
        {
          if (sourceStr[i + j] == targetStr[j])
          {
            posFinal = i + j;

            addPosition(newPositionsResult, posIni); // A new node for every new initial position.

            cout << "Target initial - index: " << targetStr[0] << " - " << posIni << endl;
            cout << "Target final   - index: " << targetStr[j] << " - " << posFinal << endl;
            cout << endl;
          }

          posIni = -1, posFinal = -1; // Reset.
        }

      } // for - inner
    } // if - check the first character.

  } // for - outer

  // -----------------------------------
  // -----------------------------------

  // -- To avoid a memory leak.

  /*
    delete[] arrayLimitsResult;
    arrayLimitsResult = newArrayLimits;
  */

  delete[] positionsResult;
  positionsResult = newPositionsResult;

}

void identifyLimitsTester ()
{

  const int ARRAY_SIZE = 9;
  arrayString a = new char[ARRAY_SIZE];

  a[0] = 'a'; a[1] = 'b'; a[2] = 'c'; a[3] = 'd';
  a[4] = 'a'; a[5] = 'b'; a[6] = 'c'; a[7] = 'e'; a[8] = 0;

  // -- Different tests for the TARGET STRING

  // const int TARGET_SIZE = 9;
  // arrayString t = new char[TARGET_SIZE];
  // t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 'd';
  // t[4] = 'a'; t[5] = 'b'; t[6] = 'c'; t[7] = 'e'; t[8] = 'f'; t[9] = 0;

  // const int TARGET_SIZE = 8;
  // arrayString t = new char[TARGET_SIZE];
  // t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 'd';
  // t[4] = 'a'; t[5] = 'b'; t[6] = 'c'; t[7] = 'e'; t[8] = 0;

  const int TARGET_SIZE = 4;
  arrayString t = new char[TARGET_SIZE];
  t[0] = 'a'; t[1] = 'b'; t[2] = 'c'; t[3] = 0;

  // const int TARGET_SIZE = 3;
  // arrayString t = new char[TARGET_SIZE];
  // t[0] = 'b'; t[1] = 'c'; t[2] = 0;

  // const int TARGET_SIZE = 2; arrayString t = new char[TARGET_SIZE];
  // t[0] = 'a'; t[1] = 0;

  /// ---

  //--------------------------

  // const int RESULT_SIZE = 1;
  // arrayInt resultLimits = new int[RESULT_SIZE];

  // -- Linked list

  // Head pointer
  posList resultLimits;

  /*
    // Nodes
    posIniNode *node1 = new posIniNode;
    node1 -> posInitial = 99;

    //Linking the list, just one node.
    resultLimits = node1;
    node1 -> next = NULL;

    // Cleaning things up to avoid cross-linking.
    node1 = NULL;

  */
  //-------------------------------------------------

  /*
  =================
  struct posIniNode
  {
    int posInitial;

    posIniNode *next; // Pointer to the same struct.
  };

  typedef posIniNode *posList;
  ==========================

  */

  cout << "Initial string : " << a << endl;
  cout << "Target string  : " << t << endl;
  cout << endl;
  identifyLimits(a, t, resultLimits);

  cout << "Initial Positions (reverse order): ";
  posIniNode *loopPtr = resultLimits;
  while (loopPtr != NULL)
  {
    cout << loopPtr->posInitial << " - ";
    loopPtr = loopPtr->next;
  }
  cout << endl;

  // Free dynamic memory.
  delete[] a;
  delete[] t;
  delete[] resultLimits;

}

int main()
{
  cout << "Variable-Length String Manipulation. Function to identify limits." << endl;
  identifyLimitsTester();

  cout << endl;
  return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "meegosensorbase.h"

SensorManagerInterface* meegosensorbase::m_remoteSensorManager = 0;

const float meegosensorbase::GRAVITY_EARTH = 9.80665;
const float meegosensorbase::GRAVITY_EARTH_THOUSANDTH = 0.00980665;
const int meegosensorbase::KErrNotFound=-1;
const int meegosensorbase::KErrInUse=-14;
const char* const meegosensorbase::ALWAYS_ON = "alwaysOn";
const char* const meegosensorbase::BUFFER_SIZE = "bufferSize";
const char* const meegosensorbase::MAX_BUFFER_SIZE = "maxBufferSize";
const char* const meegosensorbase::EFFICIENT_BUFFER_SIZE = "efficientBufferSize";

meegosensorbase::meegosensorbase(QSensor *sensor)
    : QSensorBackend(sensor), m_sensorInterface(0), m_bufferSize(-1), m_prevOutputRange(0), m_efficientBufferSize(1), m_maxBufferSize(1)
{
    if (!m_remoteSensorManager)
        m_remoteSensorManager = &SensorManagerInterface::instance();

}

meegosensorbase::~meegosensorbase()
{
    if (m_sensorInterface) {
        stop();
        QObject::disconnect(m_sensorInterface);
        delete m_sensorInterface, m_sensorInterface = 0;
    }
}

void meegosensorbase::start()
{
    if (m_sensorInterface) {
        // dataRate
        QString type = sensor()->type();
        if (type!="QTapSensor" && type!="QProximitySensor"){
            int dataRate = sensor()->dataRate();
            int interval = dataRate>0 ? 1000 / dataRate : 0;
            // for testing maximum speed
            //interval = 1;
            //dataRate = 1000;
            qDebug() << "Setting data rate" << dataRate << "Hz (interval" << interval << "ms) for" << sensor()->identifier();
            m_sensorInterface->setInterval(interval);
        }

        // outputRange
        int currentRange = sensor()->outputRange();
        int l = sensor()->outputRanges().size();
        if (l>1){
            if (currentRange != m_prevOutputRange){
#ifdef Q_WS_MAEMO6
                bool isOk = m_sensorInterface->setDataRangeIndex(currentRange); //NOTE THAT THE CHANGE MIGHT NOT SUCCEED, FIRST COME FIRST SERVED
                if (!isOk) sensorError(KErrInUse);
                else m_prevOutputRange = currentRange;
#else
                // TODO: remove when sensord integrated, in MeeGo env there is a delay
                qoutputrange range = sensor()->outputRanges().at(currentRange);
                qreal correction = 1/correctionFactor();
                DataRange range1(range.minimum*correction, range.maximum*correction, range.accuracy*correction);
                m_sensorInterface->requestDataRange(range1);
                m_prevOutputRange = currentRange;
#endif
            }
        }

        // always on
        QVariant alwaysOn = sensor()->property(ALWAYS_ON);
        alwaysOn.isValid()?
                m_sensorInterface->setStandbyOverride(alwaysOn.toBool()):
                m_sensorInterface->setStandbyOverride(false);

        // connects after buffering checks
        doConnectAfterCheck();

        int returnCode = m_sensorInterface->start().error().type();
        if (returnCode==0) return;
        qWarning()<<"m_sensorInterface did not start, error code:"<<returnCode;
    }
    sensorStopped();
}

void meegosensorbase::stop()
{
    if (m_sensorInterface) m_sensorInterface->stop();
}

void meegosensorbase::setRanges(qreal correctionFactor){
    if (!m_sensorInterface) return;

    QList<DataRange> ranges = m_sensorInterface->getAvailableDataRanges();

    for (int i=0, l=ranges.size(); i<l; i++){
        DataRange range = ranges.at(i);
        qreal rangeMin = range.min * correctionFactor;
        qreal rangeMax = range.max * correctionFactor;
        qreal resolution = range.resolution * correctionFactor;
        addOutputRange(rangeMin, rangeMax, resolution);
    }
}

bool meegosensorbase::doConnectAfterCheck(){
    if (!m_sensorInterface) return false;

    // buffer size
    int size = bufferSize();
    if (size == m_bufferSize) return true;

    m_sensorInterface->setBufferSize(size);

    // if multiple->single or single->multiple or if uninitialized
    if ((m_bufferSize>1 && size==1) || (m_bufferSize==1 && size>1) || m_bufferSize==-1){
        m_bufferSize = size;
        disconnect(this);
        if (!doConnect()){
            qWarning() << "Unable to connect "<< sensorName();
            return false;
        }
        return true;
    }
    m_bufferSize = size;
    return true;
}

const int meegosensorbase::bufferSize(){
    QVariant bufferVariant = sensor()->property(BUFFER_SIZE);
    int bufferSize = bufferVariant.isValid()?bufferVariant.toInt():1;
    if (bufferSize==1) return 1;

    // otherwise check validity
    if (bufferSize<1){
        qWarning()<<"bufferSize cannot be "<<bufferSize<<", must be a positive number";
        return m_bufferSize>0?m_bufferSize:1;
    }
    if (bufferSize>m_maxBufferSize){
        qWarning()<<"bufferSize cannot be "<<bufferSize<<", MAX value is "<<m_maxBufferSize;
        return m_bufferSize>0?m_bufferSize:1;
    }
    return bufferSize;
}

const qreal meegosensorbase::correctionFactor(){return 1;}

<commit_msg>polishing<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "meegosensorbase.h"

SensorManagerInterface* meegosensorbase::m_remoteSensorManager = 0;

//According to wikipedia link http://en.wikipedia.org/wiki/Standard_gravity
//const float meegosensorbase::GRAVITY_EARTH = 9.812865328;
const float meegosensorbase::GRAVITY_EARTH_THOUSANDTH = 0.009812865328;
const int meegosensorbase::KErrNotFound=-1;
const int meegosensorbase::KErrInUse=-14;
const char* const meegosensorbase::ALWAYS_ON = "alwaysOn";
const char* const meegosensorbase::BUFFER_SIZE = "bufferSize";
const char* const meegosensorbase::MAX_BUFFER_SIZE = "maxBufferSize";
const char* const meegosensorbase::EFFICIENT_BUFFER_SIZE = "efficientBufferSize";

meegosensorbase::meegosensorbase(QSensor *sensor)
    : QSensorBackend(sensor), m_sensorInterface(0), m_bufferSize(-1), m_prevOutputRange(0), m_efficientBufferSize(1), m_maxBufferSize(1)
{
    if (!m_remoteSensorManager)
        m_remoteSensorManager = &SensorManagerInterface::instance();

}

meegosensorbase::~meegosensorbase()
{
    if (m_sensorInterface) {
        stop();
        QObject::disconnect(m_sensorInterface);
        delete m_sensorInterface, m_sensorInterface = 0;
    }
}

void meegosensorbase::start()
{
    if (m_sensorInterface) {
        // dataRate
        QString type = sensor()->type();
        if (type!="QTapSensor" && type!="QProximitySensor"){
            int dataRate = sensor()->dataRate();
            int interval = dataRate>0 ? 1000 / dataRate : 0;
            // for testing maximum speed
            //interval = 1;
            //dataRate = 1000;
            qDebug() << "Setting data rate" << dataRate << "Hz (interval" << interval << "ms) for" << sensor()->identifier();
            m_sensorInterface->setInterval(interval);
        }

        // outputRange
        int currentRange = sensor()->outputRange();
        int l = sensor()->outputRanges().size();
        if (l>1){
            if (currentRange != m_prevOutputRange){
#ifdef Q_WS_MAEMO6
                bool isOk = m_sensorInterface->setDataRangeIndex(currentRange); //NOTE THAT THE CHANGE MIGHT NOT SUCCEED, FIRST COME FIRST SERVED
                if (!isOk) sensorError(KErrInUse);
                else m_prevOutputRange = currentRange;
#else
                // TODO: remove when sensord integrated, in MeeGo env there is a delay
                qoutputrange range = sensor()->outputRanges().at(currentRange);
                qreal correction = 1/correctionFactor();
                DataRange range1(range.minimum*correction, range.maximum*correction, range.accuracy*correction);
                m_sensorInterface->requestDataRange(range1);
                m_prevOutputRange = currentRange;
#endif
            }
        }

        // always on
        QVariant alwaysOn = sensor()->property(ALWAYS_ON);
        alwaysOn.isValid()?
                m_sensorInterface->setStandbyOverride(alwaysOn.toBool()):
                m_sensorInterface->setStandbyOverride(false);

        // connects after buffering checks
        doConnectAfterCheck();

        int returnCode = m_sensorInterface->start().error().type();
        if (returnCode==0) return;
        qWarning()<<"m_sensorInterface did not start, error code:"<<returnCode;
    }
    sensorStopped();
}

void meegosensorbase::stop()
{
    if (m_sensorInterface) m_sensorInterface->stop();
}

void meegosensorbase::setRanges(qreal correctionFactor){
    if (!m_sensorInterface) return;

    QList<DataRange> ranges = m_sensorInterface->getAvailableDataRanges();

    for (int i=0, l=ranges.size(); i<l; i++){
        DataRange range = ranges.at(i);
        qreal rangeMin = range.min * correctionFactor;
        qreal rangeMax = range.max * correctionFactor;
        qreal resolution = range.resolution * correctionFactor;
        addOutputRange(rangeMin, rangeMax, resolution);
    }
}

bool meegosensorbase::doConnectAfterCheck(){
    if (!m_sensorInterface) return false;

    // buffer size
    int size = bufferSize();
    if (size == m_bufferSize) return true;

    m_sensorInterface->setBufferSize(size);

    // if multiple->single or single->multiple or if uninitialized
    if ((m_bufferSize>1 && size==1) || (m_bufferSize==1 && size>1) || m_bufferSize==-1){
        m_bufferSize = size;
        disconnect(this);
        if (!doConnect()){
            qWarning() << "Unable to connect "<< sensorName();
            return false;
        }
        return true;
    }
    m_bufferSize = size;
    return true;
}

const int meegosensorbase::bufferSize(){
    QVariant bufferVariant = sensor()->property(BUFFER_SIZE);
    int bufferSize = bufferVariant.isValid()?bufferVariant.toInt():1;
    if (bufferSize==1) return 1;

    // otherwise check validity
    if (bufferSize<1){
        qWarning()<<"bufferSize cannot be "<<bufferSize<<", must be a positive number";
        return m_bufferSize>0?m_bufferSize:1;
    }
    if (bufferSize>m_maxBufferSize){
        qWarning()<<"bufferSize cannot be "<<bufferSize<<", MAX value is "<<m_maxBufferSize;
        return m_bufferSize>0?m_bufferSize:1;
    }
    return bufferSize;
}

const qreal meegosensorbase::correctionFactor(){return 1;}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/dp16.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file dp16.H
/// @brief Subroutines to control the DP16 logic blocks
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#ifndef _MSS_DP16_H_
#define _MSS_DP16_H_

#include <vector>
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>

namespace mss
{

///
/// @brief Given a mt/s, create a PHY 'standard' bit field for that freq.
/// @param[in] i_freq the value from mss::freq for your target
/// @return uint64_t a right-aligned bitfield which can be inserted in to a buffer
///
inline uint64_t freq_bitfield_helper( const uint64_t i_freq )
{
    fapi2::buffer<uint64_t> l_data(0b1000);

    FAPI_DBG("freq_bitfield_helper seeing MT/s: %d", i_freq);

    // Shift l_data over based on freq.
    switch(i_freq)
    {
        // We don't support 1866 on Nimbus.
        case fapi2::ENUM_ATTR_MSS_FREQ_MT1866:
            l_data >>= 3;
            break;

        case fapi2::ENUM_ATTR_MSS_FREQ_MT2133:
            l_data >>= 2;
            break;

        case fapi2::ENUM_ATTR_MSS_FREQ_MT2400:
            l_data >>= 1;
            break;

        case fapi2::ENUM_ATTR_MSS_FREQ_MT2666:
            l_data >>= 0;
            break;

        default:
            FAPI_ERR("Unkown MT/s: %d", i_freq);
            fapi2::Assert(false);
            break;
    };

    return l_data;
}

// I have a dream that the PHY code can be shared among controllers. So, I drive the
// engine from a set of traits. This might be folly. Allow me to dream. BRS

///
/// @class dp16Traits
/// @brief a collection of traits associated with the PHY DP16 block
/// @tparam T fapi2::TargetType representing the PHY
///
template< fapi2::TargetType T >
class dp16Traits;

///
/// @class dp16Traits
/// @brief a collection of traits associated with the Centaur PHY
///
template<>
class dp16Traits<fapi2::TARGET_TYPE_MBA>
{
};

///
/// @class dp16Traits
/// @brief a collection of traits associated with the Nimbus PHY DP16 block
///
template<>
class dp16Traits<fapi2::TARGET_TYPE_MCA>
{
};

namespace dp16
{

///
/// @brief Configure the DP16 sysclk
/// @tparam T the fapi2 target type
/// @tparam TT the target traits
/// @param[in] i_target a target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_sysclk( const fapi2::Target<T>& i_target );

///
/// @brief Reset the training delay configureation
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target the port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_delay_values( const fapi2::Target<T>& i_target,
                                      const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Reset the read clock enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_read_clock_enable( const fapi2::Target<T>& i_target,
        const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Resets the write clock enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target  a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_write_clock_enable( const fapi2::Target<T>& i_target,
        const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Reset the data bit enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target a port target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_data_bit_enable( const fapi2::Target<T>& i_target );

///
/// @brief Reset the bad-bits masks for a port
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target the target (MCA or MBA?)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
inline fapi2::ReturnCode reset_bad_bits(const fapi2::Target<T>& i_target);

///
/// @brief Configure the DP16 io_tx config0 registers
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target a fapi2 target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_io_tx_config0( const fapi2::Target<T>& i_target );

///
/// @brief Configure ADR DLL/VREG Config 1
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target a fapi2 target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_dll_vreg_config1( const fapi2::Target<T>& i_target );

///
/// Specializations
///

///
/// @brief Configure the DP16 sysclk
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_sysclk( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );

///
/// @brief Reset the training delay configureation
/// @param[in] i_target the port target
/// @param[in]  l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_delay_values( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                                      const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Reset the read clock enable registers
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_read_clock_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
        const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Reset the write clock enable registers
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_write_clock_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
        const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Reset the data bit enable registers
/// @param[in] i_target a port target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_data_bit_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target );

///
/// @brief Reset the bad-bits masks for a port
/// @tparam T the fapi2::TargetType
/// @param[in] i_target the target (MCA or MBA?)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
inline fapi2::ReturnCode reset_bad_bits( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target)
{
    // Note: We need to do this ... BRS
    return fapi2::FAPI2_RC_SUCCESS;
}

///
/// @brief Configure the DP16 io_tx config0 registers
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_io_tx_config0( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );

///
/// @brief Configure ADR DLL/VREG Config 1
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_dll_vreg_config1( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );

} // close namespace dp16
} // close namespace mss

#endif
<commit_msg>Add DLL Calibration<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/dp16.H $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file dp16.H
/// @brief Subroutines to control the DP16 logic blocks
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#ifndef _MSS_DP16_H_
#define _MSS_DP16_H_

#include <vector>
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>

#include <lib/utils/scom.H>

namespace mss
{

///
/// @brief Given a mt/s, create a PHY 'standard' bit field for that freq.
/// @param[in] i_freq the value from mss::freq for your target
/// @return uint64_t a right-aligned bitfield which can be inserted in to a buffer
///
inline uint64_t freq_bitfield_helper( const uint64_t i_freq )
{
    fapi2::buffer<uint64_t> l_data(0b1000);

    FAPI_DBG("freq_bitfield_helper seeing MT/s: %d", i_freq);

    // Shift l_data over based on freq.
    switch(i_freq)
    {
        // We don't support 1866 on Nimbus.
        case fapi2::ENUM_ATTR_MSS_FREQ_MT1866:
            l_data >>= 3;
            break;

        case fapi2::ENUM_ATTR_MSS_FREQ_MT2133:
            l_data >>= 2;
            break;

        case fapi2::ENUM_ATTR_MSS_FREQ_MT2400:
            l_data >>= 1;
            break;

        case fapi2::ENUM_ATTR_MSS_FREQ_MT2666:
            l_data >>= 0;
            break;

        default:
            FAPI_ERR("Unkown MT/s: %d", i_freq);
            fapi2::Assert(false);
            break;
    };

    return l_data;
}

// I have a dream that the PHY code can be shared among controllers. So, I drive the
// engine from a set of traits. This might be folly. Allow me to dream. BRS

///
/// @class dp16Traits
/// @brief a collection of traits associated with the PHY DP16 block
/// @tparam T fapi2::TargetType representing the PHY
///
template< fapi2::TargetType T >
class dp16Traits;

///
/// @class dp16Traits
/// @brief a collection of traits associated with the Centaur PHY
///
template<>
class dp16Traits<fapi2::TARGET_TYPE_MBA>
{
};

///
/// @class dp16Traits
/// @brief a collection of traits associated with the Nimbus PHY DP16 block
///
template<>
class dp16Traits<fapi2::TARGET_TYPE_MCA>
{

    public:
        // Number of DP instances
        static constexpr uint64_t DP_COUNT = 5;

        // Number of instances of the DLL per DP16. Used for checking parameters, the rest of the
        // code assumes 2 DLL per DP16. There are no DLL in Centaur so we don't need to worry about
        // any of this for some time.
        static constexpr uint64_t DLL_PER_DP16 = 2;

        // Vector of the DLL configuration registers. The pair represents the two DLL in per DP16
        static const std::vector< std::pair<uint64_t, uint64_t> > DLL_CNFG_REG;

        enum
        {
            DLL_CNTL_INIT_RXDLL_CAL_RESET = MCA_DDRPHY_DP16_DLL_CNTL0_P0_0_01_INIT_RXDLL_CAL_RESET,
        };
};

namespace dp16
{

///
/// @brief Read DLL_CNTL
/// @tparam I DP16 instance
/// @tparam D DLL instance in the specified DP16
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to dp16Traits<T>
/// @param[in] i_target the fapi2 target of the port
/// @param[out] o_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t I, uint64_t D, fapi2::TargetType T, typename TT = dp16Traits<T> >
inline fapi2::ReturnCode read_dll_cntl( const fapi2::Target<T>& i_target, fapi2::buffer<uint64_t>& o_data )
{
    static_assert( I < TT::DP_COUNT, "dp16 instance out of range");
    static_assert( D < TT::DLL_PER_DP16, "dll instance out of range");

    // The pair represents the upper and lower bytes of the DP16 - each has its own DLL regiters
    const uint64_t& l_addr = (D == 0) ? TT::DLL_CNFG_REG[I].first : TT::DLL_CNFG_REG[I].second;

    FAPI_TRY( mss::getScom(i_target, l_addr, o_data) );
    FAPI_INF("dll_cntl dp16<%d, %d>: 0x%016lx", I, D, o_data);

fapi_try_exit:
    return fapi2::current_err;

}

///
/// @brief Write DLL_CNTL
/// @tparam I DP16 instance
/// @tparam D DLL instance in the specified DP16
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to dp16Traits<T>
/// @param[in] i_target the fapi2 target of the port
/// @param[in] i_data the value of the register
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
template< uint64_t I, uint64_t D, fapi2::TargetType T, typename TT = dp16Traits<T> >
inline fapi2::ReturnCode write_dll_cntl( const fapi2::Target<T>& i_target, const fapi2::buffer<uint64_t>& i_data )
{
    static_assert( I < TT::DP_COUNT, "dp16 instance out of range");
    static_assert( D < TT::DLL_PER_DP16, "dll instance out of range");

    // The pair represents the upper and lower bytes of the DP16 - each has its own DLL regiters
    const uint64_t& l_addr = (D == 0) ? TT::DLL_CNFG_REG[I].first : TT::DLL_CNFG_REG[I].second;

    FAPI_INF("dll_cntl dp16<%d,%d>: 0x%016lx", I, D, i_data);
    FAPI_TRY( mss::putScom(i_target, l_addr, i_data) );

fapi_try_exit:
    return fapi2::current_err;

}

//
// Reseting the DLL registers TODO RTC:156518
//

///
/// @brief Set the DLL cal reset (begins DLL cal operations)
/// @tparam T fapi2 Target Type - derived
/// @tparam TT traits type defaults to dp16Traits<T>
/// @param[in] o_data the value of the register
/// @param[in] i_state mss::LOW or mss::HIGH representing the state of the bit
/// @note Default state is 'low' as writing a 0 forces the cal to begin.
///
template< fapi2::TargetType T = fapi2::TARGET_TYPE_MCA, typename TT = dp16Traits<T> >
inline void set_dll_cal_reset( fapi2::buffer<uint64_t>& o_data, const states i_state = mss::LOW )
{
    FAPI_INF("set_dll_cal_reset %s", (i_state == mss::LOW ? "low" : "high"));
    o_data.writeBit<TT::DLL_CNTL_INIT_RXDLL_CAL_RESET>(i_state);
}

///
/// @brief Configure the DP16 sysclk
/// @tparam T the fapi2 target type
/// @tparam TT the target traits
/// @param[in] i_target a target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_sysclk( const fapi2::Target<T>& i_target );

///
/// @brief Reset the training delay configureation
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target the port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_delay_values( const fapi2::Target<T>& i_target,
                                      const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Reset the read clock enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_read_clock_enable( const fapi2::Target<T>& i_target,
        const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Resets the write clock enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target  a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_write_clock_enable( const fapi2::Target<T>& i_target,
        const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Reset the data bit enable registers
/// @tparam T the type of the port
/// @tparam TT the target traits
/// @param[in] i_target a port target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_data_bit_enable( const fapi2::Target<T>& i_target );

///
/// @brief Reset the bad-bits masks for a port
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target the target (MCA or MBA?)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
inline fapi2::ReturnCode reset_bad_bits(const fapi2::Target<T>& i_target);

///
/// @brief Configure the DP16 io_tx config0 registers
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target a fapi2 target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_io_tx_config0( const fapi2::Target<T>& i_target );

///
/// @brief Configure ADR DLL/VREG Config 1
/// @tparam T the fapi2::TargetType
/// @tparam TT the target traits
/// @param[in] i_target a fapi2 target
/// @return FAPI2_RC_SUCCESs iff ok
///
template< fapi2::TargetType T, typename TT = dp16Traits<T> >
fapi2::ReturnCode reset_dll_vreg_config1( const fapi2::Target<T>& i_target );

///
/// Specializations
///

///
/// @brief Configure the DP16 sysclk
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_sysclk( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );

///
/// @brief Reset the training delay configureation
/// @param[in] i_target the port target
/// @param[in]  l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_delay_values( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
                                      const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Reset the read clock enable registers
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_read_clock_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
        const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Reset the write clock enable registers
/// @param[in] i_target a port target
/// @param[in] l_rank_pairs vector of rank pairs
/// @return FAPI2_RC_SUCCES iff ok
///
fapi2::ReturnCode reset_write_clock_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
        const std::vector< uint64_t >& l_rank_pairs );

///
/// @brief Reset the data bit enable registers
/// @param[in] i_target a port target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_data_bit_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target );

///
/// @brief Reset the bad-bits masks for a port
/// @tparam T the fapi2::TargetType
/// @param[in] i_target the target (MCA or MBA?)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
inline fapi2::ReturnCode reset_bad_bits( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target)
{
    // Note: We need to do this ... BRS
    return fapi2::FAPI2_RC_SUCCESS;
}

///
/// @brief Configure the DP16 io_tx config0 registers
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_io_tx_config0( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );

///
/// @brief Configure ADR DLL/VREG Config 1
/// @param[in] i_target a MCBIST target
/// @return FAPI2_RC_SUCCESs iff ok
///
fapi2::ReturnCode reset_dll_vreg_config1( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );

} // close namespace dp16
} // close namespace mss

#endif
<|endoftext|>


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

#include "ChartTypeTemplate.hxx"
#include "OPropertySet.hxx"
#include "MutexContainer.hxx"

#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif

namespace chart
{

class StockChartTypeTemplate :
        public helper::MutexContainer,
        public ChartTypeTemplate,
        public ::property::OPropertySet
{
public:
    enum StockVariant
    {
        LOW_HI_CLOSE,
        OPEN_LOW_HI_CLOSE,
        VOL_LOW_HI_CLOSE,
        VOL_OPEN_LOW_HI_CLOSE
    };

    explicit StockChartTypeTemplate(
        ::com::sun::star::uno::Reference<
            ::com::sun::star::uno::XComponentContext > const & xContext,
        const ::rtl::OUString & rServiceName,
        StockVariant eVariant );
    virtual ~StockChartTypeTemplate();

    /// XServiceInfo declarations
    APPHELPER_XSERVICEINFO_DECL()

    /// merge XInterface implementations
     DECLARE_XINTERFACE()
    /// merge XTypeProvider implementations
     DECLARE_XTYPEPROVIDER()

protected:
    // ____ OPropertySet ____
    virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const
        throw(::com::sun::star::beans::UnknownPropertyException);
    virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

    // ____ XPropertySet ____
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL
        getPropertySetInfo()
        throw (::com::sun::star::uno::RuntimeException);

    // ____ XChartTypeTemplate ____
    virtual sal_Bool SAL_CALL matchesTemplate(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ ChartTypeTemplate ____
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XChartType > getDefaultChartType()
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XDataSeriesTreeParent > createDataSeriesTree(
            const ::com::sun::star::uno::Sequence<
                ::com::sun::star::uno::Reference<
                    ::com::sun::star::chart2::XDataSeries > >& aSeriesSeq,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::chart2::XBoundedCoordinateSystem > & rCoordSys
            );

private:
};

} //  namespace chart

// CHART_STOCKCHARTTYPETEMPLATE_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2007/03/26 14:21:59 iha 1.2.4.23: #i75590# copy some aspects from old charttype during creation of new 2007/03/01 13:54:31 iha 1.2.4.22: #i71167 & i74564# keep charttype properties if possible when switching charttypes 2006/08/10 17:10:42 bm 1.2.4.21: second axis for stock charts fixed 2006/04/10 12:25:14 iha 1.2.4.20: api restructure axis, grids, scales and increments 2005/11/28 18:01:02 iha 1.2.4.19: set series to correct axis for stockcharts 2005/10/24 11:06:53 iha 1.2.4.18: coordinate system restructure 2005/10/13 17:39:06 iha 1.2.4.17: renamed BoundedCoordinateSystem to CoordinateSystem 2005/10/07 12:06:29 bm 1.2.4.16: RESYNC: (1.2-1.3); FILE MERGED 2005/08/04 11:53:43 bm 1.2.4.15: set stack mode at new series. Percent stacking is now set in adaptScales 2005/07/15 16:07:22 bm 1.2.4.14: keep more old objects on chart type changes 2005/05/09 09:51:28 bm 1.2.4.13: moved parts of API to data namespace 2004/09/15 17:32:08 bm 1.2.4.12: API simplification 2004/06/29 12:26:36 bm 1.2.4.11: XChartTypeTemplate changes 2004/05/27 17:27:14 bm 1.2.4.10: +getChartTypeForNewSeries at XChartTypeTemplate 2004/04/01 10:53:12 bm 1.2.4.9: XChartType: may return a coordinate system now 2004/03/24 19:05:26 bm 1.2.4.8: XChartTypeTemplate changed: matchesTemplate may modify the template s properties if bAdaptProperties is true 2004/03/22 15:28:21 iha 1.2.4.7: added parameter SwapXAndYAxis for horizontal bar chart to method createCoordinateSystems 2004/03/19 14:32:59 bm 1.2.4.6: XDataSource now contains XLabeledDataSources 2004/03/12 15:39:42 iha 1.2.4.5: create a secondary y axis for stock charts 2004/03/03 14:14:41 bm 1.2.4.4: create 2 coordinate-systems if there is volume 2004/03/02 16:40:45 bm 1.2.4.3: allow creating more than one coordinate system 2004/02/20 17:43:58 iha 1.2.4.2: integrate categories at ScaleData 2004/02/13 16:51:45 bm 1.2.4.1: join from changes on branch bm_post_chart01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: StockChartTypeTemplate.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:52:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART_STOCKCHARTTYPETEMPLATE_HXX
#define CHART_STOCKCHARTTYPETEMPLATE_HXX

#include "ChartTypeTemplate.hxx"
#include "OPropertySet.hxx"
#include "MutexContainer.hxx"

#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif

namespace chart
{

class StockChartTypeTemplate :
        public MutexContainer,
        public ChartTypeTemplate,
        public ::property::OPropertySet
{
public:
    enum StockVariant
    {
        LOW_HI_CLOSE,
        OPEN_LOW_HI_CLOSE,
        VOL_LOW_HI_CLOSE,
        VOL_OPEN_LOW_HI_CLOSE
    };

    /** CTOR

        @param bJapaneseStyle
            If true, the candlesticks are drawn as solid white or black boxes
            depending on rising or falling stock-values.  Otherwise the
            open-value will be drawn as a small line at the left side of a
            straight vertical line, and the close-value on the right hand side.
     */
    explicit StockChartTypeTemplate(
        ::com::sun::star::uno::Reference<
            ::com::sun::star::uno::XComponentContext > const & xContext,
        const ::rtl::OUString & rServiceName,
        StockVariant eVariant,
        bool bJapaneseStyle );
    virtual ~StockChartTypeTemplate();

    /// XServiceInfo declarations
    APPHELPER_XSERVICEINFO_DECL()

    /// merge XInterface implementations
     DECLARE_XINTERFACE()
    /// merge XTypeProvider implementations
     DECLARE_XTYPEPROVIDER()

protected:
    // ____ OPropertySet ____
    virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const
        throw(::com::sun::star::beans::UnknownPropertyException);
    virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();

    // ____ XPropertySet ____
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL
        getPropertySetInfo()
        throw (::com::sun::star::uno::RuntimeException);

    // ____ XChartTypeTemplate ____
    virtual sal_Bool SAL_CALL matchesTemplate(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram,
        sal_Bool bAdaptProperties )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > SAL_CALL
        getChartTypeForNewSeries( const ::com::sun::star::uno::Sequence<
            ::com::sun::star::uno::Reference<
                ::com::sun::star::chart2::XChartType > >& aFormerlyUsedChartTypes )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataInterpreter > SAL_CALL getDataInterpreter()
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL applyStyle(
        const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries,
        ::sal_Int32 nChartTypeIndex,
        ::sal_Int32 nSeriesIndex,
        ::sal_Int32 nSeriesCount )
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL resetStyles(
        const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram >& xDiagram )
        throw (::com::sun::star::uno::RuntimeException);

    // ChartTypeTemplate
    virtual sal_Int32 getAxisCountByDimension( sal_Int32 nDimension );

    // ____ ChartTypeTemplate ____
    virtual void createChartTypes(
            const ::com::sun::star::uno::Sequence<
                 ::com::sun::star::uno::Sequence<
                    ::com::sun::star::uno::Reference<
                        ::com::sun::star::chart2::XDataSeries > > >& aSeriesSeq,
            const ::com::sun::star::uno::Sequence<
                ::com::sun::star::uno::Reference<
                    ::com::sun::star::chart2::XCoordinateSystem > > & rCoordSys,
            const ::com::sun::star::uno::Sequence<
                  ::com::sun::star::uno::Reference<
                      ::com::sun::star::chart2::XChartType > > & aOldChartTypesSeq
            );

private:
    // todo: deprecate this variable
    StockVariant  m_eStockVariant;
};

} //  namespace chart

// CHART_STOCKCHARTTYPETEMPLATE_HXX
#endif
<|endoftext|>