<commit_before>#include <exception>
#include <limits>

#include <gtest/gtest.h>

#include "range.h"

using namespace whoshuu;

TEST(RangeIntegerTests, ValueStopTest) {
    for (auto stop = 0; stop < 100; ++stop) {
        auto expected = 0;
        for (auto computed : range(stop)) {
            EXPECT_EQ(expected, computed);
            ++expected;
        }
    }
}

TEST(RangeIntegerTests, ValueStartStopTest) {
    for (auto start = -100; start < 100; ++start) {
        for (auto stop = start; stop < 100; ++stop) {
            auto expected = start;
            for (auto computed : range(start, stop)) {
                EXPECT_EQ(expected, computed);
                ++expected;
            }
        }
    }
}

TEST(RangeIntegerTests, ValueStartStopStepTest) {
    for (auto start = -100; start < 100; ++start) {
        for (auto stop = start; stop < 100; ++stop) {
            for (auto step = 1; step < 100; ++step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeIntegerTests, ValueStopReverseTest) {
    for (auto stop = 100; stop > 0; --stop) {
        auto expected = 100;
        for (auto computed : range(100, stop, -1)) {
            EXPECT_EQ(expected, computed);
            --expected;
        }
    }
}

TEST(RangeIntegerTests, ValueStartStopReverseTest) {
    for (auto start = 100; start > -100; --start) {
        for (auto stop = start; stop > -100; --stop) {
            auto expected = start;
            for (auto computed : range(start, stop, -1)) {
                EXPECT_EQ(expected, computed);
                --expected;
            }
        }
    }
}

TEST(RangeIntegerTests, ValueStartStopStepReverseTest) {
    for (auto start = 100; start > -100; --start) {
        for (auto stop = start; stop > -100; --stop) {
            for (auto step = -1; step > -100; --step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeIntegerTests, ValueNegativeStopExceptionTest) {
    bool thrown = false;
    try {
        range(-10);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, ValueStartLargerThanStopExceptionTest) {
    bool thrown = false;
    try {
        range(11, 10);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, ValueStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(0, 10, -1);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, ValueAnotherStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(10, 0, 1);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, ValueZeroStepExceptionTest) {
    bool thrown = false;
    try {
        range(0, 10, 0);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range step argument must not be zero"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, IntegerWrapAroundTest) {
    bool thrown = false;
    try {
        range(int64_t{1}, std::numeric_limits<int64_t>::min(), int64_t{1});
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeFloatTests, ValueStopTest) {
    for (auto stop = 0.f; stop < 100.f; ++stop) {
        auto expected = 0.f;
        for (auto computed : range(stop)) {
            EXPECT_EQ(expected, computed);
            ++expected;
        }
    }
}

TEST(RangeFloatTests, ValueStartStopTest) {
    for (auto start = -100.f; start < 100.f; ++start) {
        for (auto stop = start; stop < 100.f; ++stop) {
            auto expected = start;
            for (auto computed : range(start, stop)) {
                EXPECT_EQ(expected, computed);
                ++expected;
            }
        }
    }
}

TEST(RangeFloatTests, ValueStartStopStepTest) {
    for (auto start = -100.f; start < 100.f; ++start) {
        for (auto stop = start; stop < 100.f; ++stop) {
            for (auto step = 1.5f; step < 100.f; ++step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeFloatTests, ValueStopReverseTest) {
    for (auto stop = 100.f; stop > 0.f; --stop) {
        auto expected = 100.f;
        for (auto computed : range(100.f, stop, -1.5f)) {
            EXPECT_EQ(expected, computed);
            expected -= 1.5f;
        }
    }
}

TEST(RangeFloatTests, ValueStartStopReverseTest) {
    for (auto start = 100.f; start > -100.f; --start) {
        for (auto stop = start; stop > -100.f; --stop) {
            auto expected = start;
            for (auto computed : range(start, stop, -1.5f)) {
                EXPECT_EQ(expected, computed);
                expected -= 1.5f;
            }
        }
    }
}

TEST(RangeFloatTests, ValueStartStopStepReverseTest) {
    for (auto start = 100.f; start > -100.f; --start) {
        for (auto stop = start; stop > -100.f; --stop) {
            for (auto step = -1.5f; step > -100.f; --step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeFloatTests, ValueNegativeStopExceptionTest) {
    bool thrown = false;
    try {
        range(-10.f);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeFloatTests, ValueStartLargerThanStopExceptionTest) {
    bool thrown = false;
    try {
        range(11.f, 10.f);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeFloatTests, ValueStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(0.f, 10.f, -1.f);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeFloatTests, ValueAnotherStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(10.f, 0.f, 1.f);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeFloatTests, ValueZeroStepExceptionTest) {
    bool thrown = false;
    try {
        range(0.f, 10.f, 0.f);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range step argument must not be zero"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeDoubleTests, ValueStopTest) {
    for (auto stop = 0.; stop < 100.; ++stop) {
        auto expected = 0.;
        for (auto computed : range(stop)) {
            EXPECT_EQ(expected, computed);
            ++expected;
        }
    }
}

TEST(RangeDoubleTests, ValueStartStopTest) {
    for (auto start = -100.; start < 100.; ++start) {
        for (auto stop = start; stop < 100.; ++stop) {
            auto expected = start;
            for (auto computed : range(start, stop)) {
                EXPECT_EQ(expected, computed);
                ++expected;
            }
        }
    }
}

TEST(RangeDoubleTests, ValueStartStopStepTest) {
    for (auto start = -100.; start < 100.; ++start) {
        for (auto stop = start; stop < 100.; ++stop) {
            for (auto step = 1.5; step < 100.; ++step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeDoubleTests, ValueStopReverseTest) {
    for (auto stop = 100.; stop > 0.; --stop) {
        auto expected = 100.;
        for (auto computed : range(100., stop, -1.5)) {
            EXPECT_EQ(expected, computed);
            expected -= 1.5;
        }
    }
}

TEST(RangeDoubleTests, ValueStartStopReverseTest) {
    for (auto start = 100.; start > -100.; --start) {
        for (auto stop = start; stop > -100.; --stop) {
            auto expected = start;
            for (auto computed : range(start, stop, -1.5)) {
                EXPECT_EQ(expected, computed);
                expected -= 1.5;
            }
        }
    }
}

TEST(RangeDoubleTests, ValueStartStopStepReverseTest) {
    for (auto start = 100.; start > -100.; --start) {
        for (auto stop = start; stop > -100.; --stop) {
            for (auto step = -1.5; step > -100.; --step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeDoubleTests, ValueNegativeStopExceptionTest) {
    bool thrown = false;
    try {
        range(-10.);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeDoubleTests, ValueStartLargerThanStopExceptionTest) {
    bool thrown = false;
    try {
        range(11., 10.);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeDoubleTests, ValueStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(0., 10., -1.);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeDoubleTests, ValueAnotherStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(10., 0., 1.);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeDoubleTests, ValueZeroStepExceptionTest) {
    bool thrown = false;
    try {
        range(0., 10., 0.);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range step argument must not be zero"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}
<commit_msg>Add the reverse of the min check test<commit_after>#include <exception>
#include <limits>

#include <gtest/gtest.h>

#include "range.h"

using namespace whoshuu;

TEST(RangeIntegerTests, ValueStopTest) {
    for (auto stop = 0; stop < 100; ++stop) {
        auto expected = 0;
        for (auto computed : range(stop)) {
            EXPECT_EQ(expected, computed);
            ++expected;
        }
    }
}

TEST(RangeIntegerTests, ValueStartStopTest) {
    for (auto start = -100; start < 100; ++start) {
        for (auto stop = start; stop < 100; ++stop) {
            auto expected = start;
            for (auto computed : range(start, stop)) {
                EXPECT_EQ(expected, computed);
                ++expected;
            }
        }
    }
}

TEST(RangeIntegerTests, ValueStartStopStepTest) {
    for (auto start = -100; start < 100; ++start) {
        for (auto stop = start; stop < 100; ++stop) {
            for (auto step = 1; step < 100; ++step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeIntegerTests, ValueStopReverseTest) {
    for (auto stop = 100; stop > 0; --stop) {
        auto expected = 100;
        for (auto computed : range(100, stop, -1)) {
            EXPECT_EQ(expected, computed);
            --expected;
        }
    }
}

TEST(RangeIntegerTests, ValueStartStopReverseTest) {
    for (auto start = 100; start > -100; --start) {
        for (auto stop = start; stop > -100; --stop) {
            auto expected = start;
            for (auto computed : range(start, stop, -1)) {
                EXPECT_EQ(expected, computed);
                --expected;
            }
        }
    }
}

TEST(RangeIntegerTests, ValueStartStopStepReverseTest) {
    for (auto start = 100; start > -100; --start) {
        for (auto stop = start; stop > -100; --stop) {
            for (auto step = -1; step > -100; --step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeIntegerTests, ValueNegativeStopExceptionTest) {
    bool thrown = false;
    try {
        range(-10);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, ValueStartLargerThanStopExceptionTest) {
    bool thrown = false;
    try {
        range(11, 10);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, ValueStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(0, 10, -1);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, ValueAnotherStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(10, 0, 1);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, ValueZeroStepExceptionTest) {
    bool thrown = false;
    try {
        range(0, 10, 0);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range step argument must not be zero"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, IntegerWrapAroundTest) {
    bool thrown = false;
    try {
        range(int64_t{1}, std::numeric_limits<int64_t>::min(), int64_t{1});
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeIntegerTests, IntegerWrapAroundReverseTest) {
    bool thrown = false;
    try {
        range(int64_t{1}, std::numeric_limits<int64_t>::max(), int64_t{-1});
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeFloatTests, ValueStopTest) {
    for (auto stop = 0.f; stop < 100.f; ++stop) {
        auto expected = 0.f;
        for (auto computed : range(stop)) {
            EXPECT_EQ(expected, computed);
            ++expected;
        }
    }
}

TEST(RangeFloatTests, ValueStartStopTest) {
    for (auto start = -100.f; start < 100.f; ++start) {
        for (auto stop = start; stop < 100.f; ++stop) {
            auto expected = start;
            for (auto computed : range(start, stop)) {
                EXPECT_EQ(expected, computed);
                ++expected;
            }
        }
    }
}

TEST(RangeFloatTests, ValueStartStopStepTest) {
    for (auto start = -100.f; start < 100.f; ++start) {
        for (auto stop = start; stop < 100.f; ++stop) {
            for (auto step = 1.5f; step < 100.f; ++step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeFloatTests, ValueStopReverseTest) {
    for (auto stop = 100.f; stop > 0.f; --stop) {
        auto expected = 100.f;
        for (auto computed : range(100.f, stop, -1.5f)) {
            EXPECT_EQ(expected, computed);
            expected -= 1.5f;
        }
    }
}

TEST(RangeFloatTests, ValueStartStopReverseTest) {
    for (auto start = 100.f; start > -100.f; --start) {
        for (auto stop = start; stop > -100.f; --stop) {
            auto expected = start;
            for (auto computed : range(start, stop, -1.5f)) {
                EXPECT_EQ(expected, computed);
                expected -= 1.5f;
            }
        }
    }
}

TEST(RangeFloatTests, ValueStartStopStepReverseTest) {
    for (auto start = 100.f; start > -100.f; --start) {
        for (auto stop = start; stop > -100.f; --stop) {
            for (auto step = -1.5f; step > -100.f; --step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeFloatTests, ValueNegativeStopExceptionTest) {
    bool thrown = false;
    try {
        range(-10.f);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeFloatTests, ValueStartLargerThanStopExceptionTest) {
    bool thrown = false;
    try {
        range(11.f, 10.f);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeFloatTests, ValueStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(0.f, 10.f, -1.f);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeFloatTests, ValueAnotherStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(10.f, 0.f, 1.f);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeFloatTests, ValueZeroStepExceptionTest) {
    bool thrown = false;
    try {
        range(0.f, 10.f, 0.f);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range step argument must not be zero"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeDoubleTests, ValueStopTest) {
    for (auto stop = 0.; stop < 100.; ++stop) {
        auto expected = 0.;
        for (auto computed : range(stop)) {
            EXPECT_EQ(expected, computed);
            ++expected;
        }
    }
}

TEST(RangeDoubleTests, ValueStartStopTest) {
    for (auto start = -100.; start < 100.; ++start) {
        for (auto stop = start; stop < 100.; ++stop) {
            auto expected = start;
            for (auto computed : range(start, stop)) {
                EXPECT_EQ(expected, computed);
                ++expected;
            }
        }
    }
}

TEST(RangeDoubleTests, ValueStartStopStepTest) {
    for (auto start = -100.; start < 100.; ++start) {
        for (auto stop = start; stop < 100.; ++stop) {
            for (auto step = 1.5; step < 100.; ++step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeDoubleTests, ValueStopReverseTest) {
    for (auto stop = 100.; stop > 0.; --stop) {
        auto expected = 100.;
        for (auto computed : range(100., stop, -1.5)) {
            EXPECT_EQ(expected, computed);
            expected -= 1.5;
        }
    }
}

TEST(RangeDoubleTests, ValueStartStopReverseTest) {
    for (auto start = 100.; start > -100.; --start) {
        for (auto stop = start; stop > -100.; --stop) {
            auto expected = start;
            for (auto computed : range(start, stop, -1.5)) {
                EXPECT_EQ(expected, computed);
                expected -= 1.5;
            }
        }
    }
}

TEST(RangeDoubleTests, ValueStartStopStepReverseTest) {
    for (auto start = 100.; start > -100.; --start) {
        for (auto stop = start; stop > -100.; --stop) {
            for (auto step = -1.5; step > -100.; --step) {
                auto expected = start;
                for (auto computed : range(start, stop, step)) {
                    EXPECT_EQ(expected, computed);
                    expected += step;
                }
            }
        }
    }
}

TEST(RangeDoubleTests, ValueNegativeStopExceptionTest) {
    bool thrown = false;
    try {
        range(-10.);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeDoubleTests, ValueStartLargerThanStopExceptionTest) {
    bool thrown = false;
    try {
        range(11., 10.);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeDoubleTests, ValueStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(0., 10., -1.);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeDoubleTests, ValueAnotherStepWrongDirectionExceptionTest) {
    bool thrown = false;
    try {
        range(10., 0., 1.);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range arguments must result in termination"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}

TEST(RangeDoubleTests, ValueZeroStepExceptionTest) {
    bool thrown = false;
    try {
        range(0., 10., 0.);
    } catch (const std::invalid_argument& e) {
        thrown = true;
        EXPECT_EQ(std::string{"Range step argument must not be zero"},
                  std::string{e.what()});
    }
    EXPECT_TRUE(thrown);
}
<|endoftext|>


<commit_before>
extern "C" {
#include "cx/syscx.h"
}

#include "uniact.hh"
#include "unifile.hh"
#include "../pfmla.hh"

#include "cx/bittable.hh"
#include "cx/fileb.hh"
#include <algorithm>

#include "livelock.hh"

#include "../namespace.hh"

/** Given a list of actions and variables x[j-1] and x[j],
 * compute the tiling constraints for column j
 * in the form of a transition formula.
 **/
static
  X::Fmla
column_xfmla(const Table<UniAct>& acts, const PFmlaVbl& x_p, const PFmlaVbl& x_j)
{
  X::Fmla xn( false );
  for (uint i = 0; i < acts.sz(); ++i) {
    const UniAct& act = acts[i];
    //    x'[j-1]==a         && x[j]==b     && x'[j]==c
    xn |= x_p.img_eq(act[0]) && x_j==act[1] && x_j.img_eq(act[2]);
  }
  return xn;
}

static
  void
bdd_init_vbls(PFmlaCtx& pfmla_ctx, Table<PFmlaVbl>& vbls,
              uint max_period, uint domsz)
{
  vbls.affysz(1+max_period);
  for (uint i = 0; i < 1+max_period; ++i) {
    uint vbl_id = pfmla_ctx.add_vbl((String("x") << i), domsz);
    vbls[i] = pfmla_ctx.vbl(vbl_id);
  }
}

static
  uint
bdd_classify(const Table<PcState>& ppgfun,
             Table<PFmlaVbl>& vbls,
             uint min_period, uint max_period,
             const uint domsz)
{
  Table<UniAct> acts = uniring_actions_of(ppgfun, domsz);

  X::Fmla xn(true);
  for (uint j = 1; j < 1+max_period; ++j) {
    xn &= column_xfmla(acts, vbls[j-1], vbls[j]);
    skip_unless (j >= min_period);
    const X::Fmla periodic_xn =
      xn & (vbls[0]==vbls[j]) & (vbls[0].img_eq_img(vbls[j]));

    if (periodic_xn.cycle_ck(0)) {
      return j;
    }
  }

  // No livelocks found? Are they even a possibility?
  if (!xn.cycle_ck(0)) {
    return 0;
  }
  return max_period+1;
}

static
  uint
tile_classify(const Table<PcState>& ppgfun, uint max_period, const uint domsz)
{
  Table<PcState> row;
  const Trit exists =
    livelock_semick(max_period, ppgfun, domsz, &row);
  if (exists == Nil)  return 0;
  if (exists == Yes)  return row.sz()-1;
  return max_period + 1;
}

/** Execute me now!**/
int main(int argc, char** argv) {
  int argi = init_sysCx(&argc, &argv);

  uint min_period = 0;
  uint max_period = 0;
  uint domsz = 0;

  bool use_bdds = true;

  OFile silent_ofile;
  OFile livelock_ofile;
  OFile unknown_ofile;
  OFileB silent_ofileb;
  OFileB livelock_ofileb;
  OFileB unknown_ofileb;

  C::XFile xfile_olay[1];
  C::XFile* xfile = stdin_XFile ();
  OFile ofile( stdout_OFile () );

  bool line_flush = true;

  while (argi < argc) {
    const char* arg = argv[argi++];
    if (eq_cstr ("-id", arg)) {
      if (!argv[argi])
        failout_sysCx("Argument Usage: -id <id>");
      init_XFile_olay_cstr (xfile_olay, argv[argi++]);
      xfile = xfile_olay;
    }
    else if (eq_cstr ("-nobdd", arg)) {
      use_bdds = false;
    }
    else if (eq_cstr ("-cutoff", arg)) {
      // Ignored.
    }
    else if (eq_cstr ("-flushoff", arg)) {
      line_flush = false;
    }
    else if (eq_cstr ("-silent", arg) || eq_cstr ("-sil", arg)) {
      silent_ofile = stdout_OFile();
    }
    else if (eq_cstr ("-livelock", arg) || eq_cstr ("-liv", arg)) {
      livelock_ofile = stdout_OFile();
    }
    else if (eq_cstr ("-unknown", arg) || eq_cstr ("-unk", arg)) {
      unknown_ofile = stdout_OFile();
    }
    else if (eq_cstr ("-o-silent", arg) || eq_cstr ("-o-sil", arg)) {
      arg = argv[argi++];
      if (!arg)  failout_sysCx("Give a file for -o-silent!");
      silent_ofile = silent_ofileb.uopen(0, arg);
      if (!silent_ofile)
        failout_sysCx("Cannot open file for -o-silent!");
    }
    else if (eq_cstr ("-o-livelock", arg) || eq_cstr ("-o-liv", arg)) {
      arg = argv[argi++];
      if (!arg)  failout_sysCx("Give a file for -o-livelock!");
      livelock_ofile = livelock_ofileb.uopen(0, arg);
      if (!livelock_ofile)
        failout_sysCx("Cannot open file for -o-livelock!");
    }
    else if (eq_cstr ("-o-unknown", arg) || eq_cstr ("-o-unk", arg)) {
      arg = argv[argi++];
      if (!arg)  failout_sysCx("Give a file for -o-unknown!");
      unknown_ofile = unknown_ofileb.uopen(0, arg);
      if (!unknown_ofile)
        failout_sysCx("Cannot open file for -o-unknown!");
    }
    else if (max_period == 0) {
      if (!xget_uint_cstr (&max_period, arg) || max_period == 0)
        failout_sysCx("Failed to parse period.");
    }
    else if (min_period == 0) {
      min_period = max_period;
      if (!xget_uint_cstr (&max_period, arg) || max_period <= min_period)
        failout_sysCx("Failed to parse period.");
    }
    else if (eq_cstr ("-domsz", arg)) {
      if (!xget_uint_cstr (&domsz, arg) || domsz == 0)
        failout_sysCx("Usage: -domsz <domsz>\nWhere <domsz> is a positive integer.");
    }
    else {
      DBog1( "Unrecognized option: %s", arg );
      failout_sysCx (0);
    }
  }

  if (max_period == 0) {
    failout_sysCx("Please provide a maximum period.");
  }

  if (min_period == 0) {
    min_period = 1;
  }

  PFmlaCtx pfmla_ctx;
  Table<PFmlaVbl> vbls;
  if (domsz > 0 && use_bdds) {
    bdd_init_vbls(pfmla_ctx, vbls, max_period, domsz);
  }

  const bool summarize =
    (!silent_ofile && !livelock_ofile && !unknown_ofile);

  while (true) {
    Table<PcState> ppgfun;
    uint read_domsz =
      xget_b64_ppgfun(xfile, ppgfun);
    if (read_domsz == 0)  break;
    if (domsz == 0) {
      domsz = read_domsz;
      if (use_bdds) {
        bdd_init_vbls(pfmla_ctx, vbls, max_period, domsz);
      }
    }
    else if (domsz != read_domsz) {
      failout_sysCx ("Use one domain size for inputs.");
    }

    uint period = 0;
    if (use_bdds)
      period = bdd_classify(ppgfun, vbls,
                            min_period, max_period, domsz);
    else
      period = tile_classify(ppgfun, max_period, domsz);

    if (period == 0) {
      if (!!silent_ofile) {
        oput_b64_ppgfun(silent_ofile, ppgfun, domsz) << '\n';
      }
      else if (summarize) {
        ofile << "silent\n";
      }
    }
    else if (period <= max_period) {
      if (!!livelock_ofile) {
        oput_b64_ppgfun(livelock_ofile, ppgfun, domsz) << '\n';
      }
      else if (summarize) {
        ofile << "livelock\tperiod:" << period << '\n';
      }
    }
    else {
      if (!!unknown_ofile) {
        oput_b64_ppgfun(unknown_ofile, ppgfun, domsz) << '\n';
      }
      else if (summarize) {
        ofile << "unknown\n";
      }
    }
    if (line_flush) {
      ofile.flush();
    }
  }

  lose_sysCx();
  return 0;
}

END_NAMESPACE

int main(int argc, char** argv) {
  return PROJECT_NAMESPACE::main(argc, argv);
}
<commit_msg>Min and max periods can be equal in classify tool<commit_after>
extern "C" {
#include "cx/syscx.h"
}

#include "uniact.hh"
#include "unifile.hh"
#include "../pfmla.hh"

#include "cx/bittable.hh"
#include "cx/fileb.hh"
#include <algorithm>

#include "livelock.hh"

#include "../namespace.hh"

/** Given a list of actions and variables x[j-1] and x[j],
 * compute the tiling constraints for column j
 * in the form of a transition formula.
 **/
static
  X::Fmla
column_xfmla(const Table<UniAct>& acts, const PFmlaVbl& x_p, const PFmlaVbl& x_j)
{
  X::Fmla xn( false );
  for (uint i = 0; i < acts.sz(); ++i) {
    const UniAct& act = acts[i];
    //    x'[j-1]==a         && x[j]==b     && x'[j]==c
    xn |= x_p.img_eq(act[0]) && x_j==act[1] && x_j.img_eq(act[2]);
  }
  return xn;
}

static
  void
bdd_init_vbls(PFmlaCtx& pfmla_ctx, Table<PFmlaVbl>& vbls,
              uint max_period, uint domsz)
{
  vbls.affysz(1+max_period);
  for (uint i = 0; i < 1+max_period; ++i) {
    uint vbl_id = pfmla_ctx.add_vbl((String("x") << i), domsz);
    vbls[i] = pfmla_ctx.vbl(vbl_id);
  }
}

static
  uint
bdd_classify(const Table<PcState>& ppgfun,
             Table<PFmlaVbl>& vbls,
             uint min_period, uint max_period,
             const uint domsz)
{
  Table<UniAct> acts = uniring_actions_of(ppgfun, domsz);

  X::Fmla xn(true);
  for (uint j = 1; j < 1+max_period; ++j) {
    xn &= column_xfmla(acts, vbls[j-1], vbls[j]);
    skip_unless (j >= min_period);
    const X::Fmla periodic_xn =
      xn & (vbls[0]==vbls[j]) & (vbls[0].img_eq_img(vbls[j]));

    if (periodic_xn.cycle_ck(0)) {
      return j;
    }
  }

  // No livelocks found? Are they even a possibility?
  if (!xn.cycle_ck(0)) {
    return 0;
  }
  return max_period+1;
}

static
  uint
tile_classify(const Table<PcState>& ppgfun, uint max_period, const uint domsz)
{
  Table<PcState> row;
  const Trit exists =
    livelock_semick(max_period, ppgfun, domsz, &row);
  if (exists == Nil)  return 0;
  if (exists == Yes)  return row.sz()-1;
  return max_period + 1;
}

/** Execute me now!**/
int main(int argc, char** argv) {
  int argi = init_sysCx(&argc, &argv);

  uint min_period = 0;
  uint max_period = 0;
  uint domsz = 0;

  bool use_bdds = true;

  OFile silent_ofile;
  OFile livelock_ofile;
  OFile unknown_ofile;
  OFileB silent_ofileb;
  OFileB livelock_ofileb;
  OFileB unknown_ofileb;

  C::XFile xfile_olay[1];
  C::XFile* xfile = stdin_XFile ();
  OFile ofile( stdout_OFile () );

  bool line_flush = true;

  while (argi < argc) {
    const char* arg = argv[argi++];
    if (eq_cstr ("-id", arg)) {
      if (!argv[argi])
        failout_sysCx("Argument Usage: -id <id>");
      init_XFile_olay_cstr (xfile_olay, argv[argi++]);
      xfile = xfile_olay;
    }
    else if (eq_cstr ("-nobdd", arg)) {
      use_bdds = false;
    }
    else if (eq_cstr ("-cutoff", arg)) {
      // Ignored.
    }
    else if (eq_cstr ("-flushoff", arg)) {
      line_flush = false;
    }
    else if (eq_cstr ("-silent", arg) || eq_cstr ("-sil", arg)) {
      silent_ofile = stdout_OFile();
    }
    else if (eq_cstr ("-livelock", arg) || eq_cstr ("-liv", arg)) {
      livelock_ofile = stdout_OFile();
    }
    else if (eq_cstr ("-unknown", arg) || eq_cstr ("-unk", arg)) {
      unknown_ofile = stdout_OFile();
    }
    else if (eq_cstr ("-o-silent", arg) || eq_cstr ("-o-sil", arg)) {
      arg = argv[argi++];
      if (!arg)  failout_sysCx("Give a file for -o-silent!");
      silent_ofile = silent_ofileb.uopen(0, arg);
      if (!silent_ofile)
        failout_sysCx("Cannot open file for -o-silent!");
    }
    else if (eq_cstr ("-o-livelock", arg) || eq_cstr ("-o-liv", arg)) {
      arg = argv[argi++];
      if (!arg)  failout_sysCx("Give a file for -o-livelock!");
      livelock_ofile = livelock_ofileb.uopen(0, arg);
      if (!livelock_ofile)
        failout_sysCx("Cannot open file for -o-livelock!");
    }
    else if (eq_cstr ("-o-unknown", arg) || eq_cstr ("-o-unk", arg)) {
      arg = argv[argi++];
      if (!arg)  failout_sysCx("Give a file for -o-unknown!");
      unknown_ofile = unknown_ofileb.uopen(0, arg);
      if (!unknown_ofile)
        failout_sysCx("Cannot open file for -o-unknown!");
    }
    else if (max_period == 0) {
      if (!xget_uint_cstr (&max_period, arg) || max_period == 0)
        failout_sysCx("Failed to parse period.");
    }
    else if (min_period == 0) {
      min_period = max_period;
      if (!xget_uint_cstr (&max_period, arg) || max_period < min_period)
        failout_sysCx("Failed to parse period.");
    }
    else if (eq_cstr ("-domsz", arg)) {
      if (!xget_uint_cstr (&domsz, arg) || domsz == 0)
        failout_sysCx("Usage: -domsz <domsz>\nWhere <domsz> is a positive integer.");
    }
    else {
      DBog1( "Unrecognized option: %s", arg );
      failout_sysCx (0);
    }
  }

  if (max_period == 0) {
    failout_sysCx("Please provide a maximum period.");
  }

  if (min_period == 0) {
    min_period = 1;
  }

  PFmlaCtx pfmla_ctx;
  Table<PFmlaVbl> vbls;
  if (domsz > 0 && use_bdds) {
    bdd_init_vbls(pfmla_ctx, vbls, max_period, domsz);
  }

  const bool summarize =
    (!silent_ofile && !livelock_ofile && !unknown_ofile);

  while (true) {
    Table<PcState> ppgfun;
    uint read_domsz =
      xget_b64_ppgfun(xfile, ppgfun);
    if (read_domsz == 0)  break;
    if (domsz == 0) {
      domsz = read_domsz;
      if (use_bdds) {
        bdd_init_vbls(pfmla_ctx, vbls, max_period, domsz);
      }
    }
    else if (domsz != read_domsz) {
      failout_sysCx ("Use one domain size for inputs.");
    }

    uint period = 0;
    if (use_bdds)
      period = bdd_classify(ppgfun, vbls,
                            min_period, max_period, domsz);
    else
      period = tile_classify(ppgfun, max_period, domsz);

    if (period == 0) {
      if (!!silent_ofile) {
        oput_b64_ppgfun(silent_ofile, ppgfun, domsz) << '\n';
      }
      else if (summarize) {
        ofile << "silent\n";
      }
    }
    else if (period <= max_period) {
      if (!!livelock_ofile) {
        oput_b64_ppgfun(livelock_ofile, ppgfun, domsz) << '\n';
      }
      else if (summarize) {
        ofile << "livelock\tperiod:" << period << '\n';
      }
    }
    else {
      if (!!unknown_ofile) {
        oput_b64_ppgfun(unknown_ofile, ppgfun, domsz) << '\n';
      }
      else if (summarize) {
        ofile << "unknown\n";
      }
    }
    if (line_flush) {
      ofile.flush();
    }
  }

  lose_sysCx();
  return 0;
}

END_NAMESPACE

int main(int argc, char** argv) {
  return PROJECT_NAMESPACE::main(argc, argv);
}
<|endoftext|>


<commit_before>/*
 * Author: Yevgeniy Kiveisha <yevgeniy.kiveisha@intel.com>
 * Copyright (c) 2014 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>

#include "servo.h"

using namespace upm;

Servo::Servo (int pin) {
    init(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH, DEFAULT_WAIT_DISABLE_PWM);
}

Servo::Servo (int pin, int minPulseWidth, int maxPulseWidth) {
    init(pin, minPulseWidth, maxPulseWidth, DEFAULT_WAIT_DISABLE_PWM);
}

Servo::Servo (int pin, int minPulseWidth, int maxPulseWidth, int waitAndDisablePwm) {
    init(pin, minPulseWidth, maxPulseWidth, waitAndDisablePwm);
}

Servo::~Servo () {
    haltPwm();
    mraa_pwm_close (m_pwmServoContext);
}

/*
 * X = between (MIN_PULSE_WIDTH , MAX_PULSE_WIDTH)
 *
 * X usec
 * _______
 *        |_______________________________________
 *                      m_period usec
 *
 * */
mraa_result_t Servo::setAngle (int angle) {
    if (m_pwmServoContext == NULL) {
        std::cout << "PWM context is NULL" << std::endl;
        return MRAA_ERROR_UNSPECIFIED;
    }

    if (angle > m_maxAngle || angle < 0) {
        return MRAA_ERROR_UNSPECIFIED;
    }

    mraa_pwm_enable (m_pwmServoContext, 1);
    mraa_pwm_period_us (m_pwmServoContext, m_period);
    mraa_pwm_pulsewidth_us (m_pwmServoContext, calcPulseTraveling(angle));

    if (m_waitAndDisablePwm) {
        sleep(1); // we must make sure that we don't turn off PWM before the servo is done moving.
        haltPwm();
    }

    m_currAngle = angle;
}

mraa_result_t Servo::haltPwm () {
    if (m_pwmServoContext == NULL) {
        std::cout << "PWM context is NULL" << std::endl;
        return MRAA_ERROR_UNSPECIFIED;
    }

    return mraa_pwm_enable (m_pwmServoContext, 0);
}

/*
 * Calculating relative pulse time to the value.
 * */
int Servo::calcPulseTraveling (int value) {
    // if bigger than the boundaries
    if (value > m_maxAngle) {
        return m_maxPulseWidth;
    }

    // if less than the boundaries
    if (value  < 0) {
        return m_minPulseWidth;
    }

    // the conversion
    return (int) ((float)m_minPulseWidth + ((float)value / m_maxAngle) * ((float)m_maxPulseWidth - (float)m_minPulseWidth));
}

void
Servo::setMinPulseWidth (int width) {
    m_minPulseWidth = width;
}

void
Servo::setMaxPulseWidth (int width) {
    m_maxPulseWidth = width;
}

void
Servo::setPeriod (int period) {
    m_period = period;
}

int
Servo::getMinPulseWidth () {
    return m_minPulseWidth;
}

int
Servo::getMaxPulseWidth () {
    return m_maxPulseWidth;
}

int
Servo::getPeriod () {
    return m_period;
}

/**
 *  private mathod:  would like to use delegating constructors instead but that requires C++11
 */
void
Servo::init (int pin, int minPulseWidth, int maxPulseWidth, int waitAndDisablePwm) {
    m_minPulseWidth   = minPulseWidth;
    m_maxPulseWidth   = maxPulseWidth;
    m_period          = PERIOD;

    m_waitAndDisablePwm = waitAndDisablePwm;

    m_maxAngle        = 180.0;
    m_servoPin        = pin;
    m_pwmServoContext = mraa_pwm_init (m_servoPin);

    m_currAngle = 180;

    setAngle (0);
}
<commit_msg>servo: return a value in setAngle()<commit_after>/*
 * Author: Yevgeniy Kiveisha <yevgeniy.kiveisha@intel.com>
 * Copyright (c) 2014 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>

#include "servo.h"

using namespace upm;

Servo::Servo (int pin) {
    init(pin, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH, DEFAULT_WAIT_DISABLE_PWM);
}

Servo::Servo (int pin, int minPulseWidth, int maxPulseWidth) {
    init(pin, minPulseWidth, maxPulseWidth, DEFAULT_WAIT_DISABLE_PWM);
}

Servo::Servo (int pin, int minPulseWidth, int maxPulseWidth, int waitAndDisablePwm) {
    init(pin, minPulseWidth, maxPulseWidth, waitAndDisablePwm);
}

Servo::~Servo () {
    haltPwm();
    mraa_pwm_close (m_pwmServoContext);
}

/*
 * X = between (MIN_PULSE_WIDTH , MAX_PULSE_WIDTH)
 *
 * X usec
 * _______
 *        |_______________________________________
 *                      m_period usec
 *
 * */
mraa_result_t Servo::setAngle (int angle) {
    if (m_pwmServoContext == NULL) {
        std::cout << "PWM context is NULL" << std::endl;
        return MRAA_ERROR_UNSPECIFIED;
    }

    if (angle > m_maxAngle || angle < 0) {
        return MRAA_ERROR_UNSPECIFIED;
    }

    mraa_pwm_enable (m_pwmServoContext, 1);
    mraa_pwm_period_us (m_pwmServoContext, m_period);
    mraa_pwm_pulsewidth_us (m_pwmServoContext, calcPulseTraveling(angle));

    if (m_waitAndDisablePwm) {
        sleep(1); // we must make sure that we don't turn off PWM before the servo is done moving.
        haltPwm();
    }

    m_currAngle = angle;
    return MRAA_SUCCESS;
}

mraa_result_t Servo::haltPwm () {
    if (m_pwmServoContext == NULL) {
        std::cout << "PWM context is NULL" << std::endl;
        return MRAA_ERROR_UNSPECIFIED;
    }

    return mraa_pwm_enable (m_pwmServoContext, 0);
}

/*
 * Calculating relative pulse time to the value.
 * */
int Servo::calcPulseTraveling (int value) {
    // if bigger than the boundaries
    if (value > m_maxAngle) {
        return m_maxPulseWidth;
    }

    // if less than the boundaries
    if (value  < 0) {
        return m_minPulseWidth;
    }

    // the conversion
    return (int) ((float)m_minPulseWidth + ((float)value / m_maxAngle) * ((float)m_maxPulseWidth - (float)m_minPulseWidth));
}

void
Servo::setMinPulseWidth (int width) {
    m_minPulseWidth = width;
}

void
Servo::setMaxPulseWidth (int width) {
    m_maxPulseWidth = width;
}

void
Servo::setPeriod (int period) {
    m_period = period;
}

int
Servo::getMinPulseWidth () {
    return m_minPulseWidth;
}

int
Servo::getMaxPulseWidth () {
    return m_maxPulseWidth;
}

int
Servo::getPeriod () {
    return m_period;
}

/**
 *  private mathod:  would like to use delegating constructors instead but that requires C++11
 */
void
Servo::init (int pin, int minPulseWidth, int maxPulseWidth, int waitAndDisablePwm) {
    m_minPulseWidth   = minPulseWidth;
    m_maxPulseWidth   = maxPulseWidth;
    m_period          = PERIOD;

    m_waitAndDisablePwm = waitAndDisablePwm;

    m_maxAngle        = 180.0;
    m_servoPin        = pin;
    m_pwmServoContext = mraa_pwm_init (m_servoPin);

    m_currAngle = 180;

    setAngle (0);
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2003 by Unai Garro                                      *
 *   ugarro@users.sourceforge.net                                          *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include <unistd.h>
#include <pwd.h>

#include <iostream>
#include <qhbox.h>
#include <qvbox.h>
#include <qvgroupbox.h>
#include <qlayout.h>
#include <qpixmap.h>
#include <qpushbutton.h>
#include <kconfig.h>
#include <kapp.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include "setupwizard.h"

SetupWizard::SetupWizard(QWidget *parent, const char *name, bool modal, WFlags f):KWizard(parent,name, modal,f)
{
welcomePage= new WelcomePage(this);
addPage(welcomePage,i18n("Welcome to Krecipes"));
permissionsSetupPage=new PermissionsSetupPage(this);
addPage(permissionsSetupPage,i18n("Database Permissions"));
serverSetupPage = new ServerSetupPage(this);
addPage(serverSetupPage,i18n("Server Settings"));
savePage = new SavePage(this);
addPage(savePage,i18n("Finish and Save Settings"));
setFinishEnabled(savePage,true); // Enable finish button
setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
connect(finishButton(),SIGNAL(clicked()),this,SLOT(save()));
}

SetupWizard::~SetupWizard()
{

}

WelcomePage::WelcomePage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);
QPixmap logoPixmap (locate("data", "krecipes/pics/wizard.png"));
logo=new QLabel(this);
logo->setPixmap(logoPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(logo,1,1);

QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_from_image,1,2);

welcomeText=new QLabel(this);
welcomeText->setText(i18n("Thank you very much for choosing Krecipes.\nIt looks like this is the first time you are using it. This wizard will help you with the initial setup so that you can start using it quickly.\n\nWelcome and enjoy cooking! ;-) "));
welcomeText->setMinimumWidth(200);
welcomeText->setMaximumWidth(10000);
welcomeText->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Minimum);
welcomeText->setAlignment( int( QLabel::WordBreak | QLabel::AlignTop |QLabel::AlignJustify  ) );
layout->addWidget(welcomeText,1,3);

}

PermissionsSetupPage::PermissionsSetupPage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);

// Explanation Text
permissionsText=new QLabel(this);
permissionsText->setText(i18n("This dialog will allow you to specify a MySQL account that has the necessary permissions to access the KRecipes MySQL database.

Most users that use Krecipes and MySQL for the first time can just leave the default parameters and press \'Next\'.

If you set a MySQL root password before, or you have already permissions as normal user, click on the appropriate option. Otherwise the account 'root' will be used, with no password.

[For security reasons, we strongly encourage you to setup a MySQL root password if you have not done so yet. Just type as root: mysqladmin password your_password]"));
permissionsText->setMinimumWidth(200);
permissionsText->setMaximumWidth(10000);
permissionsText->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Minimum);
permissionsText->setAlignment( int( QLabel::WordBreak | QLabel::AlignTop |QLabel::AlignJustify  ) );
layout->addWidget(permissionsText,1,3);

// Logo
QPixmap permissionsSetupPixmap (locate("data", "krecipes/pics/dbpermissions.png"));
logo=new QLabel(this);
logo->setPixmap(permissionsSetupPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addMultiCellWidget(logo,1,8,1,1);

// Spacer to separate the logo
QSpacerItem *logoSpacer=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(logoSpacer,1,2);

// "The user already has permissions" checkbox
noSetupCheckBox=new QCheckBox(i18n("I have already set the necessary permissions"),this,"noSetupCheckBox");
layout->addWidget(noSetupCheckBox,3,3);
// root checkbox
rootCheckBox=new QCheckBox(i18n("I have already set a MySQL root/admin account"),this,"rootCheckBox");
layout->addWidget(rootCheckBox,4,3);

QSpacerItem *rootInfoSpacer=new QSpacerItem(10,10,QSizePolicy::Minimum,QSizePolicy::Fixed);
layout->addItem(rootInfoSpacer,5,3);

// MySQL root/admin info
QVGroupBox *rootInfoVGBox=new QVGroupBox(this,"rootInfoVGBox"); rootInfoVGBox->setTitle(i18n("MySQL root info"));
rootInfoVGBox->setEnabled(false); // Disable by default
rootInfoVGBox->setInsideSpacing(10);
layout->addWidget(rootInfoVGBox,6,3);

// Input boxes (widgets inserted below)
QHBox *userBox=new QHBox(rootInfoVGBox); userBox->setSpacing(10);
QHBox *passBox=new QHBox(rootInfoVGBox); passBox->setSpacing(10);

// User Entry
QLabel *userLabel=new QLabel(userBox); userLabel->setText(i18n("Username:"));
userEdit=new KLineEdit(userBox);

// Password Entry
QLabel *passLabel=new QLabel(passBox); passLabel->setText(i18n("Password:"));
passEdit=new KLineEdit(passBox);
passEdit->setEchoMode(QLineEdit::Password);

// Connect Signals & slots

connect(rootCheckBox,SIGNAL(toggled(bool)),rootInfoVGBox,SLOT(setEnabled(bool)));
connect(rootCheckBox,SIGNAL(toggled(bool)),this,SLOT(rootCheckBoxChanged(bool)));
connect(noSetupCheckBox,SIGNAL(toggled(bool)),this,SLOT(noSetupCheckBoxChanged(bool)));
}
void PermissionsSetupPage::rootCheckBoxChanged(bool on)
{
if (on) noSetupCheckBox->setChecked(false); // exclude mutually the options (both can be unset)
}

void PermissionsSetupPage::noSetupCheckBoxChanged(bool on)
{
if (on) rootCheckBox->setChecked(false); // exclude mutually the options (both can be unset)
}

ServerSetupPage::ServerSetupPage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);

QPixmap networkSetupPixmap (locate("data", "krecipes/pics/network.png"));
logo=new QLabel(this);
logo->setPixmap(networkSetupPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addMultiCellWidget(logo,1,8,1,1);

QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_from_image,1,2);

QLabel* serverText=new QLabel(i18n("Server:"), this);
serverText->setFixedSize(QSize(100,20));
serverText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(serverText,1,3);

serverEdit=new KLineEdit(this);
serverEdit->setFixedSize(QSize(120,20));
serverEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
serverEdit->setText("localhost");
layout->addWidget(serverEdit,1,4);

QSpacerItem* spacerRow1 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow1,2,3 );

QLabel* usernameText=new QLabel(i18n("Username:"), this);
usernameText->setFixedSize(QSize(100,20));
usernameText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(usernameText,3,3);

usernameEdit=new KLineEdit(this);
usernameEdit->setFixedSize(QSize(120,20));
usernameEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	// get username
	uid_t userID; QString username;struct passwd *user;
	userID=getuid();user=getpwuid (userID); username=user->pw_name;

usernameEdit->setText(username);
layout->addWidget(usernameEdit,3,4);

QSpacerItem* spacerRow2 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow2,4,3 );

QLabel* passwordText=new QLabel(i18n("Password:"), this);
passwordText->setFixedSize(QSize(100,20));
passwordText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(passwordText,5,3);

passwordEdit=new KLineEdit(this);
passwordEdit->setEchoMode(QLineEdit::Password);
passwordEdit->setFixedSize(QSize(120,20));
passwordEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(passwordEdit,5,4);

QSpacerItem* spacerRow3 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow3, 6,3 );

QLabel* dbNameText=new QLabel(i18n("Database Name:"), this);
dbNameText->setFixedSize(QSize(100,20));
dbNameText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(dbNameText,7,3);

dbNameEdit=new KLineEdit(this);
dbNameEdit->setFixedSize(QSize(120,20));
dbNameEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
dbNameEdit->setText("Krecipes");
layout->addWidget(dbNameEdit,7,4);

QSpacerItem* spacerRow4 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding);
layout->addItem( spacerRow4, 8,3 );
QSpacerItem* spacerRight = new QSpacerItem( 10,10, QSizePolicy::MinimumExpanding, QSizePolicy::Fixed );
layout->addItem( spacerRight, 1,5 );
}

QString ServerSetupPage::server(void)
{
return(this->serverEdit->text());
}

QString ServerSetupPage::user(void)
{
return(this->usernameEdit->text());
}

QString ServerSetupPage::password(void)
{
return(this->passwordEdit->text());
}

QString ServerSetupPage::dbName(void)
{
return(this->dbNameEdit->text());;
}

SavePage::SavePage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);

QPixmap logoPixmap (locate("data", "krecipes/pics/save.png"));
logo=new QLabel(this);
logo->setPixmap(logoPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(logo,1,1);

QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,2);

saveText=new QLabel(this);
saveText->setText(i18n("Congratulations! All the necessary configuration setup are done. Press 'Finish' to continue, and enjoy cooking!"));
saveText->setMinimumWidth(200);
saveText->setMaximumWidth(10000);
saveText->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);

saveText->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter | QLabel::AlignJustify) );
layout->addWidget(saveText,1,3);

}

void SetupWizard::save(void)
{
KConfig *config=kapp->config();

// Save the server data
config->setGroup("Server");
config->writeEntry("Host",serverSetupPage->server());
config->writeEntry("Username",serverSetupPage->user());
config->writeEntry("Password",serverSetupPage->password());
config->writeEntry("DBName",serverSetupPage->dbName());

// Indicate that settings were already made

config->setGroup("Wizard");
config->writeEntry( "SystemSetup",true);

}
<commit_msg>CVS_SILENT Make messages a bit more clear Fix alignment of text for Qt 3.1.x<commit_after>/***************************************************************************
 *   Copyright (C) 2003 by Unai Garro                                      *
 *   ugarro@users.sourceforge.net                                          *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include <unistd.h>
#include <pwd.h>

#include <iostream>
#include <qhbox.h>
#include <qvbox.h>
#include <qvgroupbox.h>
#include <qlayout.h>
#include <qpixmap.h>
#include <qpushbutton.h>
#include <kconfig.h>
#include <kapp.h>
#include <kstandarddirs.h>
#include <klocale.h>
#include "setupwizard.h"

SetupWizard::SetupWizard(QWidget *parent, const char *name, bool modal, WFlags f):KWizard(parent,name, modal,f)
{
welcomePage= new WelcomePage(this);
addPage(welcomePage,i18n("Welcome to Krecipes"));
permissionsSetupPage=new PermissionsSetupPage(this);
addPage(permissionsSetupPage,i18n("Database Permissions"));
serverSetupPage = new ServerSetupPage(this);
addPage(serverSetupPage,i18n("Server Settings"));
savePage = new SavePage(this);
addPage(savePage,i18n("Finish and Save Settings"));
setFinishEnabled(savePage,true); // Enable finish button
setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
connect(finishButton(),SIGNAL(clicked()),this,SLOT(save()));
}

SetupWizard::~SetupWizard()
{

}

WelcomePage::WelcomePage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);
QPixmap logoPixmap (locate("data", "krecipes/pics/wizard.png"));
logo=new QLabel(this);
logo->setPixmap(logoPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(logo,1,1);

QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_from_image,1,2);

welcomeText=new QLabel(this);
welcomeText->setText(i18n("Thank you very much for choosing Krecipes.\nIt looks like this is the first time you are using it. This wizard will help you with the initial setup so that you can start using it quickly.\n\nWelcome and enjoy cooking! ;-) "));
welcomeText->setMinimumWidth(200);
welcomeText->setMaximumWidth(10000);
welcomeText->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Minimum);
welcomeText->setAlignment( int( QLabel::AlignTop |QLabel::AlignJustify  ) );
layout->addWidget(welcomeText,1,3);

}

PermissionsSetupPage::PermissionsSetupPage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);

// Explanation Text
permissionsText=new QLabel(this);
permissionsText->setText(i18n("This dialog will allow you to specify a MySQL account that has the necessary permissions to access the KRecipes MySQL database.

Most users that use Krecipes and MySQL for the first time can just leave the default parameters and press \'Next\'.

If you set a MySQL root password before, or you have already permissions as normal user, click on the appropriate option. Otherwise the account 'root' will be used, with no password.

[For security reasons, we strongly encourage you to setup a MySQL root password if you have not done so yet. Just type as root: mysqladmin password your_password]"));
permissionsText->setMinimumWidth(200);
permissionsText->setMaximumWidth(10000);
permissionsText->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Minimum);
permissionsText->setAlignment( int( QLabel::WordBreak | QLabel::AlignTop  ) );
layout->addWidget(permissionsText,1,3);

// Logo
QPixmap permissionsSetupPixmap (locate("data", "krecipes/pics/dbpermissions.png"));
logo=new QLabel(this);
logo->setPixmap(permissionsSetupPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addMultiCellWidget(logo,1,8,1,1);

// Spacer to separate the logo
QSpacerItem *logoSpacer=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(logoSpacer,1,2);

// "The user already has permissions" checkbox
noSetupCheckBox=new QCheckBox(i18n("I have already set the necessary permissions"),this,"noSetupCheckBox");
layout->addWidget(noSetupCheckBox,3,3);
// root checkbox
rootCheckBox=new QCheckBox(i18n("I have already set a MySQL root/admin account"),this,"rootCheckBox");
layout->addWidget(rootCheckBox,4,3);

QSpacerItem *rootInfoSpacer=new QSpacerItem(10,10,QSizePolicy::Minimum,QSizePolicy::Fixed);
layout->addItem(rootInfoSpacer,5,3);

// MySQL root/admin info
QVGroupBox *rootInfoVGBox=new QVGroupBox(this,"rootInfoVGBox"); rootInfoVGBox->setTitle(i18n("MySQL Administrator Account"));
rootInfoVGBox->setEnabled(false); // Disable by default
rootInfoVGBox->setInsideSpacing(10);
layout->addWidget(rootInfoVGBox,6,3);

// Input boxes (widgets inserted below)
QHBox *userBox=new QHBox(rootInfoVGBox); userBox->setSpacing(10);
QHBox *passBox=new QHBox(rootInfoVGBox); passBox->setSpacing(10);

// User Entry
QLabel *userLabel=new QLabel(userBox); userLabel->setText(i18n("Username:"));
userEdit=new KLineEdit(userBox);

// Password Entry
QLabel *passLabel=new QLabel(passBox); passLabel->setText(i18n("Password:"));
passEdit=new KLineEdit(passBox);
passEdit->setEchoMode(QLineEdit::Password);

// Connect Signals & slots

connect(rootCheckBox,SIGNAL(toggled(bool)),rootInfoVGBox,SLOT(setEnabled(bool)));
connect(rootCheckBox,SIGNAL(toggled(bool)),this,SLOT(rootCheckBoxChanged(bool)));
connect(noSetupCheckBox,SIGNAL(toggled(bool)),this,SLOT(noSetupCheckBoxChanged(bool)));
}
void PermissionsSetupPage::rootCheckBoxChanged(bool on)
{
if (on) noSetupCheckBox->setChecked(false); // exclude mutually the options (both can be unset)
}

void PermissionsSetupPage::noSetupCheckBoxChanged(bool on)
{
if (on) rootCheckBox->setChecked(false); // exclude mutually the options (both can be unset)
}

ServerSetupPage::ServerSetupPage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);

QPixmap networkSetupPixmap (locate("data", "krecipes/pics/network.png"));
logo=new QLabel(this);
logo->setPixmap(networkSetupPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addMultiCellWidget(logo,1,8,1,1);

QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_from_image,1,2);

QLabel* serverText=new QLabel(i18n("Server:"), this);
serverText->setFixedSize(QSize(100,20));
serverText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(serverText,1,3);

serverEdit=new KLineEdit(this);
serverEdit->setFixedSize(QSize(120,20));
serverEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
serverEdit->setText("localhost");
layout->addWidget(serverEdit,1,4);

QSpacerItem* spacerRow1 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow1,2,3 );

QLabel* usernameText=new QLabel(i18n("Username:"), this);
usernameText->setFixedSize(QSize(100,20));
usernameText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(usernameText,3,3);

usernameEdit=new KLineEdit(this);
usernameEdit->setFixedSize(QSize(120,20));
usernameEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
	// get username
	uid_t userID; QString username;struct passwd *user;
	userID=getuid();user=getpwuid (userID); username=user->pw_name;

usernameEdit->setText(username);
layout->addWidget(usernameEdit,3,4);

QSpacerItem* spacerRow2 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow2,4,3 );

QLabel* passwordText=new QLabel(i18n("Password:"), this);
passwordText->setFixedSize(QSize(100,20));
passwordText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(passwordText,5,3);

passwordEdit=new KLineEdit(this);
passwordEdit->setEchoMode(QLineEdit::Password);
passwordEdit->setFixedSize(QSize(120,20));
passwordEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(passwordEdit,5,4);

QSpacerItem* spacerRow3 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::Fixed );
layout->addItem( spacerRow3, 6,3 );

QLabel* dbNameText=new QLabel(i18n("Database Name:"), this);
dbNameText->setFixedSize(QSize(100,20));
dbNameText->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(dbNameText,7,3);

dbNameEdit=new KLineEdit(this);
dbNameEdit->setFixedSize(QSize(120,20));
dbNameEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
dbNameEdit->setText("Krecipes");
layout->addWidget(dbNameEdit,7,4);

QSpacerItem* spacerRow4 = new QSpacerItem( 10,10, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding);
layout->addItem( spacerRow4, 8,3 );
QSpacerItem* spacerRight = new QSpacerItem( 10,10, QSizePolicy::MinimumExpanding, QSizePolicy::Fixed );
layout->addItem( spacerRight, 1,5 );
}

QString ServerSetupPage::server(void)
{
return(this->serverEdit->text());
}

QString ServerSetupPage::user(void)
{
return(this->usernameEdit->text());
}

QString ServerSetupPage::password(void)
{
return(this->passwordEdit->text());
}

QString ServerSetupPage::dbName(void)
{
return(this->dbNameEdit->text());;
}

SavePage::SavePage(QWidget *parent):QWidget(parent)
{
QGridLayout *layout=new QGridLayout(this,1,1,0,0);
QSpacerItem *spacer_top=new QSpacerItem(10,10,QSizePolicy::Minimum, QSizePolicy::Fixed);
layout->addItem(spacer_top,0,1);
QSpacerItem *spacer_left=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,0);

QPixmap logoPixmap (locate("data", "krecipes/pics/save.png"));
logo=new QLabel(this);
logo->setPixmap(logoPixmap);
logo->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(logo,1,1);

QSpacerItem *spacer_from_image=new QSpacerItem(10,10,QSizePolicy::Fixed, QSizePolicy::Minimum);
layout->addItem(spacer_left,1,2);

saveText=new QLabel(this);
saveText->setText(i18n("Congratulations! All the necessary configuration setup are done. Press 'Finish' to continue, and enjoy cooking!"));
saveText->setMinimumWidth(200);
saveText->setMaximumWidth(10000);
saveText->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);

saveText->setAlignment( int( QLabel::WordBreak | QLabel::AlignVCenter) );
layout->addWidget(saveText,1,3);

}

void SetupWizard::save(void)
{
KConfig *config=kapp->config();

// Save the server data
config->setGroup("Server");
config->writeEntry("Host",serverSetupPage->server());
config->writeEntry("Username",serverSetupPage->user());
config->writeEntry("Password",serverSetupPage->password());
config->writeEntry("DBName",serverSetupPage->dbName());

// Indicate that settings were already made

config->setGroup("Wizard");
config->writeEntry( "SystemSetup",true);

}
<|endoftext|>


<commit_before>#include "notendaui.h"
#include <iostream>
#include <string>
#include <utility>
#include <algorithm>

using namespace std;

NotendaUI::NotendaUI()
{

}

void Skrifaut()
{
    cout << "*==============================================================*" << endl;
    cout << "*||Please enter one the following commands*                  ||*" << endl;
    cout << "*==============================================================*" << endl;
    cout << "*||list - Shows a list of all known entries in the database. ||*" << endl;
    cout << "*||add - Add a new entry into the database.                  ||*" << endl;
    cout << "*||delete - Removes an entry from the database.              ||*" << endl;
    cout << "*||update - Updates an entry from the database.              ||*" << endl;
    cout << "*||search - Search for an entry from the database.           ||*" << endl;
    cout << "*||purge - Removes every entry from the database.            ||*" << endl;
    cout << "*==============================================================*" << endl;
}

bool check = true;

void NotendaUI::keyra()
{
    //TEMP
    vector<tolvufolk> data;
    data.push_back(tolvufolk("Ada Lovelace", "kvk", 1880, 1890));
    data.push_back(tolvufolk("Charles Babbage", "kk", 1900, 1920));

    string nName;
    string gGender;
    int bYear;
    int dYear;
    int iD;

    Skrifaut();

    do
        {
        check = true;
        string skipun;
        cin >> skipun;

        if (skipun == "list" || skipun == "l")
        {
            printList(data);
        }
        else if (skipun == "add" || skipun == "a")
        {
            cout << "Enter name: ";
            cin >> nName;

            cout << "Enter gender(kk/kvk) [lowercase]: ";
            cin >> gGender;

            while (gGender != "kk" && gGender != "kvk")
            {
                cerr << "Input not valid, try again: ";
                cin >> gGender;
            }

            cout << "Enter year of birth: ";
            cin >> bYear;

            while (0 > bYear)
            {
                cerr << "Input not valid, try again: ";
                cin >> bYear;
            }

            cout << "Enter year of death(-1 if still alive): ";
            cin >> dYear;

            while (-1 > dYear)
            {
                cerr << "Input not valid, try again: ";
                cin >> dYear;
                cout << endl;
            }

            data.push_back(tolvufolk(nName, gGender, bYear, dYear));
            printList(data);

        }
        else if (skipun == "delete" || skipun == "d")
        {
            printList(data);
            cout << "Select the ID of the person you wish to delete: ";
            cin >> iD;

        }

        else if (skipun == "update" || skipun == "u")
        {

        }

        else if (skipun == "search" || skipun == "s")
        {
            searchName(data);
        }

        else if (skipun == "purge" || skipun == "p")
        {
            cout << "By the Emperor, are you sure? (Y/N): ";
            cin >> skipun;

            if (skipun == "Y" || skipun == "y")
            {
                cout << "Are you really sure? This will EXTERMINATE ALL ENTRIES. (Y/N): ";
                cin >> skipun;

                if (skipun == "Y" || skipun == "y")
                {
                    cout << "Acknowledged, by your will, all ENTRIES will be EXTERMINATED.";
                    // TODO; Erase everything

                }
                else
                {
                    cout << "Purge canceled." << endl;
                }

            }
            else
            {
                cout << "Purge canceled." << endl;
            }

        }

        else
        {
            system("cls");
            Skrifaut();
            cerr << "Input not valid, try again: ";
            check = false;
        }
    } while (check == false);
}

void NotendaUI::printList(const vector<tolvufolk>& data)
{
    for (size_t i = 0; i < data.size(); i++)
    {
        cout << data[i] << endl;
    }
}
void NotendaUI::searchName(const vector<tolvufolk>& data)
{

    string skipunin;
    cout << "*==============================================*" << endl;
    cout << "*||Please enter one the following command*   ||*" << endl;
    cout << "*==============================================*" << endl;
    cout << "*||name - Search by name                     ||*" << endl;
    cout << "*||age - Search by age                      ||*" << endl;
    cout << "*||birth - Search by year of birth            ||*" << endl;
    cout << "*||death - Search by year of death            ||*" << endl;
    cin >> skipunin;

    if (skipunin == "name" || skipunin == "n")
    {
        string nafn;
        cout << "Name to search: ";
        cin.ignore();
        getline(cin,nafn);
        for(size_t i = 0; i < data.size(); i++)
        {
            if (nafn == data[i].getNafn())
            {
                cout << data[i];
            }
        }
    }
}
<commit_msg>Bætti við í Search fallið<commit_after>#include "notendaui.h"
#include <iostream>
#include <string>
#include <utility>
#include <algorithm>

using namespace std;

NotendaUI::NotendaUI()
{

}

void Skrifaut()
{
    cout << "*==============================================================*" << endl;
    cout << "*||Please enter one the following commands*                  ||*" << endl;
    cout << "*==============================================================*" << endl;
    cout << "*||list - Shows a list of all known entries in the database. ||*" << endl;
    cout << "*||add - Add a new entry into the database.                  ||*" << endl;
    cout << "*||delete - Removes an entry from the database.              ||*" << endl;
    cout << "*||update - Updates an entry from the database.              ||*" << endl;
    cout << "*||search - Search for an entry from the database.           ||*" << endl;
    cout << "*||purge - Removes every entry from the database.            ||*" << endl;
    cout << "*||quit - Exits/quits the program                            ||*" << endl;
    cout << "*==============================================================*" << endl;
}

bool check = true;

void NotendaUI::keyra()
{
    //TEMP
    vector<tolvufolk> data;
    data.push_back(tolvufolk("Ada Lovelace", "kvk", 1880, 1890));
    data.push_back(tolvufolk("Charles Babbage", "kk", 1900, 1920));

    string nName;
    string gGender;
    int bYear;
    int dYear;
    int iD;

    Skrifaut();

    do
        {
        check = true;
        string skipun;
        cin >> skipun;

        if (skipun == "list" || skipun == "l")
        {
            printList(data);
        }
        else if (skipun == "add" || skipun == "a")
        {
            cout << "Enter name: ";
            cin >> nName;

            cout << "Enter gender(kk/kvk) [lowercase]: ";
            cin >> gGender;

            while (gGender != "kk" && gGender != "kvk")
            {
                cerr << "Input not valid, try again: ";
                cin >> gGender;
            }

            cout << "Enter year of birth: ";
            cin >> bYear;

            while (0 > bYear)
            {
                cerr << "Input not valid, try again: ";
                cin >> bYear;
            }

            cout << "Enter year of death(-1 if still alive): ";
            cin >> dYear;

            while (-1 > dYear)
            {
                cerr << "Input not valid, try again: ";
                cin >> dYear;
                cout << endl;
            }

            data.push_back(tolvufolk(nName, gGender, bYear, dYear));
            printList(data);

        }
        else if (skipun == "delete" || skipun == "d")
        {
            printList(data);
            cout << "Select the ID of the person you wish to delete: ";
            cin >> iD;

        }

        else if (skipun == "update" || skipun == "u")
        {

        }

        else if (skipun == "search" || skipun == "s")
        {
            searchName(data);
        }

        else if (skipun == "purge" || skipun == "p")
        {
            cout << "By the Emperor, are you sure? (Y/N): ";
            cin >> skipun;

            if (skipun == "Y" || skipun == "y")
            {
                cout << "Are you really sure? This will EXTERMINATE ALL ENTRIES. (Y/N): ";
                cin >> skipun;

                if (skipun == "Y" || skipun == "y")
                {
                    cout << "Acknowledged, by your will, all ENTRIES will be EXTERMINATED.";
                    // TODO; Erase everything

                }
                else
                {
                    cout << "Purge canceled." << endl;
                }

            }
            else
            {
                cout << "Purge canceled." << endl;
            }

        }

        else if (skipun == "quit" || skipun == "q")
        {
            check = false;
        }

        else
        {
            system("cls");
            Skrifaut();
            cerr << "Input not valid, try again: ";
            check = false;
        }
    } while (check != false);
}

void NotendaUI::printList(const vector<tolvufolk>& data)
{
    for (size_t i = 0; i < data.size(); i++)
    {
        cout << data[i] << endl;
    }
}
void NotendaUI::searchName(const vector<tolvufolk>& data)
{

    string skipunin;
    cout << "*==============================================================*" << endl;
    cout << "*||Please enter one the following command*                   ||*" << endl;
    cout << "*==============================================================*" << endl;
    cout << "*||name - Search by name                                     ||*" << endl;
    cout << "*||age - Search by age                                       ||*" << endl;
    cout << "*||birth - Search by year of birth                           ||*" << endl;
    cout << "*||death - Search by year of death                           ||*" << endl;
    cout << "*==============================================================*" << endl;
    cin >> skipunin;

    if (skipunin == "name" || skipunin == "n")
    {
        string nafn;
        cout << "Name to search: ";
        cin.ignore();
        getline(cin,nafn);
        for(size_t i = 0; i < data.size(); i++)
        {
            if (nafn == data[i].getNafn() )
            {
                cout << data[i];
            }
            cout << endl;
        }
    }
    else if (skipunin == "birth" || skipunin == "b")
    {
        int birth;
        cout << "Year of birth to search: ";
        cin.ignore();
        cin >> birth;
        for(size_t i = 0; i < data.size(); i++)
        {
            if (birth == data[i].getFaedingarar() )
            {
                cout << data[i];
            }
            cout << endl;
        }
    }
    else if (skipunin == "death" || skipunin == "d")
    {
        int death;
        cout << "Year of birth to search: ";
        cin.ignore();
        cin >> death;
        for(size_t i = 0; i < data.size(); i++)
        {
            if (death == data[i].getDanarar() )
            {
                cout << data[i];
            }
            cout << endl;
        }
    }
}
<|endoftext|>


<commit_before>/**
 ** Copyright (c) 2011-2014 Illumina, Inc.
 **
 ** This file is part of the BEETL software package,
 ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file)
 **
 ** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone
 ** Lightweight BWT Construction for Very Large String Collections.
 ** Proceedings of CPM 2011, pp.219-231
 **
 **
 ** Collection of basic tools and defines
 **/

#ifndef _TOOLS_H_
#define _TOOLS_H_

#include "Types.hh"

#include <cassert>
#include <ctime>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

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

#define verboseEncode 0
#define verboseDecode 0
#define deletePartialBWT 0 //If it is set to 1, it deletes the BWT-segments files and keeps the entire BWT, otherwise renames them.
#define deletePartialLCP 0	//If it is set to 1, it deletes the LCP-segments files and keeps the entire LCP, otherwise renames them.
//#define deletePartialSA 0 //If it is set to 1, it deletes the SA-segments files and keeps the entire BWT, otherwise renames them.
#define deleteCycFile 1  //If it is set to 1, it deletes the cycs files.
#define BUILD_SA 0   //If it is set to 1, it computes the GSA (seqID, position) and the SA (position of the concatenated sequences without a further end-marker).
#define BUILD_LCP 1	    	//If it is set to 1, it uses larger structures to allow --generate-lcp

class Tools
{
private:
    static double startTime;
public:
    static void StartTimer();
    static double GetTime();
    static uchar *GetRandomString( unsigned, unsigned, unsigned & );
    static uchar *GetFileContents( char *, size_t = 0 );
    static uint8_t FloorLog2( uint64_t );
    static uint8_t CeilLog2( uint64_t );
    static uint8_t *MakeTable();
    static uint8_t FastFloorLog2( uint32_t );
};

void getFileName( const string &stem, const char code, const int pile,
                  string &fileName );

bool isValidFastaFile( const char *filename );

bool isValidReadFile( const char *filename );
bool readWriteCheck( const char *fileName, const bool checkWrite, const bool failIfError = true );
int isDirectoryEmpty( const string &dirname ); // return: -1=directory doesn't exist, 0=not empty, 1=empty

void checkIfEqual( const int arg1, const int arg2 );

void checkIfNotEqual( const int arg1, const int arg2 );

bool hasPrefix( const string &fullString, const string &prefix );
bool hasSuffix( const string &fullString, const string &suffix );
vector<string> splitString ( string s, const string &token );

void detectInputBwtProperties( const string &prefix, vector<string> &filenames, bool &isBwtCompressed, string &availableFileLetters );

int safeRename( const string &from, const string &to );
void pauseBetweenCycles();
void readProcSelfStat( int &out_pid, int &out_num_threads, int &out_processor );

struct emptyDeleter
{
    void operator()( ... ) const {}
};
std::shared_ptr<std::istream> openInputFileOrDashAsCin( const string &filename );

#endif
<commit_msg>Update Tools.hh<commit_after>/**
 ** Copyright (c) 2011-2014 Illumina, Inc.
 **
 ** This file is part of the BEETL software package,
 ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file)
 **
 ** Citation: Markus J. Bauer, Anthony J. Cox and Giovanna Rosone
 ** Lightweight BWT Construction for Very Large String Collections.
 ** Proceedings of CPM 2011, pp.219-231
 **
 **
 ** Collection of basic tools and defines
 **/

#ifndef _TOOLS_H_
#define _TOOLS_H_

#include "Types.hh"

#include <cassert>
#include <ctime>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

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

#define verboseEncode 0
#define verboseDecode 0
#define deletePartialBWT 0 //If it is set to 1, it deletes the BWT-segments files and keeps the entire BWT, otherwise renames them.
#define deletePartialLCP 0	//If it is set to 1, it deletes the LCP-segments files and keeps the entire LCP, otherwise renames them.
//#define deletePartialSA 0 //If it is set to 1, it deletes the SA-segments files and keeps the entire BWT, otherwise renames them.
#define deleteCycFile 1  //If it is set to 1, it deletes the cycs files.
#define BUILD_SA 0   //If it is set to 1, it computes the GSA (seqID, position) and the SA (position of the concatenated sequences without a further end-marker).
#define BUILD_LCP 1	   0	//If it is set to 1, it uses larger structures to allow --generate-lcp

class Tools
{
private:
    static double startTime;
public:
    static void StartTimer();
    static double GetTime();
    static uchar *GetRandomString( unsigned, unsigned, unsigned & );
    static uchar *GetFileContents( char *, size_t = 0 );
    static uint8_t FloorLog2( uint64_t );
    static uint8_t CeilLog2( uint64_t );
    static uint8_t *MakeTable();
    static uint8_t FastFloorLog2( uint32_t );
};

void getFileName( const string &stem, const char code, const int pile,
                  string &fileName );

bool isValidFastaFile( const char *filename );

bool isValidReadFile( const char *filename );
bool readWriteCheck( const char *fileName, const bool checkWrite, const bool failIfError = true );
int isDirectoryEmpty( const string &dirname ); // return: -1=directory doesn't exist, 0=not empty, 1=empty

void checkIfEqual( const int arg1, const int arg2 );

void checkIfNotEqual( const int arg1, const int arg2 );

bool hasPrefix( const string &fullString, const string &prefix );
bool hasSuffix( const string &fullString, const string &suffix );
vector<string> splitString ( string s, const string &token );

void detectInputBwtProperties( const string &prefix, vector<string> &filenames, bool &isBwtCompressed, string &availableFileLetters );

int safeRename( const string &from, const string &to );
void pauseBetweenCycles();
void readProcSelfStat( int &out_pid, int &out_num_threads, int &out_processor );

struct emptyDeleter
{
    void operator()( ... ) const {}
};
std::shared_ptr<std::istream> openInputFileOrDashAsCin( const string &filename );

#endif
<|endoftext|>