<commit_before>/***************************************************************************
    copyright            : (C) 2013 by Lukas Krejci
    email                : krejclu6@fel.cvut.cz
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <tbytevectorlist.h>
#include <tpropertymap.h>
#include <tdebug.h>

#include "tableofcontentsframe.h"

using namespace TagLib;
using namespace ID3v2;

class TableOfContentsFrame::TableOfContentsFramePrivate
{
public:
  TableOfContentsFramePrivate() :
    tagHeader(0),
    isTopLevel(false),
    isOrdered(false)
  {
    embeddedFrameList.setAutoDelete(true);
  }

  const ID3v2::Header *tagHeader;
  ByteVector elementID;
  bool isTopLevel;
  bool isOrdered;
  ByteVectorList childElements;
  FrameListMap embeddedFrameListMap;
  FrameList embeddedFrameList;
};

namespace {

  // These functions are needed to try to aim for backward compatibility with
  // an API that previously (unreasonably) required null bytes to be appeneded
  // at the end of identifiers explicitly by the API user.

  // BIC: remove these

  ByteVector &strip(ByteVector &b)
  {
    if(b.endsWith('\0'))
      b.resize(b.size() - 1);
    return b;
  }

  ByteVectorList &strip(ByteVectorList &l)
  {
    for(ByteVectorList::Iterator it = l.begin(); it != l.end(); ++it)
    {
      strip(*it);
    }
    return l;
  }
}

////////////////////////////////////////////////////////////////////////////////
// public methods
////////////////////////////////////////////////////////////////////////////////

TableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader, const ByteVector &data) :
  ID3v2::Frame(data),
  d(new TableOfContentsFramePrivate())
{
  d->tagHeader = tagHeader;
  setData(data);
}

TableOfContentsFrame::TableOfContentsFrame(const ByteVector &elementID,
                                           const ByteVectorList &children,
                                           const FrameList &embeddedFrames) :
  ID3v2::Frame("CTOC"),
  d(new TableOfContentsFramePrivate())
{
  d->elementID = elementID;
  strip(d->elementID);
  d->childElements = children;

  for(FrameList::ConstIterator it = embeddedFrames.begin(); it != embeddedFrames.end(); ++it)
    addEmbeddedFrame(*it);
}

TableOfContentsFrame::~TableOfContentsFrame()
{
  delete d;
}

ByteVector TableOfContentsFrame::elementID() const
{
  return d->elementID;
}

bool TableOfContentsFrame::isTopLevel() const
{
  return d->isTopLevel;
}

bool TableOfContentsFrame::isOrdered() const
{
  return d->isOrdered;
}

unsigned int TableOfContentsFrame::entryCount() const
{
  return d->childElements.size();
}

ByteVectorList TableOfContentsFrame::childElements() const
{
  return d->childElements;
}

void TableOfContentsFrame::setElementID(const ByteVector &eID)
{
  d->elementID = eID;
  strip(d->elementID);
}

void TableOfContentsFrame::setIsTopLevel(const bool &t)
{
  d->isTopLevel = t;
}

void TableOfContentsFrame::setIsOrdered(const bool &o)
{
  d->isOrdered = o;
}

void TableOfContentsFrame::setChildElements(const ByteVectorList &l)
{
  d->childElements = l;
  strip(d->childElements);
}

void TableOfContentsFrame::addChildElement(const ByteVector &cE)
{
  d->childElements.append(cE);
  strip(d->childElements);
}

void TableOfContentsFrame::removeChildElement(const ByteVector &cE)
{
  ByteVectorList::Iterator it = d->childElements.find(cE);

  if(it == d->childElements.end())
    it = d->childElements.find(cE + ByteVector("\0"));

  d->childElements.erase(it);
}

const FrameListMap &TableOfContentsFrame::embeddedFrameListMap() const
{
  return d->embeddedFrameListMap;
}

const FrameList &TableOfContentsFrame::embeddedFrameList() const
{
  return d->embeddedFrameList;
}

const FrameList &TableOfContentsFrame::embeddedFrameList(const ByteVector &frameID) const
{
  return d->embeddedFrameListMap[frameID];
}

void TableOfContentsFrame::addEmbeddedFrame(Frame *frame)
{
  d->embeddedFrameList.append(frame);
  d->embeddedFrameListMap[frame->frameID()].append(frame);
}

void TableOfContentsFrame::removeEmbeddedFrame(Frame *frame, bool del)
{
  // remove the frame from the frame list
  FrameList::Iterator it = d->embeddedFrameList.find(frame);
  d->embeddedFrameList.erase(it);

  // ...and from the frame list map
  it = d->embeddedFrameListMap[frame->frameID()].find(frame);
  d->embeddedFrameListMap[frame->frameID()].erase(it);

  // ...and delete as desired
  if(del)
    delete frame;
}

void TableOfContentsFrame::removeEmbeddedFrames(const ByteVector &id)
{
  FrameList l = d->embeddedFrameListMap[id];
  for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)
    removeEmbeddedFrame(*it, true);
}

String TableOfContentsFrame::toString() const
{
  return String();
}

PropertyMap TableOfContentsFrame::asProperties() const
{
  PropertyMap map;

  map.unsupportedData().append(frameID() + String("/") + d->elementID);

  return map;
}

TableOfContentsFrame *TableOfContentsFrame::findByElementID(const ID3v2::Tag *tag,
                                                            const ByteVector &eID) // static
{
  ID3v2::FrameList tablesOfContents = tag->frameList("CTOC");

  for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();
      it != tablesOfContents.end();
      ++it)
  {
    TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);
    if(frame && frame->elementID() == eID)
      return frame;
  }

  return 0;
}

TableOfContentsFrame *TableOfContentsFrame::findTopLevel(const ID3v2::Tag *tag) // static
{
  ID3v2::FrameList tablesOfContents = tag->frameList("CTOC");

  for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();
      it != tablesOfContents.end();
      ++it)
  {
    TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);
    if(frame && frame->isTopLevel() == true)
      return frame;
  }

  return 0;
}

void TableOfContentsFrame::parseFields(const ByteVector &data)
{
  unsigned int size = data.size();
  if(size < 6) {
    debug("A CTOC frame must contain at least 6 bytes (1 byte element ID terminated by "
          "null, 1 byte flags, 1 byte entry count and 1 byte child element ID terminated "
          "by null.");
    return;
  }

  int pos = 0;
  unsigned int embPos = 0;
  d->elementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);
  d->isTopLevel = (data.at(pos) & 2) != 0;
  d->isOrdered = (data.at(pos++) & 1) != 0;
  unsigned int entryCount = static_cast<unsigned char>(data.at(pos++));
  for(unsigned int i = 0; i < entryCount; i++) {
    ByteVector childElementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);
    d->childElements.append(childElementID);
  }

  size -= pos;

  if(size < header()->size())
    return;

  while(embPos < size - header()->size()) {
    Frame *frame = FrameFactory::instance()->createFrame(data.mid(pos + embPos), (d->tagHeader != 0));

    if(!frame)
      return;

    // Checks to make sure that frame parsed correctly.
    if(frame->size() <= 0) {
      delete frame;
      return;
    }

    embPos += frame->size() + header()->size();
    addEmbeddedFrame(frame);
  }
}

ByteVector TableOfContentsFrame::renderFields() const
{
  ByteVector data;

  data.append(d->elementID);
  data.append('\0');
  char flags = 0;
  if(d->isTopLevel)
    flags += 2;
  if(d->isOrdered)
    flags += 1;
  data.append(flags);
  data.append((char)(entryCount()));
  ByteVectorList::ConstIterator it = d->childElements.begin();
  while(it != d->childElements.end()) {
    data.append(*it);
    data.append('\0');
    it++;
  }
  FrameList l = d->embeddedFrameList;
  for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)
    data.append((*it)->render());

  return data;
}

TableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader,
                                           const ByteVector &data, Header *h) :
  Frame(h),
  d(new TableOfContentsFramePrivate())
{
  d->tagHeader = tagHeader;
  parseFields(fieldData(data));
}
<commit_msg>Fill `TableOfContentsFrame::toString()`. (#852)<commit_after>/***************************************************************************
    copyright            : (C) 2013 by Lukas Krejci
    email                : krejclu6@fel.cvut.cz
 ***************************************************************************/

/***************************************************************************
 *   This library is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License version   *
 *   2.1 as published by the Free Software Foundation.                     *
 *                                                                         *
 *   This library is distributed in the hope that it will be useful, but   *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   Lesser General Public License for more details.                       *
 *                                                                         *
 *   You should have received a copy of the GNU Lesser General Public      *
 *   License along with this library; if not, write to the Free Software   *
 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA         *
 *   02110-1301  USA                                                       *
 *                                                                         *
 *   Alternatively, this file is available under the Mozilla Public        *
 *   License Version 1.1.  You may obtain a copy of the License at         *
 *   http://www.mozilla.org/MPL/                                           *
 ***************************************************************************/

#include <tbytevectorlist.h>
#include <tpropertymap.h>
#include <tdebug.h>

#include "tableofcontentsframe.h"

using namespace TagLib;
using namespace ID3v2;

class TableOfContentsFrame::TableOfContentsFramePrivate
{
public:
  TableOfContentsFramePrivate() :
    tagHeader(0),
    isTopLevel(false),
    isOrdered(false)
  {
    embeddedFrameList.setAutoDelete(true);
  }

  const ID3v2::Header *tagHeader;
  ByteVector elementID;
  bool isTopLevel;
  bool isOrdered;
  ByteVectorList childElements;
  FrameListMap embeddedFrameListMap;
  FrameList embeddedFrameList;
};

namespace {

  // These functions are needed to try to aim for backward compatibility with
  // an API that previously (unreasonably) required null bytes to be appeneded
  // at the end of identifiers explicitly by the API user.

  // BIC: remove these

  ByteVector &strip(ByteVector &b)
  {
    if(b.endsWith('\0'))
      b.resize(b.size() - 1);
    return b;
  }

  ByteVectorList &strip(ByteVectorList &l)
  {
    for(ByteVectorList::Iterator it = l.begin(); it != l.end(); ++it)
    {
      strip(*it);
    }
    return l;
  }
}

////////////////////////////////////////////////////////////////////////////////
// public methods
////////////////////////////////////////////////////////////////////////////////

TableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader, const ByteVector &data) :
  ID3v2::Frame(data),
  d(new TableOfContentsFramePrivate())
{
  d->tagHeader = tagHeader;
  setData(data);
}

TableOfContentsFrame::TableOfContentsFrame(const ByteVector &elementID,
                                           const ByteVectorList &children,
                                           const FrameList &embeddedFrames) :
  ID3v2::Frame("CTOC"),
  d(new TableOfContentsFramePrivate())
{
  d->elementID = elementID;
  strip(d->elementID);
  d->childElements = children;

  for(FrameList::ConstIterator it = embeddedFrames.begin(); it != embeddedFrames.end(); ++it)
    addEmbeddedFrame(*it);
}

TableOfContentsFrame::~TableOfContentsFrame()
{
  delete d;
}

ByteVector TableOfContentsFrame::elementID() const
{
  return d->elementID;
}

bool TableOfContentsFrame::isTopLevel() const
{
  return d->isTopLevel;
}

bool TableOfContentsFrame::isOrdered() const
{
  return d->isOrdered;
}

unsigned int TableOfContentsFrame::entryCount() const
{
  return d->childElements.size();
}

ByteVectorList TableOfContentsFrame::childElements() const
{
  return d->childElements;
}

void TableOfContentsFrame::setElementID(const ByteVector &eID)
{
  d->elementID = eID;
  strip(d->elementID);
}

void TableOfContentsFrame::setIsTopLevel(const bool &t)
{
  d->isTopLevel = t;
}

void TableOfContentsFrame::setIsOrdered(const bool &o)
{
  d->isOrdered = o;
}

void TableOfContentsFrame::setChildElements(const ByteVectorList &l)
{
  d->childElements = l;
  strip(d->childElements);
}

void TableOfContentsFrame::addChildElement(const ByteVector &cE)
{
  d->childElements.append(cE);
  strip(d->childElements);
}

void TableOfContentsFrame::removeChildElement(const ByteVector &cE)
{
  ByteVectorList::Iterator it = d->childElements.find(cE);

  if(it == d->childElements.end())
    it = d->childElements.find(cE + ByteVector("\0"));

  d->childElements.erase(it);
}

const FrameListMap &TableOfContentsFrame::embeddedFrameListMap() const
{
  return d->embeddedFrameListMap;
}

const FrameList &TableOfContentsFrame::embeddedFrameList() const
{
  return d->embeddedFrameList;
}

const FrameList &TableOfContentsFrame::embeddedFrameList(const ByteVector &frameID) const
{
  return d->embeddedFrameListMap[frameID];
}

void TableOfContentsFrame::addEmbeddedFrame(Frame *frame)
{
  d->embeddedFrameList.append(frame);
  d->embeddedFrameListMap[frame->frameID()].append(frame);
}

void TableOfContentsFrame::removeEmbeddedFrame(Frame *frame, bool del)
{
  // remove the frame from the frame list
  FrameList::Iterator it = d->embeddedFrameList.find(frame);
  d->embeddedFrameList.erase(it);

  // ...and from the frame list map
  it = d->embeddedFrameListMap[frame->frameID()].find(frame);
  d->embeddedFrameListMap[frame->frameID()].erase(it);

  // ...and delete as desired
  if(del)
    delete frame;
}

void TableOfContentsFrame::removeEmbeddedFrames(const ByteVector &id)
{
  FrameList l = d->embeddedFrameListMap[id];
  for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)
    removeEmbeddedFrame(*it, true);
}

String TableOfContentsFrame::toString() const
{
  String s = String(d->elementID) +
             ": top level: " + (d->isTopLevel ? "true" : "false") +
             ", ordered: " + (d->isOrdered ? "true" : "false");

  if(!d->childElements.isEmpty()) {
    s+= ", chapters: [ " + String(d->childElements.toByteVector(", ")) + " ]";
  }

  if(!d->embeddedFrameList.isEmpty()) {
    StringList frameIDs;
    for(FrameList::ConstIterator it = d->embeddedFrameList.begin();
        it != d->embeddedFrameList.end(); ++it)
      frameIDs.append((*it)->frameID());
    s += ", sub-frames: [ " + frameIDs.toString(", ") + " ]";
  }

  return s;
}

PropertyMap TableOfContentsFrame::asProperties() const
{
  PropertyMap map;

  map.unsupportedData().append(frameID() + String("/") + d->elementID);

  return map;
}

TableOfContentsFrame *TableOfContentsFrame::findByElementID(const ID3v2::Tag *tag,
                                                            const ByteVector &eID) // static
{
  ID3v2::FrameList tablesOfContents = tag->frameList("CTOC");

  for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();
      it != tablesOfContents.end();
      ++it)
  {
    TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);
    if(frame && frame->elementID() == eID)
      return frame;
  }

  return 0;
}

TableOfContentsFrame *TableOfContentsFrame::findTopLevel(const ID3v2::Tag *tag) // static
{
  ID3v2::FrameList tablesOfContents = tag->frameList("CTOC");

  for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();
      it != tablesOfContents.end();
      ++it)
  {
    TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);
    if(frame && frame->isTopLevel() == true)
      return frame;
  }

  return 0;
}

void TableOfContentsFrame::parseFields(const ByteVector &data)
{
  unsigned int size = data.size();
  if(size < 6) {
    debug("A CTOC frame must contain at least 6 bytes (1 byte element ID terminated by "
          "null, 1 byte flags, 1 byte entry count and 1 byte child element ID terminated "
          "by null.");
    return;
  }

  int pos = 0;
  unsigned int embPos = 0;
  d->elementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);
  d->isTopLevel = (data.at(pos) & 2) != 0;
  d->isOrdered = (data.at(pos++) & 1) != 0;
  unsigned int entryCount = static_cast<unsigned char>(data.at(pos++));
  for(unsigned int i = 0; i < entryCount; i++) {
    ByteVector childElementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);
    d->childElements.append(childElementID);
  }

  size -= pos;

  if(size < header()->size())
    return;

  while(embPos < size - header()->size()) {
    Frame *frame = FrameFactory::instance()->createFrame(data.mid(pos + embPos), (d->tagHeader != 0));

    if(!frame)
      return;

    // Checks to make sure that frame parsed correctly.
    if(frame->size() <= 0) {
      delete frame;
      return;
    }

    embPos += frame->size() + header()->size();
    addEmbeddedFrame(frame);
  }
}

ByteVector TableOfContentsFrame::renderFields() const
{
  ByteVector data;

  data.append(d->elementID);
  data.append('\0');
  char flags = 0;
  if(d->isTopLevel)
    flags += 2;
  if(d->isOrdered)
    flags += 1;
  data.append(flags);
  data.append((char)(entryCount()));
  ByteVectorList::ConstIterator it = d->childElements.begin();
  while(it != d->childElements.end()) {
    data.append(*it);
    data.append('\0');
    it++;
  }
  FrameList l = d->embeddedFrameList;
  for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)
    data.append((*it)->render());

  return data;
}

TableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader,
                                           const ByteVector &data, Header *h) :
  Frame(h),
  d(new TableOfContentsFramePrivate())
{
  d->tagHeader = tagHeader;
  parseFields(fieldData(data));
}
<|endoftext|>


<commit_before>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#include "jstreamsconfig.h"
#include "indexer.h"
#include "dummyindexwriter.h"
#include "streamindexer.h"
#include "indexerconfiguration.h"
#include "streamendanalyzer.h"
using namespace jstreams;

class FindIndexerConfiguration : public IndexerConfiguration {
public:
    bool useFactory(StreamEndAnalyzerFactory* e) const {
        return e->analyzesSubStreams();
    }
    bool useFactory(StreamThroughAnalyzerFactory*) const {return false;}
    bool indexMore() const {return true;}
    bool addMoreText() const {return false;}
};

void
printUsage(char** argv) {
    fprintf(stderr, "Usage: %s [dir-or-file-to-find]\n", argv[0]);
}
bool
containsHelp(int argc, char **argv) {
    for (int i=1; i<argc; ++i) {
         if (strcmp(argv[i], "--help") == 0
             || strcmp(argv[i], "-h") == 0) return true;
    }
    return false;
}

int
main(int argc, char **argv) {
    const char* path = ".";
    if (containsHelp(argc, argv) || argc > 2) {
        printUsage(argv);
        return -1;
    }
    if (argc == 2) {
        path = argv[1];
    }

    DummyIndexWriter writer(1);
    FindIndexerConfiguration conf;
    Indexer indexer(writer, conf);
    indexer.index(path);
    return 0;
}
<commit_msg>Add content and implement information function.<commit_after>/* This file is part of Strigi Desktop Search
 *
 * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#include "jstreamsconfig.h"
#include "indexer.h"
#include "dummyindexwriter.h"
#include "streamindexer.h"
#include "indexerconfiguration.h"
#include "streamendanalyzer.h"
using namespace jstreams;

/**
 * Special indexer that indexes only the filenames.
 **/
class FindIndexerConfiguration : public IndexerConfiguration {
public:
    bool useFactory(StreamEndAnalyzerFactory* e) const {
        return e->analyzesSubStreams();
    }
    bool useFactory(StreamThroughAnalyzerFactory*) const {return false;}
    bool indexMore() const {return true;}
    bool addMoreText() const {return false;}
    FieldType getIndexType(const cnstr& fieldname) const {
        return None;
    }
};

void
printUsage(char** argv) {
    fprintf(stderr, "Usage: %s [dir-or-file-to-find]\n", argv[0]);
}
bool
containsHelp(int argc, char **argv) {
    for (int i=1; i<argc; ++i) {
         if (strcmp(argv[i], "--help") == 0
             || strcmp(argv[i], "-h") == 0) return true;
    }
    return false;
}

int
main(int argc, char **argv) {
    const char* path = ".";
    if (containsHelp(argc, argv) || argc > 2) {
        printUsage(argv);
        return -1;
    }
    if (argc == 2) {
        path = argv[1];
    }

    DummyIndexWriter writer(1);
    FindIndexerConfiguration conf;
    Indexer indexer(writer, conf);
    indexer.index(path);
    return 0;
}
<|endoftext|>


<commit_before>#ifndef Rice__Hash__ipp_
#define Rice__Hash__ipp_

#include "protect.hpp"
#include "to_from_ruby.hpp"
#include "Builtin_Object.hpp"
#include "Exception.hpp"
#include "Builtin_Object.hpp"
#include <algorithm>

// TODO: Evil hack
struct st_table_entry {
  unsigned int hash;
  st_data_t key;
  st_data_t record;
  st_table_entry *next;
};

inline Rice::Hash::
Hash()
  : Builtin_Object<RHash, T_HASH>(protect(rb_hash_new))
{
}

inline Rice::Hash::
Hash(Object v)
  : Builtin_Object<RHash, T_HASH>(v)
{
}

inline size_t Rice::Hash::
size() const
{
  return RHASH_TBL(*this)->num_entries;
}

inline Rice::Hash::Proxy::
Proxy(Hash hash, Object key)
  : hash_(hash)
  , key_(key)
{
}

/*
inline Rice::Hash::Proxy::
operator VALUE() const
{
  return value();
}
*/

inline Rice::Hash::Proxy::
operator Rice::Object() const
{
  return value();
}

inline VALUE Rice::Hash::Proxy::
value() const
{
  return protect(rb_hash_aref, hash_, key_);
}

template<typename T>
inline Rice::Object Rice::Hash::Proxy::
operator=(T const & value)
{
  return protect(rb_hash_aset, hash_, key_, to_ruby(value));
}

inline void Rice::Hash::Proxy::
swap(Proxy & proxy)
{
  hash_.swap(proxy.hash_);
  key_.swap(proxy.key_);
}

template<typename Key_T>
inline Rice::Hash::Proxy const Rice::Hash::
operator[](Key_T const & key) const
{
  return Proxy(*this, to_ruby(key));
}

template<typename Key_T>
inline Rice::Hash::Proxy Rice::Hash::
operator[](Key_T const & key)
{
  return Proxy(*this, to_ruby(key));
}

template<typename Value_T, typename Key_T>
inline Value_T Rice::Hash::
get(Key_T const & key)
{
  Object ruby_key(to_ruby(key));
  Object value = operator[](ruby_key);
  try
  {
    return from_ruby<Value_T>(value);
  }
  catch(Exception const & ex)
  {
    String s_key(ruby_key.to_s());
    throw Exception(
        ex,
        "%s while converting value for key %s",
        ex.what(),
        s_key.c_str());
  }
}

inline Rice::Hash::Entry::
Entry(Hash hash, Object key)
  : key(key)
  , first(Hash::Entry::key)
  , value(hash, key)
  , second(Hash::Entry::value)
{
}

inline Rice::Hash::Entry::
Entry(Entry const & entry)
  : key(entry.key)
  , first(Hash::Entry::key)
  , value(entry.value)
  , second(Hash::Entry::value)
{
}

inline Rice::Hash::Entry & Rice::Hash::Entry::
operator=(Rice::Hash::Entry const & rhs)
{
  Entry tmp(rhs);
  swap(tmp);
  return *this;
}

inline void Rice::Hash::Entry::
swap(Rice::Hash::Entry & entry)
{
  const_cast<Object &>(key).swap(const_cast<Object &>(entry.key));
  value.swap(entry.value);
}

template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Hash_Ref_T hash, size_t bin, st_table_entry * ptr)
  : hash_(hash)
  , tbl_(RHASH_TBL(hash.value()))
  , bin_(bin)
  , ptr_(ptr)
  , tmp_(hash, Qnil)
{
  // If we aren't already at the end, then use the increment operator to
  // point to the first element
  if(!ptr_ && bin_ < tbl_->num_bins)
  {
    operator++();
  }
}

template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Iterator const & iterator)
  : hash_(iterator.hash_.value())
  , tbl_(iterator.tbl_)
  , bin_(iterator.bin_)
  , ptr_(iterator.ptr_)
  , tmp_(iterator.hash_, Qnil)
{
}

template<typename Hash_Ref_T, typename Value_T>
template<typename Iterator_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Iterator_T const & iterator)
  : hash_(iterator.hash_.value())
  , tbl_(iterator.tbl_)
  , bin_(iterator.bin_)
  , ptr_(iterator.ptr_)
  , tmp_(iterator.hash_, Qnil)
{
}

template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator=(Iterator const & iterator)
{
  Iterator tmp(iterator);

  this->swap(tmp);

  return *this;
}

template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator++()
{
  // Go to the next element in the bin; this will be a no-op if we were
  // called from the constructor, because ptr_ will be 0 (and if its
  // not, this function won't get called).
  if(ptr_)
  {
    ptr_ = ptr_->next;
  }

  // If we've reached the end of the bin, then try the next bin until
  // we have run out of bins
  while(ptr_ == 0)
  {
    ++bin_;
    if(bin_ == tbl_->num_bins)
    {
      // At the end..
      return *this;
    }
    ptr_ = tbl_->bins[bin_];
  }

  return *this;
}

template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator++(int)
{
  Iterator copy(*this);
  ++(*this);
  return copy;
}

template<typename Hash_Ref_T, typename Value_T>
inline Value_T
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator*()
{
  return Value_T(hash_, ptr_->key);
}

template<typename Hash_Ref_T, typename Value_T>
inline Value_T *
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator->()
{
  Entry tmp(hash_, ptr_->key);
  this->tmp_.swap(tmp);
  return &tmp_;
}

template<typename Hash_Ref_T, typename Value_T>
inline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator==(Iterator const & rhs) const
{
  return hash_.value() == rhs.hash_.value()
    && tbl_ == rhs.tbl_
    && bin_ == rhs.bin_
    && ptr_ == rhs.ptr_;
}

template<typename Hash_Ref_T, typename Value_T>
inline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator!=(Iterator const & rhs) const
{
  return !(*this == rhs);
}

template<typename Hash_Ref_T, typename Value_T>
inline void
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
swap(Iterator& iterator)
{
  using namespace std;

  hash_.swap(iterator.hash_);
  swap(tbl_, iterator.tbl_);
  swap(bin_, iterator.bin_);
  swap(ptr_, iterator.ptr_);
}

inline Rice::Hash::iterator Rice::Hash::
begin()
{
  st_table * tbl(RHASH_TBL(value()));
  return iterator(*this, 0, tbl->bins[0]);
}

inline Rice::Hash::const_iterator Rice::Hash::
begin() const
{
  st_table * tbl(RHASH_TBL(value()));
  return const_iterator(*this, 0, tbl->bins[0]);
}

inline Rice::Hash::iterator Rice::Hash::
end()
{
  st_table * tbl(RHASH_TBL(value()));
  return iterator(*this, tbl->num_bins, 0);
}

inline Rice::Hash::const_iterator Rice::Hash::
end() const
{
  st_table * tbl(RHASH_TBL(value()));
  return const_iterator(*this, tbl->num_bins, 0);
}

inline bool Rice::
operator<(
    Hash::Entry const & lhs, Hash::Entry const & rhs)
{
  Object lhs_key(lhs.key);
  Object rhs_key(rhs.key);
  if(lhs_key < rhs_key)
  {
    return true;
  }
  else if(lhs_key > rhs_key)
  {
    return false;
  }
  else if(Object(lhs.value.value()) < Object(rhs.value.value()))
  {
    return true;
  }
  else
  {
    return false;
  }
}

#endif // Rice__Hash__ipp_

<commit_msg>Fixed compile error where *this wasn't implicitly converted to a VALUE.<commit_after>#ifndef Rice__Hash__ipp_
#define Rice__Hash__ipp_

#include "protect.hpp"
#include "to_from_ruby.hpp"
#include "Builtin_Object.hpp"
#include "Exception.hpp"
#include "Builtin_Object.hpp"
#include <algorithm>

// TODO: Evil hack
struct st_table_entry {
  unsigned int hash;
  st_data_t key;
  st_data_t record;
  st_table_entry *next;
};

inline Rice::Hash::
Hash()
  : Builtin_Object<RHash, T_HASH>(protect(rb_hash_new))
{
}

inline Rice::Hash::
Hash(Object v)
  : Builtin_Object<RHash, T_HASH>(v)
{
}

inline size_t Rice::Hash::
size() const
{
  return RHASH_TBL(this->value())->num_entries;
}

inline Rice::Hash::Proxy::
Proxy(Hash hash, Object key)
  : hash_(hash)
  , key_(key)
{
}

/*
inline Rice::Hash::Proxy::
operator VALUE() const
{
  return value();
}
*/

inline Rice::Hash::Proxy::
operator Rice::Object() const
{
  return value();
}

inline VALUE Rice::Hash::Proxy::
value() const
{
  return protect(rb_hash_aref, hash_, key_);
}

template<typename T>
inline Rice::Object Rice::Hash::Proxy::
operator=(T const & value)
{
  return protect(rb_hash_aset, hash_, key_, to_ruby(value));
}

inline void Rice::Hash::Proxy::
swap(Proxy & proxy)
{
  hash_.swap(proxy.hash_);
  key_.swap(proxy.key_);
}

template<typename Key_T>
inline Rice::Hash::Proxy const Rice::Hash::
operator[](Key_T const & key) const
{
  return Proxy(*this, to_ruby(key));
}

template<typename Key_T>
inline Rice::Hash::Proxy Rice::Hash::
operator[](Key_T const & key)
{
  return Proxy(*this, to_ruby(key));
}

template<typename Value_T, typename Key_T>
inline Value_T Rice::Hash::
get(Key_T const & key)
{
  Object ruby_key(to_ruby(key));
  Object value = operator[](ruby_key);
  try
  {
    return from_ruby<Value_T>(value);
  }
  catch(Exception const & ex)
  {
    String s_key(ruby_key.to_s());
    throw Exception(
        ex,
        "%s while converting value for key %s",
        ex.what(),
        s_key.c_str());
  }
}

inline Rice::Hash::Entry::
Entry(Hash hash, Object key)
  : key(key)
  , first(Hash::Entry::key)
  , value(hash, key)
  , second(Hash::Entry::value)
{
}

inline Rice::Hash::Entry::
Entry(Entry const & entry)
  : key(entry.key)
  , first(Hash::Entry::key)
  , value(entry.value)
  , second(Hash::Entry::value)
{
}

inline Rice::Hash::Entry & Rice::Hash::Entry::
operator=(Rice::Hash::Entry const & rhs)
{
  Entry tmp(rhs);
  swap(tmp);
  return *this;
}

inline void Rice::Hash::Entry::
swap(Rice::Hash::Entry & entry)
{
  const_cast<Object &>(key).swap(const_cast<Object &>(entry.key));
  value.swap(entry.value);
}

template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Hash_Ref_T hash, size_t bin, st_table_entry * ptr)
  : hash_(hash)
  , tbl_(RHASH_TBL(hash.value()))
  , bin_(bin)
  , ptr_(ptr)
  , tmp_(hash, Qnil)
{
  // If we aren't already at the end, then use the increment operator to
  // point to the first element
  if(!ptr_ && bin_ < tbl_->num_bins)
  {
    operator++();
  }
}

template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Iterator const & iterator)
  : hash_(iterator.hash_.value())
  , tbl_(iterator.tbl_)
  , bin_(iterator.bin_)
  , ptr_(iterator.ptr_)
  , tmp_(iterator.hash_, Qnil)
{
}

template<typename Hash_Ref_T, typename Value_T>
template<typename Iterator_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Iterator_T const & iterator)
  : hash_(iterator.hash_.value())
  , tbl_(iterator.tbl_)
  , bin_(iterator.bin_)
  , ptr_(iterator.ptr_)
  , tmp_(iterator.hash_, Qnil)
{
}

template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator=(Iterator const & iterator)
{
  Iterator tmp(iterator);

  this->swap(tmp);

  return *this;
}

template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator++()
{
  // Go to the next element in the bin; this will be a no-op if we were
  // called from the constructor, because ptr_ will be 0 (and if its
  // not, this function won't get called).
  if(ptr_)
  {
    ptr_ = ptr_->next;
  }

  // If we've reached the end of the bin, then try the next bin until
  // we have run out of bins
  while(ptr_ == 0)
  {
    ++bin_;
    if(bin_ == tbl_->num_bins)
    {
      // At the end..
      return *this;
    }
    ptr_ = tbl_->bins[bin_];
  }

  return *this;
}

template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator++(int)
{
  Iterator copy(*this);
  ++(*this);
  return copy;
}

template<typename Hash_Ref_T, typename Value_T>
inline Value_T
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator*()
{
  return Value_T(hash_, ptr_->key);
}

template<typename Hash_Ref_T, typename Value_T>
inline Value_T *
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator->()
{
  Entry tmp(hash_, ptr_->key);
  this->tmp_.swap(tmp);
  return &tmp_;
}

template<typename Hash_Ref_T, typename Value_T>
inline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator==(Iterator const & rhs) const
{
  return hash_.value() == rhs.hash_.value()
    && tbl_ == rhs.tbl_
    && bin_ == rhs.bin_
    && ptr_ == rhs.ptr_;
}

template<typename Hash_Ref_T, typename Value_T>
inline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator!=(Iterator const & rhs) const
{
  return !(*this == rhs);
}

template<typename Hash_Ref_T, typename Value_T>
inline void
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
swap(Iterator& iterator)
{
  using namespace std;

  hash_.swap(iterator.hash_);
  swap(tbl_, iterator.tbl_);
  swap(bin_, iterator.bin_);
  swap(ptr_, iterator.ptr_);
}

inline Rice::Hash::iterator Rice::Hash::
begin()
{
  st_table * tbl(RHASH_TBL(value()));
  return iterator(*this, 0, tbl->bins[0]);
}

inline Rice::Hash::const_iterator Rice::Hash::
begin() const
{
  st_table * tbl(RHASH_TBL(value()));
  return const_iterator(*this, 0, tbl->bins[0]);
}

inline Rice::Hash::iterator Rice::Hash::
end()
{
  st_table * tbl(RHASH_TBL(value()));
  return iterator(*this, tbl->num_bins, 0);
}

inline Rice::Hash::const_iterator Rice::Hash::
end() const
{
  st_table * tbl(RHASH_TBL(value()));
  return const_iterator(*this, tbl->num_bins, 0);
}

inline bool Rice::
operator<(
    Hash::Entry const & lhs, Hash::Entry const & rhs)
{
  Object lhs_key(lhs.key);
  Object rhs_key(rhs.key);
  if(lhs_key < rhs_key)
  {
    return true;
  }
  else if(lhs_key > rhs_key)
  {
    return false;
  }
  else if(Object(lhs.value.value()) < Object(rhs.value.value()))
  {
    return true;
  }
  else
  {
    return false;
  }
}

#endif // Rice__Hash__ipp_

<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
 * Authors:
 *   - Paul Asmuth <paul@eventql.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <string>
#include <ctime>
#include <sys/time.h>
#include <sys/types.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "eventql/util/wallclock.h"
#include "eventql/util/logging.h"

UnixTime WallClock::now() {
  return UnixTime(WallClock::getUnixMicros());
}

uint64_t WallClock::unixSeconds() {
  struct timeval tv;

  gettimeofday(&tv, NULL);
  return tv.tv_sec;
}

uint64_t WallClock::getUnixMillis() {
  return unixMillis();
}

uint64_t WallClock::unixMillis() {
  struct timeval tv;

  gettimeofday(&tv, NULL);
  return tv.tv_sec * 1000llu + tv.tv_usec / 1000llu;
}

uint64_t WallClock::getUnixMicros() {
  return unixMicros();
}

uint64_t WallClock::unixMicros() {
  struct timeval tv;

  gettimeofday(&tv, NULL);
  return tv.tv_sec * 1000000llu + tv.tv_usec;
}

uint64_t MonotonicClock::now() {
#ifdef __MACH__
  clock_serv_t cclock;
  mach_timespec_t mts;
  host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  clock_get_time(cclock, &mts);
  mach_port_deallocate(mach_task_self(), cclock);
  return std::uint64_t(mts.tv_sec) * 1000000 + mts.tv_nsec / 1000;
#else
  timespec ts;
  if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
    logFatal("clock_gettime(CLOCK_MONOTONIC) failed");
    abort();
  } else {
    return std::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000;
  }
#endif
}

<commit_msg>fix invalid logFatal call<commit_after>/**
 * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
 * Authors:
 *   - Paul Asmuth <paul@eventql.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <string>
#include <ctime>
#include <sys/time.h>
#include <sys/types.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "eventql/util/wallclock.h"
#include "eventql/util/logging.h"

UnixTime WallClock::now() {
  return UnixTime(WallClock::getUnixMicros());
}

uint64_t WallClock::unixSeconds() {
  struct timeval tv;

  gettimeofday(&tv, NULL);
  return tv.tv_sec;
}

uint64_t WallClock::getUnixMillis() {
  return unixMillis();
}

uint64_t WallClock::unixMillis() {
  struct timeval tv;

  gettimeofday(&tv, NULL);
  return tv.tv_sec * 1000llu + tv.tv_usec / 1000llu;
}

uint64_t WallClock::getUnixMicros() {
  return unixMicros();
}

uint64_t WallClock::unixMicros() {
  struct timeval tv;

  gettimeofday(&tv, NULL);
  return tv.tv_sec * 1000000llu + tv.tv_usec;
}

uint64_t MonotonicClock::now() {
#ifdef __MACH__
  clock_serv_t cclock;
  mach_timespec_t mts;
  host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  clock_get_time(cclock, &mts);
  mach_port_deallocate(mach_task_self(), cclock);
  return std::uint64_t(mts.tv_sec) * 1000000 + mts.tv_nsec / 1000;
#else
  timespec ts;
  if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
    logFatal("evqld", "clock_gettime(CLOCK_MONOTONIC) failed");
    abort();
  } else {
    return std::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000;
  }
#endif
}

<|endoftext|>


<commit_before>409ad740-ad5a-11e7-8fcd-ac87a332f658<commit_msg>My Life for Auir<commit_after>410abed1-ad5a-11e7-b246-ac87a332f658<|endoftext|>


<commit_before>471c730c-2748-11e6-9bba-e0f84713e7b8<commit_msg>lets try again<commit_after>47275075-2748-11e6-8282-e0f84713e7b8<|endoftext|>


<commit_before>e6bd4e78-2747-11e6-92d9-e0f84713e7b8<commit_msg>Deal with it<commit_after>e6cf1da8-2747-11e6-be1c-e0f84713e7b8<|endoftext|>


<commit_before>b2f04480-ad5b-11e7-baf7-ac87a332f658<commit_msg>NO CHANGES<commit_after>b36db866-ad5b-11e7-a2ed-ac87a332f658<|endoftext|>


<commit_before>e4123eb8-2747-11e6-9413-e0f84713e7b8<commit_msg>My Life for Auir<commit_after>e421e997-2747-11e6-944a-e0f84713e7b8<|endoftext|>


<commit_before>af0649bd-ad5b-11e7-bb36-ac87a332f658<commit_msg>Stuff changed<commit_after>af8a9fdc-ad5b-11e7-a7fb-ac87a332f658<|endoftext|>


<commit_before>/****************************************************************************
 **
 ** Copyright (C) 2012 Wapp6
 ** All rights reserved.
 ** Contact: Wapp6 (contact@wapp6.com)
 **
 ** This file is part of OPR6Desktop application.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
 ** $QT_END_LICENSE$
 **
 ****************************************************************************/
#include <QCoreApplication>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QStandardPaths>
#include <QDir>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QDebug>
#include <QTextStream>
#include <QDateTime>
#include <iostream>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QString noteTable = "note";
    QCoreApplication::setApplicationName("clignote");
    QCoreApplication::setApplicationVersion("1.0");

    QString storedNotes = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    if(!QDir(storedNotes).exists() && !QDir(storedNotes).mkpath(storedNotes)) {
        std::cout  << "unable to create directory, exiting...";
        exit(-1);
    }
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    QSqlQuery query;
    QDir storage(storedNotes);
    db.setDatabaseName(storage.absoluteFilePath("notes.db"));
    if(!db.open()) {
        qDebug() << "unable to open db";
        std::cout  << db.lastError().text().toStdString();
        exit(-2);
    }   else    {
        query = QSqlQuery(db);
        if(!db.tables().contains(noteTable))  {
            qDebug() << "table note is not present, creating";
            if(!query.exec(QString("CREATE TABLE %1(id INTEGER PRIMARY KEY, created_at DATETIME, text TEXT);").arg(noteTable)))    {
                qDebug() << query.lastQuery() << query.lastError() << db.lastError();
                std::cout  << "error creating database";
                exit(-1);
            }
        }
    }
      QCommandLineParser parser;
      parser.setApplicationDescription("Note helper");
      parser.addHelpOption();
      parser.addVersionOption();
      parser.addPositionalArgument("command", QCoreApplication::translate("main", "what to do (list, add, delete)"));
      parser.addPositionalArgument("content", QCoreApplication::translate("main", "note id or text"));

      // Process the actual command line arguments given by the user
      parser.process(app);

      const QStringList args = parser.positionalArguments();
      if(!args.length())    {
          std::cout  << "argument required, use --help";
          exit(0);
      }
      // source is args.at(0), destination is args.at(1)

      if(args.at(0) == "list")  {
            if(query.exec(QString("select * from %1").arg(noteTable)))    {;
                if(query.first())   {
                    QSqlRecord record;
                    std::cout  << "  id   |    creation date    |  note \n";
                    std::cout  << QString("").fill('-',80).toStdString() << "\n";
                    do  {
                        record = query.record();
                        std::cout  << QString().fill(' ', 6-record.value(0).toString().length()).toStdString()
                                << record.value(0).toString().toStdString()
                                << " | "
                                << record.value(1).toDateTime().toString(Qt::ISODate).toStdString()
                                << " | "
                                << record.value(2).toString().toStdString()
                                << "\n";

                    }   while(query.next());
                }   else    {
                    std::cout  << QCoreApplication::translate("main", "No note available\n").toStdString();
                }
            } else    {
                std::cout  << "error querying database\n";
                qDebug() << query.lastQuery() << query.lastError() << db.lastError();
            }
            exit(0);
      }
      if(args.at(0) == "add")   {
          if(args.length() < 2) {
              std::cout  << "no note to add...";
          }
          else {
              qDebug() << args.mid(1).join(" ");
              QString text = args.mid(1).join(" ");
              query.prepare(QString("insert into %1 values(NULL, :currentDateTime, :text)").arg(noteTable));
              query.bindValue(":currentDateTime", QDateTime::currentDateTime());
              query.bindValue(":text", text);
              if(query.exec())  {
                  std::cout  << "note added\n";
              } else    {
                  std::cout  << "error saving note to database\n";
                  qDebug() << query.lastQuery() << query.lastError() << db.lastError();
              }
          }
          exit(0);
      }

      if(args.at(0) == "delete")   {
          if(args.length() < 2) {
              std::cout  << "no note to delete...\n";
          }
          else {
              qInfo() << args.at(1);
              QString intString = args.at(1);
              int noteId = QVariant(intString).toInt();
              if(noteId)    {
                  query.prepare(QString("delete from %1 where id=:id").arg(noteTable));
                  query.bindValue(":id", noteId);
                  if(query.exec())  {
                      std::cout  << "note deleted\n";
                  } else    {
                      qDebug() << query.lastQuery() << query.lastError() << db.lastError();
                      std::cout  << "error deleting note from database\n";
                  }
              }    else    {
                  std::cout  << "invalid note identifier\n";
              }
          }
          exit(0);
      }

    return app.exec();
}
<commit_msg>remove licence header<commit_after>#include <QCoreApplication>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QStandardPaths>
#include <QDir>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QDebug>
#include <QTextStream>
#include <QDateTime>
#include <iostream>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QString noteTable = "note";
    QCoreApplication::setApplicationName("clignote");
    QCoreApplication::setApplicationVersion("1.0");

    QString storedNotes = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    if(!QDir(storedNotes).exists() && !QDir(storedNotes).mkpath(storedNotes)) {
        std::cout  << "unable to create directory, exiting...";
        exit(-1);
    }
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    QSqlQuery query;
    QDir storage(storedNotes);
    db.setDatabaseName(storage.absoluteFilePath("notes.db"));
    if(!db.open()) {
        qDebug() << "unable to open db";
        std::cout  << db.lastError().text().toStdString();
        exit(-2);
    }   else    {
        query = QSqlQuery(db);
        if(!db.tables().contains(noteTable))  {
            qDebug() << "table note is not present, creating";
            if(!query.exec(QString("CREATE TABLE %1(id INTEGER PRIMARY KEY, created_at DATETIME, text TEXT);").arg(noteTable)))    {
                qDebug() << query.lastQuery() << query.lastError() << db.lastError();
                std::cout  << "error creating database";
                exit(-1);
            }
        }
    }
      QCommandLineParser parser;
      parser.setApplicationDescription("Note helper");
      parser.addHelpOption();
      parser.addVersionOption();
      parser.addPositionalArgument("command", QCoreApplication::translate("main", "what to do (list, add, delete)"));
      parser.addPositionalArgument("content", QCoreApplication::translate("main", "note id or text"));

      // Process the actual command line arguments given by the user
      parser.process(app);

      const QStringList args = parser.positionalArguments();
      if(!args.length())    {
          std::cout  << "argument required, use --help";
          exit(0);
      }
      // source is args.at(0), destination is args.at(1)

      if(args.at(0) == "list")  {
            if(query.exec(QString("select * from %1").arg(noteTable)))    {;
                if(query.first())   {
                    QSqlRecord record;
                    std::cout  << "  id   |    creation date    |  note \n";
                    std::cout  << QString("").fill('-',80).toStdString() << "\n";
                    do  {
                        record = query.record();
                        std::cout  << QString().fill(' ', 6-record.value(0).toString().length()).toStdString()
                                << record.value(0).toString().toStdString()
                                << " | "
                                << record.value(1).toDateTime().toString(Qt::ISODate).toStdString()
                                << " | "
                                << record.value(2).toString().toStdString()
                                << "\n";

                    }   while(query.next());
                }   else    {
                    std::cout  << QCoreApplication::translate("main", "No note available\n").toStdString();
                }
            } else    {
                std::cout  << "error querying database\n";
                qDebug() << query.lastQuery() << query.lastError() << db.lastError();
            }
            exit(0);
      }
      if(args.at(0) == "add")   {
          if(args.length() < 2) {
              std::cout  << "no note to add...";
          }
          else {
              qDebug() << args.mid(1).join(" ");
              QString text = args.mid(1).join(" ");
              query.prepare(QString("insert into %1 values(NULL, :currentDateTime, :text)").arg(noteTable));
              query.bindValue(":currentDateTime", QDateTime::currentDateTime());
              query.bindValue(":text", text);
              if(query.exec())  {
                  std::cout  << "note added\n";
              } else    {
                  std::cout  << "error saving note to database\n";
                  qDebug() << query.lastQuery() << query.lastError() << db.lastError();
              }
          }
          exit(0);
      }

      if(args.at(0) == "delete")   {
          if(args.length() < 2) {
              std::cout  << "no note to delete...\n";
          }
          else {
              qInfo() << args.at(1);
              QString intString = args.at(1);
              int noteId = QVariant(intString).toInt();
              if(noteId)    {
                  query.prepare(QString("delete from %1 where id=:id").arg(noteTable));
                  query.bindValue(":id", noteId);
                  if(query.exec())  {
                      std::cout  << "note deleted\n";
                  } else    {
                      qDebug() << query.lastQuery() << query.lastError() << db.lastError();
                      std::cout  << "error deleting note from database\n";
                  }
              }    else    {
                  std::cout  << "invalid note identifier\n";
              }
          }
          exit(0);
      }

    return app.exec();
}
<|endoftext|>


<commit_before>2dc2c214-2748-11e6-be5b-e0f84713e7b8<commit_msg>almost working<commit_after>2dd2bb4c-2748-11e6-800c-e0f84713e7b8<|endoftext|>


<commit_before>0116afa1-2748-11e6-8c25-e0f84713e7b8<commit_msg>Deal with it<commit_after>013296f3-2748-11e6-ae91-e0f84713e7b8<|endoftext|>


<commit_before>4f64ef00-2748-11e6-8afc-e0f84713e7b8<commit_msg>That didn't fix it<commit_after>4f778847-2748-11e6-9f44-e0f84713e7b8<|endoftext|>


<commit_before>aa84c266-4b02-11e5-8914-28cfe9171a43<commit_msg>master branch<commit_after>aa91f987-4b02-11e5-a5e4-28cfe9171a43<|endoftext|>


<commit_before>51e2dccc-ad59-11e7-916b-ac87a332f658<commit_msg>Hey we can now do a thing<commit_after>528d44a8-ad59-11e7-a450-ac87a332f658<|endoftext|>


<commit_before>95d55c38-ad5a-11e7-914b-ac87a332f658<commit_msg>Long commit messages are not required<commit_after>966df27a-ad5a-11e7-bcbc-ac87a332f658<|endoftext|>


<commit_before>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <stdio.h>
#include <string>

#include "include/logging/enumCvType.hpp"

#include "include/filters/selectMode.hpp"
#include "include/filters/gaussianBlurWindows.hpp"
#include "include/filters/hsvColorThresholdWindows.hpp"
#include "include/filters/dilateErodeWindows.hpp"
#include "include/filters/cannyEdgeDetectWindows.hpp"
#include "include/filters/laplacianSharpenWindows.hpp"
#include "include/filters/houghLinesWindows.hpp"
#include "include/filters/mergeFinalWindows.hpp"
#include "include/filters/depthDistanceWindows.hpp"

void drawBoundedRects(cv::Mat& src, int thresh)
{
 	cv::Mat threshold_output;
 	std::vector<std::vector<cv::Point> > contours;
 	std::vector<cv::Vec4i> hierarchy;

	// Convert src to gray format
	cv::cvtColor(src, threshold_output, CV_BGR2GRAY);

 	// Detect edges using Threshold
 	cv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY);
 	// Find contours
 	cv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));

	// Get the moments
  	std::vector<cv::Moments> mu(contours.size() );
  	for( int i = 0; i < contours.size(); i++ )
     		{ mu[i] = moments( contours[i], false ); }

	//  Get the mass centers:
  	std::vector<cv::Point2f> mc( contours.size() );
  	for( int i = 0; i < contours.size(); i++ )
     		{ mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }

 	// Approximate contours to rotated rectangles and ellipses
 	std::vector<cv::RotatedRect> minRect( contours.size());
 	for(int i = 0; i < contours.size(); i++)
 	{
		minRect[i] = cv::minAreaRect(cv::Mat(contours[i]));
 	}

 	// Draw polygonal contour + bounding rects
 	cv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3);
 	for(int i = 0; i < contours.size(); i++)
 	{
 		cv::Scalar color = cv::Scalar(0, 0, 255);
 		cv::drawContours(drawing, contours, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());
 		cv::Point2f rect_points[4]; minRect[i].points(rect_points);
		for(int j = 0; j < 4; j++)
		{
			cv::line(drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8);
		}
 	}

	// Calculate the area with the moments 00 and compare with the result of the OpenCV function
	printf("\t Info: Area and Contour Length \n");
  	for( int i = 0; i< contours.size(); i++ )
     	{
       		printf(" * Contour[%2d] - Area (M_00) = %4.2f - Area OpenCV: %4.2f - Length: %4.2f\n", i, mu[i].m00, contourArea(contours[i]), arcLength( contours[i], true ) );
		cv::Scalar color = cv::Scalar(0, 255, 0);
 		cv::drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );
	}

 	// Show in a window
 	cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE);
 	cv::imshow("Contours", drawing);
}

int main( int argc, char *argv[])
{
	// Parameters for selecting which filters to apply
	int blur = 0;
	int color = 0;
    	int dilate_erode = 0;
	int edge = 0;
	int laplacian = 0;
	int hough = 0;
	int depth_dist = 0;
	int merge = 0;

	// Parameters for applying filters even if windows are closed
	int apply_blur = 1;
	int apply_color = 1;
    	int apply_dilate_erode = 0;
	int apply_edge = 1;
	int apply_laplacian = 0;
	int apply_hough = 0;
	int apply_depth_dist = 0;
	int apply_merge = 1;

	// gaussianBlur parameters
	int blur_ksize = 7;
	int sigmaX = 10;
	int sigmaY = 10;

	// hsvColorThreshold parameters
	int hMin = 130;
	int hMax = 190;
	int sMin = 10;
	int sMax = 30;
	int vMin = 85;
	int vMax = 100;
	int debugMode = 0; // 0 is none, 1 is debug mode
	int bitAnd = 1; // 0 is none, 1 is bitAnd between h, s, and v

	// dilateErode parameters
	int holes = 0;
	int noise = 0;
	int size = 1;
	cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
                      cv::Size(2 * size + 1, 2 * size + 1),
                      cv::Point(size, size) );

	// cannyEdgeDetect parameters
	int threshLow = 100;
	int threshHigh = 300;

	// laplacianSharpen parameters
	int laplacian_ksize = 3;
	int scale = 1; // optional scale value added to image
	int delta = 0; // optional delta value added to image
	int ddepth = CV_16S;

	// houghLines parameters
	int rho = 1;
	int theta = 180;
	int threshold = 50;
	int lineMin = 50;
	int maxGap = 10;

	// mergeFinal parameters
	int weight1 = 100; // decide weighted sums of original rgb feed to filtered rgb feed; values = out of 100
	int weight2 = 100;

	std::cout << "\n";
	std::cout << " =========== FILTER LIST =========== " << "\n";
	std::cout << "|                                   |" << "\n";
	std::cout << "| (0) No Filter                     |" << "\n";
	std::cout << "| (1) Gaussian Blur Filter          |" << "\n";
	std::cout << "| (2) HSV Color Filter              |" << "\n";
	std::cout << "| (3) Dilate and Erode Filter       |" << "\n";
	std::cout << "| (4) Canny Edge Detection Filter   |" << "\n";
	std::cout << "| (5) Laplacian Sharpen Filter      |" << "\n";
	std::cout << "| (6) Hough Lines Filter            |" << "\n";
	std::cout << "| (7) Merge Final Outputs           |" << "\n";
	std::cout << "|                                   |" << "\n";
	std::cout << " =================================== " << "\n";
	std::cout << "\n";

	std::cout << "\n";
	std::cout << " ============== NOTICE ============= " << "\n";
	std::cout << "|                                   |" << "\n";
	std::cout << "| Press 'q' to quit without saving  |" << "\n";
	std::cout << "| Press ' ' to pause                |" << "\n";
	std::cout << "|                                   |" << "\n";
	std::cout << " =================================== " << "\n";
	std::cout << "\n";

	cv::VideoCapture camera(0);
	if( !camera.isOpened() && (argc < 2) )
	{
		std::cout << "Error - Unable to open Camera at Port 0" << std::endl;
		return -1;
	}

	// Matrices for holding image data
	cv::Mat rgb, rgb_orig;
	cv::Mat image;

	char kill = ' '; // Press q to quit the program
	int thresh = 120;

	while ((kill != 'q') && (kill != 's'))
	{
		if (kill == ' ') // Press space to pause program, then any key to resume
		{
			cv::waitKey(0);
		}
		selectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge);
		if (argc > 2) // Use images
		{
			rgb = cv::imread(argv[1]);
			rgb_orig = rgb.clone(); // Clone rgb input in order to merge at end
			if (!rgb.data || !rgb_orig.data) // No data
			{
				std::cout << "No image data" << std::endl;
				return -1;
			}
		}
		else
		{
			camera >> rgb;
			rgb_orig = rgb.clone();
		}

		cv::imshow("BGR Feed", rgb);
		rgb.copyTo(image);

		cv::namedWindow("Source", CV_WINDOW_AUTOSIZE);
		cv::createTrackbar("Threshold:", "Source", &thresh, 255);

		// Filters are only applied if last parameter is true, otherwise their windows are destroyed
		gaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur);
		hsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color);
		dilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode);
		drawBoundedRects(image, thresh);
		cannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge);
		laplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian);
#if 0
		// List sizes of image
		cv::Size imageSize = image.size();
		std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n";
#endif
		houghLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough);
#if 0
		// List sizes of image
		imageSize = image.size();
		std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n";
#endif
		mergeFinalWindows(rgb_orig, image, weight1, weight2, apply_merge, merge);
		kill = cv::waitKey(5);
	}
	return 0;
}
<commit_msg>Add in distance calculation code<commit_after>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <stdio.h>
#include <string>
#include <cmath>

#include "include/logging/enumCvType.hpp"

#include "include/filters/selectMode.hpp"
#include "include/filters/gaussianBlurWindows.hpp"
#include "include/filters/hsvColorThresholdWindows.hpp"
#include "include/filters/dilateErodeWindows.hpp"
#include "include/filters/cannyEdgeDetectWindows.hpp"
#include "include/filters/laplacianSharpenWindows.hpp"
#include "include/filters/houghLinesWindows.hpp"
#include "include/filters/mergeFinalWindows.hpp"
#include "include/filters/depthDistanceWindows.hpp"

void calculateDistance (cv::Mat& image, cv::RotatedRect& boundedRect);
double distance(cv::Point one, cv::Point two);

void drawBoundedRects(cv::Mat& src, int thresh)
{
 	cv::Mat threshold_output;
 	std::vector<std::vector<cv::Point> > contours;
 	std::vector<cv::Vec4i> hierarchy;

	// Convert src to gray format
	cv::cvtColor(src, threshold_output, CV_BGR2GRAY);

 	// Detect edges using Threshold
 	cv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY);
 	// Find contours
 	cv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));

	// Get the moments
  	std::vector<cv::Moments> mu(contours.size() );
  	for( int i = 0; i < contours.size(); i++ )
     		{ mu[i] = moments( contours[i], false ); }

	//  Get the mass centers:
  	std::vector<cv::Point2f> mc( contours.size() );
  	for( int i = 0; i < contours.size(); i++ )
     		{ mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }

 	// Approximate contours to rotated rectangles and ellipses
 	std::vector<cv::RotatedRect> minRect( contours.size());
 	for(int i = 0; i < contours.size(); i++)
 	{
		minRect[i] = cv::minAreaRect(cv::Mat(contours[i]));
 	}

 	// Draw polygonal contour + bounding rects
 	cv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3);
 	for(int i = 0; i < contours.size(); i++)
	{
 		//cv::Scalar color = cv::Scalar(0, 255, 255);
 		//cv::drawContours(drawing, contours, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());
 		cv::Point2f rect_points[4];
		minRect[i].points(rect_points);
		for(int j = 0; j < 4; j++)
		{
			//cv::line(drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8);
		}
 	}
	// Bounded rectangle is the one at the 0th index
	if (minRect.size() > 0)
		calculateDistance(drawing, minRect[0]);

	// Calculate the area with the moments 00 and compare with the result of the OpenCV function
	// printf("\t Info: Area and Contour Length \n");
  	for( int i = 0; i < contours.size(); i++ )
     	{
       		// printf(" * Contour[%2d] - Area (M_00) = %4.2f - Area OpenCV: %4.2f - Length: %4.2f\n", i, mu[i].m00, contourArea(contours[i]), arcLength( contours[i], true ) );
       		// printf("Contour[%2d] - Length: %4.2f\n", i, arcLength( contours[i], true ) );
		//cv::Scalar color = cv::Scalar(0, 255, 0);
 		//cv::drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );
	}

 	// Show in a window
 	cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE);
 	cv::imshow("Contours", drawing);
}

double distance(cv::Point one, cv::Point two)
{
    return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2));
}

void calculateDistance (cv::Mat& image, cv::RotatedRect& boundedRect)
{
	double focalLen = 673.20;
	// 20 inches real width
	double wReal = 20;
	double wPixel = 0;
	double d = 204;

	cv::Point2f vert[4];
	boundedRect.points(vert);
	cv::line(image, vert[0], vert[3], cv::Scalar (255, 0, 0));
	wPixel = distance(vert[0], vert[3]);
	// focalLen = (wPixel * d) / wReal;
	d = (wReal * focalLen) / wPixel;

	char str[50];
	sprintf(str, "Line Length  = %4.2f", wPixel);
    	cv::putText(image, str, cv::Point(10, 420), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);

	sprintf(str, "Focal Length = %4.2f", focalLen);
    	cv::putText(image, str, cv::Point(10, 440), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);

	sprintf(str, "Distance     = %4.2f", d);
    	cv::putText(image, str, cv::Point(10, 460), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
}

int main( int argc, char *argv[])
{
	// Parameters for selecting which filters to apply
	int blur = 0;
	int color = 0;
    	int dilate_erode = 0;
	int edge = 0;
	int laplacian = 0;
	int hough = 0;
	int depth_dist = 0;
	int merge = 0;

	// Parameters for applying filters even if windows are closed
	int apply_blur = 1;
	int apply_color = 1;
    	int apply_dilate_erode = 0;
	int apply_edge = 1;
	int apply_laplacian = 0;
	int apply_hough = 0;
	int apply_depth_dist = 0;
	int apply_merge = 1;

	// gaussianBlur parameters
	int blur_ksize = 7;
	int sigmaX = 10;
	int sigmaY = 10;

	// hsvColorThreshold parameters
	int hMin = 130;
	int hMax = 190;
	int sMin = 10;
	int sMax = 30;
	int vMin = 85;
	int vMax = 100;
	int debugMode = 0; // 0 is none, 1 is debug mode
	int bitAnd = 1; // 0 is none, 1 is bitAnd between h, s, and v

	// dilateErode parameters
	int holes = 0;
	int noise = 0;
	int size = 1;
	cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
                      cv::Size(2 * size + 1, 2 * size + 1),
                      cv::Point(size, size) );

	// cannyEdgeDetect parameters
	int threshLow = 100;
	int threshHigh = 300;

	// laplacianSharpen parameters
	int laplacian_ksize = 3;
	int scale = 1; // optional scale value added to image
	int delta = 0; // optional delta value added to image
	int ddepth = CV_16S;

	// houghLines parameters
	int rho = 1;
	int theta = 180;
	int threshold = 50;
	int lineMin = 50;
	int maxGap = 10;

	// mergeFinal parameters
	int weight1 = 100; // decide weighted sums of original rgb feed to filtered rgb feed; values = out of 100
	int weight2 = 100;

	std::cout << "\n";
	std::cout << " =========== FILTER LIST =========== " << "\n";
	std::cout << "|                                   |" << "\n";
	std::cout << "| (0) No Filter                     |" << "\n";
	std::cout << "| (1) Gaussian Blur Filter          |" << "\n";
	std::cout << "| (2) HSV Color Filter              |" << "\n";
	std::cout << "| (3) Dilate and Erode Filter       |" << "\n";
	std::cout << "| (4) Canny Edge Detection Filter   |" << "\n";
	std::cout << "| (5) Laplacian Sharpen Filter      |" << "\n";
	std::cout << "| (6) Hough Lines Filter            |" << "\n";
	std::cout << "| (7) Merge Final Outputs           |" << "\n";
	std::cout << "|                                   |" << "\n";
	std::cout << " =================================== " << "\n";
	std::cout << "\n";

	std::cout << "\n";
	std::cout << " ============== NOTICE ============= " << "\n";
	std::cout << "|                                   |" << "\n";
	std::cout << "| Press 'q' to quit without saving  |" << "\n";
	std::cout << "| Press ' ' to pause                |" << "\n";
	std::cout << "|                                   |" << "\n";
	std::cout << " =================================== " << "\n";
	std::cout << "\n";

	cv::VideoCapture camera(1);
	if( !camera.isOpened() )
	{
		std::cout << "Error - Unable to open Camera at Port 0" << std::endl;
		return -1;
	}

	// Matrices for holding image data
	cv::Mat rgb, rgb_orig;
	cv::Mat image;

	char kill = ' '; // Press q to quit the program
	int thresh = 120;

	while ((kill != 'q') && (kill != 's'))
	{
		if (kill == ' ') // Press space to pause program, then any key to resume
		{
			cv::waitKey(0);
		}
		selectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge);
		if (argc > 2) // Use images
		{
			rgb = cv::imread(argv[1]);
			rgb_orig = rgb.clone(); // Clone rgb input in order to merge at end
			if (!rgb.data || !rgb_orig.data) // No data
			{
				std::cout << "No image data" << std::endl;
				return -1;
			}
		}
		else
		{
			camera >> rgb;
			rgb_orig = rgb.clone();
		}

		cv::imshow("BGR Feed", rgb);
		rgb.copyTo(image);

		cv::namedWindow("Source", CV_WINDOW_AUTOSIZE);
		cv::createTrackbar("Threshold:", "Source", &thresh, 255);

		// Filters are only applied if last parameter is true, otherwise their windows are destroyed
		gaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur);
		hsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color);
		dilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode);
		drawBoundedRects(image, thresh);
		cannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge);
		laplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian);
#if 0
		// List sizes of image
		cv::Size imageSize = image.size();
		std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n";
#endif
		houghLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough);
#if 0
		// List sizes of image
		imageSize = image.size();
		std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n";
#endif
		mergeFinalWindows(rgb_orig, image, weight1, weight2, apply_merge, merge);
		kill = cv::waitKey(5);
	}
	return 0;
}
<|endoftext|>


<commit_before>#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlApplicationEngine>

#include <QObject>
#include "log.h"
#include "windowcontroller.h"

int main(int argc, char *argv[])
{
    auto v1=QString(LVIEW_VERSION);
    auto v2=QString(GIT_VERSION);
    auto lview_version=v1+"-"+v2;

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    //    auto ctx=engine.rootContext();
    //    ctx->setContextProperty("logfile", QVariant::fromValue(ll));
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    auto ctx=engine.rootContext();
    ctx->setContextProperty("lview_version", QVariant::fromValue(lview_version));
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));

    QObject* rootObject=engine.rootObjects().first();
    qDebug()<<"rootObject:"<<rootObject->objectName();
    WindowController *wc=new WindowController(rootObject);

    QObject::connect(rootObject, SIGNAL(updateAllSignal(QString)),
                     wc,  SLOT(updateAllSlot(QString)));
    QObject::connect(rootObject, SIGNAL(openFileSignal(QString)),
                     wc,  SLOT(openFileSlot(QString)));
    QObject::connect(rootObject, SIGNAL(closeFileSignal(QString)),
                     wc,  SLOT(closeFileSlot(QString)));
    QObject::connect(rootObject, SIGNAL(addHighlightedTextSignal(QString)),
                     wc,  SLOT(addHighlightedTextSlot(QString)));
    QObject::connect(rootObject, SIGNAL(clearHighlightedTextSignal()),
                     wc,  SLOT(clearHighlightedTextSlot()));
    return app.exec();
}
<commit_msg>!twice<commit_after>#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlApplicationEngine>

#include <QObject>
#include "log.h"
#include "windowcontroller.h"

int main(int argc, char *argv[])
{
    auto v1=QString(LVIEW_VERSION);
    auto v2=QString(GIT_VERSION);
    auto lview_version=v1+"-"+v2;

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    //    auto ctx=engine.rootContext();
    //    ctx->setContextProperty("logfile", QVariant::fromValue(ll));
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    auto ctx=engine.rootContext();
    ctx->setContextProperty("lview_version", QVariant::fromValue(lview_version));

    QObject* rootObject=engine.rootObjects().first();
    qDebug()<<"rootObject:"<<rootObject->objectName();
    WindowController *wc=new WindowController(rootObject);

    QObject::connect(rootObject, SIGNAL(updateAllSignal(QString)),
                     wc,  SLOT(updateAllSlot(QString)));
    QObject::connect(rootObject, SIGNAL(openFileSignal(QString)),
                     wc,  SLOT(openFileSlot(QString)));
    QObject::connect(rootObject, SIGNAL(closeFileSignal(QString)),
                     wc,  SLOT(closeFileSlot(QString)));
    QObject::connect(rootObject, SIGNAL(addHighlightedTextSignal(QString)),
                     wc,  SLOT(addHighlightedTextSlot(QString)));
    QObject::connect(rootObject, SIGNAL(clearHighlightedTextSignal()),
                     wc,  SLOT(clearHighlightedTextSlot()));
    return app.exec();
}
<|endoftext|>


<commit_before>#include <iostream>
#include "ncurses.h"

using namespace std;

int main()
{
initscr();
printw("HI PEOPLE");
refresh();
getch();
endwin();
return 0;
}

<commit_msg>Changed a few things<commit_after>#include "ncurses.h"

int main()
{
initscr();
printw("HI PEOPLE"); //HI CODERS
refresh();
getch();
endwin();
return 0;
}

<|endoftext|>


<commit_before>#include "board.h"
#include "player.h"
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

void gameLoop(Board &current_game, Player &player1, Player &player2){
    int winner = 0;
    int move;

    while((winner = current_game.win()) == 0){
        if(player1.piece == "X"){
            current_game.print();
            current_game.getMoves();
            cout << endl << "Player 1: Select move#: ";
            cin >> move;
            if (current_game.validateMove(move)){
                current_game.insertMove(player1.team, move);
            }
            if((winner = current_game.win()) != 0)
                break;
            if(player2.ishuman){
                current_game.print();
                current_game.getMoves();
                cout << endl << "Player 2: Select move#: ";
                cin >> move;
                if (current_game.validateMove(move)){
                    current_game.insertMove(player2.team, move);
                }
            }else{
                //call ai move
            }
        }else{
            if(player2.ishuman){
                current_game.print();
                current_game.getMoves();
                cout << endl << "Player 2: Select move#: ";
                cin >> move;
                if (current_game.validateMove(move)){
                    current_game.insertMove(player2.team, move);
                }
            }else{
                //call ai move
            }
            if((winner = current_game.win()) != 0)
                break;
            current_game.print();
            current_game.getMoves();
            cout << endl << "Player 1: Select move#: ";
            cin >> move;
            if (current_game.validateMove(move)){
                current_game.insertMove(player1.team, move);
            }
        }
    }
    current_game.print();
    cout << endl << winner << " won.";
}

string oppositePiece(string piece){
    if(piece == "X"){
        return "O";
    }
    return "X";
}

int main(){
  int board_size = 3;
  int humans = 1;
  string player = "X";
  cout << "Pick the size of the grid (default = 3): ";
  cin >> board_size;
  Board board(board_size); //initialize a new board
  board.print();
  cout << endl << "1 or 2 human players? ";
  cin >> humans;
  if(humans == 1){
      cout << endl << "X or O (X moves first): ";
      cin >> player;
      player = toupper(player[0]);
      Player human(player); //initializes human player to their piece
      cout << "You are " << human.convertToPiece();
      AI ai(oppositePiece(human.piece)); //initializes ai player to opposite piece
      cout << endl << "AI is " << ai.piece;
      gameLoop(board, human, ai); //game logic within the game is done here
  }else if(humans == 2){
      cout << endl << "Player 1: X or O (X moves first): ";
      cin >> player;
      player = toupper(player[0]);
      Player human1(player); //initializes human player to their piece
      Player human2(oppositePiece(human1.piece)); //initializes player 2 to opposite piece
      cout << endl << "Player 1 is: " << human1.piece;
      cout << endl << "Player 2 is: " << human2.piece;
      gameLoop(board, human1, human2); //game logic within the game is done here
  }
  return 0;
}<commit_msg>Added player win output<commit_after>#include "board.h"
#include "player.h"
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

void gameLoop(Board &current_game, Player &player1, Player &player2){
    int winner = 0;
    int move;

    while((winner = current_game.win()) == 0){
        if(player1.piece == "X"){
            current_game.print();
            current_game.getMoves();
            cout << endl << "Player 1: Select move#: ";
            cin >> move;
            if (current_game.validateMove(move)){
                current_game.insertMove(player1.team, move);
            }
            if((winner = current_game.win()) != 0)
                break;
            if(player2.ishuman){
                current_game.print();
                current_game.getMoves();
                cout << endl << "Player 2: Select move#: ";
                cin >> move;
                if (current_game.validateMove(move)){
                    current_game.insertMove(player2.team, move);
                }
            }else{
                //call ai move
            }
        }else{
            if(player2.ishuman){
                current_game.print();
                current_game.getMoves();
                cout << endl << "Player 2: Select move#: ";
                cin >> move;
                if (current_game.validateMove(move)){
                    current_game.insertMove(player2.team, move);
                }
            }else{
                //call ai move
            }
            if((winner = current_game.win()) != 0)
                break;
            current_game.print();
            current_game.getMoves();
            cout << endl << "Player 1: Select move#: ";
            cin >> move;
            if (current_game.validateMove(move)){
                current_game.insertMove(player1.team, move);
            }
        }
    }
    current_game.print();
    if(player1.team == winner){
        cout << endl  << "Player 1 won.";
    }else{
        cout << endl << "Player 2 won.";
    }
}

string oppositePiece(string piece){
    if(piece == "X"){
        return "O";
    }
    return "X";
}

int main(){
  int board_size = 3;
  int humans = 1;
  string player = "X";
  cout << "Pick the size of the grid (default = 3): ";
  cin >> board_size;
  Board board(board_size); //initialize a new board
  board.print();
  cout << endl << "1 or 2 human players? ";
  cin >> humans;
  if(humans == 1){
      cout << endl << "X or O (X moves first): ";
      cin >> player;
      player = toupper(player[0]);
      Player human(player); //initializes human player to their piece
      cout << "You are " << human.convertToPiece();
      AI ai(oppositePiece(human.piece)); //initializes ai player to opposite piece
      cout << endl << "AI is " << ai.piece;
      gameLoop(board, human, ai); //game logic within the game is done here
  }else if(humans == 2){
      cout << endl << "Player 1: X or O (X moves first): ";
      cin >> player;
      player = toupper(player[0]);
      Player human1(player); //initializes human player to their piece
      Player human2(oppositePiece(human1.piece)); //initializes player 2 to opposite piece
      cout << endl << "Player 1 is: " << human1.piece;
      cout << endl << "Player 2 is: " << human2.piece;
      gameLoop(board, human1, human2); //game logic within the game is done here
  }
  return 0;
}<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <map>
#include <eXosip2/eXosip.h>
using namespace std;
int main(int argc, char const *argv[])
{
	struct eXosip_t *context_eXosip;
	cout<<"Hello Stream Server"<<endl;
	int ret  = eXosip_init(context_eXosip);
	if(ret!=0)
	{
		cout<<"inti eXosip error"<<endl;
	}
	return 0;
}
<commit_msg>test clock_gettime<commit_after>#include <iostream>
#include <string>
#include <map>
#include <eXosip2/eXosip.h>
#include <time.h>
using namespace std;
int main(int argc, char const *argv[])
{
	struct eXosip_t *context_eXosip;
	cout<<"Hello Stream Server"<<endl;
	int ret  = eXosip_init(context_eXosip);
	if(ret!=0)
	{
		cout<<"inti eXosip error"<<endl;
	}
	timespec time1;
	clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&time1);

	return 0;
}
<|endoftext|>


<commit_before>9198a82e-4b02-11e5-b230-28cfe9171a43<commit_msg>fix for the previous fix<commit_after>91a8d6a6-4b02-11e5-ac80-28cfe9171a43<|endoftext|>


<commit_before>// gl-stuff
#include <GL/glew.h>
#include <GLFW/glfw3.h>  // GLFW helper library
#include <GL/glu.h>

// std stuff
#include <stdio.h>
#include <iostream>
#include <vector>
#include <array>

#define printOpenGLError() printOglError(__FILE__, __LINE__)

int printOglError(const char* file, int line) {
  GLenum glErr;
  int retCode = 0;

  glErr = glGetError();
  if (glErr != GL_NO_ERROR) {
    printf("glError in file %s @ line %d: %s\n", file, line,
           gluErrorString(glErr));
    retCode = 1;
  }
  return retCode;
}

void GLAPIENTRY DebugCallback(GLenum source, GLenum type, GLuint id,
                              GLenum severity, GLsizei length,
                              const GLchar* message, const void* userParam) {
  printf("0x%X: %s\n", id, message);
}

GLFWwindow* setupOpenGLContextWindow(unsigned int numSamples, bool useGLDebugOutput) {
  // start GL context and O/S window using the GLFW helper library
  if (!glfwInit()) {
    throw std::runtime_error("ERROR: could not start GLFW3\n");
  }

  glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
  glfwWindowHint(GLFW_SAMPLES, numSamples);
  GLFWwindow* window = glfwCreateWindow(1, 1, "glSampleIDCheck", NULL, NULL);
  if (!window) {
    glfwTerminate();
    throw std::runtime_error("ERROR: could not open window with GLFW3\n");
  }
  glfwMakeContextCurrent(window);

  // start GLEW extension handler
  glewExperimental = GL_TRUE;
  glewInit();

  if (useGLDebugOutput) {
    glEnable(GL_DEBUG_OUTPUT);
    glDebugMessageCallback(DebugCallback, nullptr);
    glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0,
                          GL_TRUE);
    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  }

  if (useGLDebugOutput) {
    // get version info
    const GLubyte* renderer = glGetString(GL_RENDERER);  // get renderer string
    const GLubyte* version = glGetString(GL_VERSION);    // version as a string
    printf("Renderer: %s\n", renderer);
    printf("OpenGL version supported %s\n", version);
  }

  return window;
}

void checkShaderCompilation(GLuint shader) {
  GLint success = GL_TRUE;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
  if (!success) {
    GLint maxLength = 0;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
    std::vector<GLchar> errorLog(maxLength);
    glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);
    for (auto const& character : errorLog) {
      std::cout << character;
    }
    std::cout << std::endl;
  }
}

GLuint setupShaderProgram() {
  const char* vertex_shader =
      "#version 400\n"
      "in vec3 vp;"
      "void main () {"
      "  vec2 texcoord = vec2( (gl_VertexID << 1) & 2, gl_VertexID & 2 );"
      "  gl_Position = vec4( texcoord * vec2( 2.0f, -2.0f ) + vec2( -1.0f, "
      "1.0f), 0.0f, 1.0f );"
      "}";

  const char* fragment_shader =
      "#version 440\n"
      "layout(binding = 0) uniform atomic_uint atomic_counter;"
      "void main () {"
      //ensure that only one fragment counts, should be redundant due to 1px size of the window
      "  if( ivec2( gl_FragCoord.xy ) == ivec2( 0, 0 ) ){"
      "    for(uint i = 0; i<gl_SampleID; ++i){"
      "      atomicCounterIncrement(atomic_counter);"
      "    }"
      "  }"
      "}";

  GLuint vs = glCreateShader(GL_VERTEX_SHADER);
  glShaderSource(vs, 1, &vertex_shader, NULL);
  glCompileShader(vs);
  checkShaderCompilation(vs);

  GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
  glShaderSource(fs, 1, &fragment_shader, NULL);
  glCompileShader(fs);
  checkShaderCompilation(fs);

  GLuint shader_programm = glCreateProgram();
  glAttachShader(shader_programm, fs);
  glAttachShader(shader_programm, vs);
  glLinkProgram(shader_programm);

  return shader_programm;
}

GLuint* setupBuffers(GLuint& vao, GLuint& atomicBuffer) {
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);

  glCreateBuffers(1, &atomicBuffer);
  printOpenGLError();

  GLuint const data = 0;
  GLbitfield usageFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT |
                          GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;
  glNamedBufferStorage(atomicBuffer, sizeof(data), &data, usageFlags);
  printOpenGLError();

  auto mappedBuffer = static_cast<GLuint*>(
      glMapNamedBufferRange(atomicBuffer, 0, sizeof(data), usageFlags));
  printOpenGLError();

  return mappedBuffer;
}

void testSumOfGLSLSampleIDs(unsigned int numSamples, bool useGLDebugOutput) {
  GLFWwindow* window = setupOpenGLContextWindow(numSamples, useGLDebugOutput);
  printOpenGLError();

  GLuint vaoID, atomicCounterID;
  auto atomicCounter = setupBuffers(vaoID, atomicCounterID);
  printOpenGLError();

  GLuint shader_programm = setupShaderProgram();
  printOpenGLError();

  std::cout << "atomic Counter initial value: " << atomicCounter[0]
            << " | 0 is correct" << std::endl;

  // wipe the drawing surface clear
  glUseProgram(shader_programm);

  glBindBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0, atomicCounterID, 0,
                    sizeof(GLuint));

  glBindVertexArray(vaoID);
  // draw fullscreen triangle created in vertex shader based on the VertexID
  glDrawArrays(GL_TRIANGLES, 0, 3);
  // update other events like input handling
  glfwPollEvents();
  // put the stuff we've been drawing onto the display
  glfwSwapBuffers(window);

  glFinish();
  unsigned int correctSumOfSampleIDs = 0;
  for (unsigned int i = 0; i < numSamples; ++i) {
    correctSumOfSampleIDs += i;
  }
  std::cout << "sum of gl_SampleIDs: " << atomicCounter[0] << " | "
            << correctSumOfSampleIDs << " is correct" << std::endl;

  // close GL context and any other GLFW resources
  glfwTerminate();
}

int main(int argc, char* argv[]) {
  std::array<unsigned int, 5> listOfSamples{2, 4, 8, 16, 32};
  for (auto const& numSamples : listOfSamples) {
    std::cout << "numSamples: " << numSamples << std::endl;
    testSumOfGLSLSampleIDs(numSamples, false);
    std::cout << std::endl;
  }

  return 0;
}
<commit_msg>Querying sampling limits<commit_after>// gl-stuff
#include <GL/glew.h>
#include <GLFW/glfw3.h>  // GLFW helper library
#include <GL/glu.h>

// std stuff
#include <stdio.h>
#include <iostream>
#include <vector>
#include <array>

#define printOpenGLError() printOglError(__FILE__, __LINE__)

int printOglError(const char* file, int line) {
  GLenum glErr;
  int retCode = 0;

  glErr = glGetError();
  if (glErr != GL_NO_ERROR) {
    printf("glError in file %s @ line %d: %s\n", file, line,
           gluErrorString(glErr));
    retCode = 1;
  }
  return retCode;
}

void GLAPIENTRY DebugCallback(GLenum source, GLenum type, GLuint id,
                              GLenum severity, GLsizei length,
                              const GLchar* message, const void* userParam) {
  printf("0x%X: %s\n", id, message);
}

GLFWwindow* setupOpenGLContextWindow(unsigned int numSamples, bool useGLDebugOutput) {
  // start GL context and O/S window using the GLFW helper library
  if (!glfwInit()) {
    throw std::runtime_error("ERROR: could not start GLFW3\n");
  }

  glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
  glfwWindowHint(GLFW_SAMPLES, numSamples);
  GLFWwindow* window = glfwCreateWindow(1, 1, "glSampleIDCheck", NULL, NULL);
  if (!window) {
    glfwTerminate();
    throw std::runtime_error("ERROR: could not open window with GLFW3\n");
  }
  glfwMakeContextCurrent(window);

  // start GLEW extension handler
  glewExperimental = GL_TRUE;
  glewInit();

  if (useGLDebugOutput) {
    glEnable(GL_DEBUG_OUTPUT);
    glDebugMessageCallback(DebugCallback, nullptr);
    glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0,
                          GL_TRUE);
    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  }

  if (useGLDebugOutput) {
    // get version info
    const GLubyte* renderer = glGetString(GL_RENDERER);  // get renderer string
    const GLubyte* version = glGetString(GL_VERSION);    // version as a string
    printf("Renderer: %s\n", renderer);
    printf("OpenGL version supported %s\n", version);
  }

  return window;
}

void checkShaderCompilation(GLuint shader) {
  GLint success = GL_TRUE;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
  if (!success) {
    GLint maxLength = 0;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
    std::vector<GLchar> errorLog(maxLength);
    glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);
    for (auto const& character : errorLog) {
      std::cout << character;
    }
    std::cout << std::endl;
  }
}

GLuint setupShaderProgram() {
  const char* vertex_shader =
      "#version 400\n"
      "in vec3 vp;"
      "void main () {"
      "  vec2 texcoord = vec2( (gl_VertexID << 1) & 2, gl_VertexID & 2 );"
      "  gl_Position = vec4( texcoord * vec2( 2.0f, -2.0f ) + vec2( -1.0f, "
      "1.0f), 0.0f, 1.0f );"
      "}";

  const char* fragment_shader =
      "#version 440\n"
      "layout(binding = 0) uniform atomic_uint atomic_counter;"
      "void main () {"
      //ensure that only one fragment counts, should be redundant due to 1px size of the window
      "  if( ivec2( gl_FragCoord.xy ) == ivec2( 0, 0 ) ){"
      "    for(uint i = 0; i<gl_SampleID; ++i){"
      "      atomicCounterIncrement(atomic_counter);"
      "    }"
      "  }"
      "}";

  GLuint vs = glCreateShader(GL_VERTEX_SHADER);
  glShaderSource(vs, 1, &vertex_shader, NULL);
  glCompileShader(vs);
  checkShaderCompilation(vs);

  GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
  glShaderSource(fs, 1, &fragment_shader, NULL);
  glCompileShader(fs);
  checkShaderCompilation(fs);

  GLuint shader_programm = glCreateProgram();
  glAttachShader(shader_programm, fs);
  glAttachShader(shader_programm, vs);
  glLinkProgram(shader_programm);

  return shader_programm;
}

GLuint* setupBuffers(GLuint& vao, GLuint& atomicBuffer) {
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);

  glCreateBuffers(1, &atomicBuffer);
  printOpenGLError();

  GLuint const data = 0;
  GLbitfield usageFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT |
                          GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;
  glNamedBufferStorage(atomicBuffer, sizeof(data), &data, usageFlags);
  printOpenGLError();

  auto mappedBuffer = static_cast<GLuint*>(
      glMapNamedBufferRange(atomicBuffer, 0, sizeof(data), usageFlags));
  printOpenGLError();

  return mappedBuffer;
}

GLint get(GLenum name) {
  GLint value = -1;
  glGetIntegerv(name, &value);
  return value;
}

void testSumOfGLSLSampleIDs(unsigned int numSamples, bool useGLDebugOutput) {
  GLFWwindow* window = setupOpenGLContextWindow(numSamples, useGLDebugOutput);
  printOpenGLError();

#define GLGET(NAME)  std::cout << #NAME ": " << get(NAME) << "\n"

  GLGET(GL_MAX_COLOR_TEXTURE_SAMPLES);
  GLGET(GL_MAX_DEPTH_TEXTURE_SAMPLES);
  GLGET(GL_MAX_FRAMEBUFFER_SAMPLES);

  GLuint vaoID, atomicCounterID;
  auto atomicCounter = setupBuffers(vaoID, atomicCounterID);
  printOpenGLError();

  GLuint shader_programm = setupShaderProgram();
  printOpenGLError();

  std::cout << "atomic Counter initial value: " << atomicCounter[0]
            << " | 0 is correct" << std::endl;

  // wipe the drawing surface clear
  glUseProgram(shader_programm);

  glBindBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0, atomicCounterID, 0,
                    sizeof(GLuint));

  glBindVertexArray(vaoID);
  // draw fullscreen triangle created in vertex shader based on the VertexID
  glDrawArrays(GL_TRIANGLES, 0, 3);
  // update other events like input handling
  glfwPollEvents();
  // put the stuff we've been drawing onto the display
  glfwSwapBuffers(window);

  glFinish();
  unsigned int correctSumOfSampleIDs = 0;
  for (unsigned int i = 0; i < numSamples; ++i) {
    correctSumOfSampleIDs += i;
  }
  std::cout << "sum of gl_SampleIDs: " << atomicCounter[0] << " | "
            << correctSumOfSampleIDs << " is correct" << std::endl;

  // close GL context and any other GLFW resources
  glfwTerminate();
}

int main(int argc, char* argv[]) {
  std::array<unsigned int, 5> listOfSamples{2, 4, 8, 16, 32};
  for (auto const& numSamples : listOfSamples) {
    std::cout << "numSamples: " << numSamples << std::endl;
    testSumOfGLSLSampleIDs(numSamples, false);
    std::cout << std::endl;
  }

  return 0;
}
<|endoftext|>