<commit_before>#include "LanguageTranslator.h"

#include <sstream>

#include "Logger.h"
#include "StringUtils.h"

std::vector<std::wstring> LanguageTranslator::CurrentLocale() {
    wchar_t buf[LOCALE_NAME_MAX_LENGTH];
    GetUserDefaultLocaleName(buf, LOCALE_NAME_MAX_LENGTH);
    CLOG(L"Locale: %s", buf);

    std::wstring locale(buf);

    /* Remove custom supplemental locales */
    int custom = locale.find(L"-x-");
    if (custom > 0) {
        locale.erase(custom, locale.size() - 1);
    }

    /* Split up parts of the locale string */
    std::vector<std::wstring> parts;
    std::wstring sub;
    std::wistringstream ss(locale);
    while (std::getline(ss, sub, L'-')) {
        parts.push_back(sub);
    }

    std::vector<std::wstring> finalLocale;
    for (std::wstring sub : parts) {
        /* Remove sort orders */
        int sort = sub.find(L"_");
        if (sort > 0) {
            sub.erase(sort, sub.size() - 1);
        }

        finalLocale.push_back(sub);
    }

    return finalLocale;
}

LanguageTranslator::LanguageTranslator() {

}

LanguageTranslator::LanguageTranslator(std::wstring langFileName) {
    CLOG(L"Loading language XML: %s", langFileName.c_str());
    std::string u8FileName = StringUtils::Narrow(langFileName);
    tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());
    if (result != tinyxml2::XMLError::XML_SUCCESS) {
        if (result == tinyxml2::XMLError::XML_ERROR_FILE_NOT_FOUND) {
            //Error::ErrorMessageDie(SKINERR_INVALID_SKIN);
        }
        throw std::logic_error("Failed to read XML file!");
    }

    _root = _xml.GetDocument()->FirstChildElement("translation");
    if (_root == NULL) {
        throw std::runtime_error("Could not find root XML element");
    }

    _author = StringUtils::Widen(_root->Attribute("author", ""));
    tinyxml2::XMLElement *trans = _root->FirstChildElement("language");
    if (trans == NULL) {
        CLOG(L"No <language> tag.");
        return;
    }

    CLOG(L"Loading translation header");
    _name = StringUtils::Widen(trans->Attribute("name"));
    _id = StringUtils::Widen(trans->Attribute("id"));

    if (_name == L"" || _id == L"") {
        CLOG(L"whoops");
    }

    QCLOG(L"Language name: %s", _name.c_str());
    QCLOG(L"Locale identifier: %s", _id.c_str());
    const char *regions = trans->Attribute("regions");
    if (regions != NULL) {
        std::string region;
        std::istringstream ss(regions);
        while (std::getline(ss, region, ',')) {
            std::wstring regionStr = StringUtils::Widen(region);
            _regions.push_back(regionStr);
            QCLOG(L"Region: %s", regionStr.c_str());
        }
    }
}

void LanguageTranslator::LoadTranslations() {
    if (_root == NULL) {
        return;
    }

    tinyxml2::XMLElement *string = _root->FirstChildElement("string");
    for (; string != NULL; string = string->NextSiblingElement()) {
        const char *originalText = NULL;
        const char *translatedText = NULL;

        tinyxml2::XMLElement *orig = string->FirstChildElement("original");
        if (orig) {
            originalText = orig->GetText();
        }
        tinyxml2::XMLElement *trans = string->FirstChildElement("translation");
        if (trans) {
            translatedText = trans->GetText();
        }

        if (originalText && translatedText) {
            std::wstring origStr = StringUtils::Widen(originalText);
            std::wstring transStr = StringUtils::Widen(translatedText);
            _translations[origStr] = transStr;
        }
    }
}

std::wstring &LanguageTranslator::Translate(std::wstring &str) {
    if (_translations.find(str) == _translations.end()) {
        /* If the translation isn't found, return the original string. */
        return str;
    }
    return _translations[str];
}<commit_msg>Fix error reporting<commit_after>#include "LanguageTranslator.h"

#include <sstream>

#include "Logger.h"
#include "StringUtils.h"

std::vector<std::wstring> LanguageTranslator::CurrentLocale() {
    wchar_t buf[LOCALE_NAME_MAX_LENGTH];
    GetUserDefaultLocaleName(buf, LOCALE_NAME_MAX_LENGTH);
    CLOG(L"Locale: %s", buf);

    std::wstring locale(buf);

    /* Remove custom supplemental locales */
    int custom = locale.find(L"-x-");
    if (custom > 0) {
        locale.erase(custom, locale.size() - 1);
    }

    /* Split up parts of the locale string */
    std::vector<std::wstring> parts;
    std::wstring sub;
    std::wistringstream ss(locale);
    while (std::getline(ss, sub, L'-')) {
        parts.push_back(sub);
    }

    std::vector<std::wstring> finalLocale;
    for (std::wstring sub : parts) {
        /* Remove sort orders */
        int sort = sub.find(L"_");
        if (sort > 0) {
            sub.erase(sort, sub.size() - 1);
        }

        finalLocale.push_back(sub);
    }

    return finalLocale;
}

LanguageTranslator::LanguageTranslator() {

}

LanguageTranslator::LanguageTranslator(std::wstring langFileName) {
    CLOG(L"Loading language XML: %s", langFileName.c_str());
    std::string u8FileName = StringUtils::Narrow(langFileName);
    tinyxml2::XMLError result = _xml.LoadFile(u8FileName.c_str());
    if (result != tinyxml2::XMLError::XML_SUCCESS) {
        if (result == tinyxml2::XMLError::XML_ERROR_FILE_NOT_FOUND) {
            CLOG(L"File not found");
        }
        return;
    }

    _root = _xml.GetDocument()->FirstChildElement("translation");
    if (_root == NULL) {
        throw std::runtime_error("Could not find root XML element");
    }

    /*
    _author = StringUtils::Widen(_root->Attribute("author", ""));
    */

    tinyxml2::XMLElement *trans = _root->FirstChildElement("language");
    if (trans == NULL) {
        CLOG(L"No <language> tag.");
        return;
    }

    CLOG(L"Loading translation header");
    _name = StringUtils::Widen(trans->Attribute("name"));
    _id = StringUtils::Widen(trans->Attribute("id"));

    if (_name == L"" || _id == L"") {
        CLOG(L"whoops");
    }

    QCLOG(L"Language name: %s", _name.c_str());
    QCLOG(L"Locale identifier: %s", _id.c_str());
    const char *regions = trans->Attribute("regions");
    if (regions != NULL) {
        std::string region;
        std::istringstream ss(regions);
        while (std::getline(ss, region, ',')) {
            std::wstring regionStr = StringUtils::Widen(region);
            _regions.push_back(regionStr);
            QCLOG(L"Region: %s", regionStr.c_str());
        }
    }
}

void LanguageTranslator::LoadTranslations() {
    if (_root == NULL) {
        return;
    }

    tinyxml2::XMLElement *string = _root->FirstChildElement("string");
    for (; string != NULL; string = string->NextSiblingElement()) {
        const char *originalText = NULL;
        const char *translatedText = NULL;

        tinyxml2::XMLElement *orig = string->FirstChildElement("original");
        if (orig) {
            originalText = orig->GetText();
        }
        tinyxml2::XMLElement *trans = string->FirstChildElement("translation");
        if (trans) {
            translatedText = trans->GetText();
        }

        if (originalText && translatedText) {
            std::wstring origStr = StringUtils::Widen(originalText);
            std::wstring transStr = StringUtils::Widen(translatedText);
            _translations[origStr] = transStr;
        }
    }
}

std::wstring &LanguageTranslator::Translate(std::wstring &str) {
    if (_translations.find(str) == _translations.end()) {
        /* If the translation isn't found, return the original string. */
        return str;
    }
    return _translations[str];
}<|endoftext|>


<commit_before>/**
 * \file TypedBaseFilter.cpp
 */

#include "TypedBaseFilter.h"

#include <cstdint>

#include <boost/mpl/distance.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/utility/enable_if.hpp>

#include "Utilities.h"

namespace
{
  typedef boost::mpl::vector<std::int16_t, std::int32_t, std::int64_t, float, double> ConversionTypes;

  template<typename Vector, typename DataType>
  typename boost::enable_if<typename boost::mpl::empty<Vector>::type, void>::type
  convert_array(ATK::BaseFilter* filter, int port, DataType* converted_input, int size, int type)
  {
  }

  template<typename Vector, typename DataType>
  typename boost::disable_if<typename boost::mpl::empty<Vector>::type, void>::type
      convert_array(ATK::BaseFilter* filter, int port, DataType* converted_input, int size, int type)
  {
    if(type != 0)
    {
      convert_array<typename boost::mpl::pop_front<Vector>::type, DataType>(filter, port, converted_input, size, type - 1);
    }
    else
    {
      typedef typename boost::mpl::front<Vector>::type InputOriginalType;
      InputOriginalType* original_input_array = static_cast<ATK::TypedBaseFilter<InputOriginalType>*>(filter)->get_output_array(port);
      ATK::ConversionUtilities<InputOriginalType, DataType>::convert_array(original_input_array, converted_input, size);
    }
  }
}

namespace ATK
{
  template<typename DataType>
  TypedBaseFilter<DataType>::TypedBaseFilter(int nb_input_ports, int nb_output_ports)
  :Parent(nb_input_ports, nb_output_ports), converted_inputs_delay(nb_input_ports), converted_inputs(nb_input_ports, NULL), converted_inputs_size(nb_input_ports, 0), outputs_delay(nb_output_ports), outputs(nb_output_ports, NULL), outputs_size(nb_output_ports, 0), input_delay(0), output_delay(0)
  {
  }

  template<typename DataType>
  TypedBaseFilter<DataType>::~TypedBaseFilter()
  {
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::set_nb_input_ports(int nb_ports)
  {
    Parent::set_nb_input_ports(nb_ports);
    std::vector<boost::scoped_array<DataType> > temp(nb_ports);
    converted_inputs_delay.swap(temp);
    converted_inputs.assign(nb_ports, NULL);
    converted_inputs_size.resize(nb_ports, 0);
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::set_nb_output_ports(int nb_ports)
  {
    Parent::set_nb_output_ports(nb_ports);
    std::vector<boost::scoped_array<DataType> > temp(nb_ports);
    outputs_delay.swap(temp);
    outputs.assign(nb_ports, NULL);
    outputs_size.resize(nb_ports, 0);
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::process_impl(long size)
  {
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::prepare_process(long size)
  {
    convert_inputs(size);
  }

  template<typename DataType>
  int TypedBaseFilter<DataType>::get_type() const
  {
    return boost::mpl::distance<boost::mpl::begin<ConversionTypes>::type, typename boost::mpl::find<ConversionTypes, DataType>::type >::value;
  }

  template<typename DataType>
  DataType* TypedBaseFilter<DataType>::get_output_array(int port)
  {
    return outputs[port];
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::convert_inputs(long size)
  {
    for(int i = 0; i < nb_input_ports; ++i)
    {
      if(converted_inputs_size[i] < size)
      {
        boost::scoped_array<DataType> temp(new DataType[input_delay + size]);
        if(converted_inputs_size[i] == 0)
        {
          for(int j = 0; j < input_delay; ++j)
          {
            temp[j] = 0;
          }
        }
        else
        {
          for(int j = 0; j < input_delay; ++j)
          {
            temp[j] = converted_inputs[i][converted_inputs_size[i] + j - input_delay];
          }
        }

        converted_inputs_delay[i].swap(temp);
        converted_inputs[i] = converted_inputs_delay[i].get() + input_delay;
        converted_inputs_size[i] = size;
      }
      else
      {
        for(int j = 0; j < input_delay; ++j)
        {
          converted_inputs[i][j - input_delay] = converted_inputs[i][converted_inputs_size[i] + j - input_delay];
        }
      }
      convert_array<ConversionTypes, DataType>(connections[i].second, connections[i].first, converted_inputs[i], size, connections[i].second->get_type());
    }
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::prepare_outputs(long size)
  {
    for(int i = 0; i < nb_output_ports; ++i)
    {
      if(outputs_size[i] < size)
      {
        boost::scoped_array<DataType> temp(new DataType[output_delay + size]);
        if(outputs_size[i] == 0)
        {
          for(int j = 0; j < output_delay; ++j)
          {
            temp[j] = 0;
          }
        }
        else
        {
          for(int j = 0; j < output_delay; ++j)
          {
            temp[j] = outputs[i][outputs_size[i] + j - output_delay];
          }
        }

        outputs_delay[i].swap(temp);
        outputs[i] = outputs_delay[i].get() + output_delay;
        outputs_size[i] = size;
      }
      else
      {
        for(int j = 0; j < output_delay; ++j)
        {
          outputs[i][j - output_delay] = outputs[i][outputs_size[i] + j - output_delay];
        }
      }
    }
  }

  template class TypedBaseFilter<std::int16_t>;
  template class TypedBaseFilter<std::int32_t>;
  template class TypedBaseFilter<std::int64_t>;
  template class TypedBaseFilter<float>;
  template class TypedBaseFilter<double>;
}
<commit_msg>Fixing a potential size issue<commit_after>/**
 * \file TypedBaseFilter.cpp
 */

#include "TypedBaseFilter.h"

#include <cstdint>

#include <boost/mpl/distance.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/utility/enable_if.hpp>

#include "Utilities.h"

namespace
{
  typedef boost::mpl::vector<std::int16_t, std::int32_t, std::int64_t, float, double> ConversionTypes;

  template<typename Vector, typename DataType>
  typename boost::enable_if<typename boost::mpl::empty<Vector>::type, void>::type
  convert_array(ATK::BaseFilter* filter, int port, DataType* converted_input, int size, int type)
  {
  }

  template<typename Vector, typename DataType>
  typename boost::disable_if<typename boost::mpl::empty<Vector>::type, void>::type
      convert_array(ATK::BaseFilter* filter, int port, DataType* converted_input, int size, int type)
  {
    if(type != 0)
    {
      convert_array<typename boost::mpl::pop_front<Vector>::type, DataType>(filter, port, converted_input, size, type - 1);
    }
    else
    {
      typedef typename boost::mpl::front<Vector>::type InputOriginalType;
      InputOriginalType* original_input_array = static_cast<ATK::TypedBaseFilter<InputOriginalType>*>(filter)->get_output_array(port);
      ATK::ConversionUtilities<InputOriginalType, DataType>::convert_array(original_input_array, converted_input, size);
    }
  }
}

namespace ATK
{
  template<typename DataType>
  TypedBaseFilter<DataType>::TypedBaseFilter(int nb_input_ports, int nb_output_ports)
  :Parent(nb_input_ports, nb_output_ports), converted_inputs_delay(nb_input_ports), converted_inputs(nb_input_ports, NULL), converted_inputs_size(nb_input_ports, 0), outputs_delay(nb_output_ports), outputs(nb_output_ports, NULL), outputs_size(nb_output_ports, 0), input_delay(0), output_delay(0)
  {
  }

  template<typename DataType>
  TypedBaseFilter<DataType>::~TypedBaseFilter()
  {
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::set_nb_input_ports(int nb_ports)
  {
    Parent::set_nb_input_ports(nb_ports);
    std::vector<boost::scoped_array<DataType> > temp(nb_ports);
    converted_inputs_delay.swap(temp);
    converted_inputs.assign(nb_ports, NULL);
    converted_inputs_size.assign(nb_ports, 0);
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::set_nb_output_ports(int nb_ports)
  {
    Parent::set_nb_output_ports(nb_ports);
    std::vector<boost::scoped_array<DataType> > temp(nb_ports);
    outputs_delay.swap(temp);
    outputs.assign(nb_ports, NULL);
    outputs_size.assign(nb_ports, 0);
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::process_impl(long size)
  {
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::prepare_process(long size)
  {
    convert_inputs(size);
  }

  template<typename DataType>
  int TypedBaseFilter<DataType>::get_type() const
  {
    return boost::mpl::distance<boost::mpl::begin<ConversionTypes>::type, typename boost::mpl::find<ConversionTypes, DataType>::type >::value;
  }

  template<typename DataType>
  DataType* TypedBaseFilter<DataType>::get_output_array(int port)
  {
    return outputs[port];
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::convert_inputs(long size)
  {
    for(int i = 0; i < nb_input_ports; ++i)
    {
      if(converted_inputs_size[i] < size)
      {
        boost::scoped_array<DataType> temp(new DataType[input_delay + size]);
        if(converted_inputs_size[i] == 0)
        {
          for(int j = 0; j < input_delay; ++j)
          {
            temp[j] = 0;
          }
        }
        else
        {
          for(int j = 0; j < input_delay; ++j)
          {
            temp[j] = converted_inputs[i][converted_inputs_size[i] + j - input_delay];
          }
        }

        converted_inputs_delay[i].swap(temp);
        converted_inputs[i] = converted_inputs_delay[i].get() + input_delay;
        converted_inputs_size[i] = size;
      }
      else
      {
        for(int j = 0; j < input_delay; ++j)
        {
          converted_inputs[i][j - input_delay] = converted_inputs[i][converted_inputs_size[i] + j - input_delay];
        }
      }
      convert_array<ConversionTypes, DataType>(connections[i].second, connections[i].first, converted_inputs[i], size, connections[i].second->get_type());
    }
  }

  template<typename DataType>
  void TypedBaseFilter<DataType>::prepare_outputs(long size)
  {
    for(int i = 0; i < nb_output_ports; ++i)
    {
      if(outputs_size[i] < size)
      {
        boost::scoped_array<DataType> temp(new DataType[output_delay + size]);
        if(outputs_size[i] == 0)
        {
          for(int j = 0; j < output_delay; ++j)
          {
            temp[j] = 0;
          }
        }
        else
        {
          for(int j = 0; j < output_delay; ++j)
          {
            temp[j] = outputs[i][outputs_size[i] + j - output_delay];
          }
        }

        outputs_delay[i].swap(temp);
        outputs[i] = outputs_delay[i].get() + output_delay;
        outputs_size[i] = size;
      }
      else
      {
        for(int j = 0; j < output_delay; ++j)
        {
          outputs[i][j - output_delay] = outputs[i][outputs_size[i] + j - output_delay];
        }
      }
    }
  }

  template class TypedBaseFilter<std::int16_t>;
  template class TypedBaseFilter<std::int32_t>;
  template class TypedBaseFilter<std::int64_t>;
  template class TypedBaseFilter<float>;
  template class TypedBaseFilter<double>;
}
<|endoftext|>


<commit_before>//
//     Copyright (C) Pixar. All rights reserved.
//
//     This license governs use of the accompanying software. If you
//     use the software, you accept this license. If you do not accept
//     the license, do not use the software.
//
//     1. Definitions
//     The terms "reproduce," "reproduction," "derivative works," and
//     "distribution" have the same meaning here as under U.S.
//     copyright law.  A "contribution" is the original software, or
//     any additions or changes to the software.
//     A "contributor" is any person or entity that distributes its
//     contribution under this license.
//     "Licensed patents" are a contributor's patent claims that read
//     directly on its contribution.
//
//     2. Grant of Rights
//     (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3,
//     each contributor grants you a non-exclusive, worldwide,
//     royalty-free copyright license to reproduce its contribution,
//     prepare derivative works of its contribution, and distribute
//     its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3,
//     each contributor grants you a non-exclusive, worldwide,
//     royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise
//     dispose of its contribution in the software or derivative works
//     of the contribution in the software.
//
//     3. Conditions and Limitations
//     (A) No Trademark License- This license does not grant you
//     rights to use any contributor's name, logo, or trademarks.
//     (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your
//     patent license from such contributor to the software ends
//     automatically.
//     (C) If you distribute any portion of the software, you must
//     retain all copyright, patent, trademark, and attribution
//     notices that are present in the software.
//     (D) If you distribute any portion of the software in source
//     code form, you may do so only under this license by including a
//     complete copy of this license with your distribution. If you
//     distribute any portion of the software in compiled or object
//     code form, you may only do so under a license that complies
//     with this license.
//     (E) The software is licensed "as-is." You bear the risk of
//     using it. The contributors give no express warranties,
//     guarantees or conditions. You may have additional consumer
//     rights under your local laws which this license cannot change.
//     To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for
//     a particular purpose and non-infringement.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "hdr_reader.h"

static bool
readLine(unsigned char *line, int length, FILE *fp)
{
    // 2, 2, width  (this reader only reads newer format)
    if (getc(fp) != 2) return false;
    if (getc(fp) != 2) return false;
    int w0 = getc(fp);
    int w1 = getc(fp);
    if ((w0 << 8 | w1) != length) return false;

    for (int i = 0; i < 4; ++i) {
        for (int x = 0; x < length;) {
            int c = getc(fp);
            if (c > 128) {
                // runlength
                c &= 127;
                int value = getc(fp);
                while (c--) {
                    line[x*4+i] = value;
                    x++;
                }
            } else {
                // non- runlength
                while (c--) {
                    line[x*4+i] = getc(fp);
                    x++;
                }
            }
        }
    }
    return true;
}

unsigned char *loadHdr(const char *filename, HdrInfo *info, bool convertToFloat)
{
    FILE *fp = fopen(filename, "rb");
    if (fp == NULL) return NULL;

    memset(info, 0, sizeof(HdrInfo));
    info->exposure = 1.0;

    unsigned char *dst = NULL, *line = NULL, *d;
    float *fd;

    const int MAXLINE = 1024;
    char buffer[MAXLINE];

    // read header
    while(true) {
        if (not fgets(buffer, MAXLINE, fp)) goto error;
        if (buffer[0] == '\n') break;
        if (buffer[0] == '\r' && buffer[0] == '\n') break;
        if (strncmp(buffer, "#?", 2) == 0) {
            strncpy(info->magic, buffer+2, 64);
        } else if (strncmp(buffer, "FORMAT=", 7) == 0) {
            strncpy(info->format, buffer+7, 64);
        }
    }
//    if (strncmp(info->magic, "RADIANCE", 8)) goto error;
    if (strncmp(info->format, "32-bit_rle_rgbe", 15)) goto error;

    // resolution
    if (not fgets(buffer, MAXLINE, fp)) goto error;
    {
        int n = (int)strlen(buffer);
        for (int i = 1; i < n; ++i) {
            if (buffer[i] == 'X') {
                if (not (info->flag & HDR_Y_MAJOR)) info->flag |= HDR_X_MAJOR;
                info->flag |= (buffer[i-1] == '-') ? HDR_X_DEC : 0;
                info->width = atoi(&buffer[i+1]);
            } else if (buffer[i] == 'Y') {
                if (not (info->flag & HDR_X_MAJOR)) info->flag |= HDR_Y_MAJOR;
                info->flag |= (buffer[i-1] == '-') ? HDR_Y_DEC : 0;
                info->height = atoi(&buffer[i+1]);
            }
        }
    }
    if (info->width <= 0 || info->height <= 0) goto error;

    if (info->flag & HDR_Y_MAJOR) {
        info->scanLength = info->width;
        info->scanWidth = info->height;
    } else {
        info->scanLength = info->height;
        info->scanWidth = info->width;
    }

    // read body
    if (convertToFloat) {
        dst = (unsigned char *)malloc(info->width * info->height * 4 * sizeof(float));
        fd = (float*)dst;
    } else {
        dst = (unsigned char *)malloc(info->width * info->height * 4);
        d = dst;
    }
    line = (unsigned char *)malloc(info->scanLength*4);

    for (int y = info->scanWidth-1; y >= 0; --y) {
        if (not readLine(line, info->scanLength, fp)) goto error;
        for (int x = 0; x < info->scanLength; ++x) {
            if (convertToFloat) {
                float scale = powf(2.0f, float(line[x*4+3] - 128))/255.0f;
                *fd++ = line[x*4  ]*scale;
                *fd++ = line[x*4+1]*scale;
                *fd++ = line[x*4+2]*scale;
                *fd++ = 1.0;
            } else {
                *d++ = line[x*4  ];
                *d++ = line[x*4+1];
                *d++ = line[x*4+2];
                *d++ = line[x*4+3];
            }
        }
    }
    free(line);
    fclose(fp);

    return dst;

error:
    printf("Error in reading %s\n", filename);
    if(dst) free(dst);
    if(line) free(line);
    fclose(fp);
    return NULL;
}

/*
int main(int argc, char *argv[]) {
    HdrInfo info;
    loadHdr(argv[1], &info);
}
*/
<commit_msg>hdr_reader: Fix a few compiler warnings<commit_after>//
//     Copyright (C) Pixar. All rights reserved.
//
//     This license governs use of the accompanying software. If you
//     use the software, you accept this license. If you do not accept
//     the license, do not use the software.
//
//     1. Definitions
//     The terms "reproduce," "reproduction," "derivative works," and
//     "distribution" have the same meaning here as under U.S.
//     copyright law.  A "contribution" is the original software, or
//     any additions or changes to the software.
//     A "contributor" is any person or entity that distributes its
//     contribution under this license.
//     "Licensed patents" are a contributor's patent claims that read
//     directly on its contribution.
//
//     2. Grant of Rights
//     (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3,
//     each contributor grants you a non-exclusive, worldwide,
//     royalty-free copyright license to reproduce its contribution,
//     prepare derivative works of its contribution, and distribute
//     its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3,
//     each contributor grants you a non-exclusive, worldwide,
//     royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise
//     dispose of its contribution in the software or derivative works
//     of the contribution in the software.
//
//     3. Conditions and Limitations
//     (A) No Trademark License- This license does not grant you
//     rights to use any contributor's name, logo, or trademarks.
//     (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your
//     patent license from such contributor to the software ends
//     automatically.
//     (C) If you distribute any portion of the software, you must
//     retain all copyright, patent, trademark, and attribution
//     notices that are present in the software.
//     (D) If you distribute any portion of the software in source
//     code form, you may do so only under this license by including a
//     complete copy of this license with your distribution. If you
//     distribute any portion of the software in compiled or object
//     code form, you may only do so under a license that complies
//     with this license.
//     (E) The software is licensed "as-is." You bear the risk of
//     using it. The contributors give no express warranties,
//     guarantees or conditions. You may have additional consumer
//     rights under your local laws which this license cannot change.
//     To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for
//     a particular purpose and non-infringement.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "hdr_reader.h"

static bool
readLine(unsigned char *line, int length, FILE *fp)
{
    // 2, 2, width  (this reader only reads newer format)
    if (getc(fp) != 2) return false;
    if (getc(fp) != 2) return false;
    int w0 = getc(fp);
    int w1 = getc(fp);
    if ((w0 << 8 | w1) != length) return false;

    for (int i = 0; i < 4; ++i) {
        for (int x = 0; x < length;) {
            int c = getc(fp);
            if (c > 128) {
                // runlength
                c &= 127;
                unsigned char value = (unsigned char)getc(fp);
                while (c--) {
                    line[x*4+i] = value;
                    x++;
                }
            } else {
                // non- runlength
                while (c--) {
                    unsigned char value = (unsigned char)getc(fp);
                    line[x*4+i] = value;
                    x++;
                }
            }
        }
    }
    return true;
}

unsigned char *loadHdr(const char *filename, HdrInfo *info, bool convertToFloat)
{
    FILE *fp = fopen(filename, "rb");
    if (fp == NULL) return NULL;

    memset(info, 0, sizeof(HdrInfo));
    info->exposure = 1.0;

    unsigned char *dst = NULL, *line = NULL, *d;
    float *fd;

    const int MAXLINE = 1024;
    char buffer[MAXLINE];

    // read header
    while(true) {
        if (not fgets(buffer, MAXLINE, fp)) goto error;
        if (buffer[0] == '\n') break;
        if (buffer[0] == '\r' && buffer[0] == '\n') break;
        if (strncmp(buffer, "#?", 2) == 0) {
            strncpy(info->magic, buffer+2, 64);
        } else if (strncmp(buffer, "FORMAT=", 7) == 0) {
            strncpy(info->format, buffer+7, 64);
        }
    }
//    if (strncmp(info->magic, "RADIANCE", 8)) goto error;
    if (strncmp(info->format, "32-bit_rle_rgbe", 15)) goto error;

    // resolution
    if (not fgets(buffer, MAXLINE, fp)) goto error;
    {
        int n = (int)strlen(buffer);
        for (int i = 1; i < n; ++i) {
            if (buffer[i] == 'X') {
                if (not (info->flag & HDR_Y_MAJOR)) info->flag |= HDR_X_MAJOR;
                info->flag |= (buffer[i-1] == '-') ? HDR_X_DEC : 0;
                info->width = atoi(&buffer[i+1]);
            } else if (buffer[i] == 'Y') {
                if (not (info->flag & HDR_X_MAJOR)) info->flag |= HDR_Y_MAJOR;
                info->flag |= (buffer[i-1] == '-') ? HDR_Y_DEC : 0;
                info->height = atoi(&buffer[i+1]);
            }
        }
    }
    if (info->width <= 0 || info->height <= 0) goto error;

    if (info->flag & HDR_Y_MAJOR) {
        info->scanLength = info->width;
        info->scanWidth = info->height;
    } else {
        info->scanLength = info->height;
        info->scanWidth = info->width;
    }

    // read body
    if (convertToFloat) {
        dst = (unsigned char *)malloc(info->width * info->height * 4 * sizeof(float));
        fd = (float*)dst;
    } else {
        dst = (unsigned char *)malloc(info->width * info->height * 4);
        d = dst;
    }
    line = (unsigned char *)malloc(info->scanLength*4);

    for (int y = info->scanWidth-1; y >= 0; --y) {
        if (not readLine(line, info->scanLength, fp)) goto error;
        for (int x = 0; x < info->scanLength; ++x) {
            if (convertToFloat) {
                float scale = powf(2.0f, float(line[x*4+3] - 128))/255.0f;
                *fd++ = line[x*4  ]*scale;
                *fd++ = line[x*4+1]*scale;
                *fd++ = line[x*4+2]*scale;
                *fd++ = 1.0;
            } else {
                *d++ = line[x*4  ];
                *d++ = line[x*4+1];
                *d++ = line[x*4+2];
                *d++ = line[x*4+3];
            }
        }
    }
    free(line);
    fclose(fp);

    return dst;

error:
    printf("Error in reading %s\n", filename);
    if(dst) free(dst);
    if(line) free(line);
    fclose(fp);
    return NULL;
}

/*
int main(int argc, char *argv[]) {
    HdrInfo info;
    loadHdr(argv[1], &info);
}
*/
<|endoftext|>


<commit_before>#include <iostream>

#include "vtrc-client-base/vtrc-client.h"
#include "vtrc-common/vtrc-thread-pool.h"
#include "vtrc-common/vtrc-stub-wrapper.h"

#include "protocol/hello.pb.h"

#include "boost/lexical_cast.hpp"

using namespace vtrc;

namespace {
    void on_connect( )
    {
        std::cout << "connect...";
    }
    void on_ready( )
    {
        std::cout << "ready...";
    }
    void on_disconnect( )
    {
        std::cout << "disconnect...";
    }
}

int main( int argc, const char **argv )
{
    common::thread_pool tp( 1 );

    const char *address = "127.0.0.1";
    unsigned short port = 56560;

    if( argc > 2 ) {
        address = argv[1];
        port = boost::lexical_cast<unsigned short>( argv[2] );
    } else if( argc > 1 ) {
        port = boost::lexical_cast<unsigned short>( argv[1] );
    }

    client::vtrc_client_sptr cl =
                     client::vtrc_client::create( tp.get_io_service( ) );

    cl->on_connect_connect( on_connect );
    cl->on_ready_connect( on_ready );
    cl->on_disconnect_connect( on_disconnect );

    try {

        std::cout <<  "Connecting..." << std::endl;

        cl->connect( address, port );
        std::cout << "Ok" << std::endl;

        vtrc::unique_ptr<common::rpc_channel> channel(cl->create_channel( ));

        typedef howto::hello_service_Stub stub_type;

        common::stub_wrapper<stub_type> hello(channel.get( ));

        howto::request_message  req;
        howto::response_message res;

        req.set_name( "%USERNAME%" );

        hello.call( &stub_type::send_hello, &req, &res );

        std::cout <<  res.hello( ) << std::endl;

    } catch( const std::exception &ex ) {
        std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
    }

    tp.stop( );
    tp.join_all( );

    /// make valgrind happy.
    google::protobuf::ShutdownProtobufLibrary( );

    return 0;
}
<commit_msg>proto<commit_after>#include <iostream>

#include "vtrc-client-base/vtrc-client.h"
#include "vtrc-common/vtrc-thread-pool.h"
#include "vtrc-common/vtrc-stub-wrapper.h"

#include "protocol/hello.pb.h"

#include "boost/lexical_cast.hpp"

using namespace vtrc;

namespace {
    void on_connect( )
    {
        std::cout << "connect...";
    }
    void on_ready( )
    {
        std::cout << "ready...";
    }
    void on_disconnect( )
    {
        std::cout << "disconnect...";
    }
}

int main( int argc, const char **argv )
{
    common::thread_pool tp( 1 );

    const char *address = "127.0.0.1";
    unsigned short port = 56560;

    if( argc > 2 ) {
        address = argv[1];
        port = boost::lexical_cast<unsigned short>( argv[2] );
    } else if( argc > 1 ) {
        port = boost::lexical_cast<unsigned short>( argv[1] );
    }

    try {

        client::vtrc_client_sptr cl =
                         client::vtrc_client::create( tp.get_io_service( ) );

        cl->on_connect_connect( on_connect );
        cl->on_ready_connect( on_ready );
        cl->on_disconnect_connect( on_disconnect );

        std::cout <<  "Connecting..." << std::endl;

        cl->connect( address, port );
        std::cout << "Ok" << std::endl;

        vtrc::unique_ptr<common::rpc_channel> channel(cl->create_channel( ));

        typedef howto::hello_service_Stub stub_type;

        common::stub_wrapper<stub_type> hello(channel.get( ));

        howto::request_message  req;
        howto::response_message res;

        req.set_name( "%USERNAME%" );

        hello.call( &stub_type::send_hello, &req, &res );

        std::cout <<  res.hello( ) << std::endl;

    } catch( const std::exception &ex ) {
        std::cerr << "Hello, world failed: " << ex.what( ) << "\n";
    }

    tp.stop( );
    tp.join_all( );

    /// make valgrind happy.
    google::protobuf::ShutdownProtobufLibrary( );

    return 0;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name:      managedframe.cpp
// Purpose:   Implementation of wxExManagedFrame class.
// Author:    Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <list>
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/tokenzr.h>
#include <wx/wxcrt.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/defs.h>
#include <wx/extension/ex.h>
#include <wx/extension/frd.h>
#include <wx/extension/stc.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>

#if wxUSE_GUI

// Support class.
// Offers a text ctrl related to a ex object.
class wxExExTextCtrl: public wxTextCtrl
{
public:
  /// Constructor. Creates empty control.
  wxExExTextCtrl(
    wxWindow* parent,
    wxExManagedFrame* frame,
    wxStaticText* prefix,
    wxWindowID id = wxID_ANY,
    const wxPoint& pos = wxDefaultPosition,
    const wxSize& size = wxDefaultSize);

  /// Destructor.
 ~wxExExTextCtrl();

  /// Returns ex component.
  wxExEx* GetEx() {return m_ex;};

  /// Sets ex component.
  void SetEx(wxExEx* ex);
protected:
  void OnChar(wxKeyEvent& event);
  void OnCommand(wxCommandEvent& event);
  void OnEnter(wxCommandEvent& event);
  void OnFocus(wxFocusEvent& event);
private:
  void Handle(wxKeyEvent& event);

  wxExManagedFrame* m_Frame;
  wxExEx* m_ex;
  wxStaticText* m_Prefix;
  bool m_Controlr;
  bool m_UserInput;

  std::list < wxString > m_Commands;
  std::list < wxString >::const_iterator m_CommandsIterator;

  std::list < wxString > m_Finds;
  std::list < wxString >::const_iterator m_FindsIterator;

  DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame)
  EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand)
  EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand)
  EVT_UPDATE_UI_RANGE(
    ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI)
END_EVENT_TABLE()

wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
  wxWindowID id,
  const wxString& title,
  long style)
  : wxExFrame(parent, id, title, style)
{
  m_Manager.SetManagedWindow(this);

  m_ToolBar = new wxExToolBar(this);
  m_ToolBar->AddControls();

  AddToolBarPane(m_ToolBar, "TOOLBAR", _("Toolbar"));
  AddToolBarPane(new wxExFindToolBar(this), "FINDBAR", _("Findbar"));
  AddToolBarPane(CreateExPanel(), "VIBAR");

  m_Manager.Update();
}

wxExManagedFrame::~wxExManagedFrame()
{
  m_Manager.UnInit();
}

bool wxExManagedFrame::AddToolBarPane(
  wxWindow* window,
  const wxString& name,
  const wxString& caption)
{
  wxAuiPaneInfo pane;

  pane
    .LeftDockable(false)
    .RightDockable(false)
    .Name(name);

  // If the toolbar has a caption, it is at the top,
  // otherwise fixed at the bottom and initially hidden.
  if (!caption.empty())
  {
    pane
      .Top()
      .ToolbarPane()
      .Caption(caption);
  }
  else
  {
    pane
      .Bottom()
      .CloseButton(false)
      .Hide()
      .DockFixed(true)
      .Movable(false)
      .Row(10)
      .CaptionVisible(false);
  }

  return m_Manager.AddPane(window, pane);
}

bool wxExManagedFrame::AllowClose(wxWindowID id, wxWindow* page)
{
  // The page will be closed, so do not update find focus now.
  SetFindFocus(NULL);
  return true;
}

wxPanel* wxExManagedFrame::CreateExPanel()
{
  // A ex panel starts with small static text for : or /, then
  // comes the ex ctrl for getting user input.
  wxPanel* panel = new wxPanel(this);
  m_exTextPrefix = new wxStaticText(panel, wxID_ANY, wxEmptyString);
  m_exTextCtrl = new wxExExTextCtrl(panel, this, m_exTextPrefix, wxID_ANY);

  wxFlexGridSizer* sizer = new wxFlexGridSizer(2);
  sizer->AddGrowableCol(1);
  sizer->Add(m_exTextPrefix, wxSizerFlags().Expand());
  sizer->Add(m_exTextCtrl, wxSizerFlags().Expand());

  panel->SetSizerAndFit(sizer);

  return panel;
}

void wxExManagedFrame::GetExCommand(wxExEx* ex, const wxString& command)
{
  m_exTextPrefix->SetLabel(command);
  m_exTextCtrl->SetEx(ex);

  m_Manager.GetPane("VIBAR").Show();
  m_Manager.Update();
}

void wxExManagedFrame::HideExBar(bool set_focus)
{
  if (m_Manager.GetPane("VIBAR").IsShown())
  {
    m_Manager.GetPane("VIBAR").Hide();
    m_Manager.Update();

    if (set_focus && m_exTextCtrl != NULL && m_exTextCtrl->GetEx() != NULL)
    {
      m_exTextCtrl->GetEx()->GetSTC()->SetFocus();
    }
  }
}

void wxExManagedFrame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
    case wxID_PREFERENCES:
      wxExSTC::ConfigDialog(this,
        _("Editor Options"),
        wxExSTC::STC_CONFIG_MODELESS |
        wxExSTC::STC_CONFIG_SIMPLE |
        wxExSTC::STC_CONFIG_WITH_APPLY,
        event.GetId());
    break;

    case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break;
    case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
    case ID_VIEW_FINDBAR:
      event.Check(m_Manager.GetPane("FINDBAR").IsShown());
    break;

    case ID_VIEW_TOOLBAR:
      event.Check(m_Manager.GetPane("TOOLBAR").IsShown());
    break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::OnNotebook(wxWindowID id, wxWindow* page)
{
  SetFindFocus(page);
}

void wxExManagedFrame::ShowExMessage(const wxString& text)
{
  HideExBar();

  if (GetStatusBar() != NULL && GetStatusBar()->IsShown())
  {
    GetStatusBar()->SetStatusText(text);
  }
  else
  {
    wxLogMessage(text);
  }
}

void wxExManagedFrame::SyncCloseAll(wxWindowID id)
{
  SetFindFocus(NULL);
}

bool wxExManagedFrame::TogglePane(const wxString& pane)
{
  wxAuiPaneInfo& info = m_Manager.GetPane(pane);

  if (!info.IsOk())
  {
    return false;
  }

  info.IsShown() ? info.Hide(): info.Show();

  m_Manager.Update();

  return true;
}

// Implementation of support class.

BEGIN_EVENT_TABLE(wxExExTextCtrl, wxTextCtrl)
  EVT_CHAR(wxExExTextCtrl::OnChar)
  EVT_SET_FOCUS(wxExExTextCtrl::OnFocus)
  EVT_TEXT(wxID_ANY, wxExExTextCtrl::OnCommand)
  EVT_TEXT_ENTER(wxID_ANY, wxExExTextCtrl::OnEnter)
END_EVENT_TABLE()

wxExExTextCtrl::wxExExTextCtrl(
  wxWindow* parent,
  wxExManagedFrame* frame,
  wxStaticText* prefix,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size)
  : wxTextCtrl(parent, id, wxEmptyString, pos, size, wxTE_PROCESS_ENTER)
  , m_Frame(frame)
  , m_ex(NULL)
  , m_Controlr(false)
  , m_UserInput(false)
  , m_Prefix(prefix)
{
  wxStringTokenizer tkz(wxConfigBase::Get()->Read("excommand"),
    wxExGetFieldSeparator());

  while (tkz.HasMoreTokens())
  {
    const wxString val = tkz.GetNextToken();
    m_Commands.push_front(val);
  }

  m_CommandsIterator = m_Commands.begin();

  m_Finds = wxExFindReplaceData::Get()->GetFindStrings();

  m_FindsIterator = m_Finds.begin();
}

wxExExTextCtrl::~wxExExTextCtrl()
{
  const int commandsSaveInConfig = 25;

  wxString values;
  int items = 0;

  for (
    std::list < wxString >::reverse_iterator it = m_Commands.rbegin();
    it != m_Commands.rend() && items < commandsSaveInConfig;
    ++it)
  {
    values += *it + wxExGetFieldSeparator();
    items++;
  }

  wxConfigBase::Get()->Write("excommand", values);
}

void wxExExTextCtrl::Handle(wxKeyEvent& event)
{
  bool skip = true;

  if (event.GetKeyCode() != WXK_RETURN)
  {
    if (
      m_Prefix->GetLabel() == "=" &&
      event.GetUnicodeKey() != (wxChar)WXK_NONE &&
      m_Controlr)
    {
      skip = false;

      const wxChar c = event.GetUnicodeKey();

      switch (c)
      {
      case '\"':
        AppendText(wxExClipboardGet()); break;

      default:
        if (
           m_ex != NULL &&
          !m_ex->GetMacros().GetRegister(c).empty())
          {
            AppendText(m_ex->GetMacros().GetRegister(c)); break;
          }
      }
    }

    m_UserInput = true;
  }

  if (skip)
  {
    event.Skip();
  }

  m_Controlr = false;
}

void wxExExTextCtrl::OnChar(wxKeyEvent& event)
{
  const int key = event.GetKeyCode();

  switch (key)
  {
  case WXK_UP:
  case WXK_DOWN:
    if (m_Prefix->GetLabel() == ":")
    {
      wxExSetTextCtrlValue(this, key, m_Commands, m_CommandsIterator);
    }
    else if (m_Prefix->GetLabel() == "/" || m_Prefix->GetLabel() == "?")
    {
      wxExSetTextCtrlValue(this, key, m_Finds, m_FindsIterator);
    }
    break;

  case WXK_ESCAPE:
    if (m_ex != NULL)
    {
      m_ex->GetSTC()->PositionRestore();
    }

    m_Frame->HideExBar();

    m_Controlr = false;
    m_UserInput = false;
  break;

  case WXK_CONTROL_R:
    m_Controlr = true;
    break;

  default: Handle(event);
  }
}

void wxExExTextCtrl::OnCommand(wxCommandEvent& event)
{
  event.Skip();

  if (
     m_UserInput && m_ex != NULL &&
    (m_Prefix->GetLabel() == "/" || m_Prefix->GetLabel() == "?"))
  {
    m_ex->GetSTC()->PositionRestore();
    m_ex->GetSTC()->FindNext(
      GetValue(),
      wxSTC_FIND_REGEXP | wxFR_MATCHCASE,
      m_Prefix->GetLabel() == "/");
  }
}

void wxExExTextCtrl::OnEnter(wxCommandEvent& event)
{
  if (GetValue().empty())
  {
    m_Frame->HideExBar();
    return;
  }

  if (m_Prefix->GetLabel() == ":")
  {
    m_Commands.remove(GetValue());
    m_Commands.push_front(GetValue());
    m_CommandsIterator = m_Commands.begin();

    if (m_ex != NULL)
    {
      if (m_ex->Command(m_Prefix->GetLabel() + GetValue()))
      {
        const bool set_focus =
          (GetValue() == "n" || GetValue() == "prev");

        m_Frame->HideExBar(!set_focus);
      }
    }
  }
  else if (m_Prefix->GetLabel() == "/" || m_Prefix->GetLabel() == "?")
  {
    m_Finds.remove(GetValue());
    m_Finds.push_front(GetValue());
    m_FindsIterator = m_Finds.begin();

    wxExFindReplaceData::Get()->SetFindString(GetValue());

    if (m_UserInput)
    {
      if (m_ex != NULL)
      {
        m_ex->GetMacros().Record(m_Prefix->GetLabel() + GetValue());
      }
    }
    else if (m_ex != NULL)
    {
      m_ex->Command(m_Prefix->GetLabel() + GetValue());
    }

    m_Frame->HideExBar();
  }
  else if (m_Prefix->GetLabel() == "=")
  {
    if (m_ex != NULL)
    {
      if (m_ex->Command(m_Prefix->GetLabel() + GetValue()))
      {
        m_Frame->HideExBar();
      }
    }
  }
  else
  {
    wxFAIL;
  }
}

void wxExExTextCtrl::OnFocus(wxFocusEvent& event)
{
  event.Skip();

  if (m_ex != NULL)
  {
    m_ex->GetSTC()->PositionSave();
  }
}

void wxExExTextCtrl::SetEx(wxExEx* ex)
{
  m_UserInput = false;
  m_ex = ex;

  if (m_Prefix->GetLabel() == "/" || m_Prefix->GetLabel() == "?" )
  {
    if (!m_ex->GetSTC()->GetSelectedText().empty())
    {
      SetValue(m_ex->GetSTC()->GetSelectedText());
      wxExFindReplaceData::Get()->SetFindString(GetValue());
    }
    else
    {
      SetValue(wxExFindReplaceData::Get()->GetFindString());
    }
  }
  else if (m_Prefix->GetLabel() == ":")
  {
    if (m_Commands.begin() != m_Commands.end())
    {
      SetValue(*m_Commands.begin());
    }
  }

  Show();
  SelectAll();
  SetFocus();
}
#endif // wxUSE_GUI
<commit_msg>allow register to be recorded<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name:      managedframe.cpp
// Purpose:   Implementation of wxExManagedFrame class.
// Author:    Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <list>
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/tokenzr.h>
#include <wx/wxcrt.h>
#include <wx/extension/managedframe.h>
#include <wx/extension/defs.h>
#include <wx/extension/ex.h>
#include <wx/extension/frd.h>
#include <wx/extension/stc.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>

#if wxUSE_GUI

// Support class.
// Offers a text ctrl related to a ex object.
class wxExExTextCtrl: public wxTextCtrl
{
public:
  /// Constructor. Creates empty control.
  wxExExTextCtrl(
    wxWindow* parent,
    wxExManagedFrame* frame,
    wxStaticText* prefix,
    wxWindowID id = wxID_ANY,
    const wxPoint& pos = wxDefaultPosition,
    const wxSize& size = wxDefaultSize);

  /// Destructor.
 ~wxExExTextCtrl();

  /// Returns ex component.
  wxExEx* GetEx() {return m_ex;};

  /// Sets ex component.
  void SetEx(wxExEx* ex);
protected:
  void OnChar(wxKeyEvent& event);
  void OnCommand(wxCommandEvent& event);
  void OnEnter(wxCommandEvent& event);
  void OnFocus(wxFocusEvent& event);
private:
  void Handle(wxKeyEvent& event);

  wxExManagedFrame* m_Frame;
  wxExEx* m_ex;
  wxStaticText* m_Prefix;
  bool m_Controlr;
  bool m_UserInput;

  wxString m_Command;

  std::list < wxString > m_Commands;
  std::list < wxString >::const_iterator m_CommandsIterator;

  std::list < wxString > m_Finds;
  std::list < wxString >::const_iterator m_FindsIterator;

  DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame)
  EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand)
  EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand)
  EVT_UPDATE_UI_RANGE(
    ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI)
END_EVENT_TABLE()

wxExManagedFrame::wxExManagedFrame(wxWindow* parent,
  wxWindowID id,
  const wxString& title,
  long style)
  : wxExFrame(parent, id, title, style)
{
  m_Manager.SetManagedWindow(this);

  m_ToolBar = new wxExToolBar(this);
  m_ToolBar->AddControls();

  AddToolBarPane(m_ToolBar, "TOOLBAR", _("Toolbar"));
  AddToolBarPane(new wxExFindToolBar(this), "FINDBAR", _("Findbar"));
  AddToolBarPane(CreateExPanel(), "VIBAR");

  m_Manager.Update();
}

wxExManagedFrame::~wxExManagedFrame()
{
  m_Manager.UnInit();
}

bool wxExManagedFrame::AddToolBarPane(
  wxWindow* window,
  const wxString& name,
  const wxString& caption)
{
  wxAuiPaneInfo pane;

  pane
    .LeftDockable(false)
    .RightDockable(false)
    .Name(name);

  // If the toolbar has a caption, it is at the top,
  // otherwise fixed at the bottom and initially hidden.
  if (!caption.empty())
  {
    pane
      .Top()
      .ToolbarPane()
      .Caption(caption);
  }
  else
  {
    pane
      .Bottom()
      .CloseButton(false)
      .Hide()
      .DockFixed(true)
      .Movable(false)
      .Row(10)
      .CaptionVisible(false);
  }

  return m_Manager.AddPane(window, pane);
}

bool wxExManagedFrame::AllowClose(wxWindowID id, wxWindow* page)
{
  // The page will be closed, so do not update find focus now.
  SetFindFocus(NULL);
  return true;
}

wxPanel* wxExManagedFrame::CreateExPanel()
{
  // A ex panel starts with small static text for : or /, then
  // comes the ex ctrl for getting user input.
  wxPanel* panel = new wxPanel(this);
  m_exTextPrefix = new wxStaticText(panel, wxID_ANY, wxEmptyString);
  m_exTextCtrl = new wxExExTextCtrl(panel, this, m_exTextPrefix, wxID_ANY);

  wxFlexGridSizer* sizer = new wxFlexGridSizer(2);
  sizer->AddGrowableCol(1);
  sizer->Add(m_exTextPrefix, wxSizerFlags().Expand());
  sizer->Add(m_exTextCtrl, wxSizerFlags().Expand());

  panel->SetSizerAndFit(sizer);

  return panel;
}

void wxExManagedFrame::GetExCommand(wxExEx* ex, const wxString& command)
{
  m_exTextPrefix->SetLabel(command);
  m_exTextCtrl->SetEx(ex);

  m_Manager.GetPane("VIBAR").Show();
  m_Manager.Update();
}

void wxExManagedFrame::HideExBar(bool set_focus)
{
  if (m_Manager.GetPane("VIBAR").IsShown())
  {
    m_Manager.GetPane("VIBAR").Hide();
    m_Manager.Update();

    if (set_focus && m_exTextCtrl != NULL && m_exTextCtrl->GetEx() != NULL)
    {
      m_exTextCtrl->GetEx()->GetSTC()->SetFocus();
    }
  }
}

void wxExManagedFrame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
    case wxID_PREFERENCES:
      wxExSTC::ConfigDialog(this,
        _("Editor Options"),
        wxExSTC::STC_CONFIG_MODELESS |
        wxExSTC::STC_CONFIG_SIMPLE |
        wxExSTC::STC_CONFIG_WITH_APPLY,
        event.GetId());
    break;

    case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break;
    case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
    case ID_VIEW_FINDBAR:
      event.Check(m_Manager.GetPane("FINDBAR").IsShown());
    break;

    case ID_VIEW_TOOLBAR:
      event.Check(m_Manager.GetPane("TOOLBAR").IsShown());
    break;

    default:
      wxFAIL;
  }
}

void wxExManagedFrame::OnNotebook(wxWindowID id, wxWindow* page)
{
  SetFindFocus(page);
}

void wxExManagedFrame::ShowExMessage(const wxString& text)
{
  HideExBar();

  if (GetStatusBar() != NULL && GetStatusBar()->IsShown())
  {
    GetStatusBar()->SetStatusText(text);
  }
  else
  {
    wxLogMessage(text);
  }
}

void wxExManagedFrame::SyncCloseAll(wxWindowID id)
{
  SetFindFocus(NULL);
}

bool wxExManagedFrame::TogglePane(const wxString& pane)
{
  wxAuiPaneInfo& info = m_Manager.GetPane(pane);

  if (!info.IsOk())
  {
    return false;
  }

  info.IsShown() ? info.Hide(): info.Show();

  m_Manager.Update();

  return true;
}

// Implementation of support class.

BEGIN_EVENT_TABLE(wxExExTextCtrl, wxTextCtrl)
  EVT_CHAR(wxExExTextCtrl::OnChar)
  EVT_SET_FOCUS(wxExExTextCtrl::OnFocus)
  EVT_TEXT(wxID_ANY, wxExExTextCtrl::OnCommand)
  EVT_TEXT_ENTER(wxID_ANY, wxExExTextCtrl::OnEnter)
END_EVENT_TABLE()

wxExExTextCtrl::wxExExTextCtrl(
  wxWindow* parent,
  wxExManagedFrame* frame,
  wxStaticText* prefix,
  wxWindowID id,
  const wxPoint& pos,
  const wxSize& size)
  : wxTextCtrl(parent, id, wxEmptyString, pos, size, wxTE_PROCESS_ENTER)
  , m_Frame(frame)
  , m_ex(NULL)
  , m_Controlr(false)
  , m_UserInput(false)
  , m_Prefix(prefix)
{
  wxStringTokenizer tkz(wxConfigBase::Get()->Read("excommand"),
    wxExGetFieldSeparator());

  while (tkz.HasMoreTokens())
  {
    const wxString val = tkz.GetNextToken();
    m_Commands.push_front(val);
  }

  m_CommandsIterator = m_Commands.begin();

  m_Finds = wxExFindReplaceData::Get()->GetFindStrings();

  m_FindsIterator = m_Finds.begin();
}

wxExExTextCtrl::~wxExExTextCtrl()
{
  const int commandsSaveInConfig = 25;

  wxString values;
  int items = 0;

  for (
    std::list < wxString >::reverse_iterator it = m_Commands.rbegin();
    it != m_Commands.rend() && items < commandsSaveInConfig;
    ++it)
  {
    values += *it + wxExGetFieldSeparator();
    items++;
  }

  wxConfigBase::Get()->Write("excommand", values);
}

void wxExExTextCtrl::Handle(wxKeyEvent& event)
{
  bool skip = true;

  if (event.GetKeyCode() != WXK_RETURN)
  {
    if (
      m_Prefix->GetLabel() == "=" &&
      event.GetUnicodeKey() != (wxChar)WXK_NONE &&
      m_Controlr)
    {
      skip = false;

      const wxChar c = event.GetUnicodeKey();

      switch (c)
      {
      case '\"':
        AppendText(wxExClipboardGet()); break;

      default:
        if (
           m_ex != NULL &&
          !m_ex->GetMacros().GetRegister(c).empty())
          {
            AppendText(m_ex->GetMacros().GetRegister(c)); break;
          }
      }
    }

    m_UserInput = true;
  }

  if (skip)
  {
    event.Skip();
  }

  m_Controlr = false;
}

void wxExExTextCtrl::OnChar(wxKeyEvent& event)
{
  if (event.GetUnicodeKey() != (wxChar)WXK_NONE)
  {
    if (event.GetKeyCode() == WXK_BACK)
    {
      m_Command = m_Command.Truncate(m_Command.size() - 1);
    }
    else
    {
      m_Command += event.GetUnicodeKey();
    }
  }

  const int key = event.GetKeyCode();

  switch (key)
  {
  case WXK_UP:
  case WXK_DOWN:
    if (m_Prefix->GetLabel() == ":")
    {
      wxExSetTextCtrlValue(this, key, m_Commands, m_CommandsIterator);
    }
    else if (m_Prefix->GetLabel() == "/" || m_Prefix->GetLabel() == "?")
    {
      wxExSetTextCtrlValue(this, key, m_Finds, m_FindsIterator);
    }
    break;

  case WXK_ESCAPE:
    if (m_ex != NULL)
    {
      m_ex->GetSTC()->PositionRestore();
    }

    m_Frame->HideExBar();

    m_Controlr = false;
    m_UserInput = false;
  break;

  case WXK_CONTROL_R:
    m_Controlr = true;
    break;

  default: Handle(event);
  }
}

void wxExExTextCtrl::OnCommand(wxCommandEvent& event)
{
  event.Skip();

  if (
     m_UserInput && m_ex != NULL &&
    (m_Prefix->GetLabel() == "/" || m_Prefix->GetLabel() == "?"))
  {
    m_ex->GetSTC()->PositionRestore();
    m_ex->GetSTC()->FindNext(
      GetValue(),
      wxSTC_FIND_REGEXP | wxFR_MATCHCASE,
      m_Prefix->GetLabel() == "/");
  }
}

void wxExExTextCtrl::OnEnter(wxCommandEvent& event)
{
  if (GetValue().empty())
  {
    m_Frame->HideExBar();
    return;
  }

  if (m_Prefix->GetLabel() == ":")
  {
    m_Commands.remove(GetValue());
    m_Commands.push_front(GetValue());
    m_CommandsIterator = m_Commands.begin();

    if (m_ex != NULL)
    {
      if (m_ex->Command(m_Prefix->GetLabel() + GetValue()))
      {
        const bool set_focus =
          (GetValue() == "n" || GetValue() == "prev");

        m_Frame->HideExBar(!set_focus);
      }
    }
  }
  else if (m_Prefix->GetLabel() == "/" || m_Prefix->GetLabel() == "?")
  {
    m_Finds.remove(GetValue());
    m_Finds.push_front(GetValue());
    m_FindsIterator = m_Finds.begin();

    wxExFindReplaceData::Get()->SetFindString(GetValue());

    if (m_ex != NULL)
    {
      if (m_UserInput)
      {
        m_ex->GetMacros().Record(m_Prefix->GetLabel() + GetValue());
      }
      else
      {
        m_ex->Command(m_Prefix->GetLabel() + GetValue());
      }
    }

    m_Frame->HideExBar();
  }
  else if (m_Prefix->GetLabel() == "=")
  {
    if (m_ex != NULL)
    {
      if (m_UserInput)
      {
        m_ex->GetMacros().Record(m_Prefix->GetLabel() + m_Command);
      }

      if (m_ex->Command(m_Prefix->GetLabel() + GetValue()))
      {
        m_Frame->HideExBar();
      }
    }
  }
  else
  {
    wxFAIL;
  }
}

void wxExExTextCtrl::OnFocus(wxFocusEvent& event)
{
  event.Skip();

  if (m_ex != NULL)
  {
    m_ex->GetSTC()->PositionSave();
  }
}

void wxExExTextCtrl::SetEx(wxExEx* ex)
{
  m_Command.clear();
  m_Controlr = false;
  m_UserInput = false;
  m_ex = ex;

  if (m_Prefix->GetLabel() == "/" || m_Prefix->GetLabel() == "?" )
  {
    if (!m_ex->GetSTC()->GetSelectedText().empty())
    {
      SetValue(m_ex->GetSTC()->GetSelectedText());
      wxExFindReplaceData::Get()->SetFindString(GetValue());
    }
    else
    {
      SetValue(wxExFindReplaceData::Get()->GetFindString());
    }
  }
  else if (m_Prefix->GetLabel() == ":")
  {
    if (m_Commands.begin() != m_Commands.end())
    {
      SetValue(*m_Commands.begin());
    }
  }

  Show();
  SelectAll();
  SetFocus();
}
#endif // wxUSE_GUI
<|endoftext|>


<commit_before>//
//  Set.h
//  Set
//
//  Created by Antonio Seprano on 10/08/14.
//  Copyright (c) 2014 Antonio Seprano. All rights reserved.
//

#include <vector>
#include <functional>
#include <utility>
#include <algorithm>

#ifndef _SET_HPP
#define _SET_HPP

template<class _T, class _Compare = std::less<_T>, class _Allocator = std::allocator<_T>>
class Set {
public:
	typedef _T				  value_type;
	typedef _Allocator	allocator_type;
	typedef _Compare    value_compare;

private:
	typedef Set<value_type,value_compare,allocator_type> _SET;

public:
	typedef typename std::vector<value_type,allocator_type>::iterator				iterator;
	typedef typename std::vector<value_type,allocator_type>::const_iterator	const_iterator;

	// Empty set
	Set() {};

	// Set with initializer list
	Set(const std::initializer_list<value_type>& l) {
		_set.reserve(l.size());

		for (const auto& value : l) {
			insert(value);
		}
	}

	Set(std::initializer_list<value_type>&& l) {
		_set.reserve(l.size());

		for (auto& value : l) {
			insert(std::move(value));
		}
	}

	// Copy constructor
	Set(const _SET& s) {
		_set = s._set;
	}

	// Move constructor
	Set(_SET&& s) {
		_set = std::move(s._set);
	}

	// Copy assignment
	_SET& operator=(const _SET& s) noexcept {
		_set = s._set;
		return *this;
	}

	// Move assignment
	_SET& operator=(_SET&& s) noexcept {
		_set = std::move(s._set);
		return *this;
	}

	iterator begin() noexcept {
		return _set.begin();
	}

	const_iterator begin() const noexcept {
		return _set.begin();
	}

	iterator end() noexcept {
		return _set.end();
	};

	const_iterator end() const noexcept {
		return _set.end();
	}

	size_t size() const noexcept {
		return _set.size();
	}

	bool empty() const noexcept {
		return _set.empty();
	}

	void clear() noexcept {
		_set.clear();
	}

	iterator find(const value_type& value) noexcept {
		for (auto it = _set.begin(); it != _set.end(); it++) {
			if (!value_compare()(*it,value) && !value_compare()(value,*it)) {
				return it;
			}
		}

		return _set.end();
	}

	const_iterator find(const value_type& value) const noexcept {
		return (const_iterator)find(value);
	}

	size_t count(const value_type& value) const noexcept {
		size_t ret{};

		for (const auto& v : _set) {
			if (!value_compare()(v,value) && !value_compare()(value,v)) {
				ret++;
			}
		}

		return ret;
	}

	bool operator==(const _SET& s) const noexcept {
		return this->contains(s, false) && s.contains(*this, false);
	}

	bool operator!=(const _SET& s) const noexcept {
		return !(*this == s);
	};

	bool operator<(const _SET& s) const noexcept {
		if (size() != s.size()) {
			return size() < s.size();
		}

		auto it1=begin(), it2=s.begin();

		while (it1 != end() && it2 != s.end()) {
			if (*it1 < *it2) {
				return true;
			}
			else if (*it1 > *it2) {
				return false;
			}

			it1++;
			it2++;
		};

		return false;
	}

	// Insert new value
	// unique = true => values must be unique (no duplicate values allowed)
	_SET& insert(const value_type& value, bool unique = false) noexcept {
		if (!unique || this->find(value) == _set.end()) {
			auto it = begin();

			while (it != end() && value_compare()(*it, value)) {
				it++;
			}

			_set.insert(it, value);
		}

		return *this;
	}

	_SET& insert(value_type&& value, bool unique = false) noexcept {
		if (!unique || find(value) == _set.end()) {
			auto it = begin();

			while (it != end() && value_compare()(*it, value)) {
				it++;
			}

			_set.insert(it, std::move(value));
		}

		return *this;
	}

	_SET operator+(const value_type& value) const noexcept {
		return _SET{*this}+_SET{value};
	}

	_SET operator+(value_type&& value) const noexcept {
		return _SET{*this}+_SET{std::move(value)};
	}

	_SET operator+(const _SET& s) const noexcept {
		_SET ret{*this};

		for (const auto& value : s) {
			ret.insert(value);
		}

		return ret;
	}

	_SET operator+(_SET&& s) const noexcept {
		_SET ret{*this};

		for (auto& value : s) {
			ret.insert(std::move(value));
		}

		return ret;
	}

	_SET& operator+=(const value_type& value) noexcept {
		insert(value);
		return *this;
	}

	_SET& operator+=(value_type&& value) noexcept {
		insert(std::move(value));
		return *this;
	}

	_SET& operator+=(const _SET& s) noexcept {
		for (const auto& value : s) {
			insert(value);
		}

		return *this;
	}

	_SET& operator+=(_SET&& s) noexcept {
		for (auto& value : s) {
			insert(std::move(value));
		}

		return *this;
	}

	_SET operator-(const value_type& value) const noexcept {
		_SET ret{*this};
		ret.erase(value);
		return ret;
	}

	_SET operator-(const _SET& s) const noexcept {
		_SET ret{*this};
		for (const auto& v : s) {
			ret.erase(v);
		}
		return ret;
	}

	_SET& operator-=(const value_type& value) noexcept {
		_set.erase(value);
		return *this;
	}

	_SET& operator-=(const _SET& s) noexcept {
		for (const auto& value : s) {
			_set.erase(value);
		}
		return *this;
	}

	Set<_SET> operator*(const _SET& other) noexcept {
		Set<_SET> ret;

		if (!this->empty() && !other.empty()) {
			for (const auto& v1 : _set) {
				for (const auto& v2 : other) {
					ret.insert(_SET{v1,v2});
				}
			}
		}

		return ret;
	}

	_SET intersectionWith(const _SET& s) noexcept {
		_SET s1, s2;

		if (s.size() <= size()) {
			s1 = s;
			s2 = *this;
		}
		else {
			s1 = *this;
			s2 = s;
		}

		for (const auto &v : s1) {
			if (!s2.contains(v)) s1.erase(v);
		}

		return s1;
	}

	bool contains(const value_type& value) const noexcept {
		return contains(_SET{value});
	}

	bool contains(const _SET& s, bool strict = false) const noexcept {
		for (const auto& value : s) {
			bool found{false};

			for (const auto& v : _set) {
				if (!value_compare()(value, v) && !value_compare()(v, value)) {
					found = true;
					break;
				}
			}

			if (!found) {
				return false;
			}
		}

		return strict ? (s.size() != size()) : true;
	}

	template<class InputIterator>
	void insert(InputIterator first, InputIterator last) {
		for (auto it = first; it != last; it++) {
			_set.insert(*it);
		}
	};

	iterator erase(const_iterator position) {
		return _set.erase(position);
	}

	iterator erase(const_iterator first, const_iterator last) {
		return _set.erase(first,last);
	}

	size_t erase(const value_type& value, bool all = false) {
		size_t ret{};

		if (!all) {
			auto it = find(value);

			if (it != end()) {
				erase(it);
				ret++;
			}

			return ret;
		}

		for (auto it = _set.begin(); it != _set.end(); it++) {
			if (*it == value) {
				_set.erase(it);
				++ret;
			}
		}

		return ret;
	}

	_SET& unique() noexcept {
		for (auto i = begin(); i != end(); i++) {
			auto j = i+1;

			while (j != end()) {
				if (!value_compare()(*i, *j) && !value_compare()(*j, *j)) {
					_set.erase(j);
				}
				else {
					j++;
				}
			}
		}

		return *this;
	}

private:
	std::vector<value_type,allocator_type> _set;
};

#endif /* defined(_SET_HPP) */
<commit_msg>[add] Added combinations() method to get combinations of set items, grouped by n<commit_after>//
//  Set.h
//  Set
//
//  Created by Antonio Seprano on 10/08/14.
//  Copyright (c) 2014 Antonio Seprano. All rights reserved.
//

#include <vector>
#include <functional>
#include <utility>
#include <algorithm>
#include <stdexcept>

#ifndef _SET_HPP
#define _SET_HPP

template<class _T, class _Compare = std::less<_T>, class _Allocator = std::allocator<_T>>
class Set {
public:
	typedef _T				  value_type;
	typedef _Allocator	allocator_type;
	typedef _Compare    value_compare;

private:
	typedef Set<value_type,value_compare,allocator_type> _SET;

public:
	typedef typename std::vector<value_type,allocator_type>::iterator				iterator;
	typedef typename std::vector<value_type,allocator_type>::const_iterator	const_iterator;

	// Empty set
	Set() {};

	// Set with initializer list
	Set(const std::initializer_list<value_type>& l) {
		_set.reserve(l.size());

		for (const auto& value : l) {
			insert(value);
		}
	}

	Set(std::initializer_list<value_type>&& l) {
		_set.reserve(l.size());

		for (auto& value : l) {
			insert(std::move(value));
		}
	}

	// Copy constructor
	Set(const _SET& s) {
		_set = s._set;
	}

	// Move constructor
	Set(_SET&& s) {
		_set = std::move(s._set);
	}

	// Copy assignment
	_SET& operator=(const _SET& s) noexcept {
		_set = s._set;
		return *this;
	}

	// Move assignment
	_SET& operator=(_SET&& s) noexcept {
		_set = std::move(s._set);
		return *this;
	}

	iterator begin() noexcept {
		return _set.begin();
	}

	const_iterator begin() const noexcept {
		return _set.begin();
	}

	iterator end() noexcept {
		return _set.end();
	};

	const_iterator end() const noexcept {
		return _set.end();
	}

	size_t size() const noexcept {
		return _set.size();
	}

	bool empty() const noexcept {
		return _set.empty();
	}

	void clear() noexcept {
		_set.clear();
	}

	iterator find(const value_type& value) noexcept {
		for (auto it = _set.begin(); it != _set.end(); it++) {
			if (!value_compare()(*it,value) && !value_compare()(value,*it)) {
				return it;
			}
		}

		return _set.end();
	}

	const_iterator find(const value_type& value) const noexcept {
		return (const_iterator)find(value);
	}

	size_t count(const value_type& value) const noexcept {
		size_t ret{};

		for (const auto& v : _set) {
			if (!value_compare()(v,value) && !value_compare()(value,v)) {
				ret++;
			}
		}

		return ret;
	}

	bool operator==(const _SET& s) const noexcept {
		return this->contains(s, false) && s.contains(*this, false);
	}

	bool operator!=(const _SET& s) const noexcept {
		return !(*this == s);
	};

	bool operator<(const _SET& s) const noexcept {
		if (size() != s.size()) {
			return size() < s.size();
		}

		auto it1=begin(), it2=s.begin();

		while (it1 != end() && it2 != s.end()) {
			if (*it1 < *it2) {
				return true;
			}
			else if (*it1 > *it2) {
				return false;
			}

			it1++;
			it2++;
		};

		return false;
	}

	// Insert new value
	// unique = true => values must be unique (no duplicate values allowed)
	_SET& insert(const value_type& value, bool unique = false) noexcept {
		if (!unique || this->find(value) == _set.end()) {
			auto it = begin();

			while (it != end() && value_compare()(*it, value)) {
				it++;
			}

			_set.insert(it, value);
		}

		return *this;
	}

	_SET& insert(value_type&& value, bool unique = false) noexcept {
		if (!unique || find(value) == _set.end()) {
			auto it = begin();

			while (it != end() && value_compare()(*it, value)) {
				it++;
			}

			_set.insert(it, std::move(value));
		}

		return *this;
	}

	_SET operator+(const value_type& value) const noexcept {
		return _SET{*this}+_SET{value};
	}

	_SET operator+(value_type&& value) const noexcept {
		return _SET{*this}+_SET{std::move(value)};
	}

	_SET operator+(const _SET& s) const noexcept {
		_SET ret{*this};

		for (const auto& value : s) {
			ret.insert(value);
		}

		return ret;
	}

	_SET operator+(_SET&& s) const noexcept {
		_SET ret{*this};

		for (auto& value : s) {
			ret.insert(std::move(value));
		}

		return ret;
	}

	_SET& operator+=(const value_type& value) noexcept {
		insert(value);
		return *this;
	}

	_SET& operator+=(value_type&& value) noexcept {
		insert(std::move(value));
		return *this;
	}

	_SET& operator+=(const _SET& s) noexcept {
		for (const auto& value : s) {
			insert(value);
		}

		return *this;
	}

	_SET& operator+=(_SET&& s) noexcept {
		for (auto& value : s) {
			insert(std::move(value));
		}

		return *this;
	}

	_SET operator-(const value_type& value) const noexcept {
		_SET ret{*this};
		ret.erase(value);
		return ret;
	}

	_SET operator-(const _SET& s) const noexcept {
		_SET ret{*this};
		for (const auto& v : s) {
			ret.erase(v);
		}
		return ret;
	}

	_SET& operator-=(const value_type& value) noexcept {
		_set.erase(value);
		return *this;
	}

	_SET& operator-=(const _SET& s) noexcept {
		for (const auto& value : s) {
			_set.erase(value);
		}
		return *this;
	}

	Set<_SET> operator*(const _SET& other) noexcept {
		Set<_SET> ret;

		if (!this->empty() && !other.empty()) {
			for (const auto& v1 : _set) {
				for (const auto& v2 : other) {
					ret.insert(_SET{v1,v2});
				}
			}
		}

		return ret;
	}

	_SET intersectionWith(const _SET& s) noexcept {
		_SET s1, s2;

		if (s.size() <= size()) {
			s1 = s;
			s2 = *this;
		}
		else {
			s1 = *this;
			s2 = s;
		}

		for (const auto &v : s1) {
			if (!s2.contains(v)) s1.erase(v);
		}

		return s1;
	}

	bool contains(const value_type& value) const noexcept {
		return contains(_SET{value});
	}

	bool contains(const _SET& s, bool strict = false) const noexcept {
		if (strict) {
			return this->contains(s, false) && s.contains(*this, false);
		}

		for (const auto& value : s) {
			bool found{false};

			for (const auto& v : _set) {
				if (!value_compare()(value, v) && !value_compare()(v, value)) {
					found = true;
					break;
				}
			}

			if (!found) {
				return false;
			}
		}

		return true;
	}

	template<class InputIterator>
	void insert(InputIterator first, InputIterator last) {
		for (auto it = first; it != last; it++) {
			_set.insert(*it);
		}
	};

	iterator erase(const_iterator position) {
		return _set.erase(position);
	}

	iterator erase(const_iterator first, const_iterator last) {
		return _set.erase(first,last);
	}

	size_t erase(const value_type& value, bool all = false) {
		size_t ret{};

		if (!all) {
			auto it = find(value);

			if (it != end()) {
				erase(it);
				ret++;
			}

			return ret;
		}

		for (auto it = _set.begin(); it != _set.end(); it++) {
			if (*it == value) {
				_set.erase(it);
				++ret;
			}
		}

		return ret;
	}

	_SET& unique() noexcept {
		for (auto i = begin(); i != end(); i++) {
			auto j = i+1;

			while (j != end()) {
				if (!value_compare()(*i, *j) && !value_compare()(*j, *j)) {
					_set.erase(j);
				}
				else {
					j++;
				}
			}
		}

		return *this;
	}

	Set<_SET> combinations(int n) const noexcept {
		Set<_SET> ret;

		if (n > _set.size()) {
			throw std::out_of_range("Value out of range for set combinations");
		}

		std::vector<int> counters(n);
		for (int i=0; i<n; i++) {
			counters[i] = i;
		}

		do {
			_SET s;

			for (auto index : counters) {
				s += _set[index];
			}

			ret += s;
		} while (this->_increase_counters(counters));

		return ret;
	}

private:
	std::vector<value_type,allocator_type> _set;

	bool _increase_counters(std::vector<int>& c) const noexcept {
		long int limit = _set.size()-1;
		long int i = c.size()-1;
		bool found{false};

		do {
			if (++c[i] <= (limit - (c.size()-i-1))) {
				found = true;
			}
			else {
				if (--i < 0) {
					return false;
				}
			}
		} while (!found);

		i++;

		while (i < c.size()) {
			c[i] = c[i-1]+1;
			i++;
		}

		return true;
	}
};

#endif /* defined(_SET_HPP) */
<|endoftext|>


<commit_before>inline
opt_feat::opt_feat(const std::string in_path,
		   const std::string in_actionNames,
		   const int in_col,
		   const int in_row,
		   const int in_scale_factor,
		   const int in_shift,
		   const int in_scene, //only for kth
		   const int in_dim
)
:path(in_path), actionNames(in_actionNames), col(in_col), row(in_row), scale_factor(in_scale_factor), shift(in_shift), total_scene(in_scene), dim(in_dim)
{

  actions.load( actionNames );
  //dim = 14;
  //dim = 12; //Action Recognition from Video Using feature Covariance Matrices
}

inline
void
opt_feat::features_all_videos( field<string> all_people )
{
  int n_actions = actions.n_rows;
  int n_peo =  all_people.n_rows;
  //all_people.print("people");

   int nProcessors=omp_get_max_threads();
   std::cout<<nProcessors<<std::endl;
   omp_set_num_threads(2);
   std::cout<< omp_get_num_threads()<<std::endl;

  for (int sc = 1; sc<=total_scene; ++sc) //scene
  {
    for (int pe = 0; pe< n_peo; ++pe)
    {
      wall_clock timer;
      timer.tic();

      //Tantos cores como # de acciones. Ver cuando toma para una persona y 6 acciones
      #pragma omp parallel for
      for (int act=0; act<n_actions; ++act)
      {
	features_video_i.clear();
	labels_video_i.clear();
	std::stringstream ss_video_name;
	ss_video_name << path << actions (act) << "/" << all_people (pe) << "_" << actions (act) << "_d" << sc << "_uncomp.avi";
	//Imprimir el thread que esta usando
	int tid=omp_get_thread_num();
        //std::cout<<tid<<"\t tid"<<std::endl;

	cout << "Processing on "<< tid << " for "<< ss_video_name.str() << endl;

	feature_video( ss_video_name.str() ) ; //all_actions_matrix is calculated inside this method
	mat mat_features_video_i;
	vec lab_video_i;

	if (features_video_i.size()>0)
	{
	  mat_features_video_i.zeros( dim,features_video_i.size() );
	  lab_video_i.zeros( features_video_i.size() );
	  for (uword i = 0; i < features_video_i.size(); ++i)
	  {
	    mat_features_video_i.col(i) = features_video_i.at(i)/norm(features_video_i.at(i),2);
	    lab_video_i(i) = labels_video_i.at(i);
	  }
	}
	else
	{
	  mat_features_video_i.zeros(dim,0);
	}
	std::stringstream save_folder;
	std::stringstream save_feat_video_i;
	std::stringstream save_labels_video_i;
	//tmp_ss4 << "./features_training_" << col << "x" << row << "/feature_vectors_dim" << dim << peo_train (pe) << "_" << actions(act)<< ".dat";

	cout << "Saving.." << endl;
	save_folder << "./kth-features_dim" << dim <<  "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	save_feat_video_i   << save_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";
	save_labels_video_i << save_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	cout << save_feat_video_i.str() << endl;
	//getchar();
	mat_features_video_i.save( save_feat_video_i.str(), hdf5_binary );
	lab_video_i.save( save_labels_video_i.str(), hdf5_binary );
      }

      #pragma omp barrier
      double n = timer.toc();
      cout << "number of seconds: " << n << endl;
      getchar();
    }
  }
}

// //****************** Feature Extraction**************************************
// //***************************************************************************
inline
void
opt_feat::feature_video( std::string one_video )
{

  int new_row = row;
  int new_col = col;

  cv::VideoCapture capVideo(one_video);
  int n_frames = capVideo.get(CV_CAP_PROP_FRAME_COUNT);

  if( !capVideo.isOpened() )
  {
    cout << "Video couldn't be opened" << endl;
    return;
  }

  cv::Mat prevgray, gray, flow, cflow, frame, prevflow;
  cv::Mat ixMat, iyMat, ixxMat, iyyMat;
  cv::Mat flow_xy[2], mag, ang;

  string text;

  for(int fr=0; fr<n_frames; fr++){

    //cout << fr << " " ;

    bool bSuccess = capVideo.read(frame); // read a new frame from video

    if (!bSuccess) //if not success, break loop
    {
      cout << "Cannot read the frame from video file" << endl;
      break;
    }

     if (scale_factor!=1)
     {
       new_row = row*scale_factor;
       new_col = col*scale_factor;
       cv::resize( frame, frame, cv::Size(new_row, new_col) );
     }

    cv::cvtColor(frame, gray, CV_BGR2GRAY);

    if( prevgray.data )
    {
      //cout << t << " " ;
      cv::calcOpticalFlowFarneback(prevgray,
				   gray,
				   flow,
				   0.5, //pyr_scale
				   3,   //levels
				   9,   //winsize
				   1,   //iterations
				   5,   //poly_n
				   1.1, //poly_sigma
				   0);  //flags

      //optical flow
      cv::split(flow, flow_xy);
      cv::cartToPolar(flow_xy[0], flow_xy[1], mag, ang, true);

      cv::Sobel(gray, ixMat, CV_32F, 1, 0, 1);
      cv::Sobel(gray, iyMat, CV_32F, 0, 1, 1);
      cv::Sobel(gray, ixxMat, CV_32F, 2, 0, 1);
      cv::Sobel(gray, iyyMat, CV_32F, 0, 2, 1);

      float  ux = 0, uy = 0, vx = 0,  vy = 0;
      float u, v;

      if( prevflow.data )
      {
	//cout << new_col << " " << new_row << endl;

	for (int x = 0 ; x < new_col ; ++x ){
	  for (int y = 0 ; y < new_row ; ++y ) {

	    vec features_one_pixel(dim);
	    u = flow.at<cv::Vec2f>(y, x)[0];
	    v = flow.at<cv::Vec2f>(y, x)[1];

	    //cout << "x= " << x << " - y= " << y << endl;
	    // x grad
	    //cout << " x y grad" << endl;
	    float ix = ixMat.at<float>(y, x);
	    //cout << " y grad" << endl;
	    float iy = iyMat.at<float>(y, x);

	    // grad direction &  grad magnitude. (Edges)
	    //cout << "grad direction &  grad magnitude" << endl;
	    float gd = std::atan2(std::abs(iy), std::abs(ix));
	    float gm = std::sqrt(ix * ix + iy * iy);

	    // x second grad
	    //cout << "x y  second grad " << endl;
	    float ixx = ixxMat.at<float>(y, x);
	    // y second grad
	    float iyy = iyyMat.at<float>(y, x);

	    //du/dt
	    float ut = u - prevflow.at<cv::Vec2f>(y, x)[0];
	    // dv/dt
	    float vt = v - prevflow.at<cv::Vec2f>(y, x)[1];

	    if (x>0 && y>0 )
	    {
	      ux = u - flow.at<cv::Vec2f>(y, x - 1)[0];
	      uy = u - flow.at<cv::Vec2f>(y - 1, x)[0];
	      vx = v - flow.at<cv::Vec2f>(y, x - 1)[1];
	      vy = v - flow.at<cv::Vec2f>(y - 1, x)[1];
	    }

	    float Div = (ux + vy);
	    float Vor = (vx - uy);
	    //Adding more features
            mat G (2,2);
            mat S;
            float gd_opflow = ang.at<float>(y,x);
            float mg_opflow = mag.at<float>(y,x);
            //Gradient Tensor
            G   << ux << uy << endr
            << vx << vy << endr;

            //Rate of Stein Tensor
            S = 0.5*(G + G.t());

            float tr_G = trace(G);
            float tr_G2 = trace( square(G) );
            float tr_S = trace(S);
            float tr_S2 = trace(square(S));

            //Tensor Invariants  of the optical flow
            float Gten = 0.5*( tr_G*tr_G - tr_G2 );
            float Sten = 0.5*( tr_S*tr_S - tr_S2 );

	    if (dim ==12)
	    {
	    features_one_pixel  << x       << y       << fr   << gm  << u    << v
				<< abs(ut) << abs(vt) << Div  << Vor << Gten << Sten;
	    }

	    if (dim ==14)
	    {

	    features_one_pixel  << x << y << abs(ix) << abs(iy) << abs(ixx)
	    << abs(iyy) << gm << gd <<  u << v << abs(ut)
	    << abs(vt) << (ux + vy)  << (vx - uy);
	    }

	    if (!is_finite( features_one_pixel ) )
	    {
	      cout << "It's not FINITE... continue???" << endl;
	      getchar();
	    }
	    // Plotting Moving pixels
	    //cout << " " << gm;

	    double is_zero = accu(abs(features_one_pixel));

	    if (gm>40 && is_finite( features_one_pixel ) && is_zero!=0 ) // Empirically set to 40
	    {

	      frame.at<cv::Vec3b>(y,x)[0] = 0;
	      frame.at<cv::Vec3b>(y,x)[1] = 0;
	      frame.at<cv::Vec3b>(y,x)[2] = 255;
	      features_video_i.push_back(features_one_pixel);
	      labels_video_i.push_back( fr );
	    }
	  }
	}
      }

      if(cv::waitKey(30)>=0)
	break;

    }

      std::swap(prevgray, gray);
      std::swap(prevflow, flow);

     //cv::imshow("color", frame);
     //cv::waitKey(1);

  }
}<commit_msg>Re-calculate for dim=14 features<commit_after>inline
opt_feat::opt_feat(const std::string in_path,
		   const std::string in_actionNames,
		   const int in_col,
		   const int in_row,
		   const int in_scale_factor,
		   const int in_shift,
		   const int in_scene, //only for kth
		   const int in_dim
)
:path(in_path), actionNames(in_actionNames), col(in_col), row(in_row), scale_factor(in_scale_factor), shift(in_shift), total_scene(in_scene), dim(in_dim)
{

  actions.load( actionNames );
  //dim = 14;
  //dim = 12; //Action Recognition from Video Using feature Covariance Matrices
}

inline
void
opt_feat::features_all_videos( field<string> all_people )
{
  int n_actions = actions.n_rows;
  int n_peo =  all_people.n_rows;
  //all_people.print("people");

   int nProcessors=omp_get_max_threads();
   std::cout<<nProcessors<<std::endl;
   omp_set_num_threads(1);
   std::cout<< omp_get_num_threads()<<std::endl;

  for (int sc = 1; sc<=total_scene; ++sc) //scene
  {
    for (int pe = 0; pe< n_peo; ++pe)
    {
      wall_clock timer;
      timer.tic();

      //Tantos cores como # de acciones. Ver cuando toma para una persona y 6 acciones
      #pragma omp parallel for
      for (int act=0; act<n_actions; ++act)
      {
	features_video_i.clear();
	labels_video_i.clear();
	std::stringstream ss_video_name;
	ss_video_name << path << actions (act) << "/" << all_people (pe) << "_" << actions (act) << "_d" << sc << "_uncomp.avi";
	//Imprimir el thread que esta usando
	int tid=omp_get_thread_num();
        //std::cout<<tid<<"\t tid"<<std::endl;

	cout << "Processing on "<< tid << " for "<< ss_video_name.str() << endl;

	feature_video( ss_video_name.str() ) ; //all_actions_matrix is calculated inside this method
	mat mat_features_video_i;
	vec lab_video_i;

	if (features_video_i.size()>0)
	{
	  mat_features_video_i.zeros( dim,features_video_i.size() );
	  lab_video_i.zeros( features_video_i.size() );
	  for (uword i = 0; i < features_video_i.size(); ++i)
	  {
	    mat_features_video_i.col(i) = features_video_i.at(i)/norm(features_video_i.at(i),2);
	    lab_video_i(i) = labels_video_i.at(i);
	  }
	}
	else
	{
	  mat_features_video_i.zeros(dim,0);
	}
	std::stringstream save_folder;
	std::stringstream save_feat_video_i;
	std::stringstream save_labels_video_i;
	//tmp_ss4 << "./features_training_" << col << "x" << row << "/feature_vectors_dim" << dim << peo_train (pe) << "_" << actions(act)<< ".dat";

	cout << "Saving.." << endl;
	save_folder << "./kth-features_dim" << dim <<  "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	save_feat_video_i   << save_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";
	save_labels_video_i << save_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	cout << save_feat_video_i.str() << endl;
	//getchar();
	mat_features_video_i.save( save_feat_video_i.str(), hdf5_binary );
	lab_video_i.save( save_labels_video_i.str(), hdf5_binary );
      }

      #pragma omp barrier
      double n = timer.toc();
      cout << "number of seconds: " << n << endl;
      getchar();
    }
  }
}

// //****************** Feature Extraction**************************************
// //***************************************************************************
inline
void
opt_feat::feature_video( std::string one_video )
{

  int new_row = row;
  int new_col = col;

  cv::VideoCapture capVideo(one_video);
  int n_frames = capVideo.get(CV_CAP_PROP_FRAME_COUNT);

  if( !capVideo.isOpened() )
  {
    cout << "Video couldn't be opened" << endl;
    return;
  }

  cv::Mat prevgray, gray, flow, cflow, frame, prevflow;
  cv::Mat ixMat, iyMat, ixxMat, iyyMat;
  cv::Mat flow_xy[2], mag, ang;

  string text;

  for(int fr=0; fr<n_frames; fr++){

    //cout << fr << " " ;

    bool bSuccess = capVideo.read(frame); // read a new frame from video

    if (!bSuccess) //if not success, break loop
    {
      cout << "Cannot read the frame from video file" << endl;
      break;
    }

     if (scale_factor!=1)
     {
       new_row = row*scale_factor;
       new_col = col*scale_factor;
       cv::resize( frame, frame, cv::Size(new_row, new_col) );
     }

    cv::cvtColor(frame, gray, CV_BGR2GRAY);

    if( prevgray.data )
    {
      //cout << t << " " ;
      cv::calcOpticalFlowFarneback(prevgray,
				   gray,
				   flow,
				   0.5, //pyr_scale
				   3,   //levels
				   9,   //winsize
				   1,   //iterations
				   5,   //poly_n
				   1.1, //poly_sigma
				   0);  //flags

      //optical flow
      cv::split(flow, flow_xy);
      cv::cartToPolar(flow_xy[0], flow_xy[1], mag, ang, true);

      cv::Sobel(gray, ixMat, CV_32F, 1, 0, 1);
      cv::Sobel(gray, iyMat, CV_32F, 0, 1, 1);
      cv::Sobel(gray, ixxMat, CV_32F, 2, 0, 1);
      cv::Sobel(gray, iyyMat, CV_32F, 0, 2, 1);

      float  ux = 0, uy = 0, vx = 0,  vy = 0;
      float u, v;

      if( prevflow.data )
      {
	//cout << new_col << " " << new_row << endl;

	for (int x = 0 ; x < new_col ; ++x ){
	  for (int y = 0 ; y < new_row ; ++y ) {

	    vec features_one_pixel(dim);
	    u = flow.at<cv::Vec2f>(y, x)[0];
	    v = flow.at<cv::Vec2f>(y, x)[1];

	    //cout << "x= " << x << " - y= " << y << endl;
	    // x grad
	    //cout << " x y grad" << endl;
	    float ix = ixMat.at<float>(y, x);
	    //cout << " y grad" << endl;
	    float iy = iyMat.at<float>(y, x);

	    // grad direction &  grad magnitude. (Edges)
	    //cout << "grad direction &  grad magnitude" << endl;
	    float gd = std::atan2(std::abs(iy), std::abs(ix));
	    float gm = std::sqrt(ix * ix + iy * iy);

	    // x second grad
	    //cout << "x y  second grad " << endl;
	    float ixx = ixxMat.at<float>(y, x);
	    // y second grad
	    float iyy = iyyMat.at<float>(y, x);

	    //du/dt
	    float ut = u - prevflow.at<cv::Vec2f>(y, x)[0];
	    // dv/dt
	    float vt = v - prevflow.at<cv::Vec2f>(y, x)[1];

	    if (x>0 && y>0 )
	    {
	      ux = u - flow.at<cv::Vec2f>(y, x - 1)[0];
	      uy = u - flow.at<cv::Vec2f>(y - 1, x)[0];
	      vx = v - flow.at<cv::Vec2f>(y, x - 1)[1];
	      vy = v - flow.at<cv::Vec2f>(y - 1, x)[1];
	    }

	    float Div = (ux + vy);
	    float Vor = (vx - uy);
	    //Adding more features
            mat G (2,2);
            mat S;
            float gd_opflow = ang.at<float>(y,x);
            float mg_opflow = mag.at<float>(y,x);
            //Gradient Tensor
            G   << ux << uy << endr
            << vx << vy << endr;

            //Rate of Stein Tensor
            S = 0.5*(G + G.t());

            float tr_G = trace(G);
            float tr_G2 = trace( square(G) );
            float tr_S = trace(S);
            float tr_S2 = trace(square(S));

            //Tensor Invariants  of the optical flow
            float Gten = 0.5*( tr_G*tr_G - tr_G2 );
            float Sten = 0.5*( tr_S*tr_S - tr_S2 );

	    if (dim ==12)
	    {
	    features_one_pixel  << x       << y       << fr   << gm  << u    << v
				<< abs(ut) << abs(vt) << Div  << Vor << Gten << Sten;
	    }

	    if (dim ==14)
	    {

	    features_one_pixel  << x << y << abs(ix) << abs(iy) << abs(ixx)
	    << abs(iyy) << gm << gd <<  u << v << abs(ut)
	    << abs(vt) << (ux + vy)  << (vx - uy);
	    }

	    if (!is_finite( features_one_pixel ) )
	    {
	      cout << "It's not FINITE... continue???" << endl;
	      getchar();
	    }
	    // Plotting Moving pixels
	    //cout << " " << gm;

	    double is_zero = accu(abs(features_one_pixel));

	    if (gm>40 && is_finite( features_one_pixel ) && is_zero!=0 ) // Empirically set to 40
	    {

	      frame.at<cv::Vec3b>(y,x)[0] = 0;
	      frame.at<cv::Vec3b>(y,x)[1] = 0;
	      frame.at<cv::Vec3b>(y,x)[2] = 255;
	      features_video_i.push_back(features_one_pixel);
	      labels_video_i.push_back( fr );
	    }
	  }
	}
      }

      if(cv::waitKey(30)>=0)
	break;

    }

      std::swap(prevgray, gray);
      std::swap(prevflow, flow);

     //cv::imshow("color", frame);
     //cv::waitKey(1);

  }
}<|endoftext|>


<commit_before><commit_msg>FrameGraph: add graphviz labels for size and MSAA.<commit_after><|endoftext|>


<commit_before>#include "tentacle-build.h"
<commit_msg>keep on tryin'<commit_after>#include "tentacle-particle.h"
<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

bool writeBug = false;
bool writeFileNames = false;

string waColor = "\033[1;33m";
string clearColor = "\033[0m";

string patStr;
string tesStr;

bool isWhite(char _c)
{
	if (_c == ' ' || _c == '	' || _c == '\n' || _c == '\r')
		return true;
	else
		return false;
}

bool readNext(ifstream &_file, string &_str)
{
	while(isWhite(_file.peek()))
		_file.get();
	if (_file.eof() == false)
	{
		_file >> _str;
		return true;
	}
	else
		return false;
}

int main(int _argc, char *_argv[])
{
	for (int i = 1; i < _argc; i++)
	{
		if (_argv[i][0] != '-')
		{
			if (i + 1 < _argc)
			{
				patStr = string(_argv[i]);
				tesStr = string(_argv[i + 1]);
				break;
			}
			else
			{
				cerr << "CMP: cmp/default: No second output file path" << endl;
				return -2;
			}
		}
		else
		{
			if (strcmp(_argv[i], "-bug") == 0)
				writeBug = true;
			else if (strcmp(_argv[i], "-fname") == 0)
				writeFileNames = true;
			else if (strcmp(_argv[i], "-nocolor") == 0)
			{
				waColor = "";
				clearColor = "";
			}
			else
			{
				cerr << "CMP: No arg called \"" << _argv[i] << "\" exists" << endl;
			}
		}
	}
	if (writeFileNames)
		cout << patStr << "	" << tesStr << endl;

	ifstream pat(patStr.c_str());
	ifstream tes(tesStr.c_str());

	if (pat.is_open() == false)
	{
		cerr << "CMP: Can't open:" << patStr << endl;
		return -2;
	}
	if (tes.is_open() == false)
	{
		cerr << "CMP: Can't open: " << tesStr << endl;
		return -2;
	}

	int strNr = 1;
	bool pb, tb;
	while (true)
	{
		pb = readNext(pat, patStr);
		tb = readNext(tes, tesStr);

		if (pb == false && tb == false)
			break;
		else if (pb == false || tb == false)
		{
			if (writeBug)
				cout << waColor << (pb == false ? "Output file is too long" : "Output file is too short") << clearColor << endl;

			pat.close();
			tes.close();
			return -1;
		}

		if (patStr != tesStr)
		{
			if (writeBug)
			{
				pat.close();
				tes.close();
				cout << waColor << "String:" << clearColor << strNr << waColor << " Expected:" << clearColor << patStr << waColor << " Readed:" << clearColor << tesStr << endl;
			}
			return -1;
		}

		strNr++;
	}
	pat.close();
	tes.close();
	return 0;
}
<commit_msg>default cmp display fix<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>

using namespace std;

bool writeBug = false;
bool writeFileNames = false;

string waColor = "\033[1;33m";
string clearColor = "\033[0m";

string patStr;
string tesStr;

bool isWhite(char _c)
{
	if (_c == ' ' || _c == '	' || _c == '\n' || _c == '\r')
		return true;
	else
		return false;
}

bool readNext(ifstream &_file, string &_str)
{
	while(isWhite(_file.peek()))
		_file.get();
	if (_file.eof() == false)
	{
		_file >> _str;
		return true;
	}
	else
		return false;
}

string cutString(string _str, unsigned int _maxSize = 20)	//cuts string when bigger than _maxSize
{
	string result = "";
	for (int i = 0; i < min<unsigned int>(_maxSize, _str.size()); i++)
	{
		result += _str[i];
	}
	if (_maxSize < _str.size())
		result += "...";
	return result;
}

int main(int _argc, char *_argv[])
{
	for (int i = 1; i < _argc; i++)
	{
		if (_argv[i][0] != '-')
		{
			if (i + 1 < _argc)
			{
				patStr = string(_argv[i]);
				tesStr = string(_argv[i + 1]);
				break;
			}
			else
			{
				cerr << "CMP: cmp/default: No second output file path" << endl;
				return -2;
			}
		}
		else
		{
			if (strcmp(_argv[i], "-bug") == 0)
				writeBug = true;
			else if (strcmp(_argv[i], "-fname") == 0)
				writeFileNames = true;
			else if (strcmp(_argv[i], "-nocolor") == 0)
			{
				waColor = "";
				clearColor = "";
			}
			else
			{
				cerr << "CMP: No arg called \"" << _argv[i] << "\" exists" << endl;
			}
		}
	}
	if (writeFileNames)
		cout << patStr << "	" << tesStr << endl;

	ifstream pat(patStr.c_str());
	ifstream tes(tesStr.c_str());

	if (pat.is_open() == false)
	{
		cerr << "CMP: Can't open:" << patStr << endl;
		return -2;
	}
	if (tes.is_open() == false)
	{
		cerr << "CMP: Can't open: " << tesStr << endl;
		return -2;
	}

	int strNr = 1;
	bool pb, tb;
	while (true)
	{
		pb = readNext(pat, patStr);
		tb = readNext(tes, tesStr);

		if (pb == false && tb == false)
			break;
		else if (pb == false || tb == false)
		{
			if (writeBug)
				cout << waColor << (pb == false ? "Output file is too long" : "Output file is too short") << clearColor << endl;

			pat.close();
			tes.close();
			return -1;
		}

		if (patStr != tesStr)
		{
			if (writeBug)
			{
				pat.close();
				tes.close();
				cout << waColor << "String:" << clearColor << strNr << waColor << " Expected:" << clearColor << cutString(patStr) << waColor << " Readed:" << clearColor << cutString(tesStr) << endl;
			}
			return -1;
		}

		strNr++;
	}
	pat.close();
	tes.close();
	return 0;
}
<|endoftext|>


<commit_before>#pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization ("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for (__typeof(a) i=(a); i<(b); ++i)
#define iter(it,c) for (__typeof((c).begin()) \
  it = (c).begin(); it != (c).end(); ++it)
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef long long ll;
const int INF = ~(1<<31);

const double EPS = 1e-9;
const double pi = acos(-1);
typedef unsigned long long ull;
typedef vector<vi> vvi;
typedef vector<vii> vvii;
template <class T> T smod(T a, T b) {
  return (a % b + b) % b; }
// vim: cc=60 ts=2 sts=2 sw=2:
<commit_msg>Fix GCC pragmas. Thanks @simonlindholm<commit_after>#pragma GCC optimize("Ofast","unroll-loops")
#pragma GCC target("avx2,fma")
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for (__typeof(a) i=(a); i<(b); ++i)
#define iter(it,c) for (__typeof((c).begin()) \
  it = (c).begin(); it != (c).end(); ++it)
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
typedef long long ll;
const int INF = ~(1<<31);

const double EPS = 1e-9;
const double pi = acos(-1);
typedef unsigned long long ull;
typedef vector<vi> vvi;
typedef vector<vii> vvii;
template <class T> T smod(T a, T b) {
  return (a % b + b) % b; }
// vim: cc=60 ts=2 sts=2 sw=2:
<|endoftext|>