<commit_before>#include "text/table.h"
#include "text/cmdline.h"
#include "cortex/class.h"
#include "cortex/cortex.h"
#include "math/clamp.hpp"
#include "thread/thread.h"
#include "math/random.hpp"
#include "math/numeric.hpp"
#include "tensor/numeric.hpp"
#include "cortex/measure.hpp"
#include "cortex/accumulator.h"
#include "text/table_row_mark.h"
#include "cortex/measure_and_log.hpp"
#include "cortex/layers/make_layers.h"
#include "cortex/tasks/task_charset.h"

int main(int argc, const char *argv[])
{
        using namespace nano;

        // parse the command line
        nano::cmdline_t cmdline("benchmark models");
        cmdline.add("s", "samples",     "number of samples to use [100, 100000]", "10000");
        cmdline.add("", "mlps",         "benchmark MLP models");
        cmdline.add("", "convnets",     "benchmark convolution networks");
        cmdline.add("", "forward",      "evaluate the \'forward\' pass (output)");
        cmdline.add("", "backward",     "evaluate the \'backward' pass (gradient)");

        cmdline.process(argc, argv);

        // check arguments and options
        const auto cmd_samples = nano::clamp(cmdline.get<size_t>("samples"), 100, 100 * 1000);
        const auto cmd_forward = cmdline.has("forward");
        const auto cmd_backward = cmdline.has("backward");
        const auto cmd_mlps = cmdline.has("mlps");
        const auto cmd_convnets = cmdline.has("convnets");

        if (!cmd_forward && !cmd_backward)
        {
                cmdline.usage();
        }

        if (!cmd_mlps && !cmd_convnets)
        {
                cmdline.usage();
        }

        const tensor_size_t cmd_rows = 28;
        const tensor_size_t cmd_cols = 28;
        const color_mode cmd_color = color_mode::luma;

        const size_t cmd_min_nthreads = 1;
        const size_t cmd_max_nthreads = thread::concurrency();

        // generate synthetic task
        charset_task_t task(charset::digit, cmd_color, cmd_rows, cmd_cols, cmd_samples);
        task.load();

        // construct models
        const string_t mlp0;
        const string_t mlp1 = mlp0 + make_affine_layer(100);
        const string_t mlp2 = mlp1 + make_affine_layer(100);
        const string_t mlp3 = mlp2 + make_affine_layer(100);
        const string_t mlp4 = mlp3 + make_affine_layer(100);
        const string_t mlp5 = mlp4 + make_affine_layer(100);

        const string_t convnetk2d_9x9p_5x5p_3x3 =
                make_conv_pool_layer("conv-k2d", 16, 9, 9, 1) +
                make_conv_pool_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4);

        const string_t convnettoe_9x9p_5x5p_3x3 =
                nano::replace(convnetk2d_9x9p_5x5p_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_11x11_9x9_7x7_3x3 =
                make_conv_layer("conv-k2d", 16, 11, 11, 1) +
                make_conv_layer("conv-k2d", 32, 9, 9, 2) +
                make_conv_layer("conv-k2d", 64, 7, 7, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_11x11_9x9_7x7_3x3 =
                nano::replace(convnetk2d_11x11_9x9_7x7_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_9x9_7x7_7x7_5x5_3x3 =
                make_conv_layer("conv-k2d", 16, 9, 9, 1) +
                make_conv_layer("conv-k2d", 32, 7, 7, 2) +
                make_conv_layer("conv-k2d", 32, 7, 7, 4) +
                make_conv_layer("conv-k2d", 64, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_9x9_7x7_7x7_5x5_3x3 =
                nano::replace(convnetk2d_9x9_7x7_7x7_5x5_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3 =
                make_conv_layer("conv-k2d", 16, 7, 7, 1) +
                make_conv_layer("conv-k2d", 16, 7, 7, 2) +
                make_conv_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 32, 5, 5, 4) +
                make_conv_layer("conv-k2d", 32, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4);

        const string_t convnettoe_7x7_7x7_5x5_5x5_5x5_3x3 =
                nano::replace(convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3, "conv-k2d", "conv-toe");

        const string_t outlayer = make_output_layer(task.osize());

        std::vector<std::pair<string_t, string_t>> networks;
        #define DEFINE(config) networks.emplace_back(config + outlayer, NANO_STRINGIFY(config))

        if (cmd_mlps)
        {
                DEFINE(mlp0);
                DEFINE(mlp1);
                DEFINE(mlp2);
                DEFINE(mlp3);
                DEFINE(mlp4);
                DEFINE(mlp5);
        }
        if (cmd_convnets)
        {
                DEFINE(convnetk2d_9x9p_5x5p_3x3);
                DEFINE(convnettoe_9x9p_5x5p_3x3);
                DEFINE(convnetk2d_11x11_9x9_7x7_3x3);
                DEFINE(convnettoe_11x11_9x9_7x7_3x3);
                DEFINE(convnetk2d_9x9_7x7_7x7_5x5_3x3);
                DEFINE(convnettoe_9x9_7x7_7x7_5x5_3x3);
                DEFINE(convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3);
                DEFINE(convnettoe_7x7_7x7_5x5_5x5_5x5_3x3);
        }

        #undef DEFINE

        const auto loss = nano::get_losses().get("logistic");
        const auto criterion = nano::get_criteria().get("l2n-reg");

        // construct tables to compare models
        nano::table_t ftable("model-forward [ms] / 1000 samples");
        nano::table_t btable("model-backward [ms] / 1000 samples");

        for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
        {
                ftable.header() << (nano::to_string(nthreads) + "xCPU");
                btable.header() << (nano::to_string(nthreads) + "xCPU");
        }

        // evaluate models
        for (const auto& config : networks)
        {
                const string_t cmd_network = config.first;
                const string_t cmd_name = config.second;

                log_info() << "<<< running network [" << cmd_network << "] ...";

                // create feed-forward network
                const auto model = nano::get_models().get("forward-network", cmd_network);
                model->resize(task, true);
                model->random_params();

                nano::table_row_t& frow = ftable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")");
                nano::table_row_t& brow = btable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")");

                const auto fold = fold_t{0, protocol::train};

                // process the samples
                for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
                {
                        if (cmd_forward)
                        {
                                accumulator_t lacc(*model, *loss, *criterion, criterion_t::type::value, scalar_t(0.1));
                                lacc.set_threads(nthreads);

                                const auto milis = nano::measure_robustly_msec([&] ()
                                {
                                        lacc.reset();
                                        lacc.update(task, fold);
                                }, 1);

                                log_info() << "<<< processed [" << lacc.count()
                                           << "] forward samples in " << milis.count() << " ms.";

                                frow << idiv(static_cast<size_t>(milis.count()) * 1000, lacc.count());
                        }

                        if (cmd_backward)
                        {
                                accumulator_t gacc(*model, *loss, *criterion, criterion_t::type::vgrad, scalar_t(0.1));
                                gacc.set_threads(nthreads);

                                const auto milis = nano::measure_robustly_msec([&] ()
                                {
                                        gacc.reset();
                                        gacc.update(task, fold);
                                }, 1);

                                log_info() << "<<< processed [" << gacc.count()
                                           << "] backward samples in " << milis.count() << " ms.";

                                brow << idiv(static_cast<size_t>(milis.count()) * 1000, gacc.count());
                        }
                }

                log_info();
        }

        // print results
        if (cmd_forward)
        {
                ftable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
                ftable.print(std::cout);
        }
        log_info();
        if (cmd_backward)
        {
                btable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
                btable.print(std::cout);
        }

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}
<commit_msg>extend benchmark with very deep convolution networks<commit_after>#include "text/table.h"
#include "text/cmdline.h"
#include "cortex/class.h"
#include "cortex/cortex.h"
#include "math/clamp.hpp"
#include "thread/thread.h"
#include "math/random.hpp"
#include "math/numeric.hpp"
#include "tensor/numeric.hpp"
#include "cortex/measure.hpp"
#include "cortex/accumulator.h"
#include "text/table_row_mark.h"
#include "cortex/measure_and_log.hpp"
#include "cortex/layers/make_layers.h"
#include "cortex/tasks/task_charset.h"

int main(int argc, const char *argv[])
{
        using namespace nano;

        // parse the command line
        nano::cmdline_t cmdline("benchmark models");
        cmdline.add("s", "samples",     "number of samples to use [100, 100000]", "10000");
        cmdline.add("", "mlps",         "benchmark MLP models");
        cmdline.add("", "convnets",     "benchmark convolution networks");
        cmdline.add("", "forward",      "evaluate the \'forward\' pass (output)");
        cmdline.add("", "backward",     "evaluate the \'backward' pass (gradient)");

        cmdline.process(argc, argv);

        // check arguments and options
        const auto cmd_samples = nano::clamp(cmdline.get<size_t>("samples"), 100, 100 * 1000);
        const auto cmd_forward = cmdline.has("forward");
        const auto cmd_backward = cmdline.has("backward");
        const auto cmd_mlps = cmdline.has("mlps");
        const auto cmd_convnets = cmdline.has("convnets");

        if (!cmd_forward && !cmd_backward)
        {
                cmdline.usage();
        }

        if (!cmd_mlps && !cmd_convnets)
        {
                cmdline.usage();
        }

        const tensor_size_t cmd_rows = 28;
        const tensor_size_t cmd_cols = 28;
        const color_mode cmd_color = color_mode::luma;

        const size_t cmd_min_nthreads = 1;
        const size_t cmd_max_nthreads = thread::concurrency();

        // generate synthetic task
        charset_task_t task(charset::digit, cmd_color, cmd_rows, cmd_cols, cmd_samples);
        task.load();

        // construct models
        const string_t mlp0;
        const string_t mlp1 = mlp0 + make_affine_layer(100);
        const string_t mlp2 = mlp1 + make_affine_layer(100);
        const string_t mlp3 = mlp2 + make_affine_layer(100);
        const string_t mlp4 = mlp3 + make_affine_layer(100);
        const string_t mlp5 = mlp4 + make_affine_layer(100);

        const string_t convnetk2d_9x9p_5x5p_3x3 =
                make_conv_pool_layer("conv-k2d", 16, 9, 9, 1) +
                make_conv_pool_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4);

        const string_t convnettoe_9x9p_5x5p_3x3 =
                nano::replace(convnetk2d_9x9p_5x5p_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_11x11_9x9_7x7_3x3 =
                make_conv_layer("conv-k2d", 16, 11, 11, 1) +
                make_conv_layer("conv-k2d", 32, 9, 9, 2) +
                make_conv_layer("conv-k2d", 64, 7, 7, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_11x11_9x9_7x7_3x3 =
                nano::replace(convnetk2d_11x11_9x9_7x7_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_9x9_7x7_7x7_5x5_3x3 =
                make_conv_layer("conv-k2d", 16, 9, 9, 1) +
                make_conv_layer("conv-k2d", 32, 7, 7, 2) +
                make_conv_layer("conv-k2d", 32, 7, 7, 4) +
                make_conv_layer("conv-k2d", 64, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_9x9_7x7_7x7_5x5_3x3 =
                nano::replace(convnetk2d_9x9_7x7_7x7_5x5_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3 =
                make_conv_layer("conv-k2d", 16, 7, 7, 1) +
                make_conv_layer("conv-k2d", 16, 7, 7, 2) +
                make_conv_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 32, 5, 5, 4) +
                make_conv_layer("conv-k2d", 32, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4);

        const string_t convnettoe_7x7_7x7_5x5_5x5_5x5_3x3 =
                nano::replace(convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3, "conv-k2d", "conv-toe");

        const string_t convnetk2d_5x5_5x5_5x5_5x5_5x5_5x5_5x5 =
                make_conv_layer("conv-k2d", 16, 5, 5, 1) +
                make_conv_layer("conv-k2d", 32, 5, 5, 2) +
                make_conv_layer("conv-k2d", 64, 5, 5, 4) +
                make_conv_layer("conv-k2d", 64, 5, 5, 8) +
                make_conv_layer("conv-k2d", 64, 5, 5, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_5x5_5x5_5x5_5x5_5x5_5x5_5x5 =
                nano::replace(convnetk2d_5x5_5x5_5x5_5x5_5x5_5x5_5x5, "conv-k2d", "conv-toe");

        const string_t convnetk2d_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3 =
                make_conv_layer("conv-k2d", 16, 3, 3, 1) +
                make_conv_layer("conv-k2d", 32, 3, 3, 2) +
                make_conv_layer("conv-k2d", 64, 3, 3, 4) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8) +
                make_conv_layer("conv-k2d", 64, 3, 3, 8);

        const string_t convnettoe_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3 =
                nano::replace(convnetk2d_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3, "conv-k2d", "conv-toe");

        const string_t outlayer = make_output_layer(task.osize());

        std::vector<std::pair<string_t, string_t>> networks;
        #define DEFINE(config) networks.emplace_back(config + outlayer, NANO_STRINGIFY(config))

        if (cmd_mlps)
        {
                DEFINE(mlp0);
                DEFINE(mlp1);
                DEFINE(mlp2);
                DEFINE(mlp3);
                DEFINE(mlp4);
                DEFINE(mlp5);
        }
        if (cmd_convnets)
        {
                DEFINE(convnetk2d_9x9p_5x5p_3x3);
                DEFINE(convnettoe_9x9p_5x5p_3x3);
                DEFINE(convnetk2d_11x11_9x9_7x7_3x3);
                DEFINE(convnettoe_11x11_9x9_7x7_3x3);
                DEFINE(convnetk2d_9x9_7x7_7x7_5x5_3x3);
                DEFINE(convnettoe_9x9_7x7_7x7_5x5_3x3);
                DEFINE(convnetk2d_7x7_7x7_5x5_5x5_5x5_3x3);
                DEFINE(convnettoe_7x7_7x7_5x5_5x5_5x5_3x3);
                DEFINE(convnetk2d_5x5_5x5_5x5_5x5_5x5_5x5_5x5);
                DEFINE(convnettoe_5x5_5x5_5x5_5x5_5x5_5x5_5x5);
                DEFINE(convnetk2d_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3);
                DEFINE(convnettoe_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3_3x3);
        }

        #undef DEFINE

        const auto loss = nano::get_losses().get("logistic");
        const auto criterion = nano::get_criteria().get("l2n-reg");

        // construct tables to compare models
        nano::table_t ftable("model-forward [ms] / 1000 samples");
        nano::table_t btable("model-backward [ms] / 1000 samples");

        for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
        {
                ftable.header() << (nano::to_string(nthreads) + "xCPU");
                btable.header() << (nano::to_string(nthreads) + "xCPU");
        }

        // evaluate models
        for (const auto& config : networks)
        {
                const string_t cmd_network = config.first;
                const string_t cmd_name = config.second;

                log_info() << "<<< running network [" << cmd_network << "] ...";

                // create feed-forward network
                const auto model = nano::get_models().get("forward-network", cmd_network);
                model->resize(task, true);
                model->random_params();

                nano::table_row_t& frow = ftable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")");
                nano::table_row_t& brow = btable.append(cmd_name + " (" + nano::to_string(model->psize()) + ")");

                const auto fold = fold_t{0, protocol::train};

                // process the samples
                for (size_t nthreads = cmd_min_nthreads; nthreads <= cmd_max_nthreads; ++ nthreads)
                {
                        if (cmd_forward)
                        {
                                accumulator_t lacc(*model, *loss, *criterion, criterion_t::type::value, scalar_t(0.1));
                                lacc.set_threads(nthreads);

                                const auto milis = nano::measure_robustly_msec([&] ()
                                {
                                        lacc.reset();
                                        lacc.update(task, fold);
                                }, 1);

                                log_info() << "<<< processed [" << lacc.count()
                                           << "] forward samples in " << milis.count() << " ms.";

                                frow << idiv(static_cast<size_t>(milis.count()) * 1000, lacc.count());
                        }

                        if (cmd_backward)
                        {
                                accumulator_t gacc(*model, *loss, *criterion, criterion_t::type::vgrad, scalar_t(0.1));
                                gacc.set_threads(nthreads);

                                const auto milis = nano::measure_robustly_msec([&] ()
                                {
                                        gacc.reset();
                                        gacc.update(task, fold);
                                }, 1);

                                log_info() << "<<< processed [" << gacc.count()
                                           << "] backward samples in " << milis.count() << " ms.";

                                brow << idiv(static_cast<size_t>(milis.count()) * 1000, gacc.count());
                        }
                }

                log_info();
        }

        // print results
        if (cmd_forward)
        {
                ftable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
                ftable.print(std::cout);
        }
        log_info();
        if (cmd_backward)
        {
                btable.mark(nano::make_table_mark_minimum_percentage_cols<size_t>(5));
                btable.print(std::cout);
        }

        // OK
        log_info() << done;
        return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "crib_hand_helper/card.h"
#include "crib_hand_helper/hand_counter.h"

int main()
{

}
<commit_msg>Started writing main function.<commit_after>#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

#include "crib_hand_helper/card.h"
#include "crib_hand_helper/hand_counter.h"

const std::string CARD_NAMES = "A23456789TJQK";

bool validate_input(const std::string& hand_string)
{
  if (hand_string.size() != 6)
  {
    return false;
  }

  for (const auto& card_char : hand_string)
  {
    // Must not be in hand more than four times
    if (std::count(hand_string.begin(), hand_string.end(), card_char) > 4)
    {
      return false;
    }

    // Capitalize letters
    auto card = card_char;
    if (!std::isdigit(card))
    {
      card = std::toupper(card);
    }

    // Must be in CARD_NAMES
    if (std::find(CARD_NAMES.begin(), CARD_NAMES.end(), card) ==
        CARD_NAMES.end())
    {
      return false;
    }
  }

  return true;
}

Hand parse_hand(const std::string& hand_string)
{
  const std::string suits = "cdhscd";

  Hand hand;
  for (std::string::size_type i = 0; i < hand_string.size(); ++i)
  {
    // Capitalize letters
    auto card = hand_string[i];
    if (!std::isdigit(card))
    {
      card = std::toupper(card);
    }

    hand.emplace_back(card, suits[i]);
  }

  return hand;
}

int main()
{
  bool input_is_valid = false;
  std::string hand_string;

  while (!input_is_valid)
  {
    std::cout << "Enter hand: ";
    std::cin >> hand_string;
    input_is_valid = validate_input(hand_string);
    if (!input_is_valid)
    {
      std::cout << "Invalid hand. Try again.\n";
    }
  }

  auto hand = parse_hand(hand_string);

  input_is_valid = false;
  char yes_or_no;
  while (!input_is_valid)
  {
    std::cout << "Are at least fours card the same suit? [y/n]: ";
    std::cin >> yes_or_no;
    input_is_valid = yes_or_no == 'y' || yes_or_no == 'n';
    if (!input_is_valid)
    {
      std::cout << "Invalid selection. Please enter y or n.\n";
    }
  }

  if (yes_or_no == 'y')
  {

  }
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief infrastructure for query optimizer
///
/// @file arangod/Aql/Optimizer.cpp
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Aql/Optimizer.h"
#include "Aql/OptimizerRules.h"

using namespace triagens::aql;

// -----------------------------------------------------------------------------
// --SECTION--                                               the optimizer class
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
// @brief constructor, this will initialize the rules database
////////////////////////////////////////////////////////////////////////////////

Optimizer::Optimizer () {
  // List all the rules in the system here:

  // try to find sort blocks which are superseeded by indexes
  registerRule (useIndexForSort, 2000);

  // try to find a filter after an enumerate collection and find an index . . .
  registerRule(useIndexRange, 999);

  // remove filters from the query that are not necessary at all
  // filters that are always true will be removed entirely
  // filters that are always false will be replaced with a NoResults node
  registerRule(removeUnnecessaryFiltersRule, 100);

  // move calculations up the dependency chain (to pull them out of inner loops etc.)
  registerRule(moveCalculationsUpRule, 1000);

  // move filters up the dependency chain (to make result sets as small as possible
  // as early as possible)
  registerRule(moveFiltersUpRule, 1010);

  // remove calculations that are never necessary
  registerRule(removeUnnecessaryCalculationsRule, 1020);

  // Now sort them by level:
  std::stable_sort(_rules.begin(), _rules.end());
}

////////////////////////////////////////////////////////////////////////////////
// @brief the actual optimization
////////////////////////////////////////////////////////////////////////////////

int Optimizer::createPlans (ExecutionPlan* plan) {
  int res;
  int leastDoneLevel = 0;
  int maxRuleLevel = _rules.back().level;

  // _plans contains the previous optimisation result
  _plans.clear();
  _plans.push_back(plan, 0);

  int pass = 1;
  while (leastDoneLevel < maxRuleLevel) {
    std::cout << "Entering pass " << pass << " of query optimization..."
              << std::endl;

    // This vector holds the plans we have created in this pass:
    PlanList newPlans;

    // Find variable usage for all old plans now:
    for (auto p : _plans.list) {
      if (! p->varUsageComputed()) {
        p->findVarUsage();
      }
    }

    std::cout << "Have " << _plans.size() << " plans." << std::endl;

    int count = 0;

    // For all current plans:
    while (_plans.size() > 0) {
      int level;
      auto p = _plans.pop_front(level);
      if (level == maxRuleLevel) {
        newPlans.push_back(p, level);  // nothing to do, just keep it
      }
      else {   // some rule needs applying
        Rule r(dummyRule, level);
        auto it = std::upper_bound(_rules.begin(), _rules.end(), r);
        TRI_ASSERT(it != _rules.end());
        std::cout << "Trying rule " << &(it->func) << " with level "
                  << it->level << " to plan " << count++
                  << std::endl;
        try {
          // keep should have a default value so rules that forget to set it
          // have a deterministic behavior
          res = it->func(this, p, it->level, newPlans);
        }
        catch (...) {
          delete p;
          throw;
        }
        if (res != TRI_ERROR_NO_ERROR) {
          return res;
        }
      }
    }
    _plans.steal(newPlans);
    leastDoneLevel = maxRuleLevel;
    for (auto l : _plans.levelDone) {
      if (l < leastDoneLevel) {
        leastDoneLevel = l;
      }
    }
    std::cout << "Least done level is " << leastDoneLevel << std::endl;

    // Stop if the result gets out of hand:
    if (_plans.size() >= maxNumberOfPlans) {
      break;
    }
  }

  estimatePlans();
  sortPlans();
  std::cout << "Optimisation ends with " << _plans.size() << " plans."
            << std::endl;
  std::cout << "Costs:" << std::endl;
  for (auto p : _plans.list) {
    std::cout << p->getCost() << std::endl;
  }

  return TRI_ERROR_NO_ERROR;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief estimatePlans
////////////////////////////////////////////////////////////////////////////////

void Optimizer::estimatePlans () {
  for (auto p : _plans.list) {
    p->getCost();
    // this value is cached in the plan, so formally this step is
    // unnecessary, but for the sake of cleanliness...
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief sortPlans
////////////////////////////////////////////////////////////////////////////////

void Optimizer::sortPlans () {
  std::sort(_plans.list.begin(), _plans.list.end(), [](ExecutionPlan* const& a, ExecutionPlan* const& b) -> bool {
    return a->getCost() < b->getCost();
  });
}

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:

<commit_msg>Adjust a cout message.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief infrastructure for query optimizer
///
/// @file arangod/Aql/Optimizer.cpp
///
/// DISCLAIMER
///
/// Copyright 2010-2014 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
/// @author Copyright 2014, triagens GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Aql/Optimizer.h"
#include "Aql/OptimizerRules.h"

using namespace triagens::aql;

// -----------------------------------------------------------------------------
// --SECTION--                                               the optimizer class
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
// @brief constructor, this will initialize the rules database
////////////////////////////////////////////////////////////////////////////////

Optimizer::Optimizer () {
  // List all the rules in the system here:

  // try to find sort blocks which are superseeded by indexes
  registerRule (useIndexForSort, 2000);

  // try to find a filter after an enumerate collection and find an index . . .
  registerRule(useIndexRange, 999);

  // remove filters from the query that are not necessary at all
  // filters that are always true will be removed entirely
  // filters that are always false will be replaced with a NoResults node
  registerRule(removeUnnecessaryFiltersRule, 100);

  // move calculations up the dependency chain (to pull them out of inner loops etc.)
  registerRule(moveCalculationsUpRule, 1000);

  // move filters up the dependency chain (to make result sets as small as possible
  // as early as possible)
  registerRule(moveFiltersUpRule, 1010);

  // remove calculations that are never necessary
  registerRule(removeUnnecessaryCalculationsRule, 1020);

  // Now sort them by level:
  std::stable_sort(_rules.begin(), _rules.end());
}

////////////////////////////////////////////////////////////////////////////////
// @brief the actual optimization
////////////////////////////////////////////////////////////////////////////////

int Optimizer::createPlans (ExecutionPlan* plan) {
  int res;
  int leastDoneLevel = 0;
  int maxRuleLevel = _rules.back().level;

  // _plans contains the previous optimisation result
  _plans.clear();
  _plans.push_back(plan, 0);

  int pass = 1;
  while (leastDoneLevel < maxRuleLevel) {
    std::cout << "Entering pass " << pass << " of query optimization..."
              << std::endl;

    // This vector holds the plans we have created in this pass:
    PlanList newPlans;

    // Find variable usage for all old plans now:
    for (auto p : _plans.list) {
      if (! p->varUsageComputed()) {
        p->findVarUsage();
      }
    }

    std::cout << "Have " << _plans.size() << " plans." << std::endl;

    int count = 0;

    // For all current plans:
    while (_plans.size() > 0) {
      int level;
      auto p = _plans.pop_front(level);
      if (level == maxRuleLevel) {
        newPlans.push_back(p, level);  // nothing to do, just keep it
      }
      else {   // some rule needs applying
        Rule r(dummyRule, level);
        auto it = std::upper_bound(_rules.begin(), _rules.end(), r);
        TRI_ASSERT(it != _rules.end());
        std::cout << "Trying rule " << &(it->func) << " with level "
                  << it->level << " on plan " << count++
                  << std::endl;
        try {
          // keep should have a default value so rules that forget to set it
          // have a deterministic behavior
          res = it->func(this, p, it->level, newPlans);
        }
        catch (...) {
          delete p;
          throw;
        }
        if (res != TRI_ERROR_NO_ERROR) {
          return res;
        }
      }
    }
    _plans.steal(newPlans);
    leastDoneLevel = maxRuleLevel;
    for (auto l : _plans.levelDone) {
      if (l < leastDoneLevel) {
        leastDoneLevel = l;
      }
    }
    std::cout << "Least done level is " << leastDoneLevel << std::endl;

    // Stop if the result gets out of hand:
    if (_plans.size() >= maxNumberOfPlans) {
      break;
    }
  }

  estimatePlans();
  sortPlans();
  std::cout << "Optimisation ends with " << _plans.size() << " plans."
            << std::endl;
  std::cout << "Costs:" << std::endl;
  for (auto p : _plans.list) {
    std::cout << p->getCost() << std::endl;
  }

  return TRI_ERROR_NO_ERROR;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief estimatePlans
////////////////////////////////////////////////////////////////////////////////

void Optimizer::estimatePlans () {
  for (auto p : _plans.list) {
    p->getCost();
    // this value is cached in the plan, so formally this step is
    // unnecessary, but for the sake of cleanliness...
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief sortPlans
////////////////////////////////////////////////////////////////////////////////

void Optimizer::sortPlans () {
  std::sort(_plans.list.begin(), _plans.list.end(), [](ExecutionPlan* const& a, ExecutionPlan* const& b) -> bool {
    return a->getCost() < b->getCost();
  });
}

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:

<|endoftext|>


<commit_before>#include "mywindows.h"

myWindows::myWindows(QWidget *parent) :QWidget(parent)
{
    //Getting size of the screen
    QList<QScreen*> screenObj = QGuiApplication::screens();
    screen = screenObj.at(0);
    int sizeCol;
    screenH = screen->geometry().height();
    screenW = screen->geometry().width();
    sizeCol = 150;

    sizePreviewH = 512;
    sizePreviewW = 512;

    int minPrev = screenH-sizeCol;
    if(minPrev < sizePreviewH) {
        sizePreviewH = minPrev;
        sizePreviewW = minPrev;
    }

    isShiftOn = false;
    //Globale layout
    // _____Vlayout______
    // |                |
    // |  ___HLayout___ |
    // | |            | |
    // | |   preview  | |
    // | |            | |
    // | |   file info| |
    // | |____________| |
    // |                |
    // |  column view   |
    // |________________|
    //
    layoutGlobal = new QVBoxLayout;
    layoutGlobal->setAlignment(Qt::AlignCenter);

    //Gloval preview

    preview = new imagePreview(this);

    //Preview file part

    layoutPreview = new QHBoxLayout;

    lab = new QLabel("image ici");
    lab->setMaximumHeight(sizePreviewH-110);
    imDef = QPixmap(":/images/test.png");
    lab->setPixmap(imDef);

    info = new fileInfo;

    //Column view part
    model = new QFileSystemModel(this);
    model->setRootPath(QDir::rootPath());

    model->setReadOnly(false);

    //Loading preferences
    loadSettings();

    columnView = new QColumnView(this);
    columnView->setMinimumHeight(sizeCol);
    columnView->setModel(model);
    //tree->setRootIndex(model->index(QDir::currentPath()));
    columnView->setCurrentIndex(model->index(lastPath));
    //columnView->setRootIndex());
    QItemSelectionModel* itSel = columnView->selectionModel();

    //Adding rename

    QPushButton *rename = new QPushButton("Rename");

    //Keyboard

    //global space shortcut
    shortcutSpace = new QShortcut(QKeySequence(Qt::Key_Space), this);
    shortcutSpace->setContext(Qt::ApplicationShortcut);

    //global enter shortcut
    shortcutEnter = new QShortcut(QKeySequence(Qt::Key_Return), this);
    //shortcutEnter->setContext(Qt::ApplicationShortcut);

    //Global Supr Shortcut
    shortcutDel = new QShortcut(QKeySequence(Qt::Key_Delete), this);
    shortcutDel->setContext(Qt::ApplicationShortcut);

    //Qconnect
    QObject::connect(shortcutSpace,SIGNAL(activated()),this, SLOT(keyboardEvent()));
    QObject::connect(shortcutEnter,SIGNAL(activated()),this, SLOT(keyboardEnter()));
    QObject::connect(shortcutDel,SIGNAL(activated()),this, SLOT(keyboardDel()));
    //Listen to qColumnView click
    //Selection of a file
    QObject::connect(itSel,SIGNAL(currentChanged(QModelIndex,QModelIndex)),this,SLOT(clickedNew(QModelIndex,QModelIndex)));
    QObject::connect(rename,SIGNAL(clicked()),this,SLOT(rename()));

    //Adding
    layoutPreview->addWidget(lab);
    layoutPreview->addWidget(info);
    layoutGlobal->addLayout(layoutPreview);
    layoutGlobal->addWidget(columnView);
    layoutGlobal->addWidget(rename);

    //Get event even if not in front
    eater = new KeyPressEater(this);
    preview->installEventFilter(eater);

    this->setLayout(layoutGlobal);
    this->resize(1024,900);
    this->show();
}

//Update variable last*Path AND if shift is on remember all selected files
void myWindows::updatePath(QModelIndex index){
    lastFilePath = model->filePath(index);
    QFileInfo infoFile(lastFilePath);
    lastPath = infoFile.canonicalPath();
    if (isShiftOn) {
        shiftList.append(lastFilePath);
    }else{
        shiftList.clear();
        shiftList.append(lastFilePath);
    }
}

//The actionb called by the column view when the user do something
void myWindows::clickedNew(QModelIndex index,QModelIndex){
    updatePath(index);
    QString fileName = model->fileName(index);
    QFileInfo infoFile(lastFilePath);
    QString ext = fileName.split(".").back(); //We could use here QFileInfo::completeSuffix()
    int SIZE_NAME_MAX = 50;
    if (fileName.length() > SIZE_NAME_MAX) {
        info->setName(fileName.mid(0,SIZE_NAME_MAX));
    }else{
        info->setName(fileName);
    }
    if (ext.length() == 1 or ext.length() >= 5) {
        info->setType("Not a standard file");
    } else {
        info->setType(ext.toLower());
    }
    info->setSize(model->size(index));
    info->setResolution(0,0);
    //If it's an image we update the previews and the informations
    QString lowExt = ext.toLower();
    if (infoFile.isFile() && isImage(lowExt)) {
        updateImage();
    }else if(infoFile.isDir()) {
        // If there is an image inside we try to show it
        QDir dir = QDir(lastFilePath);
        dir.setFilter(QDir::Files);
        QFileInfoList list = dir.entryInfoList();
        bool found = false;
        for (int i = 0; i < list.size(); ++i) {
            QFileInfo fileInfo = list.at(i);
            lowExt = fileInfo.suffix().toLower();
            if (fileInfo.isFile() && isImage(lowExt)) {
                updateImage(fileInfo.absoluteFilePath());
                found = true;
                break;
            }
        }
        //else we show the default image if no file is an image
        if (!found) {
            lab->setPixmap(imDef);
        }
    } else {
        //else we show the default image
        lab->setPixmap(imDef);
    }
}

bool myWindows::isImage(QString suffix) {
    return (suffix == "jpg" || suffix == "jpeg" || suffix == "png");
}

void myWindows::updateImage(){
    updateImage(lastFilePath);
}

void myWindows::updateImage(QString image){
    lastImagePath = QString(image); // For later in case of fullscreen
    QPixmap imtmp(image);
    QPixmap imtmp2 = imtmp.scaledToHeight(sizePreviewH, Qt::SmoothTransformation);
    if (imtmp2.width() > sizePreviewW) {
        lab->setPixmap(imtmp2.copy(0,0,sizePreviewW,sizePreviewH));
    }else{
        lab->setPixmap(imtmp2);
    }
    info->setResolution(imtmp.width(),imtmp.height());
    preview->updateImage(imtmp);
}

//Function to watch the global shortcut SPACE that is for showing preview
void myWindows::keyboardEvent(){
    //qDebug() << "SPACE ";
    if (preview->showing) {
        preview->hidePreview();
    } else {
        if (lastImagePath != NULL) {
            preview->showImage(lastImagePath);
            preview->activateWindow();
        }
    }
}

//Function to watch the global shortcut SPACE that is for opening the file with default app
void myWindows::keyboardEnter(){
    //qDebug() << "ENTER ";
    QDesktopServices::openUrl(QUrl::fromLocalFile(lastFilePath));
}

//Debug funtion to show all keyboard event
void myWindows::keyPressEvent(QKeyEvent* event) {
    if (event->key() == Qt::Key_Shift) {
        //qDebug() << "Key Shift";
        isShiftOn = true;
    }
}

void myWindows::rename(){
    bool ok;
    QString text = QInputDialog::getText(this, tr("Renamming"), tr("base name:"), QLineEdit::Normal,"", &ok);
    int num = 0;
    if (ok){
        for (int var = 0; var < shiftList.length(); ++var) {
            _rename(shiftList.at(var),text,&num);
        }
    }
}

void myWindows::_rename(QString path, QString newName,int *num){
    QFileInfo tmp(path);
    if (tmp.isFile()) {
        QFile file(path);
        QString newConstructedName = tmp.canonicalPath()+QDir::separator()+newName;
        //If the name if something XXX-01 else 01
        if (newName != "") {
            newConstructedName += "-";
        }
        if (*num >= 10) {
            if (*num < 100) {
                newConstructedName += QString("0");
            }
        } else {
            newConstructedName += QString("00");
        }
        newConstructedName += QString::number(*num);
        //if the file had an extension we keep it else nothing
        // prev.jpg -> XXX-01.jpg
        if (tmp.completeSuffix() != "") {
            newConstructedName += "."+tmp.completeSuffix();
        }
        file.rename(newConstructedName);
        *num = *num + 1;
    } else if (tmp.isDir()){
        //If we have a dir we get folders and files inside and try to rename them
        QDir fold(path);
        QStringList elmts = fold.entryList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files);
        for (int var = 0; var < elmts.length(); ++var) {
            _rename(path+QDir::separator()+elmts.at(var), newName ,num);
        }
    }
}

void myWindows::keyReleaseEvent(QKeyEvent* event)
{
    if (event->key() == Qt::Key_Shift) {
        //qDebug() <<"You Release Key " <<event->text();
        isShiftOn = false;
    }
}

void myWindows::loadSettings(){
    QSettings settings("IntCorpLightAssociation", "FileViewer");
    lastPath = settings.value("lastPath").toString();
}
void myWindows::saveSettings(){
    QSettings settings("IntCorpLightAssociation", "FileViewer");
    settings.setValue("lastPath", lastPath);
}

void myWindows::keyboardDel(){
    QMessageBox box;
    box.setText("Selected files/folders will be eternally deleted !!");
    box.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    box.setWindowFlags(Qt::WindowStaysOnTopHint);
    box.setDefaultButton(QMessageBox::Ok);
    int ret = box.exec();
    if (ret == QMessageBox::Ok) {
        //qDebug() << "BIM ";
        for (int i = 0; i < shiftList.length(); ++i) {
            //qDebug() << "DELETE" << shiftList.at(i);
            QFileInfo tmp(shiftList.at(i));
            if (tmp.isFile()) {
                QFile file(shiftList.at(i));
                if (!file.remove()) {
                    qDebug()<<"File not deleted: "<<file.fileName();
                }
            } else {
                QDir folder(shiftList.at(i));
                if (!folder.removeRecursively()) {
                    qDebug()<<"Not all was deleted: "<<folder.absolutePath();
                }
            }
        }
        //qDebug() << "";
    }
}

//To add coloration to folders/files
//http://stackoverflow.com/questions/1397484/custom-text-color-for-certain-indexes-in-qtreeview

//When the app is closed we saved what is necessary to save
void myWindows::closeEvent(QCloseEvent*){
    saveSettings();
}

myWindows::~myWindows(){
    delete eater;
}
<commit_msg>Little fix<commit_after>#include "mywindows.h"

myWindows::myWindows(QWidget *parent) :QWidget(parent)
{
    //Getting size of the screen
    QList<QScreen*> screenObj = QGuiApplication::screens();
    screen = screenObj.at(0);
    int sizeCol;
    screenH = screen->geometry().height();
    screenW = screen->geometry().width();
    sizeCol = 150;

    sizePreviewH = 512;
    sizePreviewW = 512;

    int minPrev = screenH-sizeCol;
    if(minPrev < sizePreviewH) {
        sizePreviewH = minPrev;
        sizePreviewW = minPrev;
    }

    isShiftOn = false;
    //Globale layout
    // _____Vlayout______
    // |                |
    // |  ___HLayout___ |
    // | |            | |
    // | |   preview  | |
    // | |            | |
    // | |   file info| |
    // | |____________| |
    // |                |
    // |  column view   |
    // |________________|
    //
    layoutGlobal = new QVBoxLayout;
    layoutGlobal->setAlignment(Qt::AlignCenter);

    //Gloval preview

    preview = new imagePreview(this);

    //Preview file part

    layoutPreview = new QHBoxLayout;

    lab = new QLabel("image ici");
    lab->setMaximumHeight(sizePreviewH-110);
    imDef = QPixmap(":/images/test.png");
    lab->setPixmap(imDef);

    info = new fileInfo;

    //Column view part
    model = new QFileSystemModel(this);
    model->setRootPath(QDir::rootPath());

    model->setReadOnly(false);

    //Loading preferences
    loadSettings();

    columnView = new QColumnView(this);
    columnView->setMinimumHeight(sizeCol);
    columnView->setModel(model);
    //tree->setRootIndex(model->index(QDir::currentPath()));
    columnView->setCurrentIndex(model->index(lastPath));
    //columnView->setRootIndex());
    QItemSelectionModel* itSel = columnView->selectionModel();

    //Adding rename

    QPushButton *rename = new QPushButton("Rename");

    //Keyboard

    //global space shortcut
    shortcutSpace = new QShortcut(QKeySequence(Qt::Key_Space), this);
    shortcutSpace->setContext(Qt::ApplicationShortcut);

    //global enter shortcut
    shortcutEnter = new QShortcut(QKeySequence(Qt::Key_Return), this);
    //shortcutEnter->setContext(Qt::ApplicationShortcut);

    //Global Supr Shortcut
    shortcutDel = new QShortcut(QKeySequence(Qt::Key_Delete), this);
    shortcutDel->setContext(Qt::ApplicationShortcut);

    //Qconnect
    QObject::connect(shortcutSpace,SIGNAL(activated()),this, SLOT(keyboardEvent()));
    QObject::connect(shortcutEnter,SIGNAL(activated()),this, SLOT(keyboardEnter()));
    QObject::connect(shortcutDel,SIGNAL(activated()),this, SLOT(keyboardDel()));
    //Listen to qColumnView click
    //Selection of a file
    QObject::connect(itSel,SIGNAL(currentChanged(QModelIndex,QModelIndex)),this,SLOT(clickedNew(QModelIndex,QModelIndex)));
    QObject::connect(rename,SIGNAL(clicked()),this,SLOT(rename()));

    //Adding
    layoutPreview->addWidget(lab);
    layoutPreview->addWidget(info);
    layoutGlobal->addLayout(layoutPreview);
    layoutGlobal->addWidget(columnView);
    layoutGlobal->addWidget(rename);

    //Get event even if not in front
    eater = new KeyPressEater(this);
    preview->installEventFilter(eater);

    this->setLayout(layoutGlobal);
    this->resize(1024,900);
    this->show();
}

//Update variable last*Path AND if shift is on remember all selected files
void myWindows::updatePath(QModelIndex index){
    lastFilePath = model->filePath(index);
    QFileInfo infoFile(lastFilePath);
    lastPath = infoFile.canonicalPath();
    if (isShiftOn) {
        shiftList.append(lastFilePath);
    }else{
        shiftList.clear();
        shiftList.append(lastFilePath);
    }
}

//The actionb called by the column view when the user do something
void myWindows::clickedNew(QModelIndex index,QModelIndex){
    updatePath(index);
    QString fileName = model->fileName(index);
    QFileInfo infoFile(lastFilePath);
    QString ext = fileName.split(".").back(); //We could use here QFileInfo::completeSuffix()
    int SIZE_NAME_MAX = 50;
    if (fileName.length() > SIZE_NAME_MAX) {
        info->setName(fileName.mid(0,SIZE_NAME_MAX));
    }else{
        info->setName(fileName);
    }
    if (ext.length() == 1 or ext.length() >= 5) {
        info->setType("Not a standard file");
    } else {
        info->setType(ext.toLower());
    }
    info->setSize(model->size(index));
    info->setResolution(0,0);
    //If it's an image we update the previews and the informations
    QString lowExt = ext.toLower();
    if (infoFile.isFile() && isImage(lowExt)) {
        updateImage();
    }else if(infoFile.isDir()) {
        // If there is an image inside we try to show it
        QDir dir = QDir(lastFilePath);
        dir.setFilter(QDir::Files);
        QFileInfoList list = dir.entryInfoList();
        bool found = false;
        for (int i = 0; i < list.size(); ++i) {
            QFileInfo fileInfo = list.at(i);
            lowExt = fileInfo.suffix().toLower();
            if (fileInfo.isFile() && isImage(lowExt)) {
                updateImage(fileInfo.absoluteFilePath());
                found = true;
                break;
            }
        }
        //else we show the default image if no file is an image
        if (!found) {
            lab->setPixmap(imDef);
        }
    } else {
        //else we show the default image
        lab->setPixmap(imDef);
    }
}

bool myWindows::isImage(QString suffix) {
    return (suffix == "jpg" || suffix == "jpeg" || suffix == "png");
}

void myWindows::updateImage(){
    updateImage(lastFilePath);
}

void myWindows::updateImage(QString image){
    lastImagePath = QString(image); // For later in case of fullscreen
    QPixmap imtmp(image);
    if (imtmp.isNull()) { // in the case someone give a bad extension (png instead of jpg)...
        imtmp = imDef;
    }
    QPixmap imtmp2 = imtmp.scaledToHeight(sizePreviewH, Qt::SmoothTransformation);

    if (imtmp2.width() > sizePreviewW) {
        lab->setPixmap(imtmp2.copy(0,0,sizePreviewW,sizePreviewH));
    }else{
        lab->setPixmap(imtmp2);
    }
    info->setResolution(imtmp.width(),imtmp.height());
    preview->updateImage(imtmp);
}

//Function to watch the global shortcut SPACE that is for showing preview
void myWindows::keyboardEvent(){
    //qDebug() << "SPACE ";
    if (preview->showing) {
        preview->hidePreview();
    } else {
        if (lastImagePath != NULL) {
            preview->showImage(lastImagePath);
            preview->activateWindow();
        }
    }
}

//Function to watch the global shortcut SPACE that is for opening the file with default app
void myWindows::keyboardEnter(){
    //qDebug() << "ENTER ";
    QDesktopServices::openUrl(QUrl::fromLocalFile(lastFilePath));
}

//Debug funtion to show all keyboard event
void myWindows::keyPressEvent(QKeyEvent* event) {
    if (event->key() == Qt::Key_Shift) {
        //qDebug() << "Key Shift";
        isShiftOn = true;
    }
}

void myWindows::rename(){
    bool ok;
    QString text = QInputDialog::getText(this, tr("Renamming"), tr("base name:"), QLineEdit::Normal,"", &ok);
    int num = 0;
    if (ok){
        for (int var = 0; var < shiftList.length(); ++var) {
            _rename(shiftList.at(var),text,&num);
        }
    }
}

void myWindows::_rename(QString path, QString newName,int *num){
    QFileInfo tmp(path);
    if (tmp.isFile()) {
        QFile file(path);
        QString newConstructedName = tmp.canonicalPath()+QDir::separator()+newName;
        //If the name if something XXX-01 else 01
        if (newName != "") {
            newConstructedName += "-";
        }
        if (*num >= 10) {
            if (*num < 100) {
                newConstructedName += QString("0");
            }
        } else {
            newConstructedName += QString("00");
        }
        newConstructedName += QString::number(*num);
        //if the file had an extension we keep it else nothing
        // prev.jpg -> XXX-01.jpg
        if (tmp.completeSuffix() != "") {
            newConstructedName += "."+tmp.completeSuffix();
        }
        file.rename(newConstructedName);
        *num = *num + 1;
    } else if (tmp.isDir()){
        //If we have a dir we get folders and files inside and try to rename them
        QDir fold(path);
        QStringList elmts = fold.entryList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files);
        for (int var = 0; var < elmts.length(); ++var) {
            _rename(path+QDir::separator()+elmts.at(var), newName ,num);
        }
    }
}

void myWindows::keyReleaseEvent(QKeyEvent* event)
{
    if (event->key() == Qt::Key_Shift) {
        //qDebug() <<"You Release Key " <<event->text();
        isShiftOn = false;
    }
}

void myWindows::loadSettings(){
    QSettings settings("IntCorpLightAssociation", "FileViewer");
    lastPath = settings.value("lastPath").toString();
}
void myWindows::saveSettings(){
    QSettings settings("IntCorpLightAssociation", "FileViewer");
    settings.setValue("lastPath", lastPath);
}

void myWindows::keyboardDel(){
    QMessageBox box;
    box.setText("Selected files/folders will be eternally deleted !!");
    box.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
    box.setWindowFlags(Qt::WindowStaysOnTopHint);
    box.setDefaultButton(QMessageBox::Ok);
    int ret = box.exec();
    if (ret == QMessageBox::Ok) {
        //qDebug() << "BIM ";
        for (int i = 0; i < shiftList.length(); ++i) {
            //qDebug() << "DELETE" << shiftList.at(i);
            QFileInfo tmp(shiftList.at(i));
            if (tmp.isFile()) {
                QFile file(shiftList.at(i));
                if (!file.remove()) {
                    qDebug()<<"File not deleted: "<<file.fileName();
                }
            } else {
                QDir folder(shiftList.at(i));
                if (!folder.removeRecursively()) {
                    qDebug()<<"Not all was deleted: "<<folder.absolutePath();
                }
            }
        }
        //qDebug() << "";
    }
}

//To add coloration to folders/files
//http://stackoverflow.com/questions/1397484/custom-text-color-for-certain-indexes-in-qtreeview

//When the app is closed we saved what is necessary to save
void myWindows::closeEvent(QCloseEvent*){
    saveSettings();
}

myWindows::~myWindows(){
    delete eater;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include "src/Options.hpp"
#include "src/Cluster.hpp"

using namespace std;
int main(int argc, char *argv[]){

    /* data printed into */
    string path2data = "../data/";
    /* material constants */
    double young_modulus = 10000;
    double poissons_ratio = 0.3;
    /* linear solver */
    double pardiso_0_dissection_1 = 0;
    int print_matrices = 0;
    int typeBc = 0;    // 0 - corners, 2 - all  (1 reserved for 'null-space case')

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

    cout << argv[0] << endl;
    Options options;
    options.set_values(path2data, argc, argv,
                        young_modulus, poissons_ratio,
                        pardiso_0_dissection_1,print_matrices,typeBc);
    Cluster cluster(options);
    cout << "----------------- done -----------------\n" ;
    return 0;
}
<commit_msg>dissection preset as tool for factorization<commit_after>#include <iostream>
#include <string>
#include "src/Options.hpp"
#include "src/Cluster.hpp"

using namespace std;
int main(int argc, char *argv[]){

    /* data printed into */
    string path2data = "../data/";
    /* material constants */
    double young_modulus = 10000;
    double poissons_ratio = 0.3;
    /* linear solver */
    double pardiso_0_dissection_1 = 1;
    int print_matrices = 0;
    int typeBc = 0;    // 0 - corners, 2 - all  (1 reserved for 'null-space case')

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

    cout << argv[0] << endl;
    Options options;
    options.set_values(path2data, argc, argv,
                        young_modulus, poissons_ratio,
                        pardiso_0_dissection_1,print_matrices,typeBc);
    Cluster cluster(options);
    cout << "----------------- done -----------------\n" ;
    return 0;
}
<|endoftext|>


<commit_before>#include "main.h"
#include "Robot.h"
#include <QApplication>

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

	(void)argc; // avoid unused variable warnings

	/*
	 * Our display window
	 * This has a trackbar at the top to select views
	 */
	cvNamedWindow("display", 0);

	/*
	 * Start robot main loop in a thread
	 * (do vision processing, sensors, and drive control)
	 */
	char* input = (argc > 1) ? argv[1] : NULL;
	Robot r(input);
	r.startRobotThread(&r); // this doesn't return

	return 0;
}

<commit_msg><commit_after>#include "main.h"
#include "Robot.h"
#include <QApplication>

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

	(void)argc; // avoid unused variable warnings

	/*
	 * Our display window
	 * This has a trackbar at the top to select views
	 */
	cvNamedWindow("display", 0);

	/*
	 * Start robot main loop in a thread
	 * (do vision processing, sensors, and drive control)
	 */
	//char* input = (argc > 1) ? argv[1] : NULL
	Robot r(argv[1]);
	r.startRobotThread(&r); // this doesn't return

	return 0;
}

<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: CompositeIteratorTraits_test.C,v 1.1 2003/06/19 10:45:51 oliver Exp $
//

#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/CONCEPT/composite.h>
#include <BALL/KERNEL/iterator.h>
#include <BALL/CONCEPT/predicate.h>

///////////////////////////

using namespace BALL;

class MyPred
	:	public UnaryPredicate<Composite>
{
	public:
	MyPred(const Composite& my_comp)
		:	composite_(&my_comp)
	{
	}

	virtual bool operator () (const Composite& composite) const throw()
	{
		return (&composite == composite_);
	}

	const Composite* composite_;
};

class True
	:	public UnaryPredicate<Composite>
{
	public:
	virtual bool operator () (const Composite&) const throw() { return true; }
};

START_TEST(CompositeIteratorTraits, "$Id: CompositeIteratorTraits_test.C,v 1.1 2003/06/19 10:45:51 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

CompositeIteratorTraits* cit_ptr = 0;
CHECK(CompositeIteratorTraits() throw())
	cit_ptr = new CompositeIteratorTraits;
	TEST_NOT_EQUAL(cit_ptr, 0)
RESULT

CHECK(~CompositeIteratorTraits() throw())
	delete cit_ptr;
RESULT

CHECK(Composite* getContainer() throw())
	CompositeIteratorTraits t;
	TEST_EQUAL(t.getContainer(), 0)
RESULT

Composite a;
Composite b;
Composite c;
Composite d;
Composite e;
Composite f;
a.appendChild(b);
a.appendChild(c);
a.appendChild(d);
c.appendChild(e);
c.appendChild(f);

CHECK(CompositeIteratorTraits(const Composite& composite) throw())
	CompositeIteratorTraits t(a);
	TEST_EQUAL(t.getContainer(), &a)
	MyPred p(c);

	TEST_EQUAL(p(a), false)
	TEST_EQUAL(p(b), false)
	TEST_EQUAL(p(c), true)
	TEST_EQUAL(p(d), false)
	TEST_EQUAL(p(e), false)
	TEST_EQUAL(p(f), false)

	STATUS(" &a = " << (void*)&a)
	STATUS(" &b = " << (void*)&b)
	STATUS(" &c = " << (void*)&c)
	STATUS(" &d = " << (void*)&d)
	STATUS(" &e = " << (void*)&e)
	STATUS(" &f = " << (void*)&f)

	t.setPredicate(p);
	t.toBegin();
	TEST_EQUAL(t.isValid(), true)
	TEST_EQUAL(&t.getData(), &c)
	t.forward();
	TEST_EQUAL(t.isValid(), false)
	TEST_EQUAL(&t.getData(), 0)
	TEST_EQUAL(t.getPredicate(), &p)
	TEST_EQUAL(t.isEnd(), true)
RESULT

CHECK(Composite& getData() throw())
  // ???
RESULT

CHECK(Composite::SubcompositeIterator& getPosition() throw())
  // ???
RESULT

CHECK(CompositeIteratorTraits& operator = (const CompositeIteratorTraits& traits) throw())
  // ???
RESULT

CHECK(CompositeIteratorTraits(const CompositeIteratorTraits& traits) throw())
  // ???
RESULT

CHECK(void toBegin() throw(Exception::Precondition))
  // ???
RESULT

CHECK(void toEnd() throw(Exception::Precondition))
  // ???
RESULT

CHECK(bool isBegin() const throw())
	CompositeIteratorTraits t(a);
	TEST_EQUAL(t.getContainer(), &a)
	MyPred p(c);
	t.setPredicate(p);

	t.toBegin();
	TEST_EQUAL(t.isBegin(), true)
	t.forward();
	TEST_EQUAL(t.isBegin(), false)
RESULT

CHECK(bool isEnd() const throw())
	CompositeIteratorTraits t(a);
	TEST_EQUAL(t.getContainer(), &a)
	MyPred p(c);
	t.setPredicate(p);

	t.toBegin();
	TEST_EQUAL(t.isEnd(), false)
	TEST_EQUAL(t.isBegin(), true)
	t.toEnd();
	TEST_EQUAL(t.isEnd(), true)
	TEST_EQUAL(t.isBegin(), false)

	True my_true;
	t.setPredicate(my_true);
	t.toBegin();
	TEST_EQUAL(t.isEnd(), false)
	TEST_EQUAL(t.isBegin(), true)
	t.toEnd();
	TEST_EQUAL(t.isEnd(), true)
	TEST_EQUAL(t.isBegin(), false)

	Composite empty;
	t = CompositeIteratorTraits(empty);
	t.setPredicate(my_true);
	t.toBegin();
	TEST_EQUAL(t.isEnd(), false)
	TEST_EQUAL(t.isBegin(), true)
	t.forward();
	TEST_EQUAL(t.isEnd(), true)
	TEST_EQUAL(t.isBegin(), false)
	t.backward();
	TEST_EQUAL(t.isEnd(), false)
	TEST_EQUAL(t.isBegin(), true)
RESULT

CHECK(bool isRBegin() const throw())
  // ???
RESULT

CHECK(bool isREnd() const throw())
  // ???
RESULT

CHECK(bool isSingular() const throw())
  // ???
RESULT

CHECK(bool isValid() const throw())
  // ???
RESULT

CHECK(bool operator != (const CompositeIteratorTraits& traits) const throw())
  // ???
RESULT

CHECK(bool operator == (const CompositeIteratorTraits& traits) const throw())
  // ???
RESULT

CHECK(const Composite& getData() const throw())
  // ???
RESULT

CHECK(const Composite* getContainer() const throw())
  // ???
RESULT

CHECK(const Composite::SubcompositeIterator& getPosition() const throw())
  // ???
RESULT

CHECK(const UnaryPredicate<Composite>* getPredicate() const throw())
  // ???
RESULT

CHECK(void backward() throw())
  // ???
RESULT

CHECK(void forward() throw())
  // ???
RESULT

CHECK(void invalidate() throw())
  // ???
RESULT

CHECK(void setPredicate(const UnaryPredicate<Composite>& predicate) throw())
  // ???
RESULT

CHECK(void toRBegin() throw(Exception::Precondition))
  // ???
RESULT

CHECK(void toREnd() throw(Exception::Precondition))
  // ???
RESULT

CHECK([EXTRA] Iteration)
	Composite ac1;
	Composite ac2;
	ac1.appendChild(ac2);
	Composite a1;
	Composite a2;
	ac2.appendChild(a1);
	ac1.appendChild(a2);
	True my_true;

	STATUS(" ac1 = " << &ac1)
	STATUS(" ac2 = " << &ac2)
	STATUS(" a1  = " << &a1)
	STATUS(" a2  = " << &a2)

	CompositeIteratorTraits t1(ac1);
	t1.setPredicate(my_true);
	t1.toBegin();
	while (!t1.isEnd())
	{
		TEST_EQUAL((ac1.isAncestorOf(t1.getData()) || (&t1.getData() == &ac1)), true)
		STATUS(" - " << &t1.getData())
		t1.forward();
	}

	CompositeIteratorTraits t2(ac2);
	t2.setPredicate(my_true);
	t2.toBegin();
	while (!t2.isEnd())
	{
		STATUS(" - " << &t2.getData())
		TEST_EQUAL((ac2.isAncestorOf(t2.getData()) || (&t2.getData() == &ac2)), true)
		t2.forward();
	}

	Composite single;
	CompositeIteratorTraits t3(single);
	t3.setPredicate(my_true);
	t3.toBegin();
	TEST_EQUAL(t3.isBegin(), true)
	TEST_EQUAL(t3.isEnd(), false)
	TEST_EQUAL(t3.isValid(), true)
	TEST_EQUAL(t3.isSingular(), false)
	TEST_EQUAL(&t3.getData(), &single)
	t3.forward();
	TEST_EQUAL(t3.isEnd(), true)
	TEST_EQUAL(t3.isBegin(), false)
	TEST_EQUAL(t3.isValid(), false)
	TEST_EQUAL(t3.isSingular(), false)
	TEST_EQUAL(&t3.getData(), 0)

	Composite root;
	root.appendChild(single);
	CompositeIteratorTraits t4(single);
	t4.setPredicate(my_true);
	t4.toBegin();
	TEST_EQUAL(t4.isBegin(), true)
	TEST_EQUAL(t4.isEnd(), false)
	TEST_EQUAL(t4.isValid(), true)
	TEST_EQUAL(t4.isSingular(), false)
	TEST_EQUAL(&t4.getData(), &single)
	t4.forward();
	TEST_EQUAL(t4.isEnd(), true)
	TEST_EQUAL(t4.isBegin(), false)
	TEST_EQUAL(t4.isValid(), false)
	TEST_EQUAL(t4.isSingular(), false)
	TEST_EQUAL(&t4.getData(), 0)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

END_TEST

<commit_msg>added tests<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: CompositeIteratorTraits_test.C,v 1.2 2004/02/24 18:37:39 anker Exp $
//

#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/CONCEPT/composite.h>
#include <BALL/KERNEL/iterator.h>
#include <BALL/CONCEPT/predicate.h>
#include <BALL/KERNEL/standardPredicates.h>

///////////////////////////

using namespace BALL;

class MyPred
	:	public UnaryPredicate<Composite>
{
	public:
	MyPred(const Composite& my_comp)
		:	composite_(&my_comp)
	{
	}

	virtual bool operator () (const Composite& composite) const throw()
	{
		return (&composite == composite_);
	}

	const Composite* composite_;
};

class True
	:	public UnaryPredicate<Composite>
{
	public:
	virtual bool operator () (const Composite&) const throw() { return true; }
};

START_TEST(CompositeIteratorTraits, "$Id: CompositeIteratorTraits_test.C,v 1.2 2004/02/24 18:37:39 anker Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

CompositeIteratorTraits* cit_ptr = 0;
CHECK(CompositeIteratorTraits() throw())
	cit_ptr = new CompositeIteratorTraits;
	TEST_NOT_EQUAL(cit_ptr, 0)
RESULT

CHECK(~CompositeIteratorTraits() throw())
	delete cit_ptr;
RESULT

CHECK(Composite* getContainer() throw())
	CompositeIteratorTraits t;
	TEST_EQUAL(t.getContainer(), 0)
RESULT

Composite a;
Composite b;
Composite c;
Composite d;
Composite e;
Composite f;
a.appendChild(b);
a.appendChild(c);
a.appendChild(d);
c.appendChild(e);
c.appendChild(f);

CHECK(CompositeIteratorTraits(const Composite& composite) throw())
	CompositeIteratorTraits t(a);
	TEST_EQUAL(t.getContainer(), &a)
	MyPred p(c);

	TEST_EQUAL(p(a), false)
	TEST_EQUAL(p(b), false)
	TEST_EQUAL(p(c), true)
	TEST_EQUAL(p(d), false)
	TEST_EQUAL(p(e), false)
	TEST_EQUAL(p(f), false)

	STATUS(" &a = " << (void*)&a)
	STATUS(" &b = " << (void*)&b)
	STATUS(" &c = " << (void*)&c)
	STATUS(" &d = " << (void*)&d)
	STATUS(" &e = " << (void*)&e)
	STATUS(" &f = " << (void*)&f)

	t.setPredicate(p);
	t.toBegin();
	TEST_EQUAL(t.isValid(), true)
	TEST_EQUAL(&t.getData(), &c)
	t.forward();
	TEST_EQUAL(t.isValid(), false)
	TEST_EQUAL(&t.getData(), 0)
	TEST_EQUAL(t.getPredicate(), &p)
	TEST_EQUAL(t.isEnd(), true)
RESULT

CHECK(Composite& getData() throw())
	CompositeIteratorTraits cit(a);
	Composite* composite = &cit.getData();
	TEST_EQUAL((composite == &a), true)
RESULT

CHECK(Composite::CompositeIterator& getPosition() throw())
	CompositeIteratorTraits cit(a);
	Composite* composite = &cit.getData();
	TEST_EQUAL((composite == &a), true)
RESULT

CHECK(CompositeIteratorTraits& operator = (const CompositeIteratorTraits& traits) throw())
	CompositeIteratorTraits cit1(a);
	CompositeIteratorTraits cit2;
	cit2 = cit1;
	TEST_EQUAL((cit1 == cit2), true)
RESULT

CHECK(CompositeIteratorTraits(const CompositeIteratorTraits& traits) throw())
	CompositeIteratorTraits cit1(a);
	CompositeIteratorTraits cit2(cit1);
	TEST_EQUAL((cit1 == cit2), true)
RESULT

CHECK(void toBegin() throw(Exception::Precondition))
	CompositeIteratorTraits cit(a);
	MyPred p(c);
	cit.setPredicate(p);
	cit.forward();
	TEST_EQUAL((&cit.getData() == &c), true)
	cit.toBegin();
	TEST_EQUAL((&cit.getData() == &c), true)
RESULT

CHECK(void toEnd() throw(Exception::Precondition))
	CompositeIteratorTraits cit(a);
	cit.toEnd();
	// TEST_EQUAL((BLUBB == &f), true)
RESULT

CHECK(bool isBegin() const throw())
	CompositeIteratorTraits t(a);
	TEST_EQUAL(t.getContainer(), &a)
	MyPred p(c);
	t.setPredicate(p);

	t.toBegin();
	TEST_EQUAL(t.isBegin(), true)
	t.forward();
	TEST_EQUAL(t.isBegin(), false)
RESULT

CHECK(bool isEnd() const throw())
	CompositeIteratorTraits t(a);
	TEST_EQUAL(t.getContainer(), &a)
	MyPred p(c);
	t.setPredicate(p);

	t.toBegin();
	TEST_EQUAL(t.isEnd(), false)
	TEST_EQUAL(t.isBegin(), true)
	t.toEnd();
	TEST_EQUAL(t.isEnd(), true)
	TEST_EQUAL(t.isBegin(), false)

	True my_true;
	t.setPredicate(my_true);
	t.toBegin();
	TEST_EQUAL(t.isEnd(), false)
	TEST_EQUAL(t.isBegin(), true)
	t.toEnd();
	TEST_EQUAL(t.isEnd(), true)
	TEST_EQUAL(t.isBegin(), false)

	Composite empty;
	t = CompositeIteratorTraits(empty);
	t.setPredicate(my_true);
	t.toBegin();
	TEST_EQUAL(t.isEnd(), false)
	TEST_EQUAL(t.isBegin(), true)
	t.forward();
	TEST_EQUAL(t.isEnd(), true)
	TEST_EQUAL(t.isBegin(), false)
	t.backward();
	TEST_EQUAL(t.isEnd(), false)
	TEST_EQUAL(t.isBegin(), true)
RESULT

CHECK(bool isRBegin() const throw())
	CompositeIteratorTraits cit(a);
	MyPred p(c);
	cit.setPredicate(p);
	TEST_EQUAL(cit.isRBegin(), false)
	cit.toRBegin();
	TEST_EQUAL(cit.isRBegin(), true)
RESULT

CHECK(bool isREnd() const throw())
	CompositeIteratorTraits cit(a);
	True tp;
	cit.setPredicate(tp);
	cit.forward();
	TEST_EQUAL(cit.isREnd(), false)
	cit.toREnd();
	TEST_EQUAL(cit.isREnd(), true)
RESULT

CHECK(bool isSingular() const throw())
	CompositeIteratorTraits cit1;
	TEST_EQUAL(cit1.isSingular(), true)
	CompositeIteratorTraits cit2(a);
	TEST_EQUAL(cit2.isSingular(), false)
RESULT

CHECK(bool isValid() const throw())
	CompositeIteratorTraits cit1;
	TEST_EQUAL(cit1.isValid(), false)
	CompositeIteratorTraits cit2(a);
	TEST_EQUAL(cit2.isValid(), true)
RESULT

CHECK(bool operator != (const CompositeIteratorTraits& traits) const throw())
	CompositeIteratorTraits cit1(a);
	True tp;
	cit1.setPredicate(tp);
	CompositeIteratorTraits cit2;
	cit2.setPredicate(tp);
	TEST_EQUAL((cit1 != cit2), true)
	CompositeIteratorTraits cit3(a);
	cit3.setPredicate(tp);
	TEST_EQUAL((cit1 != cit3), false)
RESULT

CHECK(bool operator == (const CompositeIteratorTraits& traits) const throw())
	CompositeIteratorTraits cit1(a);
	True tp;
	cit1.setPredicate(tp);
	CompositeIteratorTraits cit2;
	cit2.setPredicate(tp);
	TEST_EQUAL((cit1 == cit2), false)
	CompositeIteratorTraits cit3(a);
	cit3.setPredicate(tp);
	TEST_EQUAL((cit1 == cit3), true)
RESULT

CHECK(const Composite& getData() const throw())
	CompositeIteratorTraits cit(a);
	const Composite& composite = cit.getData();
	TEST_EQUAL((&composite == &a), true)
RESULT

CHECK(const Composite* getContainer() const throw())
	CompositeIteratorTraits t;
	const Composite* composite_const_ptr = t.getContainer();
	TEST_EQUAL(composite_const_ptr, 0)
RESULT

CHECK(const Composite::CompositeIterator& getPosition() const throw())
	CompositeIteratorTraits cit(a);
	const Composite* composite_const_ptr = &cit.getData();
	TEST_EQUAL((composite_const_ptr == &a), true)
RESULT

CHECK(const UnaryPredicate<Composite>* getPredicate() const throw())
	CompositeIteratorTraits cit(a);
	True tp;
	cit.setPredicate(tp);
	const UnaryPredicate<Composite>* predicate_const_ptr = cit.getPredicate();
	TEST_EQUAL(predicate_const_ptr, &tp)
RESULT

CHECK(void backward() throw())
	CompositeIteratorTraits cit(a);
	True tp;
	cit.setPredicate(tp);
	TEST_EQUAL((&cit.getData() == &a), true)
	cit.toRBegin();
	cit.backward();
	TEST_EQUAL((&cit.getData() == &f), true)
RESULT

CHECK(void forward() throw())
	CompositeIteratorTraits cit(a);
	True tp;
	cit.setPredicate(tp);
	TEST_EQUAL((&cit.getData() == &a), true)
	cit.forward();
	TEST_EQUAL((&cit.getData() == &b), true)
	MyPred f_predicate(f);
	cit.setPredicate(f_predicate);
	cit.forward();
	TEST_EQUAL((&cit.getData() == &f), true)
RESULT

CHECK(void invalidate() throw())
	CompositeIteratorTraits cit(a);
	True tp;
	cit.setPredicate(tp);
	TEST_EQUAL(cit.isValid(), true)
	cit.invalidate();
	TEST_EQUAL(cit.isValid(), false)
RESULT

CHECK(void setPredicate(const UnaryPredicate<Composite>& predicate) throw())
	CompositeIteratorTraits cit(a);
	MyPred c_predicate(c);
	cit.setPredicate(c_predicate);
	TEST_EQUAL(cit.getPredicate(), &c_predicate)
RESULT

CHECK(void toRBegin() throw(Exception::Precondition))
  CompositeIteratorTraits cit(a);
	True tp;
	cit.setPredicate(tp);
	TEST_EQUAL(cit.isRBegin(), false)
	cit.toRBegin();
	TEST_EQUAL(cit.isRBegin(), true)
RESULT

CHECK(void toREnd() throw(Exception::Precondition))
  CompositeIteratorTraits cit(a);
	True tp;
	cit.setPredicate(tp);
	TEST_EQUAL(cit.isREnd(), true)
	cit.forward();
	TEST_EQUAL(cit.isREnd(), false)
	cit.toREnd();
	TEST_EQUAL(cit.isREnd(), true)
RESULT

CHECK([EXTRA] Iteration)
	Composite ac1;
	Composite ac2;
	ac1.appendChild(ac2);
	Composite a1;
	Composite a2;
	ac2.appendChild(a1);
	ac1.appendChild(a2);
	True my_true;

	STATUS(" ac1 = " << &ac1)
	STATUS(" ac2 = " << &ac2)
	STATUS(" a1  = " << &a1)
	STATUS(" a2  = " << &a2)

	CompositeIteratorTraits t1(ac1);
	t1.setPredicate(my_true);
	t1.toBegin();
	while (!t1.isEnd())
	{
		TEST_EQUAL((ac1.isAncestorOf(t1.getData()) || (&t1.getData() == &ac1)), true)
		STATUS(" - " << &t1.getData())
		t1.forward();
	}

	CompositeIteratorTraits t2(ac2);
	t2.setPredicate(my_true);
	t2.toBegin();
	while (!t2.isEnd())
	{
		STATUS(" - " << &t2.getData())
		TEST_EQUAL((ac2.isAncestorOf(t2.getData()) || (&t2.getData() == &ac2)), true)
		t2.forward();
	}

	Composite single;
	CompositeIteratorTraits t3(single);
	t3.setPredicate(my_true);
	t3.toBegin();
	TEST_EQUAL(t3.isBegin(), true)
	TEST_EQUAL(t3.isEnd(), false)
	TEST_EQUAL(t3.isValid(), true)
	TEST_EQUAL(t3.isSingular(), false)
	TEST_EQUAL(&t3.getData(), &single)
	t3.forward();
	TEST_EQUAL(t3.isEnd(), true)
	TEST_EQUAL(t3.isBegin(), false)
	TEST_EQUAL(t3.isValid(), false)
	TEST_EQUAL(t3.isSingular(), false)
	TEST_EQUAL(&t3.getData(), 0)

	Composite root;
	root.appendChild(single);
	CompositeIteratorTraits t4(single);
	t4.setPredicate(my_true);
	t4.toBegin();
	TEST_EQUAL(t4.isBegin(), true)
	TEST_EQUAL(t4.isEnd(), false)
	TEST_EQUAL(t4.isValid(), true)
	TEST_EQUAL(t4.isSingular(), false)
	TEST_EQUAL(&t4.getData(), &single)
	t4.forward();
	TEST_EQUAL(t4.isEnd(), true)
	TEST_EQUAL(t4.isBegin(), false)
	TEST_EQUAL(t4.isValid(), false)
	TEST_EQUAL(t4.isSingular(), false)
	TEST_EQUAL(&t4.getData(), 0)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

END_TEST

<|endoftext|>