<commit_before>#include <bashclass/BBashHelper.h>
#include <bashclass/BGenerateCode.h>
#include <bashclass/BTypes.h>
#include <bashclass/BException.h>
#include <bashclass/BGlobal.h>
#include <bashclass/BVariableChainAccess.h>
#include <bashclass/BFunctionChainCall.h>
#include <iostream>
#include <bashclass/BArithOperation.h>
#include <bashclass/BVariableAssign.h>

// Constants
std::string FUNCTION_THIS = "_this_";
std::string FUNCTION_RETURN = "_return_";
std::string RESULT = "_result_";

/**
 * Indent generated code
 * @param parent
 * @param ss
 */
void _indent(std::shared_ptr<BScope> parent, std::stringstream& ss) {
    if(!parent) {
        throw BException("Parent scope should not be empty");
    }

    auto closestClass = parent->findClosestClass();
    while (parent != BGlobal::getInstance() && parent != closestClass) {
        ss << "\t";
        parent = parent->getParentScope();
    }
}

/**
 * Generate a unique result key/variable per element call
 * @param number
 * @return unique result string
 */
std::string _generateResultKey(unsigned int number) {
    return RESULT + std::to_string(number);
}

/**
 * Generate code for a variable chain access that is a member and is placed first in the chain
 * @param variableChainAccess
 * @param ss
 */
void _varChainAccess_member_first(std::shared_ptr<BVariableChainAccess> variableChainAccess, std::stringstream &ss) {
    ss << variableChainAccess->getVariable()->getParentScope()->findClosestClass()->getLabel().str()
       << "[" << FUNCTION_THIS << "," << variableChainAccess->getVariable()->getLabel().str() << "]";
}

/**
 * Generate code for a variable chain access that is a member and is placed in the middle of the chain
 * @param variableChainAccess
 * @param prevTypeLabel
 * @param prevResult
 * @param ss
 */
void _varChainAccess_member_middle(std::shared_ptr<BVariableChainAccess> variableChainAccess, std::string prevTypeLabel,
                            std::string prevResult, std::stringstream &ss) {
    ss << prevTypeLabel << "[" << prevResult << "," << variableChainAccess->getVariable()->getLabel().str() << "]" ;
}

/**
 * Generate code for a variable chain access that is a member and is placed last in the chain
 * @param variableChainAccess
 * @param prevResult
 * @param ss
 */
void _varChainAccess_member_last(std::shared_ptr<BVariableChainAccess> variableChainAccess,
                          std::string prevResult, std::stringstream &ss) {
    ss << variableChainAccess->getVariable()->getParentScope()->findClosestClass()->getLabel().str()
       << "[" << prevResult << "," << variableChainAccess->getVariable()->getLabel().str() << "]";
}

/**
 * Generate code for a variable call that is not a member
 * @param variableChainAccess
 * @param ss
 */
void _varChainAccess_nonMember(std::shared_ptr<BVariableChainAccess> variableChainAccess, std::stringstream &ss) {
    ss << variableChainAccess->getVariable()->getLabel().str();
}

/**
 * Generate code for a chain call
 * @param chainCall
 * @return multi-line code representing a chain call
 */
void _chainToCode(std::shared_ptr<BScope> scope, std::shared_ptr<BChain> chain, size_t from, size_t to,
                  std::stringstream &ss) {

    // Have a unique key for each result of an element call
    std::map<std::shared_ptr<IBChainable>, std::string> returnMap;

    // Assign a unique key for each result
    static unsigned int uniqueId = 0;

    // Start processing the calls
    for (size_t i = from; i <= to; i++) {

        // Cast element
        auto variableChainAccess = std::dynamic_pointer_cast<BVariableChainAccess>((*chain)[i]);
        auto functionChainCall = std::dynamic_pointer_cast<BFunctionChainCall>((*chain)[i]);
        auto thisChainAccess = std::dynamic_pointer_cast<BThisChainAccess>((*chain)[i]);

        // Add indentation
        _indent(scope, ss);

        if (variableChainAccess) {

            // Generate new key for this variable
            std::string newKey = _generateResultKey(uniqueId++);
            returnMap[variableChainAccess] = newKey;
            ss << newKey << "=";

            if(i == 0) {
                if(variableChainAccess->getVariable()->isClassMember()) {
                    _varChainAccess_member_first(variableChainAccess, ss);
                } else {
                    _varChainAccess_nonMember(variableChainAccess, ss);
                }
            } else {
                _varChainAccess_member_middle(variableChainAccess, (*chain)[i-1]->getTypeScope()->getLabel().str(),
                                       returnMap[(*chain)[i-1]], ss);
            }
            ss << std::endl;

        } else if (functionChainCall) {

            ss << functionChainCall->getFunction()->getLabel().str();

            // TODO Put all arguments
            ss << " args...";

            if(i == 0) {
                if(functionChainCall->getFunction()->isClassMember()) {
                    ss << " " << FUNCTION_THIS;
                }
            } else {
                ss << " " << returnMap[(*chain)[i-1]];
            }

            if(functionChainCall->getFunction()->requiresReturn()) {
                std::string newKey = _generateResultKey(uniqueId++);
                returnMap[functionChainCall] = newKey;
                ss << " " << newKey;
            }
            ss << std::endl;
        } else if(thisChainAccess) {
            std::string newKey = _generateResultKey(uniqueId++);
            returnMap[thisChainAccess] = newKey;
            ss  << newKey << "=" << FUNCTION_THIS << std::endl;
        } else {
            throw BException("Cannot generate code for an unrecognized element call");
        }
    }
}

void BBashHelper::header() {
    BGenerateCode::get().writePreCode();
}

void BBashHelper::footer() {
    BGenerateCode::get().writePostCode();
}

void BBashHelper::declareClass(std::shared_ptr<BClass> classScope) {
    std::stringstream ss;
    ss << "declare -A " << classScope->getLabel().str() << "=()" << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::uniqueCounter(std::shared_ptr<BClass> classScope) {
    std::stringstream ss;
    ss << "_" << classScope->getName()->getValue() << "_=0" << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::createGlobalVar(std::shared_ptr<BVariable> variable, std::string defaultValue) {
    std::stringstream ss;
    ss << std::endl;
    ss << "# Create global variable" << std::endl;

    ss << variable->getLabel().str() << "=" << defaultValue << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::createLocalVar(std::shared_ptr<BVariable> variable, std::string defaultValue) {
    std::stringstream ss;
    ss << std::endl;
    _indent(variable->getParentScope(),ss);
    ss << "# Create local variable" << std::endl;

    _indent(variable->getParentScope(), ss);
    ss << "local " << variable->getLabel().str() << "=" << defaultValue << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::bash(std::shared_ptr<ecc::LexicalToken> token) {
    std::stringstream ss;
    ss << std::endl;
    ss << "# Run BASH code" << std::endl;

    if(token->getName() == BType::TYPE_NAME_BASH_INLINE) {
        ss << token->getValue().substr(2,token->getValue().length()-2);
    } else if(token->getName() == BType::TYPE_NAME_BASH_SUB || token->getName() == BType::TYPE_NAME_BASH_BLOCK) {
        ss << token->getValue().substr(2, token->getValue().length()-4);
    } else {
        throw BException("Bash code can only be generated by bash lexical tokens");
    }
    ss << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::createFunction(std::shared_ptr<BFunction> function) {
    std::stringstream ss;
    ss << std::endl;
    ss << "# Create function" << std::endl;

    ss << "function " << function->getLabel().str() << "() {" << std::endl;
    // Create parameters
    int paramPos = 1;
    for(auto param : function->findAllParameters()) {
        _indent(param->getParentScope(), ss);
        ss << "local " << param->getLabel().str() << "=\"$" << paramPos++ << "\"" << std::endl;
    }

    // Generate 'this' if function is a class member
    if(function->isClassMember()) {
        _indent(function, ss);
        ss << "local " << FUNCTION_THIS << "=$" << paramPos++ << std::endl;
    }

    // Generate return reference if function requires a return statement
    if(function->requiresReturn()) {
        _indent(function, ss);
        ss << "declare -n " << FUNCTION_RETURN << "=$" << paramPos++ << std::endl;
    }

    BGenerateCode::get().write(ss);
}

void BBashHelper::closeFunction(std::shared_ptr<BFunction> function) {
    std::stringstream ss;
    _indent(function->getParentScope(), ss);
    ss << "}" << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::assignVariable(std::shared_ptr<BVariableAssign> variableAssign) {
    std::stringstream ss;

    // TODO Add expression
    auto variableChainAccess = variableAssign->getVariableAccess()->last();
    auto expression = variableAssign->getExpression();

    // Start converting the expression
    ss << std::endl;
    _indent(variableAssign->getParentScope(), ss);
    ss << "# Evaluating expression" << std::endl;

    // Convert chain to code
    ss << std::endl;
    _indent(variableAssign->getParentScope(), ss);
    ss << "# Assign variable" << std::endl;
    _chainToCode(variableAssign->getParentScope(), variableAssign->getVariableAccess()->getChain(), 0,
                     variableAssign->getVariableAccess()->getChain()->size()-2, ss);
    ss << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::functionExec(std::shared_ptr<BFunctionCall> functionCall) {
    std::stringstream ss;

    // Convert chain to code
    ss << std::endl;
    _indent(functionCall->getParentScope(), ss);
    ss << "# Execute a function" << std::endl;
    _chainToCode(functionCall->last()->getFunction(), functionCall->getChain(), 0, functionCall->getChain()->size()-1, ss);
    ss << std::endl;

    BGenerateCode::get().write(ss);

}<commit_msg>Generate code for expr<commit_after>#include <bashclass/BBashHelper.h>
#include <bashclass/BGenerateCode.h>
#include <bashclass/BTypes.h>
#include <bashclass/BException.h>
#include <bashclass/BGlobal.h>
#include <bashclass/BVariableChainAccess.h>
#include <bashclass/BFunctionChainCall.h>
#include <iostream>
#include <bashclass/BArithOperation.h>
#include <bashclass/BVariableAssign.h>
#include <bashclass/BVariableAccess.h>
#include <bashclass/BThisAccess.h>
#include <bashclass/BTokenUse.h>

// Constants
std::string FUNCTION_THIS = "_this_";
std::string FUNCTION_RETURN = "_return_";
std::string RESULT = "_result_";
std::string EXPRESSION = "_expression_";

/**
 * Indent generated code
 * @param parent
 * @param ss
 */
void _indent(std::shared_ptr<BScope> parent, std::stringstream& ss) {
    if(!parent) {
        throw BException("Parent scope should not be empty");
    }

    auto closestClass = parent->findClosestClass();
    while (parent != BGlobal::getInstance() && parent != closestClass) {
        ss << "\t";
        parent = parent->getParentScope();
    }
}

/**
 * Generate a unique result key/variable per element call
 * @param number
 * @return unique result string
 */
std::string _generateResultKey(unsigned int number) {
    return RESULT + std::to_string(number);
}

/**
 * Generate a unique expression key/variable per expression
 * @param number
 * @return unqieu expression string
 */
std::string _generateExpressionKey(unsigned int number) {
    return EXPRESSION + std::to_string(number);
}

/**
 * Generate code for a variable chain access that is a member and is placed first in the chain
 * @param variableChainAccess
 * @param ss
 */
void _varChainAccess_member_first(std::shared_ptr<BVariableChainAccess> variableChainAccess, std::stringstream &ss) {
    ss << variableChainAccess->getVariable()->getParentScope()->findClosestClass()->getLabel().str()
       << "[" << FUNCTION_THIS << "," << variableChainAccess->getVariable()->getLabel().str() << "]";
}

/**
 * Generate code for a variable chain access that is a member and is placed in the middle of the chain
 * @param variableChainAccess
 * @param prevTypeLabel
 * @param prevResult
 * @param ss
 */
void _varChainAccess_member_middle(std::shared_ptr<BVariableChainAccess> variableChainAccess, std::string prevTypeLabel,
                            std::string prevResult, std::stringstream &ss) {
    ss << prevTypeLabel << "[" << prevResult << "," << variableChainAccess->getVariable()->getLabel().str() << "]" ;
}

/**
 * Generate code for a variable chain access that is a member and is placed last in the chain
 * @param variableChainAccess
 * @param prevResult
 * @param ss
 */
void _varChainAccess_member_last(std::shared_ptr<BVariableChainAccess> variableChainAccess,
                          std::string prevResult, std::stringstream &ss) {
    ss << variableChainAccess->getVariable()->getParentScope()->findClosestClass()->getLabel().str()
       << "[" << prevResult << "," << variableChainAccess->getVariable()->getLabel().str() << "]";
}

/**
 * Generate code for a variable call that is not a member
 * @param variableChainAccess
 * @param ss
 */
void _varChainAccess_nonMember(std::shared_ptr<BVariableChainAccess> variableChainAccess, std::stringstream &ss) {
    ss << variableChainAccess->getVariable()->getLabel().str();
}

/**
 * Generate code for a chain call
 * @param chainCall
 * @return multi-line code representing a chain call
 */
void _chainToCode(std::shared_ptr<BScope> scope, std::shared_ptr<BChain> chain, size_t from, size_t to,
                  std::map<std::shared_ptr<IBChainable>, std::string> &returnMap, std::stringstream &ss) {

    // Assign a unique key for each result
    static unsigned int uniqueId = 0;

    // Start processing the calls
    for (size_t i = from; i <= to; i++) {

        // Cast element
        auto variableChainAccess = std::dynamic_pointer_cast<BVariableChainAccess>((*chain)[i]);
        auto functionChainCall = std::dynamic_pointer_cast<BFunctionChainCall>((*chain)[i]);
        auto thisChainAccess = std::dynamic_pointer_cast<BThisChainAccess>((*chain)[i]);

        // Add indentation
        _indent(scope, ss);

        if (variableChainAccess) {

            // Generate new key for this variable
            std::string newKey = _generateResultKey(uniqueId++);
            returnMap[variableChainAccess] = newKey;
            ss << newKey << "=";

            if(i == 0) {
                if(variableChainAccess->getVariable()->isClassMember()) {
                    _varChainAccess_member_first(variableChainAccess, ss);
                } else {
                    _varChainAccess_nonMember(variableChainAccess, ss);
                }
            } else {
                _varChainAccess_member_middle(variableChainAccess, (*chain)[i-1]->getTypeScope()->getLabel().str(),
                                       returnMap[(*chain)[i-1]], ss);
            }
            ss << std::endl;

        } else if (functionChainCall) {

            ss << functionChainCall->getFunction()->getLabel().str();

            // TODO Put all arguments
            ss << " args...";

            if(i == 0) {
                if(functionChainCall->getFunction()->isClassMember()) {
                    ss << " " << FUNCTION_THIS;
                }
            } else {
                ss << " " << returnMap[(*chain)[i-1]];
            }

            if(functionChainCall->getFunction()->requiresReturn()) {
                std::string newKey = _generateResultKey(uniqueId++);
                returnMap[functionChainCall] = newKey;
                ss << " " << newKey;
            }
            ss << std::endl;
        } else if(thisChainAccess) {
            std::string newKey = _generateResultKey(uniqueId++);
            returnMap[thisChainAccess] = newKey;
            ss  << newKey << "=" << FUNCTION_THIS << std::endl;
        } else {
            throw BException("Cannot generate code for an unrecognized element call");
        }
    }
}

std::string _expressionToCode(std::shared_ptr<BScope> scope, std::shared_ptr<IBExpression> expression,
                              std::stringstream &ss) {
    auto thisAccess = std::dynamic_pointer_cast<BThisAccess>(expression);
    auto variableAccess = std::dynamic_pointer_cast<BVariableAccess>(expression);
    auto functionCall = std::dynamic_pointer_cast<BFunctionCall>(expression);
    auto tokenUse = std::dynamic_pointer_cast<BTokenUse>(expression);
    auto arithOperation = std::dynamic_pointer_cast<BArithOperation>(expression);

    // Assign a unique key for each expression
    static unsigned int uniqueId = 0;

    if(thisAccess) {
        return FUNCTION_THIS;
    }

    if(variableAccess) {
//        std::map<std::shared_ptr<IBChainable>, std::string> returnMap;
//        _chainToCode(scope, variableAccess->getChain(), 0, variableAccess->getChain()->size(), returnMap, ss);
        return "VARIABLE_ACCESS";
    }

    if(functionCall) {
//        std::map<std::shared_ptr<IBChainable>, std::string> returnMap;
//        _chainToCode(scope, functionCall->getChain(), 0, variableAccess->getChain()->size(), returnMap, ss);
        return "FUNCTION_CALL";
    }

    if(tokenUse) {
        return tokenUse->getLexicalToken()->getValue();
    }

    auto leftStr = _expressionToCode(scope, arithOperation->getLeftOperand(), ss);
    auto rightStr = _expressionToCode(scope, arithOperation->getRightOperand(), ss);
    _indent(scope, ss);
    std::string newKey = _generateExpressionKey(uniqueId++);
    ss << newKey << "=" << leftStr + " " + arithOperation->getOperator()->getValue() + " " + rightStr << std::endl;
    return newKey;
}

void BBashHelper::header() {
    BGenerateCode::get().writePreCode();
}

void BBashHelper::footer() {
    BGenerateCode::get().writePostCode();
}

void BBashHelper::declareClass(std::shared_ptr<BClass> classScope) {
    std::stringstream ss;
    ss << "declare -A " << classScope->getLabel().str() << "=()" << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::uniqueCounter(std::shared_ptr<BClass> classScope) {
    std::stringstream ss;
    ss << "_" << classScope->getName()->getValue() << "_=0" << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::createGlobalVar(std::shared_ptr<BVariable> variable, std::string defaultValue) {
    std::stringstream ss;
    ss << std::endl;
    ss << "# Create global variable" << std::endl;

    ss << variable->getLabel().str() << "=" << defaultValue << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::createLocalVar(std::shared_ptr<BVariable> variable, std::string defaultValue) {
    std::stringstream ss;
    ss << std::endl;
    _indent(variable->getParentScope(),ss);
    ss << "# Create local variable" << std::endl;

    _indent(variable->getParentScope(), ss);
    ss << "local " << variable->getLabel().str() << "=" << defaultValue << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::bash(std::shared_ptr<ecc::LexicalToken> token) {
    std::stringstream ss;
    ss << std::endl;
    ss << "# Run BASH code" << std::endl;

    if(token->getName() == BType::TYPE_NAME_BASH_INLINE) {
        ss << token->getValue().substr(2,token->getValue().length()-2);
    } else if(token->getName() == BType::TYPE_NAME_BASH_SUB || token->getName() == BType::TYPE_NAME_BASH_BLOCK) {
        ss << token->getValue().substr(2, token->getValue().length()-4);
    } else {
        throw BException("Bash code can only be generated by bash lexical tokens");
    }
    ss << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::createFunction(std::shared_ptr<BFunction> function) {
    std::stringstream ss;
    ss << std::endl;
    ss << "# Create function" << std::endl;

    ss << "function " << function->getLabel().str() << "() {" << std::endl;
    // Create parameters
    int paramPos = 1;
    for(auto param : function->findAllParameters()) {
        _indent(param->getParentScope(), ss);
        ss << "local " << param->getLabel().str() << "=\"$" << paramPos++ << "\"" << std::endl;
    }

    // Generate 'this' if function is a class member
    if(function->isClassMember()) {
        _indent(function, ss);
        ss << "local " << FUNCTION_THIS << "=$" << paramPos++ << std::endl;
    }

    // Generate return reference if function requires a return statement
    if(function->requiresReturn()) {
        _indent(function, ss);
        ss << "declare -n " << FUNCTION_RETURN << "=$" << paramPos++ << std::endl;
    }

    BGenerateCode::get().write(ss);
}

void BBashHelper::closeFunction(std::shared_ptr<BFunction> function) {
    std::stringstream ss;
    _indent(function->getParentScope(), ss);
    ss << "}" << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::assignVariable(std::shared_ptr<BVariableAssign> variableAssign) {
    std::stringstream ss;

    std::shared_ptr<BVariableAccess> variableAccess = variableAssign->getVariableAccess();
    std::shared_ptr<BChain> variableAccessChain = variableAccess->getChain();

    // Store return values in unique keys in a map
    std::map<std::shared_ptr<IBChainable>, std::string> returnMap;

    // TODO Add expression
    // Start converting the expression
    ss << std::endl;
    _indent(variableAssign->getParentScope(), ss);
    ss << "# Evaluating expression" << std::endl;
    std::string expression = _expressionToCode(variableAssign->getParentScope(), variableAssign->getExpression(), ss);

    // Convert chain to code
    ss << std::endl;
    _indent(variableAssign->getParentScope(), ss);
    ss << "# Assign variable" << std::endl;
    _chainToCode(variableAssign->getParentScope(), variableAccessChain, 0,
                     variableAccessChain->size()-2, returnMap, ss);

    // Add the last assignment statement
    _indent(variableAssign->getParentScope(), ss);
    if(variableAccess->last()->getVariable()->isClassMember()) {
        if(variableAccessChain->size() == 1) {
            _varChainAccess_member_first(variableAccess->last(), ss);
        } else {
            _varChainAccess_member_last(variableAccess->last(),
                                        returnMap[(*variableAccessChain)[variableAccessChain->size()-2]], ss);
        }
    } else {
        _varChainAccess_nonMember(variableAccess->last(), ss);
    }
    ss << "=" << expression;
    ss << std::endl;
    BGenerateCode::get().write(ss);
}

void BBashHelper::functionExec(std::shared_ptr<BFunctionCall> functionCall) {
    std::stringstream ss;

    // Store return values in unique keys in a map
    std::map<std::shared_ptr<IBChainable>, std::string> returnMap;

    // Convert chain to code
    ss << std::endl;
    _indent(functionCall->getParentScope(), ss);
    ss << "# Execute a function" << std::endl;
    _chainToCode(functionCall->last()->getFunction(), functionCall->getChain(), 0, functionCall->getChain()->size()-1,
                 returnMap, ss);
    ss << std::endl;
    BGenerateCode::get().write(ss);
}<|endoftext|>


<commit_before>#include <cmath>
#include <iostream>
#include <ale_interface.hpp>
#include <glog/logging.h>
#include <boost/program_options.hpp>
//#include "prettyprint.hpp"
#include "../include/aleAgent.hpp"
#include "../include/tools.hpp"

/*
  DeepQLearner(
    const ActionVect& legal_actions,
    double epsilon_start,
    const double epsilon_min,
    const double epsilon_decay,
    const int epsilon_explore_idx,
    const int replay_batch_size,
    const int replay_memory_capacity,
    const int replay_start_size,
    const std::string sampleStrategy,
    const int update_frequency,
    const double discount_factor,
    const std::string solver_param
    ):
*/

using namespace deepRL;
namespace po = boost::program_options;
double EpisodeLearning( ALEInterface& ale, deepRL::DeepQLearner& dqlearner, const bool update);
po::variables_map argmap;

int main(int argc, char** argv) {

    po::options_description desc("Valid options");
    desc.add_options()
        ("help,h", "Help message")
        ("gpu,u", po::value<bool>()->default_value(false), "Use GPU to brew Caffe")
	("gui,i", po::value<bool>()->default_value(false), "Open a GUI window")
        ("rom,o", po::value<std::string>()->default_value("./roms/breakout.bin"), "Rom file to play")
	("epsilon_start,s", po::value<double>()->default_value(1.0), "Epsilon start value for action selection")
	("epsilon_min,m", po::value<double>()->default_value(0.1), "The final epsilon")
	("epsilon_decay,d", po::value<double>()->default_value(0.98), "Epsilon decay ratio")
	("epsilon_explore_idx,x", po::value<int>()->default_value(100000), "Number of iterations needed for epsilon to reach epsilon_min")
	("replay_memory_capacity,c", po::value<int>()->default_value(50000), "Capacity of replay memory")
	("replay_start_size,r", po::value<int>()->default_value(500), "UEnough amount of transitions to start learning")
	("sampleStrategy,y", po::value<std::string>()->default_value("uniform")->required(), "Sampling strategy for transition")
	("update_frequency,f", po::value<int>()->default_value(1000), "Every #update_frequency set target_net_ = net_")
	("discount_factor,n", po::value<double>()->default_value(0.98), "Discount factor of future rewards (0,1]")
	("solver,v", po::value<std::string>()->default_value("./prototxt/aleSolver.prototxt")->required(), "Solver parameter file (*.prototxt)")
	("skip_frame,p", po::value<int>()->default_value(3), "Number of frames skipped")
	("show_frame,e", po::value<bool>()->default_value(false), "Show the current frame in CUI")
	("model,l", po::value<std::string>()->default_value("")->required(), "Model file to load")
	("evaluate,u", po::value<bool>()->default_value(false), "Evaluation mode: only playing a game, no updates");

    po::store(parse_command_line(argc, argv, desc), argmap);
    po::notify(argmap);

    if (argmap.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

  google::InitGoogleLogging(argv[0]);
  google::InstallFailureSignalHandler();
  google::LogToStderr();

  if (argmap["gpu"].as<bool>()) {
    caffe::Caffe::set_mode(caffe::Caffe::GPU);
  } else {
    caffe::Caffe::set_mode(caffe::Caffe::CPU);
  }

  ALEInterface ale(argmap["gui"].as<bool>());
  std::cout << "Init ale environment ok!" << std::endl;

  // Load the ROM file
  ale.loadROM(argmap["rom"].as<std::string>());

  std::cout << "Loading rom: " << argmap["rom"].as<std::string>() << " ok!" << std::endl;

  // Get the vector of legal actions
  const auto legal_actions = ale.getMinimalActionSet();

  std::cout << "Action space: " << legal_actions.size() << std::endl;

  // deepqlearner
  deepRL::DeepQLearner dqlearner(legal_actions,
				argmap["epsilon_start"].as<double>(),
				argmap["epsilon_min"].as<double>(),
				argmap["epsilon_decay"].as<double>(),
				argmap["epsilon_explore_idx"].as<int>(),
				deepRL::kMinibatchSize,
				argmap["replay_memory_capacity"].as<int>(),
				argmap["replay_start_size"].as<int>(),
				argmap["sampleStrategy"].as<std::string>(),
				argmap["update_frequency"].as<int>(),
				argmap["discount_factor"].as<double>(),
				argmap["solver"].as<std::string>());
  dqlearner.Initialize();

  if (argmap["model"].as<std::string>() !="null") {
    // Just evaluate the given trained model
    dqlearner.LoadPretrainedModel(argmap["model"].as<std::string>());
    std::cout << "Loading " << argmap["model"].as<std::string>() << std::endl;
  }
  //evaluate mode
  if (argmap["evaluate"].as<bool>()) {
    auto total_score = 0.0;
      const auto score =
          EpisodeLearning(ale, dqlearner, false);
      std::cout << "score: " << score << std::endl;
    return 0;
  }

  // learning mode
  for (auto episode = 0;; episode++) {
    const auto score = EpisodeLearning(ale, dqlearner, true);
    std::cout << "Episode: " << episode << " ,Score: " << score << std::endl;
    if (episode % 10 == 0) {
      // After every 10 episodes, evaluate the current strength
      const auto eval_score = EpisodeLearning(ale, dqlearner,false);
      std::cout << "evaluation score: " << eval_score << std::endl;
    }
  }
}

/**
 * one episode learning and return the total score
 */
double EpisodeLearning( ALEInterface& ale, deepRL::DeepQLearner& dqlearner, const bool update) {
  assert(!ale.game_over());
  std::deque<deepRL::FrameDataSp> past_frames;
  //dqlearner.replay_memory_.resetPool();

  auto total_score = 0.0;
  for (auto frame = 0; !ale.game_over(); ++frame) {
    //std::cout << "frame: " << frame << std::endl;
    const auto current_frame = deepRL::PreprocessScreen(ale.getScreen());
    if (argmap["show_frame"].as<bool>()) {
      std::cout << deepRL::DrawFrame(*current_frame) << std::endl;
    }
    past_frames.push_back(current_frame);
    if (past_frames.size() < deepRL::kInputFrameCount) {
      // If there are not past frames enough for DQN input, just select NOOP
      for (auto i = 0; i < argmap["skip_frame"].as<int>() + 1 && !ale.game_over(); ++i) {
        total_score += ale.act(PLAYER_A_NOOP);
      }
    } else {
      if (past_frames.size() > deepRL::kInputFrameCount) {
        past_frames.pop_front();
      }
      deepRL::InputFrames input_frames;
      std::copy(past_frames.begin(), past_frames.end(), input_frames.begin());
      const auto action = dqlearner.SelectAction(input_frames);
      auto immediate_score = 0.0;

      for (auto i = 0; i < argmap["skip_frame"].as<int>() + 1 && !ale.game_over(); ++i) {
        // Last action is repeated on skipped frames
        immediate_score += ale.act(action);
      }

      total_score += immediate_score;

      //clip reward for robust gradient update
      // Rewards for DQN are normalized as follows:
      // 1 for any positive score, -1 for any negative score, otherwise 0
      const auto reward =
          immediate_score == 0 ?
              0 :
              immediate_score /= std::abs(immediate_score);

      if (update) {
        // Add the current transition to replay memory
        const auto transition = ale.game_over() ?
            deepRL::Transition(input_frames, action, reward, boost::none) :
            deepRL::Transition(
                input_frames,
                action,
                reward,
                deepRL::PreprocessScreen(ale.getScreen()));
        dqlearner.replay_memory_.addTransition(transition);
	//std::cout << "Memorypool Size: " << dqlearner.replay_memory_.memory_size() << std::endl;
        // If the size of replay memory is enough, update DQN
        if (dqlearner.replay_memory_.memory_size() >= argmap["replay_start_size"].as<int>()) {
          dqlearner.BatchUpdate();
        }
      }
    }
  }
  ale.reset_game();
  return total_score;
}

<commit_msg>add eval_epsilon for evaluation mode<commit_after>#include <cmath>
#include <iostream>
#include <ale_interface.hpp>
#include <glog/logging.h>
#include <boost/program_options.hpp>
//#include "prettyprint.hpp"
#include "../include/aleAgent.hpp"
#include "../include/tools.hpp"

/*
  DeepQLearner(
    const ActionVect& legal_actions,
    double epsilon_start,
    const double epsilon_min,
    const double epsilon_decay,
    const int epsilon_explore_idx,
    const int replay_batch_size,
    const int replay_memory_capacity,
    const int replay_start_size,
    const std::string sampleStrategy,
    const int update_frequency,
    const double discount_factor,
    const std::string solver_param
    ):
*/

using namespace deepRL;
namespace po = boost::program_options;
double EpisodeLearning( ALEInterface& ale, deepRL::DeepQLearner& dqlearner, const bool update);
po::variables_map argmap;

int main(int argc, char** argv) {

    po::options_description desc("Valid options");
    desc.add_options()
        ("help,h", "Help message")
        ("gpu,u", po::value<bool>()->default_value(false), "Use GPU to brew Caffe")
	("gui,i", po::value<bool>()->default_value(false), "Open a GUI window")
        ("rom,o", po::value<std::string>()->default_value("./roms/breakout.bin"), "Rom file to play")
	("epsilon_start,s", po::value<double>()->default_value(1.0), "Epsilon start value for action selection")
	("epsilon_min,m", po::value<double>()->default_value(0.1), "The final epsilon")
	("epsilon_decay,d", po::value<double>()->default_value(0.98), "Epsilon decay ratio")
	("epsilon_explore_idx,x", po::value<int>()->default_value(100000), "Number of iterations needed for epsilon to reach epsilon_min")
	("replay_memory_capacity,c", po::value<int>()->default_value(50000), "Capacity of replay memory")
	("replay_start_size,r", po::value<int>()->default_value(500), "UEnough amount of transitions to start learning")
	("sampleStrategy,y", po::value<std::string>()->default_value("uniform")->required(), "Sampling strategy for transition")
	("update_frequency,f", po::value<int>()->default_value(1000), "Every #update_frequency set target_net_ = net_")
	("discount_factor,n", po::value<double>()->default_value(0.98), "Discount factor of future rewards (0,1]")
	("solver,v", po::value<std::string>()->default_value("./prototxt/aleSolver.prototxt")->required(), "Solver parameter file (*.prototxt)")
	("skip_frame,p", po::value<int>()->default_value(3), "Number of frames skipped")
	("show_frame,e", po::value<bool>()->default_value(false), "Show the current frame in CUI")
	("model,l", po::value<std::string>()->default_value("")->required(), "Model file to load")
	("evaluate,u", po::value<bool>()->default_value(false), "Evaluation mode: only playing a game, no updates")
	("eval_epsilon,k", po::value<double>()->default_value(0.05), "Epsilon used in evaluate mode");

    po::store(parse_command_line(argc, argv, desc), argmap);
    po::notify(argmap);

    if (argmap.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

  google::InitGoogleLogging(argv[0]);
  google::InstallFailureSignalHandler();
  google::LogToStderr();

  if (argmap["gpu"].as<bool>()) {
    caffe::Caffe::set_mode(caffe::Caffe::GPU);
  } else {
    caffe::Caffe::set_mode(caffe::Caffe::CPU);
  }

  ALEInterface ale(argmap["gui"].as<bool>());
  std::cout << "Init ale environment ok!" << std::endl;

  // Load the ROM file
  ale.loadROM(argmap["rom"].as<std::string>());

  std::cout << "Loading rom: " << argmap["rom"].as<std::string>() << " ok!" << std::endl;

  // Get the vector of legal actions
  const auto legal_actions = ale.getMinimalActionSet();

  std::cout << "Action space: " << legal_actions.size() << std::endl;

  // deepqlearner
  deepRL::DeepQLearner dqlearner(legal_actions,
				argmap["epsilon_start"].as<double>(),
				argmap["epsilon_min"].as<double>(),
				argmap["epsilon_decay"].as<double>(),
				argmap["epsilon_explore_idx"].as<int>(),
				deepRL::kMinibatchSize,
				argmap["replay_memory_capacity"].as<int>(),
				argmap["replay_start_size"].as<int>(),
				argmap["sampleStrategy"].as<std::string>(),
				argmap["update_frequency"].as<int>(),
				argmap["discount_factor"].as<double>(),
				argmap["solver"].as<std::string>(),
				argmap["evaluate"].as<bool>(),
                                argmap["eval_epsilon"].as<double>());
  dqlearner.Initialize();

  if (argmap["model"].as<std::string>() !="null") {
    // Just evaluate the given trained model
    dqlearner.LoadPretrainedModel(argmap["model"].as<std::string>());
    std::cout << "Loading " << argmap["model"].as<std::string>() << std::endl;
  }
  //evaluate mode
  if (argmap["evaluate"].as<bool>()) {
    auto total_score = 0.0;
      const auto score =
          EpisodeLearning(ale, dqlearner, false);
      std::cout << "score: " << score << std::endl;
    return 0;
  }

  // learning mode
  for (auto episode = 0;; episode++) {
    const auto score = EpisodeLearning(ale, dqlearner, true);
    std::cout << "Episode: " << episode << " ,Score: " << score << std::endl;
    if (episode % 10 == 0) {
      // After every 10 episodes, evaluate the current strength
      const auto eval_score = EpisodeLearning(ale, dqlearner,false);
      std::cout << "evaluation score: " << eval_score << std::endl;
    }
  }
}

/**
 * one episode learning and return the total score
 */
double EpisodeLearning( ALEInterface& ale, deepRL::DeepQLearner& dqlearner, const bool update) {
  assert(!ale.game_over());
  std::deque<deepRL::FrameDataSp> past_frames;
  //dqlearner.replay_memory_.resetPool();

  auto total_score = 0.0;
  for (auto frame = 0; !ale.game_over(); ++frame) {
    //std::cout << "frame: " << frame << std::endl;
    const auto current_frame = deepRL::PreprocessScreen(ale.getScreen());
    if (argmap["show_frame"].as<bool>()) {
      std::cout << deepRL::DrawFrame(*current_frame) << std::endl;
    }
    past_frames.push_back(current_frame);
    if (past_frames.size() < deepRL::kInputFrameCount) {
      // If there are not past frames enough for DQN input, just select NOOP
      for (auto i = 0; i < argmap["skip_frame"].as<int>() + 1 && !ale.game_over(); ++i) {
        total_score += ale.act(PLAYER_A_NOOP);
      }
    } else {
      if (past_frames.size() > deepRL::kInputFrameCount) {
        past_frames.pop_front();
      }
      deepRL::InputFrames input_frames;
      std::copy(past_frames.begin(), past_frames.end(), input_frames.begin());
      const auto action = dqlearner.SelectAction(input_frames);
      auto immediate_score = 0.0;

      for (auto i = 0; i < argmap["skip_frame"].as<int>() + 1 && !ale.game_over(); ++i) {
        // Last action is repeated on skipped frames
        immediate_score += ale.act(action);
      }

      total_score += immediate_score;

      //clip reward for robust gradient update
      // Rewards for DQN are normalized as follows:
      // 1 for any positive score, -1 for any negative score, otherwise 0
      const auto reward =
          immediate_score == 0 ?
              0 :
              immediate_score /= std::abs(immediate_score);

      if (update) {
        // Add the current transition to replay memory
        const auto transition = ale.game_over() ?
            deepRL::Transition(input_frames, action, reward, boost::none) :
            deepRL::Transition(
                input_frames,
                action,
                reward,
                deepRL::PreprocessScreen(ale.getScreen()));
        dqlearner.replay_memory_.addTransition(transition);
	//std::cout << "Memorypool Size: " << dqlearner.replay_memory_.memory_size() << std::endl;
        // If the size of replay memory is enough, update DQN
        if (dqlearner.replay_memory_.memory_size() >= argmap["replay_start_size"].as<int>()) {
          dqlearner.BatchUpdate();
        }
      }
    }
  }
  ale.reset_game();
  return total_score;
}

<|endoftext|>


<commit_before>#include "Server.h"
#include "Connection.h"
#include "WebPageManager.h"

#include <QTcpServer>

Server::Server(QObject *parent) : QObject(parent) {
  m_tcp_server = new QTcpServer(this);
}

bool Server::start(int port) {
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  QTextStream(stderr) <<
    "WARNING: The next major version of capybara-webkit " <<
    "will require at least version 5.0 of Qt. " <<
    "You're using version " << QT_VERSION_STR << "." << endl;
#endif

  connect(m_tcp_server, SIGNAL(newConnection()), this, SLOT(handleConnection()));
  return m_tcp_server->listen(QHostAddress::LocalHost, port);
}

quint16 Server::server_port() const {
  return m_tcp_server->serverPort();
}
QString Server::error_string() const {
  return m_tcp_server->errorString();
}

void Server::stop() {
  while (!queue.isEmpty()) {
    QTcpSocket *socket = queue.dequeue();
    socket->close();
  }
  m_tcp_server->close();
  std::cout << "Terminated" << std::endl;
}
void Server::handleTermination() {
  stop();
}
void Server::process() {
  QTcpSocket *socket = queue.head();
  int id = socket->socketDescriptor();
  std::cout << "Start processing: " << id << std::endl;
  Connection *conn = new Connection(socket, new WebPageManager(this), this);
  connect(socket, SIGNAL(disconnected()), this, SLOT(handleDisconnection()));
  connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
  connect(socket, SIGNAL(disconnected()), conn, SLOT(handleDisconnection()));
}
void Server::handleConnection() {
  QTcpSocket *socket = m_tcp_server->nextPendingConnection();
  int id = socket->socketDescriptor();
  std::cout << "Client connected: " << id << std::endl;
  queue.enqueue(socket);
  std::cout << "Queue length: " << queue.count() << std::endl;
  if (queue.count() == 1) {
    this->process();
  }
}
void Server::handleDisconnection() {
  QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
  int id = socket->socketDescriptor();
  queue.dequeue();
  if(!queue.isEmpty()) {
    this->process();
  }
  std::cout << "Client disconnected: " << id << std::endl;
}
<commit_msg>try queue connections<commit_after>#include "Server.h"
#include "Connection.h"
#include "WebPageManager.h"

#include <QTcpServer>

Server::Server(QObject *parent) : QObject(parent) {
  m_tcp_server = new QTcpServer(this);
}

bool Server::start(int port) {
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  QTextStream(stderr) <<
    "WARNING: The next major version of capybara-webkit " <<
    "will require at least version 5.0 of Qt. " <<
    "You're using version " << QT_VERSION_STR << "." << endl;
#endif

  connect(m_tcp_server, SIGNAL(newConnection()), this, SLOT(handleConnection()));
  return m_tcp_server->listen(QHostAddress::LocalHost, port);
}

quint16 Server::server_port() const {
  return m_tcp_server->serverPort();
}
QString Server::error_string() const {
  return m_tcp_server->errorString();
}

void Server::stop() {
  while (!queue.isEmpty()) {
    QTcpSocket *socket = queue.dequeue();
    socket->close();
  }
  m_tcp_server->close();
  std::cout << "Terminated" << std::endl;
}
void Server::handleTermination() {
  stop();
}
void Server::process() {
  if (queue.count() == 0) {
    return;
  }
  QTcpSocket *socket = queue.head();
  int id = socket->socketDescriptor();
  std::cout << "Start processing: " << id << std::endl;
  Connection *conn = new Connection(socket, new WebPageManager(this), this);
  connect(socket, SIGNAL(disconnected()), this, SLOT(handleDisconnection()));
  connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
  connect(socket, SIGNAL(disconnected()), conn, SLOT(handleDisconnection()));
}
void Server::handleConnection() {
  QTcpSocket *socket = m_tcp_server->nextPendingConnection();
  int id = socket->socketDescriptor();
  std::cout << "Client connected: " << id << std::endl;
  queue.enqueue(socket);
  std::cout << "Queue length: " << queue.count() << std::endl;
  if (queue.count() == 1) {
    this->process();
  }
}
void Server::handleDisconnection() {
  QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
  int id = socket->socketDescriptor();
  queue.dequeue();
  std::cout << "Client disconnected: " << id << std::endl;
  this->process();
}
<|endoftext|>


<commit_before>#include "Target.hpp"
#include <opencv2/opencv.hpp>
#include <math.h>
#include <iostream>

Target::Target(std::vector<std::vector<cv::Point> > contour)
{
<<<<<<< HEAD
    edgeL = contour[0];
    edgeR = contour[1];
=======
    if(contour.size() > 1)
    {
        edgeL = contour[0];
        edgeR = contour[1];
    }
    else
    {
        edgeL = contour[0];
        edgeR = contour[0];
    }
>>>>>>> 3c730362ed6b5eec0a671b0e86f2f5ccc9441881

    //splits the inputted vector into two shapes again
}

void Target::setTar(bool tar) {

    Tar = tar;
}

bool Target::getTar() {

    return Tar;

}

double Target::getHeight()
{
    return fabs(getTopPoint().y - getBottomPoint().y);
}

double Target::getWidth()
{
    return fabs(getRightPoint().x - getLeftPoint().x);
}

//True if Gears, False if Boilers
bool Target::getType() {
  if (getHeight() > getWidth()) {
    return true;
  }
if (getHeight() < getWidth()) {
    return false;
  }
}

/*
bool Target::isInitialized()
{
    std::cout << "EDGE" << edge;
    if (edge.size() == 0) {
        return false;
    }
    return true;
}
*/

void Target::printPoints() //debugging
{
    std::cout << "TopPoint: " << getTopPoint().y << std::endl;
    std::cout << "BottomPoint: " << getBottomPoint().y << std::endl;
    std::cout << "LeftPoint: " << getLeftPoint().x << std::endl;
    std::cout << "RightPoint: " << getRightPoint().x << std::endl;
    std::cout << "LeftRightPoint: " << getLeftRightPoint().x << std::endl;
    std::cout << "RightLeftPoint: " << getRightLeftPoint().x << std::endl;
    std::cout << "Height: " << getHeight() << std::endl;
    std::cout << "Width: "  << getWidth() << std::endl;
}

cv::Point Target::getCenter()//finds center point of target
{
    cv::Point center((getLeftPoint().x + getRightPoint().x)/2, (getTopPoint().y + getBottomPoint().y)/2);
    return center;
}

cv::Point Target::getTopPoint()
{
    cv::Point max =  edgeL[0];
    for(unsigned int i = 0; i < edgeL.size(); i++)
    {
        if(edgeL[i].y > max.y)
        {
            max = edgeL[i];
        }
    }
    return max;
}
cv::Point Target::getBottomPoint()
{
    cv::Point min =  edgeL[0];
    for(unsigned int i = 0; i < edgeL.size(); i++)
    {
        if(edgeL[i].y < min.y)
        {
            min = edgeL[i];
        }
    }
    return min;
}
cv::Point Target::getLeftPoint()
{
    cv::Point min =  edgeL[0];
    for(unsigned int i = 0; i < edgeL.size(); i++)
    {
        if(edgeL[i].x < min.x)
        {
            min = edgeL[i];
        }
    }
    return min;
}
// Uses the right shape for right most point in order to pretend like it's one big shape
cv::Point Target::getRightPoint()
{
    cv::Point max = edgeR[0];
    for(unsigned int i = 0; i < edgeR.size(); i++)
    {
        if(edgeR[i].x > max.x)
        {
            max = edgeR[i];
        }
    }
    return max;
}

//Right-most point of left shape
cv::Point Target::getLeftRightPoint()
{
  cv::Point max = edgeL[0];
  for(unsigned int i = 0; i < edgeL.size(); i++)
  {
      if(edgeL[i].x > max.x)
      {
          max = edgeL[i];
      }
  }
  return max;
}

//Left-most point of right shape
cv::Point Target::getRightLeftPoint()
{
  cv::Point min = edgeR[0];
  for(unsigned int i = 0; i < edgeR.size(); i++)
  {
      if(edgeR[i].x < min.x)
      {
          min = edgeR[i];
      }
  }
  return min;
}
<commit_msg>Testing code to make sure nothing stupid happend<commit_after>#include "Target.hpp"
#include <opencv2/opencv.hpp>
#include <math.h>
#include <iostream>

Target::Target(std::vector<std::vector<cv::Point> > contour)
{
    edgeL = contour[0];
    edgeR = contour[1];

    //splits the inputted vector into two shapes again
}

void Target::setTar(bool tar) {

    Tar = tar;
}

bool Target::getTar() {

    return Tar;

}

double Target::getHeight()
{
    return fabs(getTopPoint().y - getBottomPoint().y);
}

double Target::getWidth()
{
    return fabs(getRightPoint().x - getLeftPoint().x);
}

//True if Gears, False if Boilers
bool Target::getType() {
  if (getHeight() > getWidth()) {
    return true;
  }
if (getHeight() < getWidth()) {
    return false;
  }
}

/*
bool Target::isInitialized()
{
    std::cout << "EDGE" << edge;
    if (edge.size() == 0) {
        return false;
    }
    return true;
}
*/

void Target::printPoints() //debugging
{
    std::cout << "TopPoint: " << getTopPoint().y << std::endl;
    std::cout << "BottomPoint: " << getBottomPoint().y << std::endl;
    std::cout << "LeftPoint: " << getLeftPoint().x << std::endl;
    std::cout << "RightPoint: " << getRightPoint().x << std::endl;
    std::cout << "LeftRightPoint: " << getLeftRightPoint().x << std::endl;
    std::cout << "RightLeftPoint: " << getRightLeftPoint().x << std::endl;
    std::cout << "Height: " << getHeight() << std::endl;
    std::cout << "Width: "  << getWidth() << std::endl;
}

cv::Point Target::getCenter()//finds center point of target
{
    cv::Point center((getLeftPoint().x + getRightPoint().x)/2, (getTopPoint().y + getBottomPoint().y)/2);
    return center;
}

cv::Point Target::getTopPoint()
{
    cv::Point max =  edgeL[0];
    for(unsigned int i = 0; i < edgeL.size(); i++)
    {
        if(edgeL[i].y > max.y)
        {
            max = edgeL[i];
        }
    }
    return max;
}
cv::Point Target::getBottomPoint()
{
    cv::Point min =  edgeL[0];
    for(unsigned int i = 0; i < edgeL.size(); i++)
    {
        if(edgeL[i].y < min.y)
        {
            min = edgeL[i];
        }
    }
    return min;
}
cv::Point Target::getLeftPoint()
{
    cv::Point min =  edgeL[0];
    for(unsigned int i = 0; i < edgeL.size(); i++)
    {
        if(edgeL[i].x < min.x)
        {
            min = edgeL[i];
        }
    }
    return min;
}
// Uses the right shape for right most point in order to pretend like it's one big shape
cv::Point Target::getRightPoint()
{
    cv::Point max = edgeR[0];
    for(unsigned int i = 0; i < edgeR.size(); i++)
    {
        if(edgeR[i].x > max.x)
        {
            max = edgeR[i];
        }
    }
    return max;
}

//Right-most point of left shape
cv::Point Target::getLeftRightPoint()
{
  cv::Point max = edgeL[0];
  for(unsigned int i = 0; i < edgeL.size(); i++)
  {
      if(edgeL[i].x > max.x)
      {
          max = edgeL[i];
      }
  }
  return max;
}

//Left-most point of right shape
cv::Point Target::getRightLeftPoint()
{
  cv::Point min = edgeR[0];
  for(unsigned int i = 0; i < edgeR.size(); i++)
  {
      if(edgeR[i].x < min.x)
      {
          min = edgeR[i];
      }
  }
  return min;
}
<|endoftext|>


<commit_before>/*
 ** Licensed under the Apache License, Version 2.0 (the "License");
 ** you may not use this file except in compliance with the License.
 ** You may obtain a copy of the License at
 ** http://www.apache.org/licenses/LICENSE-2.0
 ** Unless required by applicable law or agreed to in writing, software
 ** distributed under the License is distributed on an "AS IS" BASIS,
 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 */

#include "training.h"
#include "debug.h"
#include "memry.h"
#include "grphics.h"
#include "evnts.h"

make_int_var    (LearningDebugLevel, 0, MakeLearningDebugLevel,
		18, 5, SetLearningDebugLevel,
		"Learning Debug Level: ");

make_int_var   (NormMethod, character, MakeNormMethod,
					15, 10, SetNormMethod,   "Normalization Method   ...")

//char *demodir;                   /*demo home directory */

void						cprintf(					//Trace printf
const char					*format,...					//special message
)
{
}

char						*c_alloc_string(			//allocate string
INT32						count						//no of chars required
)
{
	return alloc_string(count);
}

void						c_free_string(				//free a string
char						*string						//string to free
)
{
	free_string(string);
}

void						*c_alloc_mem_p(				//allocate permanent space
INT32						count						//block size to allocate
)
{
	return alloc_mem_p(count);
}
void						*c_alloc_mem(				//get some memory
INT32						count						//no of bytes to get
)
{
	return alloc_mem(count);
}
void						c_free_mem(					//free mem from alloc_mem
void						*oldchunk					//chunk to free
)
{
	free_mem(oldchunk);
}
void						c_check_mem(				//check consistency
const char			*string,					//context message
INT8						level						//level of check
)
{
	check_mem(string,level);
}

void*						c_alloc_struct(				//allocate memory
INT32						count,						//no of chars required
const char*					name						//class name
)
{
	return alloc_struct(count,name);
}
void						c_free_struct(				//free a structure
void*						deadstruct,					//structure to free
INT32						count,						//no of bytes
const char*					name						//class name
)
{
	free_struct(deadstruct,count,name);
}

void						c_make_current(				/*move pen*/
void*						win
)
{
	WINDOW					window=(WINDOW)win;

	window->Make_picture_current();
}

void						reverse32(
void*						ptr
)
{
	char					tmp;
	char*					cptr=(char*)ptr;

	tmp=*cptr;
	*cptr=*(cptr+3);
	*(cptr+3)=tmp;
	tmp=*(cptr+1);
	*(cptr+1)=*(cptr+2);
	*(cptr+2)=tmp;
}

void						reverse16(
void*						ptr
)
{
	char					tmp;
	char*					cptr=(char*)ptr;

	tmp=*cptr;
	*cptr=*(cptr+1);
	*(cptr+1)=tmp;
}

void*						c_create_window(			/*create a window*/
const char					*name,						/*name/title of window*/
INT16						xpos,						/*coords of window*/
INT16						ypos,						/*coords of window*/
INT16						xsize,						/*size of window*/
INT16						ysize,						/*size of window*/
double						xmin,						/*scrolling limits*/
double						xmax,						/*to stop users*/
double						ymin,						/*getting lost in*/
double						ymax						/*empty space*/
)
{
	return create_window(name,SCROLLINGWIN,xpos,ypos,xsize,ysize,
		xmin,xmax,ymin,ymax,TRUE,FALSE,FALSE,TRUE);
}
void						c_line_color_index(			/*set color*/
void*						win,
C_COL						index
)
{
	WINDOW					window=(WINDOW)win;

//	ASSERT_HOST(index>=0 && index<=48);
	if (index<0 || index>48)
		index=(C_COL)1;
	window->Line_color_index((COLOUR)index);
}
void						c_move(						/*move pen*/
void*						win,
double						x,
double						y
)
{
	WINDOW					window=(WINDOW)win;

	window->Move2d(x,y);
}
void						c_draw(						/*move pen*/
void*						win,
double						x,
double						y
)
{
	WINDOW					window=(WINDOW)win;

	window->Draw2d(x,y);
}
void						c_clear_window(				/*move pen*/
void*						win
)
{
	WINDOW					window=(WINDOW)win;

	window->Clear_view_surface();
}
char						window_wait(				/*move pen*/
void*						win
)
{
	WINDOW					window=(WINDOW)win;
	GRAPHICS_EVENT			event;

	await_event(window,TRUE,ANY_EVENT,&event);
	if (event.type==KEYPRESS_EVENT)
		return event.key;
	else
		return '\0';
}
<commit_msg>Updated graphics output for new java-based display<commit_after>/*
 ** Licensed under the Apache License, Version 2.0 (the "License");
 ** you may not use this file except in compliance with the License.
 ** You may obtain a copy of the License at
 ** http://www.apache.org/licenses/LICENSE-2.0
 ** Unless required by applicable law or agreed to in writing, software
 ** distributed under the License is distributed on an "AS IS" BASIS,
 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 */

#include "training.h"
#include "debug.h"
#include "memry.h"
#include "grphics.h"
#include "evnts.h"

make_int_var    (LearningDebugLevel, 0, MakeLearningDebugLevel,
		18, 5, SetLearningDebugLevel,
		"Learning Debug Level: ");

make_int_var   (NormMethod, character, MakeNormMethod,
					15, 10, SetNormMethod,   "Normalization Method   ...")

//char *demodir;                   /*demo home directory */

void						cprintf(					//Trace printf
const char					*format,...					//special message
)
{
}

char						*c_alloc_string(			//allocate string
INT32						count						//no of chars required
)
{
	return alloc_string(count);
}

void						c_free_string(				//free a string
char						*string						//string to free
)
{
	free_string(string);
}

void						*c_alloc_mem_p(				//allocate permanent space
INT32						count						//block size to allocate
)
{
	return alloc_mem_p(count);
}
void						*c_alloc_mem(				//get some memory
INT32						count						//no of bytes to get
)
{
	return alloc_mem(count);
}
void						c_free_mem(					//free mem from alloc_mem
void						*oldchunk					//chunk to free
)
{
	free_mem(oldchunk);
}
void						c_check_mem(				//check consistency
const char			*string,					//context message
INT8						level						//level of check
)
{
	check_mem(string,level);
}

void*						c_alloc_struct(				//allocate memory
INT32						count,						//no of chars required
const char*					name						//class name
)
{
	return alloc_struct(count,name);
}
void						c_free_struct(				//free a structure
void*						deadstruct,					//structure to free
INT32						count,						//no of bytes
const char*					name						//class name
)
{
	free_struct(deadstruct,count,name);
}

void						c_make_current(				/*move pen*/
void*						win
)
{
  ScrollView* window = (ScrollView*) win;
  window->Update();
}

void						reverse32(
void*						ptr
)
{
	char					tmp;
	char*					cptr=(char*)ptr;

	tmp=*cptr;
	*cptr=*(cptr+3);
	*(cptr+3)=tmp;
	tmp=*(cptr+1);
	*(cptr+1)=*(cptr+2);
	*(cptr+2)=tmp;
}

void						reverse16(
void*						ptr
)
{
	char					tmp;
	char*					cptr=(char*)ptr;

	tmp=*cptr;
	*cptr=*(cptr+1);
	*(cptr+1)=tmp;
}

void*						c_create_window(			/*create a window*/
const char					*name,						/*name/title of window*/
INT16						xpos,						/*coords of window*/
INT16						ypos,						/*coords of window*/
INT16						xsize,						/*size of window*/
INT16						ysize,						/*size of window*/
double						xmin,						/*scrolling limits*/
double						xmax,						/*to stop users*/
double						ymin,						/*getting lost in*/
double						ymax						/*empty space*/
)
{
   return new ScrollView(name, xpos, ypos, xsize, ysize, xmin + xmax, ymin + ymax, true);
}
void						c_line_color_index(			/*set color*/
void*						win,
C_COL						index
)
{
 // The colors are the same as the SV ones except that SV has COLOR:NONE --> offset of 1
 ScrollView* window = (ScrollView*) win;
 window->Pen((ScrollView::Color) (index + 1));
}
void						c_move(						/*move pen*/
void*						win,
double						x,
double						y
)
{
  ScrollView* window = (ScrollView*) win;
  window->SetCursor((int) x, (int) y);
}
void						c_draw(						/*move pen*/
void*						win,
double						x,
double						y
)
{
  ScrollView* window = (ScrollView*) win;
  window->DrawTo((int) x, (int) y);
}
void						c_clear_window(				/*move pen*/
void*						win
)
{
  ScrollView* window = (ScrollView*) win;
  window->Clear();
}
char						window_wait(				/*move pen*/
void*						win
)
{
	  ScrollView* window = (ScrollView*) win;
  SVEvent* ev;

  // Wait till an input event (all others are thrown away)
  ev = window->AwaitEvent(SVET_ANY);
  char ret = '\0';
  if (ev->type == SVET_INPUT) { ret = ev->parameter[0]; }
  delete ev;
  return ret;
}
<|endoftext|>


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

#include "atom/browser/atom_download_manager_delegate.h"

#include <string>

#include "atom/browser/api/atom_api_download_item.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/common/options_switches.h"
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/task/post_task.h"
#include "chrome/common/pref_names.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager.h"
#include "net/base/filename_util.h"

namespace atom {

namespace {

// Generate default file path to save the download.
base::FilePath CreateDownloadPath(const GURL& url,
                                  const std::string& content_disposition,
                                  const std::string& suggested_filename,
                                  const std::string& mime_type,
                                  const base::FilePath& default_download_path) {
  auto generated_name =
      net::GenerateFileName(url, content_disposition, std::string(),
                            suggested_filename, mime_type, "download");

  if (!base::PathExists(default_download_path))
    base::CreateDirectory(default_download_path);

  return default_download_path.Append(generated_name);
}

}  // namespace

AtomDownloadManagerDelegate::AtomDownloadManagerDelegate(
    content::DownloadManager* manager)
    : download_manager_(manager), weak_ptr_factory_(this) {}

AtomDownloadManagerDelegate::~AtomDownloadManagerDelegate() {
  if (download_manager_) {
    DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this),
              download_manager_->GetDelegate());
    download_manager_->SetDelegate(nullptr);
    download_manager_ = nullptr;
  }
}

void AtomDownloadManagerDelegate::GetItemSavePath(download::DownloadItem* item,
                                                  base::FilePath* path) {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  v8::Locker locker(isolate);
  v8::HandleScope handle_scope(isolate);
  api::DownloadItem* download =
      api::DownloadItem::FromWrappedClass(isolate, item);
  if (download)
    *path = download->GetSavePath();
}

void AtomDownloadManagerDelegate::GetItemSaveDialogOptions(
    download::DownloadItem* item,
    file_dialog::DialogSettings* options) {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  v8::Locker locker(isolate);
  v8::HandleScope handle_scope(isolate);
  api::DownloadItem* download =
      api::DownloadItem::FromWrappedClass(isolate, item);
  if (download)
    *options = download->GetSaveDialogOptions();
}

void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
    uint32_t download_id,
    const content::DownloadTargetCallback& callback,
    const base::FilePath& default_path) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  auto* item = download_manager_->GetDownload(download_id);
  if (!item)
    return;

  NativeWindow* window = nullptr;
  content::WebContents* web_contents =
      content::DownloadItemUtils::GetWebContents(item);
  auto* relay =
      web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr;
  if (relay)
    window = relay->GetNativeWindow();

  auto* web_preferences = WebContentsPreferences::From(web_contents);
  bool offscreen =
      !web_preferences || web_preferences->IsEnabled(options::kOffscreen);

  base::FilePath path;
  GetItemSavePath(item, &path);
  // Show save dialog if save path was not set already on item
  file_dialog::DialogSettings settings;
  GetItemSaveDialogOptions(item, &settings);
  if (!settings.parent_window)
    settings.parent_window = window;
  settings.force_detached = offscreen;
  if (settings.title.size() == 0)
    settings.title = item->GetURL().spec();
  if (!settings.default_path.empty())
    settings.default_path = default_path;
  if (path.empty() && file_dialog::ShowSaveDialog(settings, &path)) {
    // Remember the last selected download directory.
    AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>(
        download_manager_->GetBrowserContext());
    browser_context->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory,
                                          path.DirName());

    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    v8::Locker locker(isolate);
    v8::HandleScope handle_scope(isolate);
    api::DownloadItem* download_item =
        api::DownloadItem::FromWrappedClass(isolate, item);
    if (download_item)
      download_item->SetSavePath(path);
  }

  // Running the DownloadTargetCallback with an empty FilePath signals that the
  // download should be cancelled.
  // If user cancels the file save dialog, run the callback with empty FilePath.
  callback.Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT,
               download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path,
               path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
                            : download::DOWNLOAD_INTERRUPT_REASON_NONE);
}

void AtomDownloadManagerDelegate::Shutdown() {
  weak_ptr_factory_.InvalidateWeakPtrs();
  download_manager_ = nullptr;
}

bool AtomDownloadManagerDelegate::DetermineDownloadTarget(
    download::DownloadItem* download,
    const content::DownloadTargetCallback& callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (!download->GetForcedFilePath().empty()) {
    callback.Run(download->GetForcedFilePath(),
                 download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
                 download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
                 download->GetForcedFilePath(),
                 download::DOWNLOAD_INTERRUPT_REASON_NONE);
    return true;
  }

  // Try to get the save path from JS wrapper.
  base::FilePath save_path;
  GetItemSavePath(download, &save_path);
  if (!save_path.empty()) {
    callback.Run(save_path,
                 download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
                 download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, save_path,
                 download::DOWNLOAD_INTERRUPT_REASON_NONE);
    return true;
  }

  AtomBrowserContext* browser_context =
      static_cast<AtomBrowserContext*>(download_manager_->GetBrowserContext());
  base::FilePath default_download_path =
      browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory);

  base::PostTaskWithTraitsAndReplyWithResult(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BACKGROUND,
       base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
      base::BindOnce(&CreateDownloadPath, download->GetURL(),
                     download->GetContentDisposition(),
                     download->GetSuggestedFilename(), download->GetMimeType(),
                     default_download_path),
      base::BindOnce(&AtomDownloadManagerDelegate::OnDownloadPathGenerated,
                     weak_ptr_factory_.GetWeakPtr(), download->GetId(),
                     callback));
  return true;
}

bool AtomDownloadManagerDelegate::ShouldOpenDownload(
    download::DownloadItem* download,
    const content::DownloadOpenDelayedCallback& callback) {
  return true;
}

void AtomDownloadManagerDelegate::GetNextId(
    const content::DownloadIdCallback& callback) {
  static uint32_t next_id = download::DownloadItem::kInvalidId + 1;
  callback.Run(next_id++);
}

}  // namespace atom
<commit_msg>Complete TaskPriority::BACKGROUND->BEST_EFFORT mass rename<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/atom_download_manager_delegate.h"

#include <string>

#include "atom/browser/api/atom_api_download_item.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/native_window.h"
#include "atom/browser/ui/file_dialog.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/common/options_switches.h"
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/task/post_task.h"
#include "chrome/common/pref_names.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/browser/download_manager.h"
#include "net/base/filename_util.h"

namespace atom {

namespace {

// Generate default file path to save the download.
base::FilePath CreateDownloadPath(const GURL& url,
                                  const std::string& content_disposition,
                                  const std::string& suggested_filename,
                                  const std::string& mime_type,
                                  const base::FilePath& default_download_path) {
  auto generated_name =
      net::GenerateFileName(url, content_disposition, std::string(),
                            suggested_filename, mime_type, "download");

  if (!base::PathExists(default_download_path))
    base::CreateDirectory(default_download_path);

  return default_download_path.Append(generated_name);
}

}  // namespace

AtomDownloadManagerDelegate::AtomDownloadManagerDelegate(
    content::DownloadManager* manager)
    : download_manager_(manager), weak_ptr_factory_(this) {}

AtomDownloadManagerDelegate::~AtomDownloadManagerDelegate() {
  if (download_manager_) {
    DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this),
              download_manager_->GetDelegate());
    download_manager_->SetDelegate(nullptr);
    download_manager_ = nullptr;
  }
}

void AtomDownloadManagerDelegate::GetItemSavePath(download::DownloadItem* item,
                                                  base::FilePath* path) {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  v8::Locker locker(isolate);
  v8::HandleScope handle_scope(isolate);
  api::DownloadItem* download =
      api::DownloadItem::FromWrappedClass(isolate, item);
  if (download)
    *path = download->GetSavePath();
}

void AtomDownloadManagerDelegate::GetItemSaveDialogOptions(
    download::DownloadItem* item,
    file_dialog::DialogSettings* options) {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
  v8::Locker locker(isolate);
  v8::HandleScope handle_scope(isolate);
  api::DownloadItem* download =
      api::DownloadItem::FromWrappedClass(isolate, item);
  if (download)
    *options = download->GetSaveDialogOptions();
}

void AtomDownloadManagerDelegate::OnDownloadPathGenerated(
    uint32_t download_id,
    const content::DownloadTargetCallback& callback,
    const base::FilePath& default_path) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  auto* item = download_manager_->GetDownload(download_id);
  if (!item)
    return;

  NativeWindow* window = nullptr;
  content::WebContents* web_contents =
      content::DownloadItemUtils::GetWebContents(item);
  auto* relay =
      web_contents ? NativeWindowRelay::FromWebContents(web_contents) : nullptr;
  if (relay)
    window = relay->GetNativeWindow();

  auto* web_preferences = WebContentsPreferences::From(web_contents);
  bool offscreen =
      !web_preferences || web_preferences->IsEnabled(options::kOffscreen);

  base::FilePath path;
  GetItemSavePath(item, &path);
  // Show save dialog if save path was not set already on item
  file_dialog::DialogSettings settings;
  GetItemSaveDialogOptions(item, &settings);
  if (!settings.parent_window)
    settings.parent_window = window;
  settings.force_detached = offscreen;
  if (settings.title.size() == 0)
    settings.title = item->GetURL().spec();
  if (!settings.default_path.empty())
    settings.default_path = default_path;
  if (path.empty() && file_dialog::ShowSaveDialog(settings, &path)) {
    // Remember the last selected download directory.
    AtomBrowserContext* browser_context = static_cast<AtomBrowserContext*>(
        download_manager_->GetBrowserContext());
    browser_context->prefs()->SetFilePath(prefs::kDownloadDefaultDirectory,
                                          path.DirName());

    v8::Isolate* isolate = v8::Isolate::GetCurrent();
    v8::Locker locker(isolate);
    v8::HandleScope handle_scope(isolate);
    api::DownloadItem* download_item =
        api::DownloadItem::FromWrappedClass(isolate, item);
    if (download_item)
      download_item->SetSavePath(path);
  }

  // Running the DownloadTargetCallback with an empty FilePath signals that the
  // download should be cancelled.
  // If user cancels the file save dialog, run the callback with empty FilePath.
  callback.Run(path, download::DownloadItem::TARGET_DISPOSITION_PROMPT,
               download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path,
               path.empty() ? download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
                            : download::DOWNLOAD_INTERRUPT_REASON_NONE);
}

void AtomDownloadManagerDelegate::Shutdown() {
  weak_ptr_factory_.InvalidateWeakPtrs();
  download_manager_ = nullptr;
}

bool AtomDownloadManagerDelegate::DetermineDownloadTarget(
    download::DownloadItem* download,
    const content::DownloadTargetCallback& callback) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  if (!download->GetForcedFilePath().empty()) {
    callback.Run(download->GetForcedFilePath(),
                 download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
                 download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
                 download->GetForcedFilePath(),
                 download::DOWNLOAD_INTERRUPT_REASON_NONE);
    return true;
  }

  // Try to get the save path from JS wrapper.
  base::FilePath save_path;
  GetItemSavePath(download, &save_path);
  if (!save_path.empty()) {
    callback.Run(save_path,
                 download::DownloadItem::TARGET_DISPOSITION_OVERWRITE,
                 download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, save_path,
                 download::DOWNLOAD_INTERRUPT_REASON_NONE);
    return true;
  }

  AtomBrowserContext* browser_context =
      static_cast<AtomBrowserContext*>(download_manager_->GetBrowserContext());
  base::FilePath default_download_path =
      browser_context->prefs()->GetFilePath(prefs::kDownloadDefaultDirectory);

  base::PostTaskWithTraitsAndReplyWithResult(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN},
      base::BindOnce(&CreateDownloadPath, download->GetURL(),
                     download->GetContentDisposition(),
                     download->GetSuggestedFilename(), download->GetMimeType(),
                     default_download_path),
      base::BindOnce(&AtomDownloadManagerDelegate::OnDownloadPathGenerated,
                     weak_ptr_factory_.GetWeakPtr(), download->GetId(),
                     callback));
  return true;
}

bool AtomDownloadManagerDelegate::ShouldOpenDownload(
    download::DownloadItem* download,
    const content::DownloadOpenDelayedCallback& callback) {
  return true;
}

void AtomDownloadManagerDelegate::GetNextId(
    const content::DownloadIdCallback& callback) {
  static uint32_t next_id = download::DownloadItem::kInvalidId + 1;
  callback.Run(next_id++);
}

}  // namespace atom
<|endoftext|>


<commit_before>
#include "Vector.h"
#include <iostream>

using namespace Kona;
using namespace std;

Vector::Vector (const Point& in_start, const Point& in_end) {
    start = in_start;
    end = in_end;
}

Vector::~Vector() {
    // nop
}

Vector&
Vector::operator= (Vector& in_v) {
    this->start = in_v.start;
    this->end = in_v.end;
    return *this;
}

Vector&
Vector::operator+ (Vector& in_v) {
    // TODO: implement correctly
    this->start.x += in_v.start.x;
    this->start.y += in_v.start.y;
    this->end.x   += in_v.end.x;
    this->end.y   += in_v.end.y;
    return *this;
}

void
Vector::show () {
    cout << "(" << this->start.x << ", " << this->start.y << "), "
         << "(" << this->end.x   << ", " << this->end.y   << ")"
         << endl;
}

<commit_msg>[#13] remove unnecessary comment.<commit_after>
#include "Vector.h"
#include <iostream>

using namespace Kona;
using namespace std;

Vector::Vector (const Point& in_start, const Point& in_end) {
    start = in_start;
    end = in_end;
}

Vector::~Vector() {
    // nop
}

Vector&
Vector::operator= (Vector& in_v) {
    this->start = in_v.start;
    this->end = in_v.end;
    return *this;
}

Vector&
Vector::operator+ (Vector& in_v) {
    this->start.x += in_v.start.x;
    this->start.y += in_v.start.y;
    this->end.x   += in_v.end.x;
    this->end.y   += in_v.end.y;
    return *this;
}

void
Vector::show () {
    cout << "(" << this->start.x << ", " << this->start.y << "), "
         << "(" << this->end.x   << ", " << this->end.y   << ")"
         << endl;
}

<|endoftext|>


<commit_before>#include "headers.hpp"
#include "helpers.hpp"
#include "create_db.hpp"

void usage(string prog);

map<uint32_t, uint32_t> parentMap;
map<uint32_t, string> rankMap;
map<uint32_t, uint32_t> standardMap;
map<uint32_t, string> namesMap;
uint32_t undefined=0;

int main(int argc, char *argv[])
{
	string nodesFilename="";
	string namesFilename="";
	string query="";
	string prefix="";
	string taxonomyDB="";
	bool verbose=false;
	uint32_t score=0;
	int threads=1;
	int penalty=2;
	int minNumAgreed=0;

	if (argc<2)
	{
		cout << "less than the required minimum number of options\n";
		usage(argv[0]);
		exit(1);
	}

	/// parse commandline arguments
	while (1)
	{
		static struct option long_options[] =
		{
			{"v", 0, 0, 0},
			{"i", 1, 0, 0},
			{"p", 1, 0, 0},
			{"d", 1, 0, 0},
			{"s", 1, 0, 0},
			{"n", 1, 0, 0},
			{"k", 1, 0, 0},
			{"a", 1, 0, 0}
		};

		int longindex = -1;
		int c = getopt_long_only(argc, argv, "", long_options, &longindex);
		if(c == -1) break;
		else if(c == '?')
		{
			/// If the user entered junk, let him know.
			cerr << "Invalid parameters." << endl;
			usage(argv[0]);
			exit(1);
		}
		else
		{
			switch(longindex)
			{
				case 0: verbose = true; break;
				case 1: query=optarg; break;
				case 2: prefix=optarg; break;
				case 3: taxonomyDB=optarg; break;
				case 4: score=atol(optarg); break;
				case 5: threads=atol(optarg); break;
				case 6: penalty=atol(optarg); break;
				case 7: minNumAgreed=atol(optarg); break;
				default: break;
			}
		}
	}

	nodesFilename=taxonomyDB+"/nodes_wevote.dmp";
	namesFilename=taxonomyDB+"/names_wevote.dmp";
	string OutputDetails= prefix + "_WEVOTE_Details.txt";
	string OutputWEVOTE= prefix + "_WEVOTE.csv";
	cout << "NodesFilename= " << nodesFilename << "\n";
	cout << "NamesFilename= " << namesFilename << "\n";

	/// Build taxonomy trees
	parentMap = build_full_taxid_map(nodesFilename);
	rankMap = build_full_rank_map(nodesFilename);
	standardMap=build_standard_taxid_map(nodesFilename, parentMap, rankMap);
	namesMap = build_taxname_map(namesFilename);

	/// Read CSV formated input file
	vector<readsInfo> Reads;
	readsInfo OneRead;
	Reads.clear();
	ifstream file (query.c_str());
	string line = "";
	int it=0;

	if (!file.is_open())
	{
		cout << "Error opening file:" << query  <<"\n";
		exit(1);
	}

	while (getline(file, line))
	{
		stringstream strstr(line);
		string word = "";
		it=0;
		int value=0;
		(OneRead.annotation).clear();

		while (getline(strstr,word, ','))
		{
			if(it==0)
				OneRead.seqID=word;
			else
			{
				value=atoi(word.c_str());
				(OneRead.annotation).push_back(value);
			}
			it++;
		}
		Reads.push_back(OneRead);
	}

	uint32_t numToolsUsed=(Reads[0].annotation).size();
	uint32_t numReads= Reads.size();

	cout << "Num of reads= " << numReads << "\n";
	cout << "Num of used tools= " << numToolsUsed << "\n";

	if(minNumAgreed>numToolsUsed)
	{
		cout<< "It's not allwed that minNumAgreed > numTools \n";
		exit(1);
	}

	for (uint32_t i=0 ; i<Reads.size() ; i++)
	{
		Reads[i].numToolsUsed=numToolsUsed;
	}

    /// Correct TaxonID for the not standard ranks
    correctTaxa(Reads);

    /// Count number of tools that identified each sequences
    uint32_t count=0;
	for (uint32_t i=0 ; i<Reads.size() ; i++)
	{
		count=0;
		for (uint32_t j=0 ; j<(Reads[i].annotation).size() ; j++)
		{

			if (Reads[i].annotation[j] && 1)
			count++;
		}
		Reads[i].numToolsReported=count;
	}

	/// WEVOTE algorithm
	map<uint32_t, uint32_t> hit_counts;
	set<uint32_t> parents;
	std::set<uint32_t>::iterator set_iterator;
    std::map<uint32_t, uint32_t>::iterator iterator_name;
    uint32_t SavedTax_2[2];
    uint32_t n=0;

    double start = omp_get_wtime();
    omp_set_num_threads(threads);
	cout << "Min Number of Agreed= "<< minNumAgreed << "\n";

    #pragma omp parallel for private (hit_counts, parents, set_iterator, iterator_name, SavedTax_2, n)
	for (uint32_t i=0 ; i<Reads.size() ;i++)
	{
		if (Reads[i].numToolsReported == 0)
		{
			Reads[i].resolvedTaxon=0;
			Reads[i].numToolsAgreed=0;
			Reads[i].score=0;
			continue;
		}
		else if(Reads[i].numToolsReported == 1 && minNumAgreed<=1)
		{
			Reads[i].resolvedTaxon=0;
			for (uint32_t j=0 ; j<numToolsUsed ; j++)
			{
				Reads[i].resolvedTaxon += Reads[i].annotation[j];
			}
			Reads[i].numToolsAgreed=1;
			if(Reads[i].numToolsAgreed==Reads[i].numToolsReported)
			{
				Reads[i].score=(double)Reads[i].numToolsAgreed / (double)Reads[i].numToolsUsed;
			}
			else
			{
				Reads[i].score=((double)Reads[i].numToolsAgreed / (double)Reads[i].numToolsUsed) - (1/penalty*((double)Reads[i].numToolsUsed));
			}
			continue;
		}
		else if(Reads[i].numToolsReported==2 && minNumAgreed<=2)
		{
			n=0;

			for (uint32_t j=0 ; j<numToolsUsed ; j++)
			{
				if(Reads[i].annotation[j])
				{
					SavedTax_2[n]=Reads[i].annotation[j];
					n++;
				}
			}

			Reads[i].resolvedTaxon=lca(SavedTax_2[0], SavedTax_2[1]);
			Reads[i].numToolsAgreed=2;
			if(Reads[i].numToolsAgreed==Reads[i].numToolsReported)
			{
				Reads[i].score=(double)Reads[i].numToolsAgreed / (double)Reads[i].numToolsUsed;
			}
			else
			{
				Reads[i].score=(double)Reads[i].numToolsReported / (double)(Reads[i].numToolsUsed * Reads[i].numToolsAgreed);
			}
			continue;
		}
		else if(Reads[i].numToolsReported>=3)
		{
			hit_counts.clear();
			for (uint32_t j=0 ; j<numToolsUsed ; j++)
			{
				parents=get_ancestry(Reads[i].annotation[j]);
				for(set_iterator = parents.begin(); set_iterator != parents.end(); set_iterator++)
				{
					hit_counts[*set_iterator]++;
				}
			}

			/// Resolve tree for each sequence to get WEVOTE annotation
			Reads[i].resolvedTaxon=resolve_tree(hit_counts, Reads[i].numToolsReported, minNumAgreed);
			Reads[i].numToolsAgreed=hit_counts[Reads[i].resolvedTaxon];

			if(Reads[i].numToolsAgreed==Reads[i].numToolsReported)
			{
				Reads[i].score=(double)Reads[i].numToolsAgreed / (double)Reads[i].numToolsUsed;
			}
			else
			{
				Reads[i].score=((double)Reads[i].numToolsAgreed / (double)(Reads[i].numToolsUsed)) - (1/ (penalty * ((double)Reads[i].numToolsUsed)));
			}
		}
		else
		{
			Reads[i].resolvedTaxon=0;
                        Reads[i].numToolsAgreed=0;
                        Reads[i].score=0;
                        continue;
		}
	}
	double end = omp_get_wtime();
	double total=end-start;
	cout << "WEVOTE classification executed in= " << total << "\n";

	/// Export the detailed output in txt format
	ofstream myfile;
	myfile.open (OutputDetails.c_str());
	if (!myfile.is_open())
	{
		cout << "Error opening Output file: " << OutputDetails << "\n";
		exit(1);
	}

	string PrintString="";
	std::ostringstream ss;
	for (uint32_t i=0 ; i<Reads.size() ;i++)
	{
		ss.clear();
		ss.str("");
		PrintString="";
		for (uint32_t j=0 ; j<(Reads[i].annotation).size() ; j++)
		{
			ss.clear();
			ss.str("");
			PrintString = PrintString + "\t";
			ss << Reads[i].annotation[j];
			PrintString = PrintString + ss.str();
		}

		myfile << Reads[i].seqID << "\t" << Reads[i].numToolsAgreed<<"\t"<< Reads[i].numToolsReported << "\t" << Reads[i].score << "\t" << Reads[i].resolvedTaxon << PrintString << "\n";

	}
	myfile.close();

	/// Export WEVOTE output in CSV format <seqID, taxID, score, # toolsAgreed>
	myfile.open (OutputWEVOTE.c_str());
	if (!myfile.is_open())
	{
		cout << "Error opening Output file: " << OutputWEVOTE << "\n";
		exit(1);
	}
	for (uint32_t i=0 ; i<Reads.size() ;i++)
	{
		myfile << Reads[i].seqID << "," << Reads[i].resolvedTaxon << "," << Reads[i].numToolsAgreed << "," << Reads[i].score <<"\n";
	}
	myfile.close();

}

void usage(string prog)
{
	cerr << "Usage: " << prog << " -i <input-file> [options]" << endl;
	cerr << "\n";
	cerr << "Implemented Options:" << endl;
	cerr << "-i      InputFile" << endl;
	cerr << "-d      Taxonomy database path" << endl;
	cerr << "-p      OutputFile Prefix" << endl;
	cerr << "-n      Num of threads" << endl;
	cerr << "-k      Penalty " << endl;
	cerr << "-a      Minimum number of tools agreed tools on WEVOTE decision " << endl;
	cerr << "-s      Score threshold " << endl;

	exit(1);
}
<commit_msg>update scoring system in case of all tools give taxon 0<commit_after>#include "headers.hpp"
#include "helpers.hpp"
#include "create_db.hpp"

void usage(string prog);

map<uint32_t, uint32_t> parentMap;
map<uint32_t, string> rankMap;
map<uint32_t, uint32_t> standardMap;
map<uint32_t, string> namesMap;
uint32_t undefined=0;

int main(int argc, char *argv[])
{
	string nodesFilename="";
	string namesFilename="";
	string query="";
	string prefix="";
	string taxonomyDB="";
	bool verbose=false;
	uint32_t score=0;
	int threads=1;
	int penalty=2;
	int minNumAgreed=0;

	if (argc<2)
	{
		cout << "less than the required minimum number of options\n";
		usage(argv[0]);
		exit(1);
	}

	/// parse commandline arguments
	while (1)
	{
		static struct option long_options[] =
		{
			{"v", 0, 0, 0},
			{"i", 1, 0, 0},
			{"p", 1, 0, 0},
			{"d", 1, 0, 0},
			{"s", 1, 0, 0},
			{"n", 1, 0, 0},
			{"k", 1, 0, 0},
			{"a", 1, 0, 0}
		};

		int longindex = -1;
		int c = getopt_long_only(argc, argv, "", long_options, &longindex);
		if(c == -1) break;
		else if(c == '?')
		{
			/// If the user entered junk, let him know.
			cerr << "Invalid parameters." << endl;
			usage(argv[0]);
			exit(1);
		}
		else
		{
			switch(longindex)
			{
				case 0: verbose = true; break;
				case 1: query=optarg; break;
				case 2: prefix=optarg; break;
				case 3: taxonomyDB=optarg; break;
				case 4: score=atol(optarg); break;
				case 5: threads=atol(optarg); break;
				case 6: penalty=atol(optarg); break;
				case 7: minNumAgreed=atol(optarg); break;
				default: break;
			}
		}
	}

	nodesFilename=taxonomyDB+"/nodes_wevote.dmp";
	namesFilename=taxonomyDB+"/names_wevote.dmp";
	string OutputDetails= prefix + "_WEVOTE_Details.txt";
	string OutputWEVOTE= prefix + "_WEVOTE.csv";
	cout << "NodesFilename= " << nodesFilename << "\n";
	cout << "NamesFilename= " << namesFilename << "\n";

	/// Build taxonomy trees
	parentMap = build_full_taxid_map(nodesFilename);
	rankMap = build_full_rank_map(nodesFilename);
	standardMap=build_standard_taxid_map(nodesFilename, parentMap, rankMap);
	namesMap = build_taxname_map(namesFilename);

	/// Read CSV formated input file
	vector<readsInfo> Reads;
	readsInfo OneRead;
	Reads.clear();
	ifstream file (query.c_str());
	string line = "";
	int it=0;

	if (!file.is_open())
	{
		cout << "Error opening file:" << query  <<"\n";
		exit(1);
	}

	while (getline(file, line))
	{
		stringstream strstr(line);
		string word = "";
		it=0;
		int value=0;
		(OneRead.annotation).clear();

		while (getline(strstr,word, ','))
		{
			if(it==0)
				OneRead.seqID=word;
			else
			{
				value=atoi(word.c_str());
				(OneRead.annotation).push_back(value);
			}
			it++;
		}
		Reads.push_back(OneRead);
	}

	uint32_t numToolsUsed=(Reads[0].annotation).size();
	uint32_t numReads= Reads.size();

	cout << "Num of reads= " << numReads << "\n";
	cout << "Num of used tools= " << numToolsUsed << "\n";

	if(minNumAgreed>numToolsUsed)
	{
		cout<< "It's not allwed that minNumAgreed > numTools \n";
		exit(1);
	}

	for (uint32_t i=0 ; i<Reads.size() ; i++)
	{
		Reads[i].numToolsUsed=numToolsUsed;
	}

    /// Correct TaxonID for the not standard ranks
    correctTaxa(Reads);

    /// Count number of tools that identified each sequences
    uint32_t count=0;
	for (uint32_t i=0 ; i<Reads.size() ; i++)
	{
		count=0;
		for (uint32_t j=0 ; j<(Reads[i].annotation).size() ; j++)
		{

			if (Reads[i].annotation[j] && 1)
			count++;
		}
		Reads[i].numToolsReported=count;
	}

	/// WEVOTE algorithm
	map<uint32_t, uint32_t> hit_counts;
	set<uint32_t> parents;
	std::set<uint32_t>::iterator set_iterator;
    std::map<uint32_t, uint32_t>::iterator iterator_name;
    uint32_t SavedTax_2[2];
    uint32_t n=0;

    double start = omp_get_wtime();
    omp_set_num_threads(threads);
	cout << "Min Number of Agreed= "<< minNumAgreed << "\n";

    #pragma omp parallel for private (hit_counts, parents, set_iterator, iterator_name, SavedTax_2, n)
	for (uint32_t i=0 ; i<Reads.size() ;i++)
	{
		if (Reads[i].numToolsReported == 0)
		{
			Reads[i].resolvedTaxon=0;
			Reads[i].numToolsAgreed=numToolsUsed;
			Reads[i].score=1;
			continue;
		}
		else if(Reads[i].numToolsReported == 1 && minNumAgreed<=1)
		{
			Reads[i].resolvedTaxon=0;
			for (uint32_t j=0 ; j<numToolsUsed ; j++)
			{
				Reads[i].resolvedTaxon += Reads[i].annotation[j];
			}
			Reads[i].numToolsAgreed=1;
			if(Reads[i].numToolsAgreed==Reads[i].numToolsReported)
			{
				Reads[i].score=(double)Reads[i].numToolsAgreed / (double)Reads[i].numToolsUsed;
			}
			else
			{
				Reads[i].score=((double)Reads[i].numToolsAgreed / (double)Reads[i].numToolsUsed) - (1/penalty*((double)Reads[i].numToolsUsed));
			}
			continue;
		}
		else if(Reads[i].numToolsReported==2 && minNumAgreed<=2)
		{
			n=0;

			for (uint32_t j=0 ; j<numToolsUsed ; j++)
			{
				if(Reads[i].annotation[j])
				{
					SavedTax_2[n]=Reads[i].annotation[j];
					n++;
				}
			}

			Reads[i].resolvedTaxon=lca(SavedTax_2[0], SavedTax_2[1]);
			Reads[i].numToolsAgreed=2;
			if(Reads[i].numToolsAgreed==Reads[i].numToolsReported)
			{
				Reads[i].score=(double)Reads[i].numToolsAgreed / (double)Reads[i].numToolsUsed;
			}
			else
			{
				Reads[i].score=(double)Reads[i].numToolsReported / (double)(Reads[i].numToolsUsed * Reads[i].numToolsAgreed);
			}
			continue;
		}
		else if(Reads[i].numToolsReported>=3)
		{
			hit_counts.clear();
			for (uint32_t j=0 ; j<numToolsUsed ; j++)
			{
				parents=get_ancestry(Reads[i].annotation[j]);
				for(set_iterator = parents.begin(); set_iterator != parents.end(); set_iterator++)
				{
					hit_counts[*set_iterator]++;
				}
			}

			/// Resolve tree for each sequence to get WEVOTE annotation
			Reads[i].resolvedTaxon=resolve_tree(hit_counts, Reads[i].numToolsReported, minNumAgreed);
			Reads[i].numToolsAgreed=hit_counts[Reads[i].resolvedTaxon];

			if(Reads[i].numToolsAgreed==Reads[i].numToolsReported)
			{
				Reads[i].score=(double)Reads[i].numToolsAgreed / (double)Reads[i].numToolsUsed;
			}
			else
			{
				Reads[i].score=((double)Reads[i].numToolsAgreed / (double)(Reads[i].numToolsUsed)) - (1/ (penalty * ((double)Reads[i].numToolsUsed)));
			}
		}
		else
		{
			Reads[i].resolvedTaxon=0;
                        Reads[i].numToolsAgreed=0;
                        Reads[i].score=0;
                        continue;
		}
	}
	double end = omp_get_wtime();
	double total=end-start;
	cout << "WEVOTE classification executed in= " << total << "\n";

	/// Export the detailed output in txt format
	ofstream myfile;
	myfile.open (OutputDetails.c_str());
	if (!myfile.is_open())
	{
		cout << "Error opening Output file: " << OutputDetails << "\n";
		exit(1);
	}

	string PrintString="";
	std::ostringstream ss;
	for (uint32_t i=0 ; i<Reads.size() ;i++)
	{
		ss.clear();
		ss.str("");
		PrintString="";
		for (uint32_t j=0 ; j<(Reads[i].annotation).size() ; j++)
		{
			ss.clear();
			ss.str("");
			PrintString = PrintString + "\t";
			ss << Reads[i].annotation[j];
			PrintString = PrintString + ss.str();
		}

		myfile << Reads[i].seqID << "\t" << Reads[i].numToolsAgreed<<"\t"<< Reads[i].numToolsReported << "\t" << Reads[i].score << "\t" << Reads[i].resolvedTaxon << PrintString << "\n";

	}
	myfile.close();

	/// Export WEVOTE output in CSV format <seqID, taxID, score, # toolsAgreed>
	myfile.open (OutputWEVOTE.c_str());
	if (!myfile.is_open())
	{
		cout << "Error opening Output file: " << OutputWEVOTE << "\n";
		exit(1);
	}
	for (uint32_t i=0 ; i<Reads.size() ;i++)
	{
		myfile << Reads[i].seqID << "," << Reads[i].resolvedTaxon << "," << Reads[i].numToolsAgreed << "," << Reads[i].score <<"\n";
	}
	myfile.close();

}

void usage(string prog)
{
	cerr << "Usage: " << prog << " -i <input-file> [options]" << endl;
	cerr << "\n";
	cerr << "Implemented Options:" << endl;
	cerr << "-i      InputFile" << endl;
	cerr << "-d      Taxonomy database path" << endl;
	cerr << "-p      OutputFile Prefix" << endl;
	cerr << "-n      Num of threads" << endl;
	cerr << "-k      Penalty " << endl;
	cerr << "-a      Minimum number of tools agreed tools on WEVOTE decision " << endl;
	cerr << "-s      Score threshold " << endl;

	exit(1);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: hf_funcdecl.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: np $ $Date: 2002-11-01 17:15:23 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include <toolkit/hf_funcdecl.hxx>

// NOT FULLY DEFINED SERVICES

const String C_sValignTop("top");

HF_FunctionDeclaration::HF_FunctionDeclaration( Xml::Element & o_rParent )
    :   HtmlMaker(o_rParent),
        pFront(0),
        pTypes(0),
        pNames(0)
{
    Xml::Element &
        rRow = CurOut()
                >> *new Html::Table
                    << new Xml::AnAttribute("border","0")
                    >> *new Html::TableRow;
    pFront = &(rRow >> *new Html::TableCell << new Html::VAlignAttr(C_sValignTop));
    pTypes = &(rRow >> *new Html::TableCell << new Html::VAlignAttr(C_sValignTop));
    pNames = &(rRow >> *new Html::TableCell << new Html::VAlignAttr(C_sValignTop));
}

HF_FunctionDeclaration::~HF_FunctionDeclaration()
{
}

Xml::Element &
HF_FunctionDeclaration::Add_ReturnLine()
{
    (*pTypes) << new Xml::XmlCode("
\n");
    (*pNames) << new Xml::XmlCode("
\n");
    return *pFront;
}

Xml::Element &
HF_FunctionDeclaration::Add_RaisesLine( const char * i_sRaisesText,
                                        bool         i_bSuppressExtraLine )
{
    if (NOT i_bSuppressExtraLine)
    {
        (*pTypes) << new Xml::XmlCode("
");
        (*pNames) << new Xml::XmlCode("
\n");
    }
    (*pTypes)
        << new Xml::XmlCode("
")
        << i_sRaisesText
        << new Xml::XmlCode("(
\n");
    return *pNames;
}

 <commit_msg>INTEGRATION: CWS ooo11rc (1.1.38); FILE MERGED 2003/06/28 10:37:25 waratah 1.1.38.1: #I11742: remove warnings from autodoc source<commit_after>/*************************************************************************
 *
 *  $RCSfile: hf_funcdecl.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2003-07-02 13:49:59 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include <toolkit/hf_funcdecl.hxx>

// NOT FULLY DEFINED SERVICES

const String C_sValignTop("top");

HF_FunctionDeclaration::HF_FunctionDeclaration( Xml::Element & o_rParent )
    :   HtmlMaker(o_rParent),
        pFront(0),
        pTypes(0),
        pNames(0)
{
    Xml::Element &
        rRow = CurOut()
                >> *new Html::Table
                    << new Xml::AnAttribute("border","0")
                    >> *new Html::TableRow;
    pFront = &(rRow >> *new Html::TableCell << new Html::VAlignAttr(C_sValignTop));
    pTypes = &(rRow >> *new Html::TableCell << new Html::VAlignAttr(C_sValignTop));
    pNames = &(rRow >> *new Html::TableCell << new Html::VAlignAttr(C_sValignTop));
}

HF_FunctionDeclaration::~HF_FunctionDeclaration()
{
}

Xml::Element &
HF_FunctionDeclaration::Add_ReturnLine()
{
    (*pTypes) << new Xml::XmlCode("
\n");
    (*pNames) << new Xml::XmlCode("
\n");
    return *pFront;
}

Xml::Element &
HF_FunctionDeclaration::Add_RaisesLine( const char * i_sRaisesText,
                                        bool         i_bSuppressExtraLine )
{
    if (NOT i_bSuppressExtraLine)
    {
        (*pTypes) << new Xml::XmlCode("
");
        (*pNames) << new Xml::XmlCode("
\n");
    }
    (*pTypes)
        << new Xml::XmlCode("
")
        << i_sRaisesText
        << new Xml::XmlCode("(
\n");
    return *pNames;
}
<|endoftext|>