<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013-2014 winlin

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.
*/

#ifndef SRS_CORE_HPP
#define SRS_CORE_HPP

/*
#include <srs_core.hpp>
*/

// current release version
#define VERSION_MAJOR       2
#define VERSION_MINOR       0
#define VERSION_REVISION    16
// server info.
#define RTMP_SIG_SRS_KEY "SRS"
#define RTMP_SIG_SRS_ROLE "origin/edge server"
#define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY"(Simple RTMP Server)"
#define RTMP_SIG_SRS_URL_SHORT "github.com/winlinvip/simple-rtmp-server"
#define RTMP_SIG_SRS_URL "https://"RTMP_SIG_SRS_URL_SHORT
#define RTMP_SIG_SRS_WEB "http://blog.csdn.net/win_lin"
#define RTMP_SIG_SRS_EMAIL "winlin@vip.126.com"
#define RTMP_SIG_SRS_LICENSE "The MIT License (MIT)"
#define RTMP_SIG_SRS_COPYRIGHT "Copyright (c) 2013-2014 winlin"
#define RTMP_SIG_SRS_PRIMARY_AUTHROS "winlin,wenjie.zhao"
#define RTMP_SIG_SRS_CONTRIBUTORS_URL RTMP_SIG_SRS_URL"/blob/master/AUTHORS.txt"
#define RTMP_SIG_SRS_HANDSHAKE RTMP_SIG_SRS_KEY"("RTMP_SIG_SRS_VERSION")"
#define RTMP_SIG_SRS_RELEASE "https://github.com/winlinvip/simple-rtmp-server/tree/1.0release"
#define RTMP_SIG_SRS_HTTP_SERVER "https://github.com/winlinvip/simple-rtmp-server/wiki/v1_CN_HTTPServer#feature"
#define RTMP_SIG_SRS_VERSION __SRS_XSTR(VERSION_MAJOR)"."__SRS_XSTR(VERSION_MINOR)"."__SRS_XSTR(VERSION_REVISION)

// internal macros, covert macro values to str,
// see: read https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification
#define __SRS_XSTR(v) __SRS_STR(v)
#define __SRS_STR(v) #v

/**
* the core provides the common defined macros, utilities,
* user must include the srs_core.hpp before any header, or maybe
* build failed.
*/

// for 32bit os, 2G big file limit for unistd io,
// ie. read/write/lseek to use 64bits size for huge file.
#ifndef _FILE_OFFSET_BITS
    #define _FILE_OFFSET_BITS 64
#endif

// for int64_t print using PRId64 format.
#ifndef __STDC_FORMAT_MACROS
    #define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>

#include <assert.h>
#define srs_assert(expression) assert(expression)

#include <stddef.h>
#include <sys/types.h>

// generated by configure.
#include <srs_auto_headers.hpp>

// free the p and set to NULL.
// p must be a T*.
#define srs_freep(p) \
    if (p) { \
        delete p; \
        p = NULL; \
    } \
    (void)0
// sometimes, the freepa is useless,
// it's recomments to free each elem explicit.
// so we remove the srs_freepa utility.

/**
* disable copy constructor of class,
* to avoid the memory leak or corrupt by copy instance.
*/
#define disable_default_copy(className)\
    private:\
        /** \
        * disable the copy constructor and operator=, donot allow directly copy. \
        */ \
        className(const className&); \
        className& operator= (const className&)

#endif

<commit_msg>for bug #194, refine code, to 2.0.17<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013-2014 winlin

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.
*/

#ifndef SRS_CORE_HPP
#define SRS_CORE_HPP

/*
#include <srs_core.hpp>
*/

// current release version
#define VERSION_MAJOR       2
#define VERSION_MINOR       0
#define VERSION_REVISION    17
// server info.
#define RTMP_SIG_SRS_KEY "SRS"
#define RTMP_SIG_SRS_ROLE "origin/edge server"
#define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY"(Simple RTMP Server)"
#define RTMP_SIG_SRS_URL_SHORT "github.com/winlinvip/simple-rtmp-server"
#define RTMP_SIG_SRS_URL "https://"RTMP_SIG_SRS_URL_SHORT
#define RTMP_SIG_SRS_WEB "http://blog.csdn.net/win_lin"
#define RTMP_SIG_SRS_EMAIL "winlin@vip.126.com"
#define RTMP_SIG_SRS_LICENSE "The MIT License (MIT)"
#define RTMP_SIG_SRS_COPYRIGHT "Copyright (c) 2013-2014 winlin"
#define RTMP_SIG_SRS_PRIMARY_AUTHROS "winlin,wenjie.zhao"
#define RTMP_SIG_SRS_CONTRIBUTORS_URL RTMP_SIG_SRS_URL"/blob/master/AUTHORS.txt"
#define RTMP_SIG_SRS_HANDSHAKE RTMP_SIG_SRS_KEY"("RTMP_SIG_SRS_VERSION")"
#define RTMP_SIG_SRS_RELEASE "https://github.com/winlinvip/simple-rtmp-server/tree/1.0release"
#define RTMP_SIG_SRS_HTTP_SERVER "https://github.com/winlinvip/simple-rtmp-server/wiki/v1_CN_HTTPServer#feature"
#define RTMP_SIG_SRS_VERSION __SRS_XSTR(VERSION_MAJOR)"."__SRS_XSTR(VERSION_MINOR)"."__SRS_XSTR(VERSION_REVISION)

// internal macros, covert macro values to str,
// see: read https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification
#define __SRS_XSTR(v) __SRS_STR(v)
#define __SRS_STR(v) #v

/**
* the core provides the common defined macros, utilities,
* user must include the srs_core.hpp before any header, or maybe
* build failed.
*/

// for 32bit os, 2G big file limit for unistd io,
// ie. read/write/lseek to use 64bits size for huge file.
#ifndef _FILE_OFFSET_BITS
    #define _FILE_OFFSET_BITS 64
#endif

// for int64_t print using PRId64 format.
#ifndef __STDC_FORMAT_MACROS
    #define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>

#include <assert.h>
#define srs_assert(expression) assert(expression)

#include <stddef.h>
#include <sys/types.h>

// generated by configure.
#include <srs_auto_headers.hpp>

// free the p and set to NULL.
// p must be a T*.
#define srs_freep(p) \
    if (p) { \
        delete p; \
        p = NULL; \
    } \
    (void)0
// sometimes, the freepa is useless,
// it's recomments to free each elem explicit.
// so we remove the srs_freepa utility.

/**
* disable copy constructor of class,
* to avoid the memory leak or corrupt by copy instance.
*/
#define disable_default_copy(className)\
    private:\
        /** \
        * disable the copy constructor and operator=, donot allow directly copy. \
        */ \
        className(const className&); \
        className& operator= (const className&)

#endif

<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "profilehighlighter.h"

#include <QtCore/QRegExp>
#include <QtGui/QColor>
#include <QtGui/QTextDocument>
#include <QtGui/QTextEdit>

using namespace Qt4ProjectManager::Internal;

#define MAX_VARIABLES 50
const char *const variables[MAX_VARIABLES] = {
    "CONFIG",
    "DEFINES",
    "DEF_FILE",
    "DEPENDPATH",
    "DESTDIR",
    "DESTDIR_TARGET",
    "DISTFILES",
    "DLLDESTDIR",
    "FORMS",
    "HEADERS",
    "INCLUDEPATH",
    "LEXSOURCES",
    "LIBS",
    "MAKEFILE",
    "MOC_DIR",
    "OBJECTS",
    "OBJECTS_DIR",
    "OBJMOC",
    "OTHER_FILES",
    "PKGCONFIG",
    "POST_TARGETDEPS",
    "PRECOMPILED_HEADER",
    "PRE_TARGETDEPS",
    "QMAKE",
    "QMAKESPEC",
    "QT",
    "RCC_DIR",
    "RC_FILE",
    "REQUIRES",
    "RESOURCES",
    "RES_FILE",
    "SOURCES",
    "SRCMOC",
    "SUBDIRS",
    "TARGET",
    "TARGET_EXT",
    "TARGET_x",
    "TARGET_x.y.z",
    "TEMPLATE",
    "TRANSLATIONS",
    "UI_DIR",
    "UI_HEADERS_DIR",
    "UI_SOURCES_DIR",
    "VER_MAJ",
    "VER_MIN",
    "VER_PAT",
    "VERSION",
    "VPATH",
    "YACCSOURCES",
    0
};

#define MAX_FUNCTIONS 22
const char *const functions[MAX_FUNCTIONS] = {
    "basename",
    "CONFIG",
    "contains",
    "count",
    "dirname",
    "error",
    "exists",
    "find",
    "for",
    "include",
    "infile",
    "isEmpty",
    "join",
    "member",
    "message",
    "prompt",
    "quote",
    "sprintf",
    "system",
    "unique",
    "warning",
    0
};

struct KeywordHelper
{
    inline KeywordHelper(const QString &word) : needle(word) {}
    const QString needle;
};

static bool operator<(const KeywordHelper &helper, const char *kw)
{
    return helper.needle < QLatin1String(kw);
}

static bool operator<(const char *kw, const KeywordHelper &helper)
{
    return QLatin1String(kw) < helper.needle;
}

static bool isVariable(const QString &word)
{
    const char *const *start = &variables[0];
    const char *const *end = &variables[MAX_VARIABLES - 1];
    const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
    return *kw != 0;
}

static bool isFunction(const QString &word)
{
    const char *const *start = &functions[0];
    const char *const *end = &functions[MAX_FUNCTIONS - 1];
    const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
    return *kw != 0;
}

ProFileHighlighter::ProFileHighlighter(QTextDocument *document) :
    QSyntaxHighlighter(document)
{
}

void ProFileHighlighter::highlightBlock(const QString &text)
{
    if (text.isEmpty())
        return;

    QString buf;
    bool inCommentMode = false;

    QTextCharFormat emptyFormat;
    int i = 0;
    for (;;) {
        const QChar c = text.at(i);
        if (inCommentMode) {
            setFormat(i, 1, m_formats[ProfileCommentFormat]);
        } else {
            if (c.isLetter() || c == '_' || c == '.') {
                buf += c;
                setFormat(i - buf.length()+1, buf.length(), emptyFormat);
                if (!buf.isEmpty() && isFunction(buf))
                    setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileFunctionFormat]);
                else if (!buf.isEmpty() && isVariable(buf))
                    setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileVariableFormat]);
            } else if (c == '(') {
                if (!buf.isEmpty() && isFunction(buf))
                    setFormat(i - buf.length(), buf.length(), m_formats[ProfileFunctionFormat]);
                buf.clear();
            } else if (c == '#') {
                inCommentMode = true;
                setFormat(i, 1, m_formats[ProfileCommentFormat]);
                buf.clear();
            } else {
                if (!buf.isEmpty() && isVariable(buf))
                    setFormat(i - buf.length(), buf.length(), m_formats[ProfileVariableFormat]);
                buf.clear();
            }
        }
        i++;
        if (i >= text.length())
            break;
    }
}

<commit_msg>Highlight CCFLAGS and INSTALLS and STATECHARTS in .pro files.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "profilehighlighter.h"

#include <QtCore/QRegExp>
#include <QtGui/QColor>
#include <QtGui/QTextDocument>
#include <QtGui/QTextEdit>

using namespace Qt4ProjectManager::Internal;

#define MAX_VARIABLES 53
const char *const variables[MAX_VARIABLES] = {
    "CCFLAG",
    "CONFIG",
    "DEFINES",
    "DEF_FILE",
    "DEPENDPATH",
    "DESTDIR",
    "DESTDIR_TARGET",
    "DISTFILES",
    "DLLDESTDIR",
    "FORMS",
    "HEADERS",
    "INCLUDEPATH",
    "INSTALLS",
    "LEXSOURCES",
    "LIBS",
    "MAKEFILE",
    "MOC_DIR",
    "OBJECTS",
    "OBJECTS_DIR",
    "OBJMOC",
    "OTHER_FILES",
    "PKGCONFIG",
    "POST_TARGETDEPS",
    "PRECOMPILED_HEADER",
    "PRE_TARGETDEPS",
    "QMAKE",
    "QMAKESPEC",
    "QT",
    "RCC_DIR",
    "RC_FILE",
    "REQUIRES",
    "RESOURCES",
    "RES_FILE",
    "SOURCES",
    "SRCMOC",
    "STATECHARTS",
    "SUBDIRS",
    "TARGET",
    "TARGET_EXT",
    "TARGET_x",
    "TARGET_x.y.z",
    "TEMPLATE",
    "TRANSLATIONS",
    "UI_DIR",
    "UI_HEADERS_DIR",
    "UI_SOURCES_DIR",
    "VER_MAJ",
    "VER_MIN",
    "VER_PAT",
    "VERSION",
    "VPATH",
    "YACCSOURCES",
    0
};

#define MAX_FUNCTIONS 22
const char *const functions[MAX_FUNCTIONS] = {
    "basename",
    "CONFIG",
    "contains",
    "count",
    "dirname",
    "error",
    "exists",
    "find",
    "for",
    "include",
    "infile",
    "isEmpty",
    "join",
    "member",
    "message",
    "prompt",
    "quote",
    "sprintf",
    "system",
    "unique",
    "warning",
    0
};

struct KeywordHelper
{
    inline KeywordHelper(const QString &word) : needle(word) {}
    const QString needle;
};

static bool operator<(const KeywordHelper &helper, const char *kw)
{
    return helper.needle < QLatin1String(kw);
}

static bool operator<(const char *kw, const KeywordHelper &helper)
{
    return QLatin1String(kw) < helper.needle;
}

static bool isVariable(const QString &word)
{
    const char *const *start = &variables[0];
    const char *const *end = &variables[MAX_VARIABLES - 1];
    const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
    return *kw != 0;
}

static bool isFunction(const QString &word)
{
    const char *const *start = &functions[0];
    const char *const *end = &functions[MAX_FUNCTIONS - 1];
    const char *const *kw = qBinaryFind(start, end, KeywordHelper(word));
    return *kw != 0;
}

ProFileHighlighter::ProFileHighlighter(QTextDocument *document) :
    QSyntaxHighlighter(document)
{
}

void ProFileHighlighter::highlightBlock(const QString &text)
{
    if (text.isEmpty())
        return;

    QString buf;
    bool inCommentMode = false;

    QTextCharFormat emptyFormat;
    int i = 0;
    for (;;) {
        const QChar c = text.at(i);
        if (inCommentMode) {
            setFormat(i, 1, m_formats[ProfileCommentFormat]);
        } else {
            if (c.isLetter() || c == '_' || c == '.') {
                buf += c;
                setFormat(i - buf.length()+1, buf.length(), emptyFormat);
                if (!buf.isEmpty() && isFunction(buf))
                    setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileFunctionFormat]);
                else if (!buf.isEmpty() && isVariable(buf))
                    setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileVariableFormat]);
            } else if (c == '(') {
                if (!buf.isEmpty() && isFunction(buf))
                    setFormat(i - buf.length(), buf.length(), m_formats[ProfileFunctionFormat]);
                buf.clear();
            } else if (c == '#') {
                inCommentMode = true;
                setFormat(i, 1, m_formats[ProfileCommentFormat]);
                buf.clear();
            } else {
                if (!buf.isEmpty() && isVariable(buf))
                    setFormat(i - buf.length(), buf.length(), m_formats[ProfileVariableFormat]);
                buf.clear();
            }
        }
        i++;
        if (i >= text.length())
            break;
    }
}

<|endoftext|>


<commit_before>/* algorithm.cpp - CS 472 Project #2: Genetic Programming
 * Copyright 2014 Andrew Schwartzmeyer
 *
 * Source file for algorithm namespace
 */

#include <ctime>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <thread>

#include "algorithm.hpp"
#include "../individual/individual.hpp"
#include "../problem/problem.hpp"
#include "../random_generator/random_generator.hpp"

namespace algorithm {
  using std::vector;
  using individual::Individual;
  using problem::Problem;
  using namespace random_generator;

  bool compare_fitness(const Individual & a, const Individual & b) {
    return (std::isnan(a.get_fitness())) ? false : a.get_fitness() < b.get_fitness();
  }

  std::ofstream open_log(const std::time_t & time) {
    std::stringstream time_string;
    time_string << std::put_time(std::localtime(&time), "%y%m%d_%H%M%S");
    std::ofstream log("logs/" + time_string.str(), std::ios_base::app);
    if (!log.is_open()) {
      std::cerr << "Log file logs/" << time_string.str() << " could not be opened!";
      std::exit(EXIT_FAILURE);
    }
    return log;
  }

  void log_info(const std::time_t & time, const Individual & best, const vector<Individual> & population) {
    double total_fitness = std::accumulate(population.begin(), population.end(), 0.,
					   [](const double & a, const Individual & b)->double const {return a + b.get_fitness();});
    int total_size = std::accumulate(population.begin(), population.end(), 0,
				     [](const int & a, const Individual & b)->double const {return a + b.get_total();});
    std::ofstream log = open_log(time);
    log << best.get_fitness() << "\t"
	<< total_fitness / population.size() << "\t"
	<< best.get_total() << "\t"
	<< total_size / population.size() << "\n";
    log.close();
  }

  vector<Individual> new_population(const Problem & problem) {
    vector<Individual> population;
    for (int i = 0; i < problem.population_size; ++i)
      population.emplace_back(Individual(problem));
    return population;
  }

  Individual selection(const Problem & problem, const vector<Individual> & population) {
    int_dist dis(0, problem.population_size - 1); // closed interval
    vector<Individual> contestants;
    // get contestants
    for (int i = 0; i < problem.tournament_size; ++i)
      contestants.emplace_back(population[dis(rg.engine)]);
    return *std::min_element(contestants.begin(), contestants.end(), compare_fitness);
  }

  vector<Individual> new_offspring(const Problem & problem, const vector<Individual> & population) {
    vector<Individual> offspring;
    while (offspring.size() != population.size()) {
      // select parents for children
      vector<Individual> parents;
      for (int i = 0; i < problem.crossover_size; ++i)
	parents.emplace_back(selection(problem, population));
      // crossover with probability
      real_dist dis(0, 1);
      if (dis(rg.engine) < problem.crossover_chance)
	crossover(problem.internals_chance, parents[0], parents[1]);
      // process children
      for (Individual & child : parents) {
	// mutate children
	child.mutate(problem.mutate_chance, problem.constant_min, problem.constant_max);
	// update fitness and size
	child.evaluate(problem.values);
	// save children
	offspring.emplace_back(child);
      }
    }
    return offspring;
  }

  const individual::Individual genetic(const problem::Problem & problem) {
    // setup time and start log
    std::time_t time = std::time(nullptr);
    std::ofstream log = open_log(time);
    log << "# running a Genetic Program on "
	<< std::ctime(&time) << "\n";
    log.close();
    // start timing algorithm
    std::chrono::time_point<std::chrono::system_clock> start, end;
    start = std::chrono::system_clock::now();
    // create initial popuation
    vector<Individual> population = new_population(problem);
    Individual best;
    // run algorithm to termination
    for (int iteration = 0; iteration < problem.iterations; ++iteration) {
      // find Individual with lowest "fitness" AKA error from populaiton
      best = *std::min_element(population.begin(), population.end(), compare_fitness);
      std::thread log_thread([time, best, population] {log_info(time, best, population);});
      // create replacement population
      vector<Individual> offspring = new_offspring(problem, population);
      // perform elitism
      int_dist dis(0, problem.population_size - 1);
      for (int i = 0; i < problem.elitism_size; ++i)
	offspring[dis(rg.engine)] = best;
      // replace current population with offspring
      population.swap(offspring);
      log_thread.join();
    }
    // end timing algorithm
    end = std::chrono::system_clock::now();
    // log duration
    std::chrono::duration<double> elapsed_seconds = end - start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);
    std::ofstream log_after = open_log(time);
    log_after << "# finished computation at " << std::ctime(&end_time)
	      << "# elapsed time: " << elapsed_seconds.count() << "s\n";
    log_after.close();
    return best;
  }
}
<commit_msg>More logged info<commit_after>/* algorithm.cpp - CS 472 Project #2: Genetic Programming
 * Copyright 2014 Andrew Schwartzmeyer
 *
 * Source file for algorithm namespace
 */

#include <ctime>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <thread>

#include "algorithm.hpp"
#include "../individual/individual.hpp"
#include "../problem/problem.hpp"
#include "../random_generator/random_generator.hpp"

namespace algorithm {
  using std::vector;
  using individual::Individual;
  using problem::Problem;
  using namespace random_generator;

  bool compare_fitness(const Individual & a, const Individual & b) {
    return (std::isnan(a.get_fitness())) ? false : a.get_fitness() < b.get_fitness();
  }

  std::ofstream open_log(const std::time_t & time) {
    std::stringstream time_string;
    time_string << std::put_time(std::localtime(&time), "%y%m%d_%H%M%S");
    std::ofstream log("logs/" + time_string.str(), std::ios_base::app);
    if (!log.is_open()) {
      std::cerr << "Log file logs/" << time_string.str() << " could not be opened!";
      std::exit(EXIT_FAILURE);
    }
    return log;
  }

  void log_info(const std::time_t & time, const Individual & best, const vector<Individual> & population) {
    double total_fitness = std::accumulate(population.begin(), population.end(), 0.,
					   [](const double & a, const Individual & b)->double const {return a + b.get_fitness();});
    int total_size = std::accumulate(population.begin(), population.end(), 0,
				     [](const int & a, const Individual & b)->double const {return a + b.get_total();});
    std::ofstream log = open_log(time);
    log << best.get_fitness() << "\t"
	<< total_fitness / population.size() << "\t"
	<< best.get_total() << "\t"
	<< total_size / population.size() << "\n";
    log.close();
  }

  vector<Individual> new_population(const Problem & problem) {
    vector<Individual> population;
    for (int i = 0; i < problem.population_size; ++i)
      population.emplace_back(Individual(problem));
    return population;
  }

  Individual selection(const Problem & problem, const vector<Individual> & population) {
    int_dist dis(0, problem.population_size - 1); // closed interval
    vector<Individual> contestants;
    // get contestants
    for (int i = 0; i < problem.tournament_size; ++i)
      contestants.emplace_back(population[dis(rg.engine)]);
    return *std::min_element(contestants.begin(), contestants.end(), compare_fitness);
  }

  vector<Individual> new_offspring(const Problem & problem, const vector<Individual> & population) {
    vector<Individual> offspring;
    while (offspring.size() != population.size()) {
      // select parents for children
      vector<Individual> parents;
      for (int i = 0; i < problem.crossover_size; ++i)
	parents.emplace_back(selection(problem, population));
      // crossover with probability
      real_dist dis(0, 1);
      if (dis(rg.engine) < problem.crossover_chance)
	crossover(problem.internals_chance, parents[0], parents[1]);
      // process children
      for (Individual & child : parents) {
	// mutate children
	child.mutate(problem.mutate_chance, problem.constant_min, problem.constant_max);
	// update fitness and size
	child.evaluate(problem.values);
	// save children
	offspring.emplace_back(child);
      }
    }
    return offspring;
  }

  const individual::Individual genetic(const problem::Problem & problem) {
    // setup time and start log
    std::time_t time = std::time(nullptr);
    std::ofstream log = open_log(time);
    log << "# running a Genetic Program @ "
	<< std::ctime(&time)
	<< "# initial depth: " << problem.max_depth
	<< ", iterations: " << problem.iterations
	<< ", population size: " << problem.population_size
	<< ", tournament size: " << problem.tournament_size << "\n"
	<< "# best fitness - average fitness - size of best - average size\n";
    log.close();
    // start timing algorithm
    std::chrono::time_point<std::chrono::system_clock> start, end;
    start = std::chrono::system_clock::now();
    // create initial popuation
    vector<Individual> population = new_population(problem);
    Individual best;
    // run algorithm to termination
    for (int iteration = 0; iteration < problem.iterations; ++iteration) {
      // find Individual with lowest "fitness" AKA error from populaiton
      best = *std::min_element(population.begin(), population.end(), compare_fitness);
      std::thread log_thread([time, best, population] {log_info(time, best, population);});
      // create replacement population
      vector<Individual> offspring = new_offspring(problem, population);
      // perform elitism
      int_dist dis(0, problem.population_size - 1);
      for (int i = 0; i < problem.elitism_size; ++i)
	offspring[dis(rg.engine)] = best;
      // replace current population with offspring
      population.swap(offspring);
      log_thread.join();
    }
    // end timing algorithm
    end = std::chrono::system_clock::now();
    // log duration
    std::chrono::duration<double> elapsed_seconds = end - start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);
    std::ofstream log_after = open_log(time);
    log_after << "# finished computation @ " << std::ctime(&end_time)
	      << "# elapsed time: " << elapsed_seconds.count() << "s\n";
    log_after.close();
    return best;
  }
}
<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <algorithm>
#include <thread>
#include <fnord-eventdb/TableReader.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-msg/MessageDecoder.h>
#include <fnord-msg/MessageEncoder.h>

namespace fnord {
namespace eventdb {

static uint64_t findHeadGen(
    const String& table_name,
    const String& replica_id,
    const String& db_path) {
  uint64_t head_gen = 0;
  auto gen_prefix = StringUtil::format("$0.$1.", table_name, replica_id);
  FileUtil::ls(db_path, [gen_prefix, &head_gen] (const String& file) -> bool {
    if (StringUtil::beginsWith(file, gen_prefix) &&
        StringUtil::endsWith(file, ".idx")) {
      auto s = file.substr(gen_prefix.size());
      auto gen = std::stoul(s.substr(0, s.size() - 4));

      if (gen > head_gen) {
        head_gen = gen;
      }
    }

    return true;
  });

  return head_gen;
}

RefPtr<TableReader> TableReader::open(
    const String& table_name,
    const String& replica_id,
    const String& db_path,
    const msg::MessageSchema& schema) {

  return new TableReader(
      table_name,
      replica_id,
      db_path,
      schema,
      findHeadGen(table_name, replica_id, db_path));
}

TableReader::TableReader(
    const String& table_name,
    const String& replica_id,
    const String& db_path,
    const msg::MessageSchema& schema,
    uint64_t head_generation) :
    name_(table_name),
    replica_id_(replica_id),
    db_path_(db_path),
    schema_(schema),
    head_gen_(head_generation) {}

const String& TableReader::name() const {
  return name_;
}

const String& TableReader::basePath() const {
  return db_path_;
}

const msg::MessageSchema& TableReader::schema() const {
  return schema_;
}

RefPtr<TableSnapshot> TableReader::getSnapshot() {
  std::unique_lock<std::mutex> lk(mutex_);
  auto g = head_gen_;
  lk.unlock();

  auto maxg = g + 100;
  while (g < maxg && !FileUtil::exists(
      StringUtil::format(
          "$0$1.$2.$3.idx",
          db_path_,
          name_,
          replica_id_,
          g + 1))) ++g;

  if (!FileUtil::exists(
      StringUtil::format(
          "$0$1.$2.$3.idx",
          db_path_,
          name_,
          replica_id_,
          g ))) {
    g = findHeadGen(name_, replica_id_, db_path_);
  }

  while (FileUtil::exists(
      StringUtil::format(
          "$0$1.$2.$3.idx",
          db_path_,
          name_,
          replica_id_,
          g + 1))) ++g;

  if (g != head_gen_) {
    lk.lock();
    head_gen_ = g;
    lk.unlock();
  }

  RefPtr<TableGeneration> head(new TableGeneration);
  head->table_name = name_;
  head->generation = g;

  if (head_gen_ > 0) {
    auto file = FileUtil::read(StringUtil::format(
        "$0/$1.$2.$3.idx",
        db_path_,
        name_,
        replica_id_,
        g));

    head->decode(file);
  }

  return new TableSnapshot(
      head,
      List<RefPtr<fnord::eventdb::TableArena>>{});
}

size_t TableReader::fetchRecords(
    const String& replica_id,
    uint64_t start_sequence,
    size_t limit,
    Function<bool (const msg::MessageObject& record)> fn) {
  auto snap = getSnapshot();

  for (const auto& c : snap->head->chunks) {
    auto cbegin = c.start_sequence;
    auto cend = cbegin + c.num_records;

    if (cbegin <= start_sequence && cend > start_sequence) {
      auto roff = start_sequence - cbegin;
      auto rlen = c.num_records - roff;

      if (limit != size_t(-1) && rlen > limit) {
        rlen = limit;
      }

      return fetchRecords(c, roff, rlen, fn);
    }
  }

  return 0;
}

size_t TableReader::fetchRecords(
    const TableChunkRef& chunk,
    size_t offset,
    size_t limit,
    Function<bool (const msg::MessageObject& record)> fn) {
  auto filename = StringUtil::format(
      "$0/$1.$2.$3.sst",
      db_path_,
      name_,
      chunk.replica_id,
      chunk.chunk_id);

#ifndef FNORD_NOTRACE
  fnord::logTrace(
      "fnord.evdb",
      "Reading rows local=$0..$1 global=$2..$3 from table=$4 chunk=$5",
      offset,
      offset + limit,
      chunk.start_sequence + offset,
      chunk.start_sequence + offset + limit,
      name_,
      chunk.replica_id + "." + chunk.chunk_id);
#endif

  sstable::SSTableReader reader(File::openFile(filename, File::O_READ));

  if (!reader.isFinalized()) {
    RAISEF(kRuntimeError, "unfinished table chunk: $0", filename);
  }

  auto body_size = reader.bodySize();
  if (body_size == 0) {
    fnord::logWarning("fnord.evdb", "empty table chunk: $0", filename);
    return 0;
  }

  size_t n = 0;
  auto cursor = reader.getCursor();
  while (cursor->valid()) {
    auto buf = cursor->getDataBuffer();

    msg::MessageObject record;
    msg::MessageDecoder::decode(buf, schema_, &record);

    fn(record);
    if (++n == limit) {
      break;
    }

    if (!cursor->next()) {
      break;
    }
  }

  return n;
}

} // namespace eventdb
} // namespace fnord

<commit_msg>fix off by one<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <algorithm>
#include <thread>
#include <fnord-eventdb/TableReader.h>
#include <fnord-base/logging.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-msg/MessageDecoder.h>
#include <fnord-msg/MessageEncoder.h>

namespace fnord {
namespace eventdb {

static uint64_t findHeadGen(
    const String& table_name,
    const String& replica_id,
    const String& db_path) {
  uint64_t head_gen = 0;
  auto gen_prefix = StringUtil::format("$0.$1.", table_name, replica_id);
  FileUtil::ls(db_path, [gen_prefix, &head_gen] (const String& file) -> bool {
    if (StringUtil::beginsWith(file, gen_prefix) &&
        StringUtil::endsWith(file, ".idx")) {
      auto s = file.substr(gen_prefix.size());
      auto gen = std::stoul(s.substr(0, s.size() - 4));

      if (gen > head_gen) {
        head_gen = gen;
      }
    }

    return true;
  });

  return head_gen;
}

RefPtr<TableReader> TableReader::open(
    const String& table_name,
    const String& replica_id,
    const String& db_path,
    const msg::MessageSchema& schema) {

  return new TableReader(
      table_name,
      replica_id,
      db_path,
      schema,
      findHeadGen(table_name, replica_id, db_path));
}

TableReader::TableReader(
    const String& table_name,
    const String& replica_id,
    const String& db_path,
    const msg::MessageSchema& schema,
    uint64_t head_generation) :
    name_(table_name),
    replica_id_(replica_id),
    db_path_(db_path),
    schema_(schema),
    head_gen_(head_generation) {}

const String& TableReader::name() const {
  return name_;
}

const String& TableReader::basePath() const {
  return db_path_;
}

const msg::MessageSchema& TableReader::schema() const {
  return schema_;
}

RefPtr<TableSnapshot> TableReader::getSnapshot() {
  std::unique_lock<std::mutex> lk(mutex_);
  auto g = head_gen_;
  lk.unlock();

  auto maxg = g + 100;
  while (g < maxg && !FileUtil::exists(
      StringUtil::format(
          "$0$1.$2.$3.idx",
          db_path_,
          name_,
          replica_id_,
          g))) ++g;

  if (!FileUtil::exists(
      StringUtil::format(
          "$0$1.$2.$3.idx",
          db_path_,
          name_,
          replica_id_,
          g ))) {
    g = findHeadGen(name_, replica_id_, db_path_);
  }

  while (FileUtil::exists(
      StringUtil::format(
          "$0$1.$2.$3.idx",
          db_path_,
          name_,
          replica_id_,
          g + 1))) ++g;

  if (g != head_gen_) {
    lk.lock();
    head_gen_ = g;
    lk.unlock();
  }

  RefPtr<TableGeneration> head(new TableGeneration);
  head->table_name = name_;
  head->generation = g;

  if (head_gen_ > 0) {
    auto file = FileUtil::read(StringUtil::format(
        "$0/$1.$2.$3.idx",
        db_path_,
        name_,
        replica_id_,
        g));

    head->decode(file);
  }

  return new TableSnapshot(
      head,
      List<RefPtr<fnord::eventdb::TableArena>>{});
}

size_t TableReader::fetchRecords(
    const String& replica_id,
    uint64_t start_sequence,
    size_t limit,
    Function<bool (const msg::MessageObject& record)> fn) {
  auto snap = getSnapshot();

  for (const auto& c : snap->head->chunks) {
    auto cbegin = c.start_sequence;
    auto cend = cbegin + c.num_records;

    if (cbegin <= start_sequence && cend > start_sequence) {
      auto roff = start_sequence - cbegin;
      auto rlen = c.num_records - roff;

      if (limit != size_t(-1) && rlen > limit) {
        rlen = limit;
      }

      return fetchRecords(c, roff, rlen, fn);
    }
  }

  return 0;
}

size_t TableReader::fetchRecords(
    const TableChunkRef& chunk,
    size_t offset,
    size_t limit,
    Function<bool (const msg::MessageObject& record)> fn) {
  auto filename = StringUtil::format(
      "$0/$1.$2.$3.sst",
      db_path_,
      name_,
      chunk.replica_id,
      chunk.chunk_id);

#ifndef FNORD_NOTRACE
  fnord::logTrace(
      "fnord.evdb",
      "Reading rows local=$0..$1 global=$2..$3 from table=$4 chunk=$5",
      offset,
      offset + limit,
      chunk.start_sequence + offset,
      chunk.start_sequence + offset + limit,
      name_,
      chunk.replica_id + "." + chunk.chunk_id);
#endif

  sstable::SSTableReader reader(File::openFile(filename, File::O_READ));

  if (!reader.isFinalized()) {
    RAISEF(kRuntimeError, "unfinished table chunk: $0", filename);
  }

  auto body_size = reader.bodySize();
  if (body_size == 0) {
    fnord::logWarning("fnord.evdb", "empty table chunk: $0", filename);
    return 0;
  }

  size_t n = 0;
  auto cursor = reader.getCursor();
  while (cursor->valid()) {
    auto buf = cursor->getDataBuffer();

    msg::MessageObject record;
    msg::MessageDecoder::decode(buf, schema_, &record);

    fn(record);
    if (++n == limit) {
      break;
    }

    if (!cursor->next()) {
      break;
    }
  }

  return n;
}

} // namespace eventdb
} // namespace fnord

<|endoftext|>


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

#ifndef SD_SLIDESORTER_SELECTION_FUNCTION_HXX
#define SD_SLIDESORTER_SELECTION_FUNCTION_HXX

#include "controller/SlsSlideFunction.hxx"

#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif

class SdSlideViewShell;
class SdWindow;
class SdSlideView;
class SdDrawDocument;
class Sound;

namespace sd { namespace slidesorter { namespace model {
class PageDescriptor;
} } }

namespace sd { namespace slidesorter { namespace controller {

class SlideSorterController;

class SelectionFunction
    : public SlideFunction
{
public:
    TYPEINFO();

    SelectionFunction (
        SlideSorterController& rController,
        SfxRequest& rRequest);

    virtual ~SelectionFunction (void);
                                                   // Mouse- & Key-Events
    virtual BOOL KeyInput(const KeyEvent& rKEvt);
    virtual BOOL MouseMove(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);
    virtual void Paint(const Rectangle& rRect, SdWindow* pWin);

    virtual void Activate();           // Function aktivieren
    virtual void Deactivate();         // Function deaktivieren

    virtual void ScrollStart();
    virtual void ScrollEnd();

    /// Forward to the clipboard manager.
    virtual void DoCut (void);

    /// Forward to the clipboard manager.
    virtual void DoCopy (void);

    /// Forward to the clipboard manager.
    virtual void DoPaste (void);

    /** is called when the current function should be aborted.

        This is used when a function gets a KEY_ESCAPE but can also
        be called directly.

        @returns
            true if a active function was aborted
    */
    virtual bool cancel();

protected:
    SlideSorterController& mrController;

private:
    /// Set in MouseButtonDown this flag indicates that a page has been hit.
    bool mbPageHit;

    /// This flag indicates whether the selection rectangle is visible.
    bool mbRectangleSelection;

    /// The rectangle of the mouse drag selection.
    Rectangle maDragSelectionRectangle;
    bool mbDragSelection;

    /// Box of the insert marker in model coordinates.
    Rectangle maInsertionMarkerBox;
    Sound* mpSound;
    class ShowingEffectInfo;
    ShowingEffectInfo* mpShowingEffectInfo;

    model::PageDescriptor* mpRangeSelectionAnchor;

    /** We use this flag to filter out the cases where MouseMotion() is called
        with a pressed mouse button but without a prior MouseButtonDown()
        call.  This is an indication that the mouse button was pressed over
        another control, e.g. the view tab bar, and that a re-layout of the
        controls moved the slide sorter under the mouse.
    */
    bool mbProcessingMouseButtonDown;

    /** Show the effect of the specified page.
    */
    void ShowEffect (model::PageDescriptor& rDescriptor);

    /** Return whether there is currently an effect being shown.
    */
    bool IsShowingEffect (void) const;

    DECL_LINK( DragSlideHdl, Timer* );
    void StartDrag (void);

    /** Set the selection to exactly the specified page and also set it as
        the current page.  Furthermore, if the view on which this selection
        function is working is the main view then the view is switched to
        the regular editing view.
        @param rDescriptor
            This page descriptor represents the page which will (a) replace
            the current selection and (b) become the current page of the
            main view.
    */
    void SetCurrentPageAndSwitchView (model::PageDescriptor& rDescriptor);

    /** Make the slide nOffset slides away of the current one the new
        current slide.  When the new index is outside the range of valid
        page numbers it is clipped to that range.
        @param nOffset
            When nOffset is negative then go back.  When nOffset if positive go
            forward.  When it is zero then ignore the call.
    */
    void GotoNextPage (int nOffset);

    void ProcessMouseEvent (sal_uInt32 nEventType, const MouseEvent& rEvent);

    // What follows are a couple of helper methods that are used by
    // ProcessMouseEvent().

    /// Select the specified page and set the selection anchor.
    void SelectHitPage (model::PageDescriptor& rDescriptor);
    /// Deselect the specified page.
    void DeselectHitPage (model::PageDescriptor& rDescriptor);
    /// Deselect all pages.
    void DeselectAllPages (void);

    /** for a possibly following mouse motion by starting the drag timer
        that after a short time of pressed but un-moved mouse starts a drag
        operation.
    */
    void PrepareMouseMotion (const Point& aMouseModelPosition);

    /** Set the current page of the main view to the one specified by the
        given descriptor.
    */
    void SetCurrentPage (model::PageDescriptor& rDescriptor);
    /** Select all pages between and including the selection anchor and the
        specified page.
    */
    void RangeSelect (model::PageDescriptor& rDescriptor);

    /** Start a rectangle selection at the given position.
    */
    void StartRectangleSelection (const Point& aMouseModelPosition);

    /** Update the rectangle selection so that the given position becomes
        the new second point of the selection rectangle.
    */
    void UpdateRectangleSelection (const Point& aMouseModelPosition);

    /** Select all pages that lie completly in the selection rectangle.
    */
    void ProcessRectangleSelection (bool bToggleSelection);

    /** Create a substitution display of the currently selected pages and
        use the given position as the anchor point.
    */
    void CreateSubstitution (const Point& rMouseModelPosition);

    /** Move the substitution display by the distance the mouse has
        travelled since the last call to this method or to
        CreateSubstitution().  The given point becomes the new anchor.
    */
    void UpdateSubstitution (const Point& rMouseModelPosition);

    /** Move the substitution display of the currently selected pages.
    */
    void MoveSubstitution (void);
};

} } } // end of namespace ::sd::slidesorter::controller

#endif

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

#include "controller/SlsSlideFunction.hxx"

#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#include <memory>

class SdSlideViewShell;
class SdWindow;
class SdSlideView;
class SdDrawDocument;
class Sound;

namespace sd { namespace slidesorter { namespace model {
class PageDescriptor;
} } }

namespace sd { namespace slidesorter { namespace controller {

class SlideSorterController;

class SelectionFunction
    : public SlideFunction
{
public:
    TYPEINFO();

    SelectionFunction (
        SlideSorterController& rController,
        SfxRequest& rRequest);

    virtual ~SelectionFunction (void);
                                                   // Mouse- & Key-Events
    virtual BOOL KeyInput(const KeyEvent& rKEvt);
    virtual BOOL MouseMove(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);
    virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);
    virtual void Paint(const Rectangle& rRect, SdWindow* pWin);

    virtual void Activate();           // Function aktivieren
    virtual void Deactivate();         // Function deaktivieren

    virtual void ScrollStart();
    virtual void ScrollEnd();

    /// Forward to the clipboard manager.
    virtual void DoCut (void);

    /// Forward to the clipboard manager.
    virtual void DoCopy (void);

    /// Forward to the clipboard manager.
    virtual void DoPaste (void);

    /** is called when the current function should be aborted.

        This is used when a function gets a KEY_ESCAPE but can also
        be called directly.

        @returns
            true if a active function was aborted
    */
    virtual bool cancel();

protected:
    SlideSorterController& mrController;

private:
    class SubstitutionHandler;
    class EventDescriptor;
    class InsertionIndicatorHandler;

    /// Set in MouseButtonDown this flag indicates that a page has been hit.
    bool mbPageHit;

    /// The rectangle of the mouse drag selection.
    Rectangle maDragSelectionRectangle;
    bool mbDragSelection;

    /// Box of the insert marker in model coordinates.
    Rectangle maInsertionMarkerBox;

    /** We use this flag to filter out the cases where MouseMotion() is called
        with a pressed mouse button but without a prior MouseButtonDown()
        call.  This is an indication that the mouse button was pressed over
        another control, e.g. the view tab bar, and that a re-layout of the
        controls moved the slide sorter under the mouse.
    */
    bool mbProcessingMouseButtonDown;

    ::std::auto_ptr<SubstitutionHandler> mpSubstitutionHandler;

    ::std::auto_ptr<InsertionIndicatorHandler> mpInsertionIndicatorHandler;

    DECL_LINK( DragSlideHdl, Timer* );
    void StartDrag (void);

    /** Set the selection to exactly the specified page and also set it as
        the current page.
    */
    void SetCurrentPage (model::PageDescriptor& rDescriptor);

    /** When the view on which this selection function is working is the
        main view then the view is switched to the regular editing view.
    */
    void SwitchView (model::PageDescriptor& rDescriptor);

    /** Make the slide nOffset slides away of the current one the new
        current slide.  When the new index is outside the range of valid
        page numbers it is clipped to that range.
        @param nOffset
            When nOffset is negative then go back.  When nOffset if positive go
            forward.  When it is zero then ignore the call.
    */
    void GotoNextPage (int nOffset);

    void ProcessMouseEvent (sal_uInt32 nEventType, const MouseEvent& rEvent);

    // What follows are a couple of helper methods that are used by
    // ProcessMouseEvent().

    /// Select the specified page and set the selection anchor.
    void SelectHitPage (model::PageDescriptor& rDescriptor);
    /// Deselect the specified page.
    void DeselectHitPage (model::PageDescriptor& rDescriptor);
    /// Deselect all pages.
    void DeselectAllPages (void);

    /** for a possibly following mouse motion by starting the drag timer
        that after a short time of pressed but un-moved mouse starts a drag
        operation.
    */
    void PrepareMouseMotion (const Point& aMouseModelPosition);

    /** Select all pages between and including the selection anchor and the
        specified page.
    */
    void RangeSelect (model::PageDescriptor& rDescriptor);

    /** Start a rectangle selection at the given position.
    */
    void StartRectangleSelection (const Point& aMouseModelPosition);

    /** Update the rectangle selection so that the given position becomes
        the new second point of the selection rectangle.
    */
    void UpdateRectangleSelection (const Point& aMouseModelPosition);

    /** Select all pages that lie completly in the selection rectangle.
    */
    void ProcessRectangleSelection (bool bToggleSelection);

    /** Hide and clear the insertion indiciator, substitution display and
        selection rectangle.
    */
    void ClearOverlays (void);

    /** Compute a numerical code that describes a mouse event and that can
        be used for fast look up of the appropriate reaction.
    */
    sal_uInt32 EncodeMouseEvent (
        const EventDescriptor& rDescriptor,
        const MouseEvent& rEvent) const;

    void EventPreprocessing (const EventDescriptor& rEvent);
    bool EventProcessing (const EventDescriptor& rEvent);
    void EventPostprocessing (const EventDescriptor& rEvent);
};

} } } // end of namespace ::sd::slidesorter::controller

#endif

<|endoftext|>


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

#ifndef PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_
#define PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_

#include "pcl/features/principal_curvatures.h"

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::PrincipalCurvaturesEstimation<PointInT, PointNT, PointOutT>::computePointPrincipalCurvatures (
      const pcl::PointCloud<PointNT> &normals, int p_idx, const std::vector<int> &indices,
      float &pcx, float &pcy, float &pcz, float &pc1, float &pc2)
{
  EIGEN_ALIGN16 Eigen::Matrix3f I = Eigen::Matrix3f::Identity ();
  Eigen::Vector3f n_idx (normals.points[p_idx].normal[0], normals.points[p_idx].normal[1], normals.points[p_idx].normal[2]);
  EIGEN_ALIGN16 Eigen::Matrix3f M = I - n_idx * n_idx.transpose ();    // projection matrix (into tangent plane)

  // Project normals into the tangent plane
  Eigen::Vector3f normal;
  projected_normals_.resize (indices.size ());
  xyz_centroid_.setZero ();
  for (size_t idx = 0; idx < indices.size(); ++idx)
  {
    normal[0] = normals.points[indices[idx]].normal[0];
    normal[1] = normals.points[indices[idx]].normal[1];
    normal[2] = normals.points[indices[idx]].normal[2];

    projected_normals_[idx] = M * normal;
    xyz_centroid_ += projected_normals_[idx];
  }

  // Estimate the XYZ centroid
  xyz_centroid_ /= indices.size ();

  // Initialize to 0
  covariance_matrix_.setZero ();

  double demean_xy, demean_xz, demean_yz;
  // For each point in the cloud
  for (size_t idx = 0; idx < indices.size (); ++idx)
  {
    demean_ = projected_normals_[idx] - xyz_centroid_;

    demean_xy = demean_[0] * demean_[1];
    demean_xz = demean_[0] * demean_[2];
    demean_yz = demean_[1] * demean_[2];

    covariance_matrix_(0, 0) += demean_[0] * demean_[0];
    covariance_matrix_(0, 1) += demean_xy;
    covariance_matrix_(0, 2) += demean_xz;

    covariance_matrix_(1, 0) += demean_xy;
    covariance_matrix_(1, 1) += demean_[1] * demean_[1];
    covariance_matrix_(1, 2) += demean_yz;

    covariance_matrix_(2, 0) += demean_xz;
    covariance_matrix_(2, 1) += demean_yz;
    covariance_matrix_(2, 2) += demean_[2] * demean_[2];
  }

  // Extract the eigenvalues and eigenvectors
  //Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> ei_symm (covariance_matrix_);
  //eigenvalues_  = ei_symm.eigenvalues ();
  //eigenvectors_ = ei_symm.eigenvectors ();
  pcl::eigen33 (covariance_matrix_, eigenvectors_, eigenvalues_);

  pcx = eigenvectors_ (0, 2);
  pcy = eigenvectors_ (1, 2);
  pcz = eigenvectors_ (2, 2);
  pc1 = eigenvalues_ (2);
  //pc2 = eigenvalues_ (1); Here is an error, min eval has zero index. Fixed in r2635.
  pc2 = eigenvalues_ (0);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::PrincipalCurvaturesEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output)
{
  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);

  // Iterating over the entire index vector
  for (size_t idx = 0; idx < indices_->size (); ++idx)
  {
    this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists);

    // Estimate the principal curvatures at each patch
    computePointPrincipalCurvatures (*normals_, (*indices_)[idx], nn_indices,
                                     output.points[idx].principal_curvature[0], output.points[idx].principal_curvature[1], output.points[idx].principal_curvature[2],
                                     output.points[idx].pc1, output.points[idx].pc2);
  }
}

#define PCL_INSTANTIATE_PrincipalCurvaturesEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::PrincipalCurvaturesEstimation<T,NT,OutT>;

#endif    // PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_
<commit_msg>issue #364, reverted commit r2635. First eigen value evaluates to 0, that's why middle is taken.<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2009, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 */

#ifndef PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_
#define PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_

#include "pcl/features/principal_curvatures.h"

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::PrincipalCurvaturesEstimation<PointInT, PointNT, PointOutT>::computePointPrincipalCurvatures (
      const pcl::PointCloud<PointNT> &normals, int p_idx, const std::vector<int> &indices,
      float &pcx, float &pcy, float &pcz, float &pc1, float &pc2)
{
  EIGEN_ALIGN16 Eigen::Matrix3f I = Eigen::Matrix3f::Identity ();
  Eigen::Vector3f n_idx (normals.points[p_idx].normal[0], normals.points[p_idx].normal[1], normals.points[p_idx].normal[2]);
  EIGEN_ALIGN16 Eigen::Matrix3f M = I - n_idx * n_idx.transpose ();    // projection matrix (into tangent plane)

  // Project normals into the tangent plane
  Eigen::Vector3f normal;
  projected_normals_.resize (indices.size ());
  xyz_centroid_.setZero ();
  for (size_t idx = 0; idx < indices.size(); ++idx)
  {
    normal[0] = normals.points[indices[idx]].normal[0];
    normal[1] = normals.points[indices[idx]].normal[1];
    normal[2] = normals.points[indices[idx]].normal[2];

    projected_normals_[idx] = M * normal;
    xyz_centroid_ += projected_normals_[idx];
  }

  // Estimate the XYZ centroid
  xyz_centroid_ /= indices.size ();

  // Initialize to 0
  covariance_matrix_.setZero ();

  double demean_xy, demean_xz, demean_yz;
  // For each point in the cloud
  for (size_t idx = 0; idx < indices.size (); ++idx)
  {
    demean_ = projected_normals_[idx] - xyz_centroid_;

    demean_xy = demean_[0] * demean_[1];
    demean_xz = demean_[0] * demean_[2];
    demean_yz = demean_[1] * demean_[2];

    covariance_matrix_(0, 0) += demean_[0] * demean_[0];
    covariance_matrix_(0, 1) += demean_xy;
    covariance_matrix_(0, 2) += demean_xz;

    covariance_matrix_(1, 0) += demean_xy;
    covariance_matrix_(1, 1) += demean_[1] * demean_[1];
    covariance_matrix_(1, 2) += demean_yz;

    covariance_matrix_(2, 0) += demean_xz;
    covariance_matrix_(2, 1) += demean_yz;
    covariance_matrix_(2, 2) += demean_[2] * demean_[2];
  }

  // Extract the eigenvalues and eigenvectors
  //Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> ei_symm (covariance_matrix_);
  //eigenvalues_  = ei_symm.eigenvalues ();
  //eigenvectors_ = ei_symm.eigenvectors ();
  pcl::eigen33 (covariance_matrix_, eigenvectors_, eigenvalues_);

  pcx = eigenvectors_ (0, 2);
  pcy = eigenvectors_ (1, 2);
  pcz = eigenvectors_ (2, 2);
  pc1 = eigenvalues_ (2);
  pc2 = eigenvalues_ (1);
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT> void
pcl::PrincipalCurvaturesEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output)
{
  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);

  // Iterating over the entire index vector
  for (size_t idx = 0; idx < indices_->size (); ++idx)
  {
    this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists);

    // Estimate the principal curvatures at each patch
    computePointPrincipalCurvatures (*normals_, (*indices_)[idx], nn_indices,
                                     output.points[idx].principal_curvature[0], output.points[idx].principal_curvature[1], output.points[idx].principal_curvature[2],
                                     output.points[idx].pc1, output.points[idx].pc2);
  }
}

#define PCL_INSTANTIATE_PrincipalCurvaturesEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::PrincipalCurvaturesEstimation<T,NT,OutT>;

#endif    // PCL_FEATURES_IMPL_PRINCIPAL_CURVATURES_H_
<|endoftext|>


<commit_before>#include "minishift.h"
#include "glcdfont.h"

Minishift::Minishift(int data_pin, int clock_pin, int latch_pin) {
	this->data_pin = data_pin;
	this->clock_pin = clock_pin;
	this->latch_pin = latch_pin;
	this->latch_state = HIGH;

	pinMode(data_pin, OUTPUT);
	pinMode(clock_pin, OUTPUT);
	digitalWrite(latch_pin, HIGH);
	pinMode(latch_pin, OUTPUT);
}

void Minishift::startTransaction() {
	if(this->latch_state != LOW) {
		this->latch_state = LOW;
		digitalWrite(this->latch_pin, this->latch_state);
	}
}

void Minishift::writeColumns(const uint8_t *buf, int len) {
	this->writeColumns(buf, len, -1);
}

void Minishift::writeColumns(const uint8_t *buf, int len, int ms) {
	for(int i = 0; i < len; i++) {
		this->startTransaction();
		shiftOut(this->data_pin, this->clock_pin, LSBFIRST, buf[i]);
		if(ms != -1) {
			this->update();
			delay(ms);
		}
	}
}

void Minishift::writeString(const char *str) {
	this->writeString(str, -1);
}

void Minishift::writeString(const char *str, int ms) {
	this->writeString(str, ms, 0);
}

void Minishift::writeString(const char *str, int ms, int trailing) {
	for(const char *c = str; *c != '\0'; c++) {
		for(int col = 0; col < 5; col++) {
			this->startTransaction();
			shiftOut(this->data_pin, this->clock_pin, LSBFIRST, pgm_read_byte(font + (*c * 5) + col));
			this->update();
			if(ms != -1) {
				delay(ms);
			}
		}
		for(int col = 0; col < trailing; col++) {
			this->startTransaction();
			shiftOut(this->data_pin, this->clock_pin, LSBFIRST, 0);
			this->update();
			if(ms != -1) {
				delay(ms);
			}
		}
	}
}

void Minishift::update() {
	if(this->latch_state != HIGH) {
		this->latch_state = HIGH;
		digitalWrite(this->latch_pin, this->latch_state);
	}
}
<commit_msg>Update minishift.cpp<commit_after>#include "minishift.h"
#include "glcdfont.h"

Minishift::Minishift(int data_pin, int clock_pin, int latch_pin) {
	this->data_pin = data_pin;
	this->clock_pin = clock_pin;
	this->latch_pin = latch_pin;
	this->latch_state = HIGH;

	pinMode(data_pin, OUTPUT);
	pinMode(clock_pin, OUTPUT);
	digitalWrite(latch_pin, HIGH);
	pinMode(latch_pin, OUTPUT);
}

void Minishift::startTransaction() {
	if(this->latch_state != LOW) {
		this->latch_state = LOW;
		digitalWrite(this->latch_pin, this->latch_state);
	}
}

void Minishift::writeColumns(const uint8_t *buf, int len) {
	this->writeColumns(buf, len, -1);
}

void Minishift::writeColumns(const uint8_t *buf, int len, int ms) {
	for(int i = 0; i < len; i++) {
		this->startTransaction();
		shiftOut(this->data_pin, this->clock_pin, LSBFIRST, buf[i]);
		this->update();
		if(ms != -1) {
			delay(ms);
		}
	}
}

void Minishift::writeString(const char *str) {
	this->writeString(str, -1);
}

void Minishift::writeString(const char *str, int ms) {
	this->writeString(str, ms, 0);
}

void Minishift::writeString(const char *str, int ms, int trailing) {
	for(const char *c = str; *c != '\0'; c++) {
		for(int col = 0; col < 5; col++) {
			this->startTransaction();
			shiftOut(this->data_pin, this->clock_pin, LSBFIRST, pgm_read_byte(font + (*c * 5) + col));
			this->update();
			if(ms != -1) {
				delay(ms);
			}
		}
		for(int col = 0; col < trailing; col++) {
			this->startTransaction();
			shiftOut(this->data_pin, this->clock_pin, LSBFIRST, 0);
			this->update();
			if(ms != -1) {
				delay(ms);
			}
		}
	}
}

void Minishift::update() {
	if(this->latch_state != HIGH) {
		this->latch_state = HIGH;
		digitalWrite(this->latch_pin, this->latch_state);
	}
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <iostream>

#include "../include/spica.h"
using namespace spica;

int main(int argc, char** argv) {
    std::cout << "*** spica: Subsurface scattering (SPPM) ***" << std::endl;

    const int width = argc >= 2 ? atoi(argv[1]) : 320;
    const int height = argc >= 3 ? atoi(argv[2]) : 240;
    const int samplePerPixel = argc >= 4 ? atoi(argv[3]) : 32;
    const int numPhotons = argc >= 5 ? atoi(argv[4]) : 1000000;

    std::cout << "      width: " << width << std::endl;
    std::cout << "     height: " << height << std::endl;
    std::cout << "  sample/px: " << samplePerPixel << std::endl;
    std::cout << "    photons: " << numPhotons << std::endl << std::endl;

    Scene scene;
    Camera camera;
    // cornellBoxDragon(&scene, &camera, width, height);
    kittenBox(&scene, &camera, width, height);

    BSSRDF bssrdf = DiffusionBSSRDF::factory(1.0e-4, 10.0, 1.3);

    SubsurfaceSPPMRenderer renderer;

    Timer timer;
    timer.start();
    renderer.render(scene, camera, bssrdf, samplePerPixel, numPhotons, QUASI_MONTE_CARLO);
    printf("Time: %f sec\n", timer.stop());
}
<commit_msg>Minor bug fix.<commit_after>#include <cstdio>
#include <iostream>

#include "../include/spica.h"
using namespace spica;

int main(int argc, char** argv) {
    std::cout << "*** spica: Subsurface scattering (SPPM) ***" << std::endl;

    const int width = argc >= 2 ? atoi(argv[1]) : 320;
    const int height = argc >= 3 ? atoi(argv[2]) : 240;
    const int samplePerPixel = argc >= 4 ? atoi(argv[3]) : 32;
    const int numPhotons = argc >= 5 ? atoi(argv[4]) : 1000000;

    std::cout << "      width: " << width << std::endl;
    std::cout << "     height: " << height << std::endl;
    std::cout << "  sample/px: " << samplePerPixel << std::endl;
    std::cout << "    photons: " << numPhotons << std::endl << std::endl;

    Scene scene;
    Camera camera;
    // cornellBoxDragon(&scene, &camera, width, height);
    kittenBox(&scene, &camera, width, height);

    BSSRDF bssrdf = DipoleBSSRDF::factory(1.0e-4, 10.0, 1.3);

    SubsurfaceSPPMRenderer renderer;

    Timer timer;
    timer.start();
    renderer.render(scene, camera, bssrdf, samplePerPixel, numPhotons, QUASI_MONTE_CARLO);
    printf("Time: %f sec\n", timer.stop());
}
<|endoftext|>