<commit_before>#include <cassert>
#include <ctime>
#include <iostream>
#include <list>
#include <sstream>
#include <string>
#include <typeinfo>

#include "../../include/domains/racetrack/RacetrackProblem.h"
#include "../../include/domains/racetrack/RTrackDetHeuristic.h"
#include "../../include/domains/DummyState.h"

#include "../include/ppddl/mini-gpt/states.h"
#include "../include/ppddl/mini-gpt/problems.h"
#include "../include/ppddl/mini-gpt/domains.h"
#include "../include/ppddl/mini-gpt/states.h"
#include "../include/ppddl/mini-gpt/exceptions.h"
#include "../../include/ppddl/PPDDLHeuristic.h"
#include "../../include/ppddl/PPDDLProblem.h"

#include "../../include/reduced/PPDDLTaggedReduction.h"
#include "../../include/reduced/ReducedHeuristicWrapper.h"
#include "../../include/reduced/ReducedModel.h"
#include "../../include/reduced/ReducedState.h"
#include "../../include/reduced/ReducedTransition.h"

#include "../../include/solvers/FFReducedModelSolver.h"
#include "../../include/solvers/LAOStarSolver.h"

#include "../../include/util/flags.h"
#include "../../include/util/general.h"

#include "../../include/Problem.h"

using namespace std;
using namespace mdplib;
using namespace mlppddl;
using namespace mlreduced;
using namespace mlsolvers;

extern int yyparse();
extern FILE* yyin;
string current_file;
int warning_level = 0;

static int verbosity = 0;
static int k = 0;

mlcore::Problem* problem = nullptr;
mlcore::Heuristic* heuristic = nullptr;
ReducedModel* reducedModel = nullptr;
ReducedHeuristicWrapper* reducedHeuristic = nullptr;
list<ReducedTransition *> reductions;

string ffExec = "/home/lpineda/Desktop/FF-v2.3/ff";
string ffDomain = "-o /home/lpineda/Desktop/domain.pddl";
string ffProblem = "-f /home/lpineda/Desktop/problem.pddl";
string ffCommand = ffExec + " " + ffDomain + " " + ffProblem;

/*
 * Parses the given PPDDL file, and returns true on success.
 */
static bool read_file( const char* ppddlFileName )
{
    yyin = fopen( ppddlFileName, "r" );
    if( yyin == NULL ) {
        cout << "parser:" << ppddlFileName <<
            ": " << strerror( errno ) << endl;
        return( false );
    }
    else {
        current_file = ppddlFileName;
        bool success;
        try {
            success = (yyparse() == 0);
        }
        catch( Exception exception ) {
            fclose( yyin );
            cout << exception << endl;
            return( false );
        }
        fclose( yyin );
        return( success );
    }
}

bool initPPDDL(string ppddlArgs)
{
    size_t pos_equals = ppddlArgs.find(":");
    assert(pos_equals != string::npos);
    string file = ppddlArgs.substr(0, pos_equals);
    string prob =
        ppddlArgs.substr(pos_equals + 1, ppddlArgs.size() - pos_equals);

    pair<state_t *,Rational> *initial = nullptr;

    if( !read_file( file.c_str() ) ) {
        cerr << "<main>: ERROR: couldn't read problem file `" << file << endl;
        return false;
    }
    problem_t* internalPPDDLProblem =
        (problem_t *)(problem_t::find(prob.c_str()));
    if( !internalPPDDLProblem ) {
        cerr << "<main>: ERROR: problem `" << prob <<
            "' is not defined in file '" << file << "'" << endl;
        return false;
    }

    problem = new PPDDLProblem(internalPPDDLProblem);
    heuristic = new mlppddl::PPDDLHeuristic(static_cast<PPDDLProblem*>(problem),
                                            mlppddl::FF);
    problem->setHeuristic(heuristic);
}

/**
 * This program creates a reduced model for a given PPDDL file and solves
 * using LAO* and FF.
 *
 * The type of model is a Mk1 reduction (at most one primary outcome),
 * which implies that after k exceptions a deterministic model is used. LAO*
 * will solve this model and use FF on states with k-exceptions so that they
 * can be treated as tip nodes with a fixed cost.
 *
 * The reduction to use is specified by a set of command line arguments:
 *
 *    --det_problem: the path to a PDDL file describing the deterministic
 *        model to be passed to FF after k-exceptions.
 *    --det_descriptor: a configuration file describing the determinization
 *        in a simple format. The user of testReducedFF is responsible for
 *        ensuring consistency between the files det_problem and
 *        det_descriptor. The format of this file will be one action name per
 *        line followed by a number specifying which of the outcomes is primary.
 *    --k: The maximum number of exceptions.
 *
 * Other required command line arguments are:
 *    --problem: the PPDDL domain/problem to solve. The format is
 *        ppddlFilename:problemName
 *    --dir: the directory to use for FF. This directory must contain the file
 *        at "det_problem" as well as a file called "p01.pddl" containing only
 *        the PPDDL problem description (i.e., init and goal, not the domain).
 *        The init state must be described in a single line.
 *        The user of testReducedFF is responsible for ensuring consistency
 *        between p01.pddl and the file passed in the "problem" flag.
 */
int main(int argc, char* args[])
{
    register_flags(argc, args);

    if (flag_is_registered("debug"))
        mdplib_debug = true;

    // Reading flags.
    register_flags(argc, args);

    // The PPDDL problem to solve.
    assert(flag_is_registered_with_value("problem"));;
    string ppddlArgs = flag_value("problem");

    // The PDDL determinization to use.
    assert(flag_is_registered_with_value("det_problem"));
    string detProblem = flag_value("det_problem");

    // The configuration file for this determinization.
    assert(flag_is_registered_with_value("det_descriptor"));
    string detDescriptor = flag_value("det_descriptor");

    //The directory where the determinization is stored.
    assert(flag_is_registered_with_value("dir"));
    string directory = flag_value("dir");

    //The maximum number of exceptions.
    assert(flag_is_registered_with_value("k"));
    int k = stoi(flag_value("k"));

    // The verbosity level.
    if (flag_is_registered_with_value("v"))
        verbosity = stoi(flag_value("v"));

    bool useFF = true;
    if (flag_is_registered("no-ff"))
        useFF = false;

    // The number of simulations for the experiments.
    int nsims = 100;
    if (flag_is_registered_with_value("n"))
        nsims = stoi(flag_value("n"));

    initPPDDL(ppddlArgs);

    // Creating the reduced model.
    ReducedTransition* reduction =
        new PPDDLTaggedReduction(problem, detDescriptor);
    reducedModel = new ReducedModel(problem, reduction, k);
    reducedHeuristic = new ReducedHeuristicWrapper(heuristic);
    reducedModel->setHeuristic(reducedHeuristic);

    // Solving reduced model using LAO* + FF.
    double totalPlanningTime = 0.0;
    clock_t startTime = clock();
    FFReducedModelSolver solver(reducedModel,
                                ffExec,
                                directory + "/" + detProblem,
                                directory + "/ff-template.pddl",
                                k,
                                1.0e-3,
                                useFF);
    solver.solve(reducedModel->initialState());
    clock_t endTime = clock();
    totalPlanningTime += (double(endTime - startTime) / CLOCKS_PER_SEC);
    cout << "cost " << reducedModel->initialState()->cost() <<
        " time " << totalPlanningTime << endl;

    // Running a trial of the continual planning approach.
    double expectedCost = 0.0;
    for (int i = 0; i < nsims; i++) {
        double cost = 0.0;
        ReducedState* currentState =
            static_cast<ReducedState*> (reducedModel->initialState());
        mlcore::Action* action = currentState->bestAction();
        while (cost < mdplib::dead_end_cost) {
            cost += problem->cost(currentState->originalState(), action);
            // The successor state according to the original transition model.
            mlcore::State* nextOriginalState =
                randomSuccessor(problem, currentState->originalState(), action);

            if (problem->goal(nextOriginalState)) {
                dprint1("GOAL!");
                break;
            }

            bool isException =
                reducedModel->isException(currentState->originalState(),
                                          nextOriginalState,
                                          action);
            int exceptionCount =
                currentState->exceptionCount() + int(isException);
            currentState = new ReducedState(nextOriginalState,
                                            exceptionCount,
                                            reducedModel);

            // Re-planning if needed.
            if (currentState->bestAction() == nullptr ||
                    exceptionCount > k) {
                currentState->exceptionCount(0);
                currentState = static_cast<ReducedState*> (
                    reducedModel->addState(currentState));
                solver.solve(currentState);
            }

            if (currentState->deadEnd()) {
                cost = mdplib::dead_end_cost;
            }

            action = currentState->bestAction();
        }
        expectedCost += cost;
    }
    cout << expectedCost / nsims << endl;
    cout << totalPlanningTime << endl;

    // Releasing memory
    for (auto reduction : reductions)
        delete reduction;
    reducedModel->cleanup();
    delete reducedModel;
    delete problem;
    return 0;
}

<commit_msg>minor changes<commit_after>#include <cassert>
#include <ctime>
#include <iostream>
#include <list>
#include <sstream>
#include <string>
#include <typeinfo>

#include "../../include/domains/racetrack/RacetrackProblem.h"
#include "../../include/domains/racetrack/RTrackDetHeuristic.h"
#include "../../include/domains/DummyState.h"

#include "../include/ppddl/mini-gpt/states.h"
#include "../include/ppddl/mini-gpt/problems.h"
#include "../include/ppddl/mini-gpt/domains.h"
#include "../include/ppddl/mini-gpt/states.h"
#include "../include/ppddl/mini-gpt/exceptions.h"
#include "../../include/ppddl/PPDDLHeuristic.h"
#include "../../include/ppddl/PPDDLProblem.h"

#include "../../include/reduced/PPDDLTaggedReduction.h"
#include "../../include/reduced/ReducedHeuristicWrapper.h"
#include "../../include/reduced/ReducedModel.h"
#include "../../include/reduced/ReducedState.h"
#include "../../include/reduced/ReducedTransition.h"

#include "../../include/solvers/FFReducedModelSolver.h"
#include "../../include/solvers/LAOStarSolver.h"

#include "../../include/util/flags.h"
#include "../../include/util/general.h"

#include "../../include/Problem.h"

using namespace std;
using namespace mdplib;
using namespace mlppddl;
using namespace mlreduced;
using namespace mlsolvers;

extern int yyparse();
extern FILE* yyin;
string current_file;
int warning_level = 0;

static int verbosity = 0;
static int k = 0;

mlcore::Problem* problem = nullptr;
mlcore::Heuristic* heuristic = nullptr;
ReducedModel* reducedModel = nullptr;
ReducedHeuristicWrapper* reducedHeuristic = nullptr;
list<ReducedTransition *> reductions;

string ffExec = "/home/lpineda/Desktop/FF-v2.3/ff";
string ffDomain = "-o /home/lpineda/Desktop/domain.pddl";
string ffProblem = "-f /home/lpineda/Desktop/problem.pddl";
string ffCommand = ffExec + " " + ffDomain + " " + ffProblem;

/*
 * Parses the given PPDDL file, and returns true on success.
 */
static bool read_file( const char* ppddlFileName )
{
    yyin = fopen( ppddlFileName, "r" );
    if( yyin == NULL ) {
        cout << "parser:" << ppddlFileName <<
            ": " << strerror( errno ) << endl;
        return( false );
    }
    else {
        current_file = ppddlFileName;
        bool success;
        try {
            success = (yyparse() == 0);
        }
        catch( Exception exception ) {
            fclose( yyin );
            cout << exception << endl;
            return( false );
        }
        fclose( yyin );
        return( success );
    }
}

bool initPPDDL(string ppddlArgs)
{
    size_t pos_equals = ppddlArgs.find(":");
    assert(pos_equals != string::npos);
    string file = ppddlArgs.substr(0, pos_equals);
    string prob =
        ppddlArgs.substr(pos_equals + 1, ppddlArgs.size() - pos_equals);

    pair<state_t *,Rational> *initial = nullptr;

    if( !read_file( file.c_str() ) ) {
        cerr << "<main>: ERROR: couldn't read problem file `" << file << endl;
        return false;
    }
    problem_t* internalPPDDLProblem =
        (problem_t *)(problem_t::find(prob.c_str()));
    if( !internalPPDDLProblem ) {
        cerr << "<main>: ERROR: problem `" << prob <<
            "' is not defined in file '" << file << "'" << endl;
        return false;
    }

    problem = new PPDDLProblem(internalPPDDLProblem);
    heuristic = new mlppddl::PPDDLHeuristic(static_cast<PPDDLProblem*>(problem),
                                            mlppddl::FF);
    problem->setHeuristic(heuristic);
}

/**
 * This program creates a reduced model for a given PPDDL file and solves
 * using LAO* and FF.
 *
 * The type of model is a Mk1 reduction (at most one primary outcome),
 * which implies that after k exceptions a deterministic model is used. LAO*
 * will solve this model and use FF on states with k-exceptions so that they
 * can be treated as tip nodes with a fixed cost.
 *
 * The reduction to use is specified by a set of command line arguments:
 *
 *    --det_problem: the path to a PDDL file describing the deterministic
 *        model to be passed to FF after k-exceptions.
 *    --det_descriptor: a configuration file describing the determinization
 *        in a simple format. The user of testReducedFF is responsible for
 *        ensuring consistency between the files det_problem and
 *        det_descriptor. The format of this file will be one action name per
 *        line followed by a number specifying which of the outcomes is primary.
 *    --k: The maximum number of exceptions.
 *
 * Other required command line arguments are:
 *    --problem: the PPDDL domain/problem to solve. The format is
 *        ppddlFilename:problemName
 *    --dir: the directory to use for FF. This directory must contain the file
 *        at "det_problem" as well as a file called "p01.pddl" containing only
 *        the PPDDL problem description (i.e., init and goal, not the domain).
 *        The init state must be described in a single line.
 *        The user of testReducedFF is responsible for ensuring consistency
 *        between p01.pddl and the file passed in the "problem" flag.
 */
int main(int argc, char* args[])
{
    register_flags(argc, args);

    if (flag_is_registered("debug"))
        mdplib_debug = true;

    // Reading flags.
    register_flags(argc, args);

    // The PPDDL problem to solve.
    assert(flag_is_registered_with_value("problem"));;
    string ppddlArgs = flag_value("problem");

    // The PDDL determinization to use.
    assert(flag_is_registered_with_value("det_problem"));
    string detProblem = flag_value("det_problem");

    // The configuration file for this determinization.
    assert(flag_is_registered_with_value("det_descriptor"));
    string detDescriptor = flag_value("det_descriptor");

    //The directory where the determinization is stored.
    assert(flag_is_registered_with_value("dir"));
    string directory = flag_value("dir");

    //The maximum number of exceptions.
    assert(flag_is_registered_with_value("k"));
    int k = stoi(flag_value("k"));

    // The verbosity level.
    if (flag_is_registered_with_value("v"))
        verbosity = stoi(flag_value("v"));

    bool useFF = true;
    if (flag_is_registered("no-ff"))
        useFF = false;

    // The number of simulations for the experiments.
    int nsims = 100;
    if (flag_is_registered_with_value("n"))
        nsims = stoi(flag_value("n"));

    initPPDDL(ppddlArgs);

    // Creating the reduced model.
    ReducedTransition* reduction =
        new PPDDLTaggedReduction(problem, directory + "/" + detDescriptor);
    reducedModel = new ReducedModel(problem, reduction, k);
    reducedHeuristic = new ReducedHeuristicWrapper(heuristic);
    reducedModel->setHeuristic(reducedHeuristic);

    // Solving reduced model using LAO* + FF.
    double totalPlanningTime = 0.0;
    clock_t startTime = clock();
    FFReducedModelSolver solver(reducedModel,
                                ffExec,
                                directory + "/" + detProblem,
                                directory + "/ff-template.pddl",
                                k,
                                1.0e-3,
                                useFF);
    solver.solve(reducedModel->initialState());
    clock_t endTime = clock();
    totalPlanningTime += (double(endTime - startTime) / CLOCKS_PER_SEC);
    cout << "cost " << reducedModel->initialState()->cost() <<
        " time " << totalPlanningTime << endl;

    // Running a trial of the continual planning approach.
    double expectedCost = 0.0;
    int countSuccess = 0;
    for (int i = 0; i < nsims; i++) {
        double cost = 0.0;
        ReducedState* currentState =
            static_cast<ReducedState*> (reducedModel->initialState());
        mlcore::Action* action = currentState->bestAction();
        while (cost < mdplib::dead_end_cost) {
            cost += problem->cost(currentState->originalState(), action);
            // The successor state according to the original transition model.
            mlcore::State* nextOriginalState =
                randomSuccessor(problem, currentState->originalState(), action);

            if (problem->goal(nextOriginalState)) {
                countSuccess++;
                dprint1("GOAL!");
                break;
            }

            bool isException =
                reducedModel->isException(currentState->originalState(),
                                          nextOriginalState,
                                          action);
            int exceptionCount =
                currentState->exceptionCount() + int(isException);
            currentState = new ReducedState(nextOriginalState,
                                            exceptionCount,
                                            reducedModel);

            // Re-planning if needed.
            if (currentState->bestAction() == nullptr ||
                    exceptionCount > k) {
                currentState->exceptionCount(0);
                currentState = static_cast<ReducedState*> (
                    reducedModel->addState(currentState));
                solver.solve(currentState);
            }

            if (currentState->deadEnd()) {
                cost = mdplib::dead_end_cost;
            }

            action = currentState->bestAction();
        }
        expectedCost += cost;
        if (verbosity > 1)
            cout << "sim " << i << ", success: " << countSuccess << endl;
    }
    cout << expectedCost / nsims << endl;
    cout << totalPlanningTime << endl;
    cout << countSuccess << endl;

    // Releasing memory
    for (auto reduction : reductions)
        delete reduction;
    reducedModel->cleanup();
    delete reducedModel;
    delete problem;
    return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

std::vector<int> generate_range(int lowerbound, int upperbound) {
	int length = upperbound - lowerbound;
	std::vector<int> range;
	for(int i = lowerbound + 1; i <= upperbound; i++) {
		range << i;
	}
	return range;
}

void apply_sieve(std::vector<int> range, std::vector<int> primes) {
	int lowerbound = range.front();
	int upperbound = range.back();
	for(std::vector<int>::iterator it = primes.begin(); it != primes.end(); ++it) {
		int p = *it;
		int composite = lowerbound / p + p;
		while(composite <= upperbound) {
			int index = composite - lowerbound;
			range.at(index) = 0;
		}
	}
}

int main(int argc, char** argv) {
	std::vector<int> primes;
	primes << 2;
	primes << 3;
	primes << 5;
	std::vector range = generate_range(6, 25);
	apply_sieve(range, primes);

	for(std::vector<int>::iterator it = range.begin(); it != range.end(); ++it) {
		std::cout << *it << ",";
	}
	std::cout << "\n";
	return 0;
}
<commit_msg>It's alive<commit_after>#include <iostream>
#include <vector>

std::vector<int> generate_range(int lowerbound, int upperbound) {
	int length = upperbound - lowerbound;
	std::vector<int> range;
	for(int i = lowerbound; i <= upperbound; i++) {
		range.push_back(i);
	}
	return range;
}

void mark_composites_in_range(int prime, std::vector<int> &range, int lowerbound, int upperbound) {
	// Determine smallest composite in range (start)
	int lb_mod_p = (lowerbound % prime);
	int start = (lb_mod_p == 0) ? lowerbound : lowerbound - lb_mod_p + prime;

	// Determine largest composite in range (stop)
	int ub_mod_p = (upperbound % prime);
	int stop = upperbound - ub_mod_p;

	// Adjust for appropriate index range
	start = start - lowerbound;
	stop = stop - lowerbound;
	for(int index = start; index <= stop; index += prime) {
		std::cout << "\tMarking " << index + lowerbound << " as 0 at position " << index << "\n";
		range.at(index) = 0;
	}
}

void apply_sieve(std::vector<int> &range, std::vector<int> primes) {
	int lowerbound = range.front();
	int upperbound = range.back();
	for(std::vector<int>::iterator it = primes.begin(); it != primes.end(); ++it) {
		int p = *it;
		std::cout << "Attempting to sieve for prime " << p << "\n";
		mark_composites_in_range(p, range, lowerbound, upperbound);
	}
}

int main(int argc, char** argv) {
	std::vector<int> primes;
	primes.push_back(2);
	primes.push_back(3);
	primes.push_back(5);
	std::vector<int> range = generate_range(6, 25);
	apply_sieve(range, primes);

	for(std::vector<int>::iterator it = range.begin(); it != range.end(); ++it) {
		std::cout << *it << ",";
	}
	std::cout << "\n";
	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/controls/menu/menu_config.h"

#include "build/build_config.h"

namespace views {

static MenuConfig* config_instance = NULL;

MenuConfig::MenuConfig()
    : text_color(SK_ColorBLACK),
      item_top_margin(3),
      item_bottom_margin(4),
      item_no_icon_top_margin(1),
      item_no_icon_bottom_margin(3),
      item_left_margin(4),
      label_to_arrow_padding(10),
      arrow_to_edge_padding(5),
      icon_to_label_padding(8),
      gutter_to_label(5),
      check_width(16),
      check_height(16),
      radio_width(16),
      radio_height(16),
      arrow_height(9),
      arrow_width(9),
      gutter_width(0),
      separator_height(6),
      render_gutter(false),
      show_mnemonics(false),
      scroll_arrow_height(3),
      label_to_accelerator_padding(10),
      show_accelerators(true) {
}

MenuConfig::~MenuConfig() {}

void MenuConfig::Reset() {
  delete config_instance;
  config_instance = NULL;
}

// static
const MenuConfig& MenuConfig::instance() {
  if (!config_instance)
    config_instance = Create();
  return *config_instance;
}

}  // namespace views
<commit_msg>Make menu items 40px tall when touch-optimized-ui is set.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/controls/menu/menu_config.h"

#include "base/command_line.h"
#include "build/build_config.h"
#include "ui/base/ui_base_switches.h"

namespace views {

static MenuConfig* config_instance = NULL;

MenuConfig::MenuConfig()
    : text_color(SK_ColorBLACK),
      item_top_margin(3),
      item_bottom_margin(4),
      item_no_icon_top_margin(1),
      item_no_icon_bottom_margin(3),
      item_left_margin(4),
      label_to_arrow_padding(10),
      arrow_to_edge_padding(5),
      icon_to_label_padding(8),
      gutter_to_label(5),
      check_width(16),
      check_height(16),
      radio_width(16),
      radio_height(16),
      arrow_height(9),
      arrow_width(9),
      gutter_width(0),
      separator_height(6),
      render_gutter(false),
      show_mnemonics(false),
      scroll_arrow_height(3),
      label_to_accelerator_padding(10),
      show_accelerators(true) {
  // Use 40px tall menu items when running in touch optimized mode.
  if (CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kTouchOptimizedUI)) {
    item_top_margin = item_no_icon_top_margin = 12;
    item_bottom_margin = item_no_icon_bottom_margin = 13;
  }
}

MenuConfig::~MenuConfig() {}

void MenuConfig::Reset() {
  delete config_instance;
  config_instance = NULL;
}

// static
const MenuConfig& MenuConfig::instance() {
  if (!config_instance)
    config_instance = Create();
  return *config_instance;
}

}  // namespace views
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "frtconfigresponsev3.h"
#include "compressioninfo.h"
#include <vespa/fnet/frt/frt.h>

#include <vespa/log/log.h>
LOG_SETUP(".config.frt.frtconfigresponsev3");

using namespace vespalib;
using namespace vespalib::slime;
using namespace vespalib::slime::convenience;
using namespace config::protocol;
using namespace config::protocol::v2;
using namespace config::protocol::v3;

namespace config {

std::string make_json(const Slime &slime, bool compact) {
    vespalib::SimpleBuffer buf;
    vespalib::slime::JsonFormat::encode(slime, buf, compact);
    return buf.get().make_string();
}

class V3Payload : public Payload
{
public:
    V3Payload(const SlimePtr & data)
        : _data(data)
    {
    }

    const Inspector & getSlimePayload() const override {
        return _data->get();
    }
private:
    SlimePtr _data;
};

const vespalib::string FRTConfigResponseV3::RESPONSE_TYPES = "sx";

FRTConfigResponseV3::FRTConfigResponseV3(FRT_RPCRequest * request)
    : SlimeConfigResponse(request)
{
}

const vespalib::string &
FRTConfigResponseV3::getResponseTypes() const
{
    return RESPONSE_TYPES;
}

const ConfigValue
FRTConfigResponseV3::readConfigValue() const
{
    vespalib::string md5(_data->get()[RESPONSE_CONFIG_MD5].asString().make_string());
    CompressionInfo info;
    info.deserialize(_data->get()[RESPONSE_COMPRESSION_INFO]);
    Slime * rawData = new Slime();
    SlimePtr payloadData(rawData);
    DecompressedData data(decompress(((*_returnValues)[1]._data._buf), ((*_returnValues)[1]._data._len), info.compressionType, info.uncompressedSize));
    size_t consumedSize = JsonFormat::decode(data.memRef, *rawData);
    if (consumedSize == 0) {
        std::string json(make_json(*payloadData, true));
        LOG(error, "Error decoding JSON. Consumed size: %lu, uncompressed size: %u, compression type: %s, assumed uncompressed size(%u), compressed size: %u, slime(%s)", consumedSize, data.size, compressionTypeToString(info.compressionType).c_str(), info.uncompressedSize, ((*_returnValues)[1]._data._len), json.c_str());
        assert(false);
    }
    if (LOG_WOULD_LOG(spam)) {
        LOG(spam, "read config value md5(%s), payload size: %lu", md5.c_str(), data.memRef.size);
    }
    return ConfigValue(PayloadPtr(new V3Payload(payloadData)), md5);
}

} // namespace config
<commit_msg>Allow empty input to preserve behavior<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "frtconfigresponsev3.h"
#include "compressioninfo.h"
#include <vespa/fnet/frt/frt.h>

#include <vespa/log/log.h>
LOG_SETUP(".config.frt.frtconfigresponsev3");

using namespace vespalib;
using namespace vespalib::slime;
using namespace vespalib::slime::convenience;
using namespace config::protocol;
using namespace config::protocol::v2;
using namespace config::protocol::v3;

namespace config {

std::string make_json(const Slime &slime, bool compact) {
    vespalib::SimpleBuffer buf;
    vespalib::slime::JsonFormat::encode(slime, buf, compact);
    return buf.get().make_string();
}

class V3Payload : public Payload
{
public:
    V3Payload(const SlimePtr & data)
        : _data(data)
    {
    }

    const Inspector & getSlimePayload() const override {
        return _data->get();
    }
private:
    SlimePtr _data;
};

const vespalib::string FRTConfigResponseV3::RESPONSE_TYPES = "sx";

FRTConfigResponseV3::FRTConfigResponseV3(FRT_RPCRequest * request)
    : SlimeConfigResponse(request)
{
}

const vespalib::string &
FRTConfigResponseV3::getResponseTypes() const
{
    return RESPONSE_TYPES;
}

const ConfigValue
FRTConfigResponseV3::readConfigValue() const
{
    vespalib::string md5(_data->get()[RESPONSE_CONFIG_MD5].asString().make_string());
    CompressionInfo info;
    info.deserialize(_data->get()[RESPONSE_COMPRESSION_INFO]);
    Slime * rawData = new Slime();
    SlimePtr payloadData(rawData);
    DecompressedData data(decompress(((*_returnValues)[1]._data._buf), ((*_returnValues)[1]._data._len), info.compressionType, info.uncompressedSize));
    if (data.memRef.size > 0) {
        size_t consumedSize = JsonFormat::decode(data.memRef, *rawData);
        if (consumedSize == 0) {
            std::string json(make_json(*payloadData, true));
            LOG(error, "Error decoding JSON. Consumed size: %lu, uncompressed size: %u, compression type: %s, assumed uncompressed size(%u), compressed size: %u, slime(%s)", consumedSize, data.size, compressionTypeToString(info.compressionType).c_str(), info.uncompressedSize, ((*_returnValues)[1]._data._len), json.c_str());
            assert(false);
        }
    }
    if (LOG_WOULD_LOG(spam)) {
        LOG(spam, "read config value md5(%s), payload size: %lu", md5.c_str(), data.memRef.size);
    }
    return ConfigValue(PayloadPtr(new V3Payload(payloadData)), md5);
}

} // namespace config
<|endoftext|>


<commit_before>//===- OperationSupportTest.cpp - Operation support unit tests ------------===//
//
// Copyright 2019 The MLIR Authors.
//
// 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 "mlir/IR/OperationSupport.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/StandardTypes.h"
#include "gtest/gtest.h"

using namespace mlir;
using namespace mlir::detail;

namespace {
Operation *createOp(MLIRContext *context, bool resizableOperands,
                    ArrayRef<Value *> operands = llvm::None,
                    ArrayRef<Type> resultTypes = llvm::None) {
  return Operation::create(
      UnknownLoc::get(context), OperationName("foo.bar", context), operands,
      resultTypes, llvm::None, llvm::None, 0, resizableOperands, context);
}

TEST(OperandStorageTest, NonResizable) {
  MLIRContext context;
  Builder builder(&context);

  Operation *useOp =
      createOp(&context, /*resizableOperands=*/false, /*operands=*/llvm::None,
               builder.getIntegerType(16));
  Value *operand = useOp->getResult(0);

  // Create a non-resizable operation with one operand.
  Operation *user = createOp(&context, /*resizableOperands=*/false, operand,
                             builder.getIntegerType(16));

  // Sanity check the storage.
  EXPECT_EQ(user->hasResizableOperandsList(), false);

  // The same number of operands is okay.
  user->setOperands(operand);
  EXPECT_EQ(user->getNumOperands(), 1);

  // Removing is okay.
  user->setOperands(llvm::None);
  EXPECT_EQ(user->getNumOperands(), 0);

  // Destroy the operations.
  user->destroy();
  useOp->destroy();
}

TEST(OperandStorageDeathTest, AddToNonResizable) {
  MLIRContext context;
  Builder builder(&context);

  Operation *useOp =
      createOp(&context, /*resizableOperands=*/false, /*operands=*/llvm::None,
               builder.getIntegerType(16));
  Value *operand = useOp->getResult(0);

  // Create a non-resizable operation with one operand.
  Operation *user = createOp(&context, /*resizableOperands=*/false, operand,
                             builder.getIntegerType(16));

  // Sanity check the storage.
  EXPECT_EQ(user->hasResizableOperandsList(), false);

  // Adding operands to a non resizable operation should result in a failure.
  ASSERT_DEATH(user->setOperands({operand, operand}), "");
}

TEST(OperandStorageTest, Resizable) {
  MLIRContext context;
  Builder builder(&context);

  Operation *useOp =
      createOp(&context, /*resizableOperands=*/false, /*operands=*/llvm::None,
               builder.getIntegerType(16));
  Value *operand = useOp->getResult(0);

  // Create a resizable operation with one operand.
  Operation *user = createOp(&context, /*resizableOperands=*/true, operand,
                             builder.getIntegerType(16));

  // Sanity check the storage.
  EXPECT_EQ(user->hasResizableOperandsList(), true);

  // The same number of operands is okay.
  user->setOperands(operand);
  EXPECT_EQ(user->getNumOperands(), 1);

  // Removing is okay.
  user->setOperands(llvm::None);
  EXPECT_EQ(user->getNumOperands(), 0);

  // Adding more operands is okay.
  user->setOperands({operand, operand, operand});
  EXPECT_EQ(user->getNumOperands(), 3);

  // Destroy the operations.
  user->destroy();
  useOp->destroy();
}

} // end namespace
<commit_msg>    Fix -Wsign-compare in OperationSupportTest.cpp<commit_after>//===- OperationSupportTest.cpp - Operation support unit tests ------------===//
//
// Copyright 2019 The MLIR Authors.
//
// 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 "mlir/IR/OperationSupport.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/StandardTypes.h"
#include "gtest/gtest.h"

using namespace mlir;
using namespace mlir::detail;

namespace {
Operation *createOp(MLIRContext *context, bool resizableOperands,
                    ArrayRef<Value *> operands = llvm::None,
                    ArrayRef<Type> resultTypes = llvm::None) {
  return Operation::create(
      UnknownLoc::get(context), OperationName("foo.bar", context), operands,
      resultTypes, llvm::None, llvm::None, 0, resizableOperands, context);
}

TEST(OperandStorageTest, NonResizable) {
  MLIRContext context;
  Builder builder(&context);

  Operation *useOp =
      createOp(&context, /*resizableOperands=*/false, /*operands=*/llvm::None,
               builder.getIntegerType(16));
  Value *operand = useOp->getResult(0);

  // Create a non-resizable operation with one operand.
  Operation *user = createOp(&context, /*resizableOperands=*/false, operand,
                             builder.getIntegerType(16));

  // Sanity check the storage.
  EXPECT_EQ(user->hasResizableOperandsList(), false);

  // The same number of operands is okay.
  user->setOperands(operand);
  EXPECT_EQ(user->getNumOperands(), 1u);

  // Removing is okay.
  user->setOperands(llvm::None);
  EXPECT_EQ(user->getNumOperands(), 0u);

  // Destroy the operations.
  user->destroy();
  useOp->destroy();
}

TEST(OperandStorageDeathTest, AddToNonResizable) {
  MLIRContext context;
  Builder builder(&context);

  Operation *useOp =
      createOp(&context, /*resizableOperands=*/false, /*operands=*/llvm::None,
               builder.getIntegerType(16));
  Value *operand = useOp->getResult(0);

  // Create a non-resizable operation with one operand.
  Operation *user = createOp(&context, /*resizableOperands=*/false, operand,
                             builder.getIntegerType(16));

  // Sanity check the storage.
  EXPECT_EQ(user->hasResizableOperandsList(), false);

  // Adding operands to a non resizable operation should result in a failure.
  ASSERT_DEATH(user->setOperands({operand, operand}), "");
}

TEST(OperandStorageTest, Resizable) {
  MLIRContext context;
  Builder builder(&context);

  Operation *useOp =
      createOp(&context, /*resizableOperands=*/false, /*operands=*/llvm::None,
               builder.getIntegerType(16));
  Value *operand = useOp->getResult(0);

  // Create a resizable operation with one operand.
  Operation *user = createOp(&context, /*resizableOperands=*/true, operand,
                             builder.getIntegerType(16));

  // Sanity check the storage.
  EXPECT_EQ(user->hasResizableOperandsList(), true);

  // The same number of operands is okay.
  user->setOperands(operand);
  EXPECT_EQ(user->getNumOperands(), 1u);

  // Removing is okay.
  user->setOperands(llvm::None);
  EXPECT_EQ(user->getNumOperands(), 0u);

  // Adding more operands is okay.
  user->setOperands({operand, operand, operand});
  EXPECT_EQ(user->getNumOperands(), 3u);

  // Destroy the operations.
  user->destroy();
  useOp->destroy();
}

} // end namespace
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "Main.h"

#include "Config.h"
#include "PacketType.h"

#include "Exception.h"
#include "ClientSession.h"
#include "ClientManager.h"
#include "DatabaseJobManager.h"
#include "DbHelper.h"

#include "GameMap.h"
#include "PlayerManager.h"
#include "GameManager.h"
#include "BulletManager.h"
#include "SkillManager.h"
#pragma comment(lib,"ws2_32.lib")

SOCKET g_AcceptedSocket = NULL ;

__declspec(thread) int LThreadType = -1 ;

int _tmain(int argc, _TCHAR* argv[])
{
#ifdef _DEBUG
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
	//_CrtSetBreakAlloc( 155 );
#endif

	/// crash ߻ dump  ؼ
	SetUnhandledExceptionFilter(ExceptionFilter) ;

	LThreadType = THREAD_MAIN ;

	/// Manager Init
	GClientManager = new ClientManager ;
	GDatabaseJobManager = new DatabaseJobManager ;
	GPlayerManager = new PlayerManager;
	GGameMap = new GameMap(L"map/gamemap.csm");
	GGameManager = new GameManager(10);
	GBulletManager = new BulletManager();
	GSkillManager = new SkillManager();

	/// DB Helper ʱȭ
	if ( false == DbHelper::Initialize(DB_CONN_STR) )
		return -1 ;

	///  ʱȭ
	WSADATA wsa ;
	if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
		return -1 ;

	SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, 0) ;
	if (listenSocket == INVALID_SOCKET)
		return -1 ;

	int opt = 1 ;
	::setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(int) ) ;

	/// bind
	SOCKADDR_IN serveraddr ;
	ZeroMemory(&serveraddr, sizeof(serveraddr)) ;
	serveraddr.sin_family = AF_INET ;
	serveraddr.sin_port = htons(LISTEN_PORT) ;
	serveraddr.sin_addr.s_addr = htonl(INADDR_ANY) ;
	int ret = bind(listenSocket, (SOCKADDR*)&serveraddr, sizeof(serveraddr)) ;
	if (ret == SOCKET_ERROR)
		return -1 ;

	/// listen
	ret = listen(listenSocket, SOMAXCONN) ;
	if (ret == SOCKET_ERROR)
		return -1 ;

	/// auto-reset event
	HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL) ;
	if (hEvent == NULL)
		return -1 ;

	/// I/O Thread
	DWORD dwThreadId ;
	HANDLE hThread = (HANDLE)_beginthreadex (NULL, 0, ClientHandlingThread, hEvent, 0, (unsigned int*)&dwThreadId) ;
    if (hThread == NULL)
		return -1 ;

	/// DB Thread
	HANDLE hDbThread = (HANDLE)_beginthreadex (NULL, 0, DatabaseHandlingThread, NULL, 0, (unsigned int*)&dwThreadId) ;
	if (hDbThread == NULL)
		return -1 ;

	/// accept loop
	while ( true )
	{
		g_AcceptedSocket = accept(listenSocket, NULL, NULL) ;
		if ( g_AcceptedSocket == INVALID_SOCKET )
		{
			printf("accept: invalid socket\n") ;
			continue ;
		}/*
		SOCKADDR_IN clientaddr ;
		int addrlen = sizeof(clientaddr) ;
		getpeername(g_AcceptedSocket, (SOCKADDR*)&clientaddr, &addrlen) ;
		if( ntohs(clientaddr.sin_port) > 50000)
		{
			printf("port : %d is wrong!\n",clientaddr.sin_port);
			continue;
		}*/
		/// accept event fire!
		if ( !SetEvent(hEvent) )
		{
			printf("SetEvent error: %d\n",GetLastError()) ;
			break ;
		}
	}

	CloseHandle( hThread ) ;
	CloseHandle( hEvent ) ;
	CloseHandle( hDbThread ) ;

	//
	WSACleanup() ;

	DbHelper::Finalize() ;

	delete GClientManager ;
	delete GDatabaseJobManager ;
	return 0 ;
}

unsigned int WINAPI ClientHandlingThread( LPVOID lpParam )
{
	LThreadType = THREAD_CLIENT ;

	HANDLE hEvent = (HANDLE)lpParam ;

	/// Timer
	HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL) ;
	if (hTimer == NULL)
		return -1 ;

	LARGE_INTEGER liDueTime ;
	liDueTime.QuadPart = -10000000 ; ///< 1 ĺ
	if ( !SetWaitableTimer(hTimer, &liDueTime, 1, TimerProc, NULL, TRUE) )
		return -1 ;

	while ( true )
	{
		/// accept or IO/Timer completion
		DWORD result = WaitForSingleObjectEx(hEvent, INFINITE, TRUE) ;

		/// client connected
		if ( result == WAIT_OBJECT_0 )
		{

			///   ü Ҵ ʱȭ

			ClientSession* client = GClientManager->CreateClient(g_AcceptedSocket) ;

			SOCKADDR_IN clientaddr ;
			int addrlen = sizeof(clientaddr) ;
			getpeername(g_AcceptedSocket, (SOCKADDR*)&clientaddr, &addrlen) ;

			// Ŭ  ó
			if ( false == client->OnConnect(&clientaddr) )
			{
				client->Disconnect() ;
			}

			continue ; ///< ٽ
		}

		// APC ִ completion ƴ϶
		if ( result != WAIT_IO_COMPLETION )
			return -1 ;
	}

	CloseHandle( hTimer ) ;
	return 0;
}

unsigned int WINAPI DatabaseHandlingThread( LPVOID lpParam )
{
	LThreadType = THREAD_DATABASE ;

	while ( true )
	{
		/// ⺻ polling ϸ鼭 Job ִٸ ó ϴ
		GDatabaseJobManager->ExecuteDatabaseJobs() ;

		Sleep(1) ;
	}

	return 0 ;
}

void CALLBACK TimerProc(LPVOID lpArg, DWORD dwTimerLowValue, DWORD dwTimerHighValue)
{
	assert( LThreadType == THREAD_CLIENT ) ;

	GClientManager->OnPeriodWork() ;
}
<commit_msg>* Fixed MemoryLeak<commit_after>#include "stdafx.h"
#include "Main.h"

#include "Config.h"
#include "PacketType.h"

#include "Exception.h"
#include "ClientSession.h"
#include "ClientManager.h"
#include "DatabaseJobManager.h"
#include "DbHelper.h"

#include "GameMap.h"
#include "PlayerManager.h"
#include "GameManager.h"
#include "BulletManager.h"
#include "SkillManager.h"
#pragma comment(lib,"ws2_32.lib")

SOCKET g_AcceptedSocket = NULL ;

__declspec(thread) int LThreadType = -1 ;

int _tmain(int argc, _TCHAR* argv[])
{
#ifdef _DEBUG
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
	//_CrtSetBreakAlloc( 3651 );
#endif

	/// crash ߻ dump  ؼ
	SetUnhandledExceptionFilter(ExceptionFilter) ;

	LThreadType = THREAD_MAIN ;

	/// Manager Init
	GClientManager = new ClientManager ;
	GDatabaseJobManager = new DatabaseJobManager ;
	GPlayerManager = new PlayerManager;
	GGameMap = new GameMap(L"map/gamemap.csm");
	GGameManager = new GameManager(10);
	GBulletManager = new BulletManager();
	GSkillManager = new SkillManager();

	/// DB Helper ʱȭ
	if ( false == DbHelper::Initialize(DB_CONN_STR) )
		return -1 ;

	///  ʱȭ
	WSADATA wsa ;
	if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
		return -1 ;

	SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, 0) ;
	if (listenSocket == INVALID_SOCKET)
		return -1 ;

	int opt = 1 ;
	::setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(int) ) ;

	/// bind
	SOCKADDR_IN serveraddr ;
	ZeroMemory(&serveraddr, sizeof(serveraddr)) ;
	serveraddr.sin_family = AF_INET ;
	serveraddr.sin_port = htons(LISTEN_PORT) ;
	serveraddr.sin_addr.s_addr = htonl(INADDR_ANY) ;
	int ret = bind(listenSocket, (SOCKADDR*)&serveraddr, sizeof(serveraddr)) ;
	if (ret == SOCKET_ERROR)
		return -1 ;

	/// listen
	ret = listen(listenSocket, SOMAXCONN) ;
	if (ret == SOCKET_ERROR)
		return -1 ;

	/// auto-reset event
	HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL) ;
	if (hEvent == NULL)
		return -1 ;

	/// I/O Thread
	DWORD dwThreadId ;
	HANDLE hThread = (HANDLE)_beginthreadex (NULL, 0, ClientHandlingThread, hEvent, 0, (unsigned int*)&dwThreadId) ;
    if (hThread == NULL)
		return -1 ;

	/// DB Thread
	HANDLE hDbThread = (HANDLE)_beginthreadex (NULL, 0, DatabaseHandlingThread, NULL, 0, (unsigned int*)&dwThreadId) ;
	if (hDbThread == NULL)
		return -1 ;

	/// accept loop
	while ( true )
	{
		g_AcceptedSocket = accept(listenSocket, NULL, NULL) ;
		if ( g_AcceptedSocket == INVALID_SOCKET )
		{
			printf("accept: invalid socket\n") ;
			continue ;
		}/*
		SOCKADDR_IN clientaddr ;
		int addrlen = sizeof(clientaddr) ;
		getpeername(g_AcceptedSocket, (SOCKADDR*)&clientaddr, &addrlen) ;
		if( ntohs(clientaddr.sin_port) > 50000)
		{
			printf("port : %d is wrong!\n",clientaddr.sin_port);
			continue;
		}*/
		/// accept event fire!
		if ( !SetEvent(hEvent) )
		{
			printf("SetEvent error: %d\n",GetLastError()) ;
			break ;
		}
	}

	CloseHandle( hThread ) ;
	CloseHandle( hEvent ) ;
	CloseHandle( hDbThread ) ;

	//
	WSACleanup() ;

	delete GGameMap;
	delete GGameManager;
	delete GPlayerManager;
	delete GBulletManager;
	delete GSkillManager;

	delete GResourceManager;

	DbHelper::Finalize() ;

	delete GClientManager ;
	delete GDatabaseJobManager ;

	return 0 ;
}

unsigned int WINAPI ClientHandlingThread( LPVOID lpParam )
{
	LThreadType = THREAD_CLIENT ;

	HANDLE hEvent = (HANDLE)lpParam ;

	/// Timer
	HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL) ;
	if (hTimer == NULL)
		return -1 ;

	LARGE_INTEGER liDueTime ;
	liDueTime.QuadPart = -10000000 ; ///< 1 ĺ
	if ( !SetWaitableTimer(hTimer, &liDueTime, 1, TimerProc, NULL, TRUE) )
		return -1 ;

	while ( true )
	{
		/// accept or IO/Timer completion
		DWORD result = WaitForSingleObjectEx(hEvent, INFINITE, TRUE) ;

		/// client connected
		if ( result == WAIT_OBJECT_0 )
		{

			///   ü Ҵ ʱȭ

			ClientSession* client = GClientManager->CreateClient(g_AcceptedSocket) ;

			SOCKADDR_IN clientaddr ;
			int addrlen = sizeof(clientaddr) ;
			getpeername(g_AcceptedSocket, (SOCKADDR*)&clientaddr, &addrlen) ;

			// Ŭ  ó
			if ( false == client->OnConnect(&clientaddr) )
			{
				client->Disconnect() ;
			}

			continue ; ///< ٽ
		}

		// APC ִ completion ƴ϶
		if ( result != WAIT_IO_COMPLETION )
			return -1 ;
	}

	CloseHandle( hTimer ) ;
	return 0;
}

unsigned int WINAPI DatabaseHandlingThread( LPVOID lpParam )
{
	LThreadType = THREAD_DATABASE ;

	while ( true )
	{
		/// ⺻ polling ϸ鼭 Job ִٸ ó ϴ
		GDatabaseJobManager->ExecuteDatabaseJobs() ;

		Sleep(1) ;
	}

	return 0 ;
}

void CALLBACK TimerProc(LPVOID lpArg, DWORD dwTimerLowValue, DWORD dwTimerHighValue)
{
	assert( LThreadType == THREAD_CLIENT ) ;

	GClientManager->OnPeriodWork() ;
}
<|endoftext|>


<commit_before>/*
    <one line to give the library's name and an idea of what it does.>
    Copyright (C) 2012  Dan Vratil <dvratil@redhat.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "qmloutput.h"
#include <kscreen/output.h>
#include <KDebug>

#include <QStandardItem>
#include <QStandardItemModel>
#include <QStringBuilder>

Q_DECLARE_METATYPE(KScreen::Mode*);

QMLOutput::QMLOutput():
    QDeclarativeItem(),
    m_output(0),
    m_cloneOf(0),
    m_modesModel(new QStandardItemModel(this))
{

}

QMLOutput::~QMLOutput()
{

}

void QMLOutput::setOutput(KScreen::Output* output)
{
    m_output = output;

    QList<KScreen::Mode*> modes = m_output->modes().values();
    Q_FOREACH (KScreen::Mode *mode, modes) {
	QList<QStandardItem*> items = m_modesModel->findItems(mode->name(), Qt::MatchExactly, 0);
	if (items.isEmpty()) {
	  QStandardItem *item = new QStandardItem(mode->name());
	  item->setData(mode->size(), QMLOutput::SizeRole);

	  m_modesModel->appendRow(item);
	  items << item;

	  kDebug() << "Added size " << mode->name();
	}

	QStandardItem *modeItem = new QStandardItem(QString::number(mode->refreshRate(), 'f', 1) % QLatin1String("Hz"));
	modeItem->setData(mode->refreshRate(), QMLOutput::RefreshRateRole);
	modeItem->setData(mode->id(), QMLOutput::ModeIdRole);
	modeItem->setData(QVariant::fromValue(mode), QMLOutput::ModeRole);

	kDebug() << "Added mode" << mode->refreshRate() << "to" << mode->name();

	QStandardItem *item = items.first();
	item->appendRow(modeItem);
    }

    connect(output, SIGNAL(clonesChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(currentModeChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(isEnabledChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(isPrimaryChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(outputChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(posChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(rotationChanged()), SIGNAL(changed()));

    Q_EMIT outputChanged();
}

KScreen::Output* QMLOutput::output() const
{
    return m_output;
}

void QMLOutput::setCloneOf(QMLOutput* other)
{
    m_cloneOf = other;

    Q_EMIT cloneOfChanged();
}

QMLOutput* QMLOutput::cloneOf() const
{
    return m_cloneOf;
}

QAbstractItemModel* QMLOutput::modesModel()
{
    return m_modesModel;
}
<commit_msg>Remove annoying debug messages<commit_after>/*
    <one line to give the library's name and an idea of what it does.>
    Copyright (C) 2012  Dan Vratil <dvratil@redhat.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "qmloutput.h"
#include <kscreen/output.h>
#include <KDebug>

#include <QStandardItem>
#include <QStandardItemModel>
#include <QStringBuilder>

Q_DECLARE_METATYPE(KScreen::Mode*);

QMLOutput::QMLOutput():
    QDeclarativeItem(),
    m_output(0),
    m_cloneOf(0),
    m_modesModel(new QStandardItemModel(this))
{

}

QMLOutput::~QMLOutput()
{

}

void QMLOutput::setOutput(KScreen::Output* output)
{
    m_output = output;

    QList<KScreen::Mode*> modes = m_output->modes().values();
    Q_FOREACH (KScreen::Mode *mode, modes) {
	QList<QStandardItem*> items = m_modesModel->findItems(mode->name(), Qt::MatchExactly, 0);
	if (items.isEmpty()) {
	  QStandardItem *item = new QStandardItem(mode->name());
	  item->setData(mode->size(), QMLOutput::SizeRole);

	  m_modesModel->appendRow(item);
	  items << item;
	}

	QStandardItem *modeItem = new QStandardItem(QString::number(mode->refreshRate(), 'f', 1) % QLatin1String("Hz"));
	modeItem->setData(mode->refreshRate(), QMLOutput::RefreshRateRole);
	modeItem->setData(mode->id(), QMLOutput::ModeIdRole);
	modeItem->setData(QVariant::fromValue(mode), QMLOutput::ModeRole);

	QStandardItem *item = items.first();
	item->appendRow(modeItem);
    }

    connect(output, SIGNAL(clonesChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(currentModeChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(isEnabledChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(isPrimaryChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(outputChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(posChanged()), SIGNAL(changed()));
    connect(output, SIGNAL(rotationChanged()), SIGNAL(changed()));

    Q_EMIT outputChanged();
}

KScreen::Output* QMLOutput::output() const
{
    return m_output;
}

void QMLOutput::setCloneOf(QMLOutput* other)
{
    m_cloneOf = other;

    Q_EMIT cloneOfChanged();
}

QMLOutput* QMLOutput::cloneOf() const
{
    return m_cloneOf;
}

QAbstractItemModel* QMLOutput::modesModel()
{
    return m_modesModel;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.       *
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org          *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of EITHER:                                  *
 *   (1) The GNU Lesser General Public License as published by the Free  *
 *       Software Foundation; either version 2.1 of the License, or (at  *
 *       your option) any later version. The text of the GNU Lesser      *
 *       General Public License is included with this library in the     *
 *       file LICENSE.TXT.                                               *
 *   (2) The BSD-style license that is included with this library in     *
 *       the file LICENSE-BSD.TXT.                                       *
 *                                                                       *
 * 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 files    *
 * LICENSE.TXT and LICENSE-BSD.TXT for more details.                     *
 *                                                                       *
 *************************************************************************/

// main window and event handling for X11

#include <ode/config.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
#include <GL/glx.h>

#include <drawstuff/drawstuff.h>
#include <drawstuff/version.h>
#include "internal.h"

//***************************************************************************
// error handling for unix

static void printMessage (char *msg1, char *msg2, va_list ap)
{
  fflush (stderr);
  fflush (stdout);
  fprintf (stderr,"\n%s: ",msg1);
  vfprintf (stderr,msg2,ap);
  fprintf (stderr,"\n");
  fflush (stderr);
}

extern "C" void dsError (char *msg, ...)
{
  va_list ap;
  va_start (ap,msg);
  printMessage ("Error",msg,ap);
  exit (1);
}

extern "C" void dsDebug (char *msg, ...)
{
  va_list ap;
  va_start (ap,msg);
  printMessage ("INTERNAL ERROR",msg,ap);
  // *((char *)0) = 0;	 ... commit SEGVicide ?
  abort();
}

extern "C" void dsPrint (char *msg, ...)
{
  va_list ap;
  va_start (ap,msg);
  vprintf (msg,ap);
}

//***************************************************************************
// openGL window

// X11 display info
static Display *display=0;
static int screen=0;
static XVisualInfo *visual=0;		// best visual for openGL
static Colormap colormap=0;		// window's colormap
static Atom wm_protocols_atom = 0;
static Atom wm_delete_window_atom = 0;

// window and openGL
static Window win=0;			// X11 window, 0 if not initialized
static int width=0,height=0;		// window size
static GLXContext glx_context=0;	// openGL rendering context
static int last_key_pressed=0;		// last key pressed in the window
static int run=1;			// 1 if simulation running
static int pause=0;			// 1 if in `pause' mode
static int singlestep=0;		// 1 if single step key pressed
static int writeframes=0;		// 1 if frame files to be written

static void createMainWindow (int _width, int _height)
{
  // create X11 display connection
  display = XOpenDisplay (0);
  if (!display) dsError (0,"can not open X11 display");
  screen = DefaultScreen(display);

  // get GL visual
  static int attribList[] = {GLX_RGBA, GLX_DOUBLEBUFFER, GLX_DEPTH_SIZE,16,
			     GLX_RED_SIZE,4, GLX_GREEN_SIZE,4,
			     GLX_BLUE_SIZE,4, None};
  visual = glXChooseVisual (display,screen,attribList);
  if (!visual) dsError ("no good X11 visual found for OpenGL");

  // create colormap
  colormap = XCreateColormap (display,RootWindow(display,screen),
			      visual->visual,AllocNone);

  // initialize variables
  win = 0;
  width = _width;
  height = _height;
  glx_context = 0;
  last_key_pressed = 0;

  if (width < 1 || height < 1) dsDebug (0,"bad window width or height");

  // create the window
  XSetWindowAttributes attributes;
  attributes.background_pixel = BlackPixel(display,screen);
  attributes.colormap = colormap;
  attributes.event_mask = ButtonPressMask | ButtonReleaseMask |
    KeyPressMask | KeyReleaseMask | ButtonMotionMask | PointerMotionHintMask |
    StructureNotifyMask;
  win = XCreateWindow (display,RootWindow(display,screen),50,50,width,height,
		       0,visual->depth, InputOutput,visual->visual,
		       CWBackPixel | CWColormap | CWEventMask,&attributes);

  // associate a GLX context with the window
  glx_context = glXCreateContext (display,visual,0,GL_TRUE);
  if (!glx_context) dsError ("can't make an OpenGL context");

  // set the window title
  XTextProperty window_name;
  window_name.value = (unsigned char *) "Simulation";
  window_name.encoding = XA_STRING;
  window_name.format = 8;
  window_name.nitems = strlen((char *) window_name.value);
  XSetWMName (display,win,&window_name);

  // participate in the window manager 'delete yourself' protocol
  wm_protocols_atom = XInternAtom (display,"WM_PROTOCOLS",False);
  wm_delete_window_atom = XInternAtom (display,"WM_DELETE_WINDOW",False);
  if (XSetWMProtocols (display,win,&wm_delete_window_atom,1)==0)
    dsError ("XSetWMProtocols() call failed");

  // pop up the window
  XMapWindow (display,win);
  XSync (display,win);
}

static void destroyMainWindow()
{
  glXDestroyContext (display,glx_context);
  XDestroyWindow (display,win);
  XSync (display,0);
  display = 0;
  win = 0;
  glx_context = 0;
}

static void handleEvent (XEvent &event, dsFunctions *fn)
{
  static int mx=0,my=0; 	// mouse position
  static int mode = 0;		// mouse button bits

  switch (event.type) {

  case ButtonPress: {
    if (event.xbutton.button == Button1) mode |= 1;
    if (event.xbutton.button == Button2) mode |= 2;
    if (event.xbutton.button == Button3) mode |= 4;
    mx = event.xbutton.x;
    my = event.xbutton.y;
  }
  return;

  case ButtonRelease: {
    if (event.xbutton.button == Button1) mode &= (~1);
    if (event.xbutton.button == Button2) mode &= (~2);
    if (event.xbutton.button == Button3) mode &= (~4);
    mx = event.xbutton.x;
    my = event.xbutton.x;
  }
  return;

  case MotionNotify: {
    if (event.xmotion.is_hint) {
      Window root,child;
      unsigned int mask;
      XQueryPointer (display,win,&root,&child,&event.xbutton.x_root,
		     &event.xbutton.y_root,&event.xbutton.x,&event.xbutton.y,
		     &mask);
    }
    dsMotion (mode, event.xmotion.x - mx, event.xmotion.y - my);
    mx = event.xmotion.x;
    my = event.xmotion.y;
  }
  return;

  case KeyPress: {
    KeySym key;
    XLookupString (&event.xkey,NULL,0,&key,0);
    if ((event.xkey.state & ControlMask) == 0) {
      if (key >= ' ' && key <= 126 && fn->command) fn->command (key);
    }
    else if (event.xkey.state & ControlMask) {
      switch (key) {
      case 't': case 'T':
	dsSetTextures (dsGetTextures() ^ 1);
	break;
      case 's': case 'S':
	dsSetShadows (dsGetShadows() ^ 1);
	break;
      case 'x': case 'X':
	run = 0;
	break;
      case 'p': case 'P':
	pause ^= 1;
	singlestep = 0;
	break;
      case 'o': case 'O':
	if (pause) singlestep = 1;
	break;
      case 'v': case 'V': {
	float xyz[3],hpr[3];
	dsGetViewpoint (xyz,hpr);
	printf ("Viewpoint = (%.4f,%.4f,%.4f,%.4f,%.4f,%.4f)\n",
		xyz[0],xyz[1],xyz[2],hpr[0],hpr[1],hpr[2]);
	break;
      }
      case 'w': case 'W':
	writeframes ^= 1;
	if (writeframes) printf ("Now writing frames to PPM files\n");
	break;
      }
    }
    last_key_pressed = key;		// a kludgy place to put this...
  }
  return;

  case KeyRelease: {
    // hmmmm...
  }
  return;

  case ClientMessage:
    if (event.xclient.message_type == wm_protocols_atom &&
	event.xclient.format == 32 &&
	Atom(event.xclient.data.l[0]) == wm_delete_window_atom) {
      run = 0;
      return;
    }
    return;

  case ConfigureNotify:
    width = event.xconfigure.width;
    height = event.xconfigure.height;
    return;
  }
}

// return the index of the highest bit
static int getHighBitIndex (unsigned int x)
{
  int i = 0;
  while (x) {
    i++;
    x >>= 1;
  }
  return i-1;
}

// shift x left by i, where i can be positive or negative
#define SHIFTL(x,i) (((i) >= 0) ? ((x) << (i)) : ((x) >> (-i)))

static void captureFrame (int num)
{
  fprintf (stderr,"capturing frame %04d\n",num);

  char s[100];
  sprintf (s,"frame/frame%04d.ppm",num);
  FILE *f = fopen (s,"wb");
  if (!f) dsError ("can't open \"%s\" for writing",s);
  fprintf (f,"P6\n%d %d\n255\n",width,height);
  XImage *image = XGetImage (display,win,0,0,width,height,~0,ZPixmap);

  int rshift = 7 - getHighBitIndex (image->red_mask);
  int gshift = 7 - getHighBitIndex (image->green_mask);
  int bshift = 7 - getHighBitIndex (image->blue_mask);

  for (int y=0; y<height; y++) {
    for (int x=0; x<width; x++) {
      unsigned long pixel = XGetPixel (image,x,y);
      unsigned char b[3];
      b[0] = SHIFTL(pixel & image->red_mask,rshift);
      b[1] = SHIFTL(pixel & image->green_mask,gshift);
      b[2] = SHIFTL(pixel & image->blue_mask,bshift);
      fwrite (b,3,1,f);
    }
  }
  fclose (f);
  XDestroyImage (image);
}

void dsPlatformSimLoop (int window_width, int window_height, dsFunctions *fn,
			int initial_pause)
{
  pause = initial_pause;
  createMainWindow (window_width, window_height);
  glXMakeCurrent (display,win,glx_context);

  dsStartGraphics (window_width,window_height,fn);

  fprintf (stderr,
	   "\n"
	   "Simulation test environment v%d.%02d\n"
	   "   Ctrl-P : pause / unpause (or say `-pause' on command line).\n"
	   "   Ctrl-O : single step when paused.\n"
	   "   Ctrl-T : toggle textures (or say `-notex' on command line).\n"
	   "   Ctrl-S : toggle shadows (or say `-noshadow' on command line).\n"
	   "   Ctrl-V : print current viewpoint coordinates (x,y,z,h,p,r).\n"
	   "   Ctrl-W : write frames to ppm files: frame/frameNNN.ppm\n"
	   "   Ctrl-X : exit.\n"
	   "\n"
	   "Change the camera position by clicking + dragging in the window.\n"
	   "   Left button - pan and tilt.\n"
	   "   Right button - forward and sideways.\n"
	   "   Left + Right button (or middle button) - sideways and up.\n"
	   "\n",DS_VERSION >> 8,DS_VERSION & 0xff);

  if (fn->start) fn->start();

  int frame = 1;
  run = 1;
  while (run) {
    // read in and process all pending events for the main window
    XEvent event;
    while (run && XPending (display)) {
      XNextEvent (display,&event);
      handleEvent (event,fn);
    }

    dsDrawFrame (width,height,fn,pause && !singlestep);
    singlestep = 0;

    glFlush();
    glXSwapBuffers (display,win);
    XSync (display,0);

    // capture frames if necessary
    if (pause==0 && writeframes) {
      captureFrame (frame);
      frame++;
    }
  };

  if (fn->stop) fn->stop();
  dsStopGraphics();

  destroyMainWindow();
}

extern "C" void dsStop()
{
  run = 0;
}
<commit_msg>fixes from d redgrave<commit_after>/*************************************************************************
 *                                                                       *
 * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith.       *
 * All rights reserved.  Email: russ@q12.org   Web: www.q12.org          *
 *                                                                       *
 * This library is free software; you can redistribute it and/or         *
 * modify it under the terms of EITHER:                                  *
 *   (1) The GNU Lesser General Public License as published by the Free  *
 *       Software Foundation; either version 2.1 of the License, or (at  *
 *       your option) any later version. The text of the GNU Lesser      *
 *       General Public License is included with this library in the     *
 *       file LICENSE.TXT.                                               *
 *   (2) The BSD-style license that is included with this library in     *
 *       the file LICENSE-BSD.TXT.                                       *
 *                                                                       *
 * 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 files    *
 * LICENSE.TXT and LICENSE-BSD.TXT for more details.                     *
 *                                                                       *
 *************************************************************************/

// main window and event handling for X11

#include <ode/config.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
#include <GL/glx.h>

#include <drawstuff/drawstuff.h>
#include <drawstuff/version.h>
#include "internal.h"

//***************************************************************************
// error handling for unix

static void printMessage (char *msg1, char *msg2, va_list ap)
{
  fflush (stderr);
  fflush (stdout);
  fprintf (stderr,"\n%s: ",msg1);
  vfprintf (stderr,msg2,ap);
  fprintf (stderr,"\n");
  fflush (stderr);
}

extern "C" void dsError (char *msg, ...)
{
  va_list ap;
  va_start (ap,msg);
  printMessage ("Error",msg,ap);
  exit (1);
}

extern "C" void dsDebug (char *msg, ...)
{
  va_list ap;
  va_start (ap,msg);
  printMessage ("INTERNAL ERROR",msg,ap);
  // *((char *)0) = 0;	 ... commit SEGVicide ?
  abort();
}

extern "C" void dsPrint (char *msg, ...)
{
  va_list ap;
  va_start (ap,msg);
  vprintf (msg,ap);
}

//***************************************************************************
// openGL window

// X11 display info
static Display *display=0;
static int screen=0;
static XVisualInfo *visual=0;		// best visual for openGL
static Colormap colormap=0;		// window's colormap
static Atom wm_protocols_atom = 0;
static Atom wm_delete_window_atom = 0;

// window and openGL
static Window win=0;			// X11 window, 0 if not initialized
static int width=0,height=0;		// window size
static GLXContext glx_context=0;	// openGL rendering context
static int last_key_pressed=0;		// last key pressed in the window
static int run=1;			// 1 if simulation running
static int pause=0;			// 1 if in `pause' mode
static int singlestep=0;		// 1 if single step key pressed
static int writeframes=0;		// 1 if frame files to be written

static void createMainWindow (int _width, int _height)
{
  // create X11 display connection
  display = XOpenDisplay (NULL);
  if (!display) dsError ("can not open X11 display");
  screen = DefaultScreen(display);

  // get GL visual
  static int attribList[] = {GLX_RGBA, GLX_DOUBLEBUFFER, GLX_DEPTH_SIZE,16,
			     GLX_RED_SIZE,4, GLX_GREEN_SIZE,4,
			     GLX_BLUE_SIZE,4, None};
  visual = glXChooseVisual (display,screen,attribList);
  if (!visual) dsError ("no good X11 visual found for OpenGL");

  // create colormap
  colormap = XCreateColormap (display,RootWindow(display,screen),
			      visual->visual,AllocNone);

  // initialize variables
  win = 0;
  width = _width;
  height = _height;
  glx_context = 0;
  last_key_pressed = 0;

  if (width < 1 || height < 1) dsDebug (0,"bad window width or height");

  // create the window
  XSetWindowAttributes attributes;
  attributes.background_pixel = BlackPixel(display,screen);
  attributes.colormap = colormap;
  attributes.event_mask = ButtonPressMask | ButtonReleaseMask |
    KeyPressMask | KeyReleaseMask | ButtonMotionMask | PointerMotionHintMask |
    StructureNotifyMask;
  win = XCreateWindow (display,RootWindow(display,screen),50,50,width,height,
		       0,visual->depth, InputOutput,visual->visual,
		       CWBackPixel | CWColormap | CWEventMask,&attributes);

  // associate a GLX context with the window
  glx_context = glXCreateContext (display,visual,0,GL_TRUE);
  if (!glx_context) dsError ("can't make an OpenGL context");

  // set the window title
  XTextProperty window_name;
  window_name.value = (unsigned char *) "Simulation";
  window_name.encoding = XA_STRING;
  window_name.format = 8;
  window_name.nitems = strlen((char *) window_name.value);
  XSetWMName (display,win,&window_name);

  // participate in the window manager 'delete yourself' protocol
  wm_protocols_atom = XInternAtom (display,"WM_PROTOCOLS",False);
  wm_delete_window_atom = XInternAtom (display,"WM_DELETE_WINDOW",False);
  if (XSetWMProtocols (display,win,&wm_delete_window_atom,1)==0)
    dsError ("XSetWMProtocols() call failed");

  // pop up the window
  XMapWindow (display,win);
  XSync (display,win);
}

static void destroyMainWindow()
{
  glXDestroyContext (display,glx_context);
  XDestroyWindow (display,win);
  XSync (display,0);
  display = 0;
  win = 0;
  glx_context = 0;
}

static void handleEvent (XEvent &event, dsFunctions *fn)
{
  static int mx=0,my=0; 	// mouse position
  static int mode = 0;		// mouse button bits

  switch (event.type) {

  case ButtonPress: {
    if (event.xbutton.button == Button1) mode |= 1;
    if (event.xbutton.button == Button2) mode |= 2;
    if (event.xbutton.button == Button3) mode |= 4;
    mx = event.xbutton.x;
    my = event.xbutton.y;
  }
  return;

  case ButtonRelease: {
    if (event.xbutton.button == Button1) mode &= (~1);
    if (event.xbutton.button == Button2) mode &= (~2);
    if (event.xbutton.button == Button3) mode &= (~4);
    mx = event.xbutton.x;
    my = event.xbutton.x;
  }
  return;

  case MotionNotify: {
    if (event.xmotion.is_hint) {
      Window root,child;
      unsigned int mask;
      XQueryPointer (display,win,&root,&child,&event.xbutton.x_root,
		     &event.xbutton.y_root,&event.xbutton.x,&event.xbutton.y,
		     &mask);
    }
    dsMotion (mode, event.xmotion.x - mx, event.xmotion.y - my);
    mx = event.xmotion.x;
    my = event.xmotion.y;
  }
  return;

  case KeyPress: {
    KeySym key;
    XLookupString (&event.xkey,NULL,0,&key,0);
    if ((event.xkey.state & ControlMask) == 0) {
      if (key >= ' ' && key <= 126 && fn->command) fn->command (key);
    }
    else if (event.xkey.state & ControlMask) {
      switch (key) {
      case 't': case 'T':
	dsSetTextures (dsGetTextures() ^ 1);
	break;
      case 's': case 'S':
	dsSetShadows (dsGetShadows() ^ 1);
	break;
      case 'x': case 'X':
	run = 0;
	break;
      case 'p': case 'P':
	pause ^= 1;
	singlestep = 0;
	break;
      case 'o': case 'O':
	if (pause) singlestep = 1;
	break;
      case 'v': case 'V': {
	float xyz[3],hpr[3];
	dsGetViewpoint (xyz,hpr);
	printf ("Viewpoint = (%.4f,%.4f,%.4f,%.4f,%.4f,%.4f)\n",
		xyz[0],xyz[1],xyz[2],hpr[0],hpr[1],hpr[2]);
	break;
      }
      case 'w': case 'W':
	writeframes ^= 1;
	if (writeframes) printf ("Now writing frames to PPM files\n");
	break;
      }
    }
    last_key_pressed = key;		// a kludgy place to put this...
  }
  return;

  case KeyRelease: {
    // hmmmm...
  }
  return;

  case ClientMessage:
    if (event.xclient.message_type == wm_protocols_atom &&
	event.xclient.format == 32 &&
	Atom(event.xclient.data.l[0]) == wm_delete_window_atom) {
      run = 0;
      return;
    }
    return;

  case ConfigureNotify:
    width = event.xconfigure.width;
    height = event.xconfigure.height;
    return;
  }
}

// return the index of the highest bit
static int getHighBitIndex (unsigned int x)
{
  int i = 0;
  while (x) {
    i++;
    x >>= 1;
  }
  return i-1;
}

// shift x left by i, where i can be positive or negative
#define SHIFTL(x,i) (((i) >= 0) ? ((x) << (i)) : ((x) >> (-i)))

static void captureFrame (int num)
{
  fprintf (stderr,"capturing frame %04d\n",num);

  char s[100];
  sprintf (s,"frame/frame%04d.ppm",num);
  FILE *f = fopen (s,"wb");
  if (!f) dsError ("can't open \"%s\" for writing",s);
  fprintf (f,"P6\n%d %d\n255\n",width,height);
  XImage *image = XGetImage (display,win,0,0,width,height,~0,ZPixmap);

  int rshift = 7 - getHighBitIndex (image->red_mask);
  int gshift = 7 - getHighBitIndex (image->green_mask);
  int bshift = 7 - getHighBitIndex (image->blue_mask);

  for (int y=0; y<height; y++) {
    for (int x=0; x<width; x++) {
      unsigned long pixel = XGetPixel (image,x,y);
      unsigned char b[3];
      b[0] = SHIFTL(pixel & image->red_mask,rshift);
      b[1] = SHIFTL(pixel & image->green_mask,gshift);
      b[2] = SHIFTL(pixel & image->blue_mask,bshift);
      fwrite (b,3,1,f);
    }
  }
  fclose (f);
  XDestroyImage (image);
}

void dsPlatformSimLoop (int window_width, int window_height, dsFunctions *fn,
			int initial_pause)
{
  pause = initial_pause;
  createMainWindow (window_width, window_height);
  glXMakeCurrent (display,win,glx_context);

  dsStartGraphics (window_width,window_height,fn);

  fprintf (stderr,
	   "\n"
	   "Simulation test environment v%d.%02d\n"
	   "   Ctrl-P : pause / unpause (or say `-pause' on command line).\n"
	   "   Ctrl-O : single step when paused.\n"
	   "   Ctrl-T : toggle textures (or say `-notex' on command line).\n"
	   "   Ctrl-S : toggle shadows (or say `-noshadow' on command line).\n"
	   "   Ctrl-V : print current viewpoint coordinates (x,y,z,h,p,r).\n"
	   "   Ctrl-W : write frames to ppm files: frame/frameNNN.ppm\n"
	   "   Ctrl-X : exit.\n"
	   "\n"
	   "Change the camera position by clicking + dragging in the window.\n"
	   "   Left button - pan and tilt.\n"
	   "   Right button - forward and sideways.\n"
	   "   Left + Right button (or middle button) - sideways and up.\n"
	   "\n",DS_VERSION >> 8,DS_VERSION & 0xff);

  if (fn->start) fn->start();

  int frame = 1;
  run = 1;
  while (run) {
    // read in and process all pending events for the main window
    XEvent event;
    while (run && XPending (display)) {
      XNextEvent (display,&event);
      handleEvent (event,fn);
    }

    dsDrawFrame (width,height,fn,pause && !singlestep);
    singlestep = 0;

    glFlush();
    glXSwapBuffers (display,win);
    XSync (display,0);

    // capture frames if necessary
    if (pause==0 && writeframes) {
      captureFrame (frame);
      frame++;
    }
  };

  if (fn->stop) fn->stop();
  dsStopGraphics();

  destroyMainWindow();
}

extern "C" void dsStop()
{
  run = 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
** Copyright (c) 2014-2015, Intel Corporation                                **
** All rights reserved.                                                      **
**                                                                           **
** Redistribution and use in source and binary forms, with or without        **
** modification, are permitted provided that the following conditions        **
** are met:                                                                  **
** 1. Redistributions of source code must retain the above copyright         **
**    notice, this list of conditions and the following disclaimer.          **
** 2. Redistributions in binary form must reproduce the above copyright      **
**    notice, this list of conditions and the following disclaimer in the    **
**    documentation and/or other materials provided with the distribution.   **
** 3. Neither the name of the copyright holder nor the names of its          **
**    contributors may be used to endorse or promote products derived        **
**    from this software without specific prior written permission.          **
**                                                                           **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR     **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              **
******************************************************************************/
/* Hans Pabst (Intel Corp.)
******************************************************************************/
#include "multi-dgemm-type.hpp"

#include <libxstream_begin.h>
#include <stdexcept>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#if defined(_OPENMP)
# include <omp.h>
#endif
#include <libxstream_end.h>

//#define MULTI_DGEMM_USE_NESTED
#define MULTI_DGEMM_USE_SYNC 1
#define MULTI_DGEMM_USE_CHECK

#define DGEMM dgemm_

LIBXSTREAM_EXTERN_C LIBXSTREAM_TARGET(mic) void DGEMM(
  const char*, const char*, const int*, const int*, const int*,
  const double*, const double*, const int*, const double*, const int*,
  const double*, double*, const int*);

LIBXSTREAM_TARGET(mic) void process(LIBXSTREAM_INVAL(size_t) size, LIBXSTREAM_INVAL(size_t) nn, const size_t* idata,
  const double* adata, const double* bdata, double* cdata)
{
  if (0 < LIBXSTREAM_GETVAL(size)) {
    static const double alpha = 1, beta = 1;
    static const char trans = 'N';
    const int isize = static_cast<int>(size);
    const size_t base = idata[0];

#if defined(_OPENMP) && defined(MULTI_DGEMM_USE_NESTED)
    const int nthreads = omp_get_max_threads() / LIBXSTREAM_GETVAL(size);
    const int dynamic = omp_get_dynamic(), nested = omp_get_nested();
    omp_set_dynamic(0);
    omp_set_nested(1);
#   pragma omp parallel for schedule(dynamic,1) num_threads(LIBXSTREAM_GETVAL(size))
#endif
    for (int i = 0; i < isize; ++i) {
#if defined(_OPENMP) && defined(MULTI_DGEMM_USE_NESTED)
      omp_set_num_threads(nthreads);
#endif
      LIBXSTREAM_ASSERT(base <= idata[i]);
      const size_t i0 = idata[i], i1 = (i + 1) < isize ? idata[i+1] : (i0 + LIBXSTREAM_GETVAL(nn)), n2 = i1 - i0, offset = i0 - base;
      const int n = static_cast<int>(std::sqrt(static_cast<double>(n2)) + 0.5);
      DGEMM(&trans, &trans, &n, &n, &n, &alpha, adata + offset, &n, bdata + offset, &n, &beta, cdata + offset, &n);
    }

#if defined(_OPENMP) && defined(MULTI_DGEMM_USE_NESTED)
    omp_set_dynamic(dynamic);
    omp_set_nested(nested);
#endif
  }
}

int main(int argc, char* argv[])
{
  try {
    const int nitems = std::max(1 < argc ? std::atoi(argv[1]) : 60, 0);
    const int nbatch = std::max(2 < argc ? std::atoi(argv[2]) : 10, 1);
    const int nstreams = std::min(std::max(3 < argc ? std::atoi(argv[3]) : 2, 1), LIBXSTREAM_MAX_NSTREAMS);
#if defined(MULTI_DGEMM_USE_SYNC)
    const int demux = 4 < argc ? std::atoi(argv[4]) : 1;
#else
    const int demux = -1;
#endif
    size_t ndevices = 0;
    if (LIBXSTREAM_ERROR_NONE != libxstream_get_ndevices(&ndevices) || 0 == ndevices) {
      throw std::runtime_error("no device found!");
    }
#if !defined(_OPENMP)
    fprintf(stderr, "Warning: OpenMP support needed for performance results.\n");
#endif

    fprintf(stdout, "Initializing %i device%s and host data...", static_cast<int>(ndevices), 1 == ndevices ? "" : "s");
    const size_t split[] = { size_t(nitems * 18.0 / 250.0 + 0.5), size_t(nitems * 74.0 / 250.0 + 0.5) };
    multi_dgemm_type::host_data_type host_data(reinterpret_cast<libxstream_function>(&process), nitems, split);
    fprintf(stdout, " %.1f MB\n", host_data.bytes() * 1E-6);

    fprintf(stdout, "Initializing %i stream%s per device...", nstreams, 1 < nstreams ? "s" : "");
    const size_t nstreams_total = ndevices * nstreams;
    multi_dgemm_type multi_dgemm[LIBXSTREAM_MAX_NSTREAMS];
    for (size_t i = 0; i < nstreams_total; ++i) {
      char name[128];
      LIBXSTREAM_SNPRINTF(name, sizeof(name), "Stream %i", static_cast<int>(i + 1));
      LIBXSTREAM_CHECK_CALL_THROW(multi_dgemm[i].init(name, host_data, static_cast<int>(i % ndevices), demux, static_cast<size_t>(nbatch)));
    }
    if (0 < nstreams_total) {
      fprintf(stdout, " %.1f MB\n", nstreams * multi_dgemm[0].bytes() * 1E-6);
    }

    const int nbatches = (nitems + nbatch - 1) / nbatch;
    fprintf(stdout, "Running %i batch%s of %i item%s...\n", nbatches,
      1 < nbatches ? "es" : "", std::min(nbatch, nitems),
      1 < nbatch ? "s" : "");

#if defined(_OPENMP)
# if !defined(LIBXSTREAM_OFFLOAD)
    omp_set_dynamic(0);
    omp_set_nested(0);
# endif
    const double start = omp_get_wtime();
#   pragma omp parallel for schedule(dynamic)
#endif
    for (int i = 0; i < nitems; i += nbatch) {
      const size_t j = i / nbatch, n = j % nstreams_total;
      multi_dgemm_type& call = multi_dgemm[n];
      LIBXSTREAM_CHECK_CALL_ASSERT(call(i, std::min(nbatch, nitems - i)));
#if defined(MULTI_DGEMM_USE_SYNC) && (1 <= MULTI_DGEMM_USE_SYNC)
      LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_event_record(call.event(), call.stream()));
#endif
      // synchronize every Nth iteration with N being the total number of streams
      if (n == (nstreams_total - 1)) {
        for (size_t k = 0; k < nstreams_total; ++k) {
#if defined(MULTI_DGEMM_USE_SYNC)
# if (2 <= (MULTI_DGEMM_USE_SYNC))
          // wait for an event within a stream
          LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_wait_event(multi_dgemm[0].stream(), multi_dgemm[k].event()));
# elif (1 <= (MULTI_DGEMM_USE_SYNC))
          // wait for an event on the host
          LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_event_synchronize(multi_dgemm[k].event()));
# else
          // wait for all work in a stream
          LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_sync(multi_dgemm[k].stream()));
# endif
#endif
        }
      }
    }

    // sync all streams to complete any pending work
    LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_sync(0));

#if defined(_OPENMP)
    const double duration = omp_get_wtime() - start;
    fprintf(stdout, "Performance: %.1f GFLOPS/s (%s)\n", host_data.flops() * 1E-9 / duration,
      0 == demux ? "manual locking" : (0 < demux ? "synchronization" : "automatic locking"));
    fprintf(stdout, "Duration: %.1f s\n", duration);
#endif

#if defined(MULTI_DGEMM_USE_CHECK)
    std::vector<double> expected(host_data.max_matrix_size());
    const size_t testbatchsize = 1;
    double max_error = 0;
    size_t i0 = 0;
    for (int i = 0; i < nitems; ++i) {
      const size_t i1 = host_data.idata()[i+1];
      const int nn = static_cast<int>(i1 - i0);
      std::fill_n(&expected[0], nn, 0.0);
      process(LIBXSTREAM_SETVAL(testbatchsize), LIBXSTREAM_SETVAL(nn), host_data.idata() + i, host_data.adata() + i0, host_data.bdata() + i0, &expected[0]);
      for (int n = 0; n < nn; ++n) max_error = std::max(max_error, std::abs(expected[n] - host_data.cdata()[i0+n]));
      i0 = i1;
    }
    fprintf(stdout, "Error: %g\n", max_error);
#endif
    fprintf(stdout, "Finished\n");
  }
  catch(const std::exception& e) {
    fprintf(stderr, "Error: %s\n", e.what());
    return EXIT_FAILURE;
  }
  catch(...) {
    fprintf(stderr, "Error: unknown exception caught!\n");
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<commit_msg>Avoid "potential" division by zero (duration / run time).<commit_after>/******************************************************************************
** Copyright (c) 2014-2015, Intel Corporation                                **
** All rights reserved.                                                      **
**                                                                           **
** Redistribution and use in source and binary forms, with or without        **
** modification, are permitted provided that the following conditions        **
** are met:                                                                  **
** 1. Redistributions of source code must retain the above copyright         **
**    notice, this list of conditions and the following disclaimer.          **
** 2. Redistributions in binary form must reproduce the above copyright      **
**    notice, this list of conditions and the following disclaimer in the    **
**    documentation and/or other materials provided with the distribution.   **
** 3. Neither the name of the copyright holder nor the names of its          **
**    contributors may be used to endorse or promote products derived        **
**    from this software without specific prior written permission.          **
**                                                                           **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR     **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT      **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              **
******************************************************************************/
/* Hans Pabst (Intel Corp.)
******************************************************************************/
#include "multi-dgemm-type.hpp"

#include <libxstream_begin.h>
#include <stdexcept>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#if defined(_OPENMP)
# include <omp.h>
#endif
#include <libxstream_end.h>

//#define MULTI_DGEMM_USE_NESTED
#define MULTI_DGEMM_USE_SYNC 1
#define MULTI_DGEMM_USE_CHECK

#define DGEMM dgemm_

LIBXSTREAM_EXTERN_C LIBXSTREAM_TARGET(mic) void DGEMM(
  const char*, const char*, const int*, const int*, const int*,
  const double*, const double*, const int*, const double*, const int*,
  const double*, double*, const int*);

LIBXSTREAM_TARGET(mic) void process(LIBXSTREAM_INVAL(size_t) size, LIBXSTREAM_INVAL(size_t) nn, const size_t* idata,
  const double* adata, const double* bdata, double* cdata)
{
  if (0 < LIBXSTREAM_GETVAL(size)) {
    static const double alpha = 1, beta = 1;
    static const char trans = 'N';
    const int isize = static_cast<int>(size);
    const size_t base = idata[0];

#if defined(_OPENMP) && defined(MULTI_DGEMM_USE_NESTED)
    const int nthreads = omp_get_max_threads() / LIBXSTREAM_GETVAL(size);
    const int dynamic = omp_get_dynamic(), nested = omp_get_nested();
    omp_set_dynamic(0);
    omp_set_nested(1);
#   pragma omp parallel for schedule(dynamic,1) num_threads(LIBXSTREAM_GETVAL(size))
#endif
    for (int i = 0; i < isize; ++i) {
#if defined(_OPENMP) && defined(MULTI_DGEMM_USE_NESTED)
      omp_set_num_threads(nthreads);
#endif
      LIBXSTREAM_ASSERT(base <= idata[i]);
      const size_t i0 = idata[i], i1 = (i + 1) < isize ? idata[i+1] : (i0 + LIBXSTREAM_GETVAL(nn)), n2 = i1 - i0, offset = i0 - base;
      const int n = static_cast<int>(std::sqrt(static_cast<double>(n2)) + 0.5);
      DGEMM(&trans, &trans, &n, &n, &n, &alpha, adata + offset, &n, bdata + offset, &n, &beta, cdata + offset, &n);
    }

#if defined(_OPENMP) && defined(MULTI_DGEMM_USE_NESTED)
    omp_set_dynamic(dynamic);
    omp_set_nested(nested);
#endif
  }
}

int main(int argc, char* argv[])
{
  try {
    const int nitems = std::max(1 < argc ? std::atoi(argv[1]) : 60, 0);
    const int nbatch = std::max(2 < argc ? std::atoi(argv[2]) : 10, 1);
    const int nstreams = std::min(std::max(3 < argc ? std::atoi(argv[3]) : 2, 1), LIBXSTREAM_MAX_NSTREAMS);
#if defined(MULTI_DGEMM_USE_SYNC)
    const int demux = 4 < argc ? std::atoi(argv[4]) : 1;
#else
    const int demux = -1;
#endif
    size_t ndevices = 0;
    if (LIBXSTREAM_ERROR_NONE != libxstream_get_ndevices(&ndevices) || 0 == ndevices) {
      throw std::runtime_error("no device found!");
    }
#if !defined(_OPENMP)
    fprintf(stderr, "Warning: OpenMP support needed for performance results.\n");
#endif

    fprintf(stdout, "Initializing %i device%s and host data...", static_cast<int>(ndevices), 1 == ndevices ? "" : "s");
    const size_t split[] = { size_t(nitems * 18.0 / 250.0 + 0.5), size_t(nitems * 74.0 / 250.0 + 0.5) };
    multi_dgemm_type::host_data_type host_data(reinterpret_cast<libxstream_function>(&process), nitems, split);
    fprintf(stdout, " %.1f MB\n", host_data.bytes() * 1E-6);

    fprintf(stdout, "Initializing %i stream%s per device...", nstreams, 1 < nstreams ? "s" : "");
    const size_t nstreams_total = ndevices * nstreams;
    multi_dgemm_type multi_dgemm[LIBXSTREAM_MAX_NSTREAMS];
    for (size_t i = 0; i < nstreams_total; ++i) {
      char name[128];
      LIBXSTREAM_SNPRINTF(name, sizeof(name), "Stream %i", static_cast<int>(i + 1));
      LIBXSTREAM_CHECK_CALL_THROW(multi_dgemm[i].init(name, host_data, static_cast<int>(i % ndevices), demux, static_cast<size_t>(nbatch)));
    }
    if (0 < nstreams_total) {
      fprintf(stdout, " %.1f MB\n", nstreams * multi_dgemm[0].bytes() * 1E-6);
    }

    const int nbatches = (nitems + nbatch - 1) / nbatch;
    fprintf(stdout, "Running %i batch%s of %i item%s...\n", nbatches,
      1 < nbatches ? "es" : "", std::min(nbatch, nitems),
      1 < nbatch ? "s" : "");

#if defined(_OPENMP)
# if !defined(LIBXSTREAM_OFFLOAD)
    omp_set_dynamic(0);
    omp_set_nested(0);
# endif
    const double start = omp_get_wtime();
#   pragma omp parallel for schedule(dynamic)
#endif
    for (int i = 0; i < nitems; i += nbatch) {
      const size_t j = i / nbatch, n = j % nstreams_total;
      multi_dgemm_type& call = multi_dgemm[n];
      LIBXSTREAM_CHECK_CALL_ASSERT(call(i, std::min(nbatch, nitems - i)));
#if defined(MULTI_DGEMM_USE_SYNC) && (1 <= MULTI_DGEMM_USE_SYNC)
      LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_event_record(call.event(), call.stream()));
#endif
      // synchronize every Nth iteration with N being the total number of streams
      if (n == (nstreams_total - 1)) {
        for (size_t k = 0; k < nstreams_total; ++k) {
#if defined(MULTI_DGEMM_USE_SYNC)
# if (2 <= (MULTI_DGEMM_USE_SYNC))
          // wait for an event within a stream
          LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_wait_event(multi_dgemm[0].stream(), multi_dgemm[k].event()));
# elif (1 <= (MULTI_DGEMM_USE_SYNC))
          // wait for an event on the host
          LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_event_synchronize(multi_dgemm[k].event()));
# else
          // wait for all work in a stream
          LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_sync(multi_dgemm[k].stream()));
# endif
#endif
        }
      }
    }

    // sync all streams to complete any pending work
    LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_sync(0));

#if defined(_OPENMP)
    const double duration = omp_get_wtime() - start;
    if (0 < duration) {
      fprintf(stdout, "Performance: %.1f GFLOPS/s (%s)\n", host_data.flops() * 1E-9 / duration,
        0 == demux ? "manual locking" : (0 < demux ? "synchronization" : "automatic locking"));
    }
    fprintf(stdout, "Duration: %.1f s\n", duration);
#endif

#if defined(MULTI_DGEMM_USE_CHECK)
    std::vector<double> expected(host_data.max_matrix_size());
    const size_t testbatchsize = 1;
    double max_error = 0;
    size_t i0 = 0;
    for (int i = 0; i < nitems; ++i) {
      const size_t i1 = host_data.idata()[i+1];
      const int nn = static_cast<int>(i1 - i0);
      std::fill_n(&expected[0], nn, 0.0);
      process(LIBXSTREAM_SETVAL(testbatchsize), LIBXSTREAM_SETVAL(nn), host_data.idata() + i, host_data.adata() + i0, host_data.bdata() + i0, &expected[0]);
      for (int n = 0; n < nn; ++n) max_error = std::max(max_error, std::abs(expected[n] - host_data.cdata()[i0+n]));
      i0 = i1;
    }
    fprintf(stdout, "Error: %g\n", max_error);
#endif
    fprintf(stdout, "Finished\n");
  }
  catch(const std::exception& e) {
    fprintf(stderr, "Error: %s\n", e.what());
    return EXIT_FAILURE;
  }
  catch(...) {
    fprintf(stderr, "Error: unknown exception caught!\n");
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
<|endoftext|>