<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2007, 2008 Tokutek Inc.  All rights reserved."

#include "test.h"

/* Insert a bunch of stuff */
#include "includes.h"
#include <toku_time.h>

static const char *fname ="sinsert.ft_handle";

enum { SERIAL_SPACING = 1<<6 };
enum { ITEMS_TO_INSERT_PER_ITERATION = 1<<20 };
//enum { ITEMS_TO_INSERT_PER_ITERATION = 1<<14 };
enum { BOUND_INCREASE_PER_ITERATION = SERIAL_SPACING*ITEMS_TO_INSERT_PER_ITERATION };

enum { NODE_SIZE = 1<<20 };
enum { BASEMENT_NODE_SIZE = 128 * 1024 };

static int nodesize = NODE_SIZE;
static int basementnodesize = BASEMENT_NODE_SIZE;
static enum toku_compression_method compression_method = TOKU_DEFAULT_COMPRESSION_METHOD;
static int keysize = sizeof (long long);
static int valsize = sizeof (long long);
static int do_verify =0; /* Do a slow verify after every insert. */

static int do_serial = 1;
static int do_random = 1;

static CACHETABLE ct;
static FT_HANDLE t;

static void setup (void) {
    int r;
    unlink(fname);
    toku_cachetable_create(&ct, 0, ZERO_LSN, NULL_LOGGER);
    r = toku_open_ft_handle(fname, 1, &t, nodesize, basementnodesize, compression_method, ct, NULL_TXN, toku_builtin_compare_fun); assert(r==0);
}

static void toku_shutdown (void) {
    int r;
    r = toku_close_ft_handle_nolsn(t, 0); assert(r==0);
    toku_cachetable_close(&ct);
}
static void long_long_to_array (unsigned char *a, unsigned long long l) {
    int i;
    for (i=0; i<8; i++)
	a[i] = (l>>(56-8*i))&0xff;
}

static void insert (long long v) {
    unsigned char kc[keysize], vc[valsize];
    DBT  kt, vt;
    memset(kc, 0, sizeof kc);
    long_long_to_array(kc, v);
    memset(vc, 0, sizeof vc);
    long_long_to_array(vc, v);
    toku_ft_insert(t, toku_fill_dbt(&kt, kc, keysize), toku_fill_dbt(&vt, vc, valsize), 0);
    if (do_verify) toku_cachetable_verify(ct);
}

static void serial_insert_from (long long from) {
    long long i;
    for (i=0; i<ITEMS_TO_INSERT_PER_ITERATION; i++) {
	insert((from+i)*SERIAL_SPACING);
    }
}

static long long llrandom (void) {
    return (((long long)(random()))<<32) + random();
}

static void random_insert_below (long long below) {
    long long i;
    assert(0 < below);
    for (i=0; i<ITEMS_TO_INSERT_PER_ITERATION; i++) {
	insert(llrandom()%below);
    }
}

static void biginsert (long long n_elements, struct timeval *starttime) {
    long long i;
    struct timeval t1,t2;
    int iteration;
    for (i=0, iteration=0; i<n_elements; i+=ITEMS_TO_INSERT_PER_ITERATION, iteration++) {
	gettimeofday(&t1,0);
	if (do_serial)
            serial_insert_from(i);
	gettimeofday(&t2,0);
	if (verbose && do_serial) {
	    printf("serial %9.6fs %8.0f/s    ", toku_tdiff(&t2, &t1), ITEMS_TO_INSERT_PER_ITERATION/toku_tdiff(&t2, &t1));
	    fflush(stdout);
	}
	gettimeofday(&t1,0);
        if (do_random)
            random_insert_below((i+ITEMS_TO_INSERT_PER_ITERATION)*SERIAL_SPACING);
	gettimeofday(&t2,0);
	if (verbose && do_random) {
	    printf("random %9.6fs %8.0f/s    ", toku_tdiff(&t2, &t1), ITEMS_TO_INSERT_PER_ITERATION/toku_tdiff(&t2, &t1));
	    fflush(stdout);
        }
        if (verbose && (do_serial || do_random)) {
            double f = 0;
            if (do_serial) f += 1.0;
            if (do_random) f += 1.0;
	    printf("cumulative %9.6fs %8.0f/s\n", toku_tdiff(&t2, starttime), (ITEMS_TO_INSERT_PER_ITERATION*f/toku_tdiff(&t2, starttime))*(iteration+1));
	    fflush(stdout);
	}
    }
}

static void usage(void) {
    printf("benchmark-test [OPTIONS] [ITERATIONS]\n");
    printf("[-v]\n");
    printf("[-q]\n");
    printf("[--nodesize NODESIZE]\n");
    printf("[--keysize KEYSIZE]\n");
    printf("[--valsize VALSIZE]\n");
    printf("[--noserial]\n");
    printf("[--norandom]\n");
    printf("[--verify]\n");
}

int
test_main (int argc, const char *argv[]) {
    verbose=1; //Default
    /* parse parameters */
    int i;
    for (i=1; i<argc; i++) {
        const char *arg = argv[i];
        if (arg[0] != '-')
            break;
        if (strcmp(arg, "--nodesize") == 0) {
            if (i+1 < argc) {
                i++;
                nodesize = atoi(argv[i]);
            }
        } else if (strcmp(arg, "--keysize") == 0) {
            if (i+1 < argc) {
                i++;
                keysize = atoi(argv[i]);
            }
        } else if (strcmp(arg, "--valsize") == 0) {
            if (i+1 < argc) {
                i++;
                valsize = atoi(argv[i]);
            }
        } else if (strcmp(arg, "--verify")==0) {
	    do_verify = 1;
        } else if (strcmp(arg, "--noserial") == 0) {
            do_serial = 0;
        } else if (strcmp(arg, "--fname") == 0) {
            if (i+1 < argc) {
                i++;
                fname = argv[i];
            }
        } else if (strcmp(arg, "--norandom") == 0) {
            do_random = 0;
	} else if (strcmp(arg, "-v")==0) {
	    verbose++;
	} else if (strcmp(arg, "-q")==0) {
	    verbose = 0;
	} else {
	    usage();
	    return 1;
	}
    }

    struct timeval t1,t2,t3;
    long long total_n_items;
    if (i < argc) {
	char *end;
	errno=0;
	total_n_items = ITEMS_TO_INSERT_PER_ITERATION * (long long) strtol(argv[i], &end, 10);
	assert(errno==0);
	assert(*end==0);
	assert(end!=argv[i]);
    } else {
	total_n_items = 1LL<<22; // 1LL<<16
    }

    if (verbose) {
	printf("nodesize=%d\n", nodesize);
	printf("keysize=%d\n", keysize);
	printf("valsize=%d\n", valsize);
	printf("Serial and random insertions of %d per batch\n", ITEMS_TO_INSERT_PER_ITERATION);
        fflush(stdout);
    }
    setup();
    gettimeofday(&t1,0);
    biginsert(total_n_items, &t1);
    gettimeofday(&t2,0);
    toku_shutdown();
    gettimeofday(&t3,0);
    if (verbose) {
        int f = 0;
        if (do_serial) f += 1;
        if (do_random) f += 1;
	printf("Shutdown %9.6fs\n", toku_tdiff(&t3, &t2));
	printf("Total time %9.6fs for %lld insertions = %8.0f/s\n", toku_tdiff(&t3, &t1), f*total_n_items, f*total_n_items/toku_tdiff(&t3, &t1));
        fflush(stdout);
    }
    unlink(fname);

    return 0;
}

<commit_msg>Add extra options to benchmark-test<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2007, 2008 Tokutek Inc.  All rights reserved."

#include "test.h"

/* Insert a bunch of stuff */
#include "includes.h"
#include <toku_time.h>

static const char *fname ="sinsert.ft_handle";

enum { SERIAL_SPACING = 1<<6 };
int64_t ITEMS_TO_INSERT_PER_ITERATION = 1<<20;
int64_t BOUND_INCREASE_PER_ITERATION = SERIAL_SPACING*ITEMS_TO_INSERT_PER_ITERATION;

enum { NODE_SIZE = 1<<20 };
enum { BASEMENT_NODE_SIZE = 128 * 1024 };

static int nodesize = NODE_SIZE;
static int basementnodesize = BASEMENT_NODE_SIZE;
static enum toku_compression_method compression_method = TOKU_DEFAULT_COMPRESSION_METHOD;
static int keysize = sizeof (long long);
static int valsize = sizeof (long long);
static int do_verify =0; /* Do a slow verify after every insert. */

static int do_serial = 1;
static int do_random = 1;

static CACHETABLE ct;
static FT_HANDLE t;

static void setup (void) {
    int r;
    unlink(fname);
    toku_cachetable_create(&ct, 0, ZERO_LSN, NULL_LOGGER);
    r = toku_open_ft_handle(fname, 1, &t, nodesize, basementnodesize, compression_method, ct, NULL_TXN, toku_builtin_compare_fun); assert(r==0);
}

static void toku_shutdown (void) {
    int r;
    r = toku_close_ft_handle_nolsn(t, 0); assert(r==0);
    toku_cachetable_close(&ct);
}
static void long_long_to_array (unsigned char *a, unsigned long long l) {
    int i;
    for (i=0; i<8; i++)
	a[i] = (l>>(56-8*i))&0xff;
}

static void insert (long long v) {
    unsigned char kc[keysize], vc[valsize];
    DBT  kt, vt;
    memset(kc, 0, sizeof kc);
    long_long_to_array(kc, v);
    memset(vc, 0, sizeof vc);
    long_long_to_array(vc, v);
    toku_ft_insert(t, toku_fill_dbt(&kt, kc, keysize), toku_fill_dbt(&vt, vc, valsize), 0);
    if (do_verify) toku_cachetable_verify(ct);
}

static void serial_insert_from (long long from) {
    long long i;
    for (i=0; i<ITEMS_TO_INSERT_PER_ITERATION; i++) {
	insert((from+i)*SERIAL_SPACING);
    }
}

static long long llrandom (void) {
    return (((long long)(random()))<<32) + random();
}

static void random_insert_below (long long below) {
    long long i;
    assert(0 < below);
    for (i=0; i<ITEMS_TO_INSERT_PER_ITERATION; i++) {
	insert(llrandom()%below);
    }
}

static void biginsert (long long n_elements, struct timeval *starttime) {
    long long i;
    struct timeval t1,t2;
    int iteration;
    for (i=0, iteration=0; i<n_elements; i+=ITEMS_TO_INSERT_PER_ITERATION, iteration++) {
	gettimeofday(&t1,0);
	if (do_serial)
            serial_insert_from(i);
	gettimeofday(&t2,0);
	if (verbose && do_serial) {
	    printf("serial %9.6fs %8.0f/s    ", toku_tdiff(&t2, &t1), ITEMS_TO_INSERT_PER_ITERATION/toku_tdiff(&t2, &t1));
	    fflush(stdout);
	}
	gettimeofday(&t1,0);
        if (do_random)
            random_insert_below((i+ITEMS_TO_INSERT_PER_ITERATION)*SERIAL_SPACING);
	gettimeofday(&t2,0);
	if (verbose && do_random) {
	    printf("random %9.6fs %8.0f/s    ", toku_tdiff(&t2, &t1), ITEMS_TO_INSERT_PER_ITERATION/toku_tdiff(&t2, &t1));
	    fflush(stdout);
        }
        if (verbose && (do_serial || do_random)) {
            double f = 0;
            if (do_serial) f += 1.0;
            if (do_random) f += 1.0;
	    printf("cumulative %9.6fs %8.0f/s\n", toku_tdiff(&t2, starttime), (ITEMS_TO_INSERT_PER_ITERATION*f/toku_tdiff(&t2, starttime))*(iteration+1));
	    fflush(stdout);
	}
    }
}

static void usage(void) {
    printf("benchmark-test [OPTIONS] [ITERATIONS]\n");
    printf("[-v]\n");
    printf("[-q]\n");
    printf("[--nodesize NODESIZE]\n");
    printf("[--keysize KEYSIZE]\n");
    printf("[--valsize VALSIZE]\n");
    printf("[--noserial]\n");
    printf("[--norandom]\n");
    printf("[--verify]\n");
}

int
test_main (int argc, const char *argv[]) {
    verbose=1; //Default
    /* parse parameters */
    int i;
    for (i=1; i<argc; i++) {
        const char *arg = argv[i];
        if (arg[0] != '-')
            break;
        if (strcmp(arg, "--nodesize") == 0) {
            if (i+1 < argc) {
                i++;
                nodesize = atoi(argv[i]);
            }
        } else if (strcmp(arg, "--keysize") == 0) {
            if (i+1 < argc) {
                i++;
                keysize = atoi(argv[i]);
            }
        } else if (strcmp(arg, "--periter") == 0) {
            if (i+1 < argc) {
                i++;
                ITEMS_TO_INSERT_PER_ITERATION = atoi(argv[i]);
            }
        } else if (strcmp(arg, "--valsize") == 0) {
            if (i+1 < argc) {
                i++;
                valsize = atoi(argv[i]);
            }
        } else if (strcmp(arg, "--verify")==0) {
	    do_verify = 1;
        } else if (strcmp(arg, "--noserial") == 0) {
            do_serial = 0;
        } else if (strcmp(arg, "--fname") == 0) {
            if (i+1 < argc) {
                i++;
                fname = argv[i];
            }
        } else if (strcmp(arg, "--norandom") == 0) {
            do_random = 0;
	} else if (strcmp(arg, "-v")==0) {
	    verbose++;
	} else if (strcmp(arg, "-q")==0) {
	    verbose = 0;
	} else {
	    usage();
	    return 1;
	}
    }

    struct timeval t1,t2,t3;
    long long total_n_items;
    if (i < argc) {
	char *end;
	errno=0;
	total_n_items = ITEMS_TO_INSERT_PER_ITERATION * (long long) strtol(argv[i], &end, 10);
	assert(errno==0);
	assert(*end==0);
	assert(end!=argv[i]);
    } else {
	total_n_items = 1LL<<22; // 1LL<<16
    }

    if (verbose) {
	printf("nodesize=%d\n", nodesize);
	printf("keysize=%d\n", keysize);
	printf("valsize=%d\n", valsize);
	printf("Serial and random insertions of %" PRId64 " per batch\n", ITEMS_TO_INSERT_PER_ITERATION);
        fflush(stdout);
    }
    setup();
    gettimeofday(&t1,0);
    biginsert(total_n_items, &t1);
    gettimeofday(&t2,0);
    toku_shutdown();
    gettimeofday(&t3,0);
    if (verbose) {
        int f = 0;
        if (do_serial) f += 1;
        if (do_random) f += 1;
	printf("Shutdown %9.6fs\n", toku_tdiff(&t3, &t2));
	printf("Total time %9.6fs for %lld insertions = %8.0f/s\n", toku_tdiff(&t3, &t1), f*total_n_items, f*total_n_items/toku_tdiff(&t3, &t1));
        fflush(stdout);
    }
    unlink(fname);

    return 0;
}

<|endoftext|>


<commit_before>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <errno.h>
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <qtimer.h>

#include <kuniqueapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>
#include <knotifyclient.h>
#include <dcopclient.h>
#include <kcrash.h>

#include "kmkernel.h" //control center

#undef Status // stupid X headers
#include "kmailIface_stub.h" // to call control center of master kmail

#include <kaboutdata.h>

#include "kmversion.h"

// OLD about text.  This is horrbly outdated.
/*const char* aboutText =
    "KMail [" KMAIL_VERSION "] by\n\n"
    "Stefan Taferner <taferner@kde.org>,\n"
    "Markus Wbben <markus.wuebben@kde.org>\n\n"
    "based on the work of:\n"
    "Lynx <lynx@topaz.hknet.com>,\n"
    "Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
    "and the above authors.\n\n"
    "This program is covered by the GPL.\n\n"
    "Please send bugreports to taferner@kde.org";
*/

static KCmdLineOptions kmoptions[] =
{
  { "s", 0 , 0 },
  { "subject <subject>",	I18N_NOOP("Set subject of message."), 0 },
  { "c", 0 , 0 },
  { "cc <address>",		I18N_NOOP("Send CC: to 'address'."), 0 },
  { "b", 0 , 0 },
  { "bcc <address>",		I18N_NOOP("Send BCC: to 'address'."), 0 },
  { "h", 0 , 0 },
  { "header <header>",		I18N_NOOP("Add 'header' to message."), 0 },
  { "msg <file>",		I18N_NOOP("Read message body from 'file'."), 0 },
  { "body <text>",              I18N_NOOP("Set body of message."), 0 },
  { "attach <url>",             I18N_NOOP("Add an attachment to the mail. This can be repeated."), 0 },
  { "check",			I18N_NOOP("Only check for new mail."), 0 },
  { "composer",			I18N_NOOP("Only open composer window."), 0 },
  { "+[address]",		I18N_NOOP("Send message to 'address'."), 0 },
//  { "+[file]",                  I18N_NOOP("Show message from file 'file'."), 0 },
  { 0, 0, 0}
};

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

extern "C" {

static void setSignalHandler(void (*handler)(int));

// Crash recovery signal handler
static void signalHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  ::exit(-1); //
}

// Crash recovery signal handler
static void crashHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  // Return to DrKonqi.
}
//-----------------------------------------------------------------------------

static void setSignalHandler(void (*handler)(int))
{
  signal(SIGKILL, handler);
  signal(SIGTERM, handler);
  signal(SIGHUP,  handler);
  KCrash::setEmergencySaveFunction(crashHandler);
}

}
//-----------------------------------------------------------------------------

class KMailApplication : public KUniqueApplication
{
public:
  KMailApplication() : KUniqueApplication() { };

  virtual int newInstance();

  void commitData(QSessionManager& sm) {
    kernel->notClosedByUser();
    KApplication::commitData( sm );
  }
};

int KMailApplication::newInstance()
{
  QString to, cc, bcc, subj, body;
  KURL messageFile = QString::null;
  KURL::List attachURLs;
  bool mailto = false;
  bool checkMail = false;
  //bool viewOnly = false;

  // process args:
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if (args->getOption("subject"))
  {
     mailto = true;
     subj = QString::fromLocal8Bit(args->getOption("subject"));
  }

  if (args->getOption("cc"))
  {
     mailto = true;
     cc = QString::fromLocal8Bit(args->getOption("cc"));
  }

  if (args->getOption("bcc"))
  {
     mailto = true;
     bcc = QString::fromLocal8Bit(args->getOption("bcc"));
  }

  if (args->getOption("msg"))
  {
     mailto = true;
     messageFile = QString::fromLocal8Bit(args->getOption("msg"));
  }

  if (args->getOption("body"))
  {
     mailto = true;
     body = QString::fromLocal8Bit(args->getOption("body"));
  }

  QCStringList attachList = args->getOptionList("attach");
  if (!attachList.isEmpty())
  {
     mailto = true;
     for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )
       if ( !(*it).isEmpty() )
         attachURLs += KURL( QString::fromLocal8Bit( *it ) );
  }

  if (args->isSet("composer"))
    mailto = true;

  if (args->isSet("check"))
    checkMail = true;

  for(int i= 0; i < args->count(); i++)
  {
    if (!to.isEmpty())
      to += ", ";
     if (strncasecmp(args->arg(i),"mailto:",7)==0)
       to += args->arg(i);
     else
       to += args->arg(i);
     mailto = true;
  }

  args->clear();

  if (!kernel->firstInstance() || !kapp->isRestored())
    kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);
  kernel->setFirstInstance(FALSE);
  return 0;
}

namespace
{
QString getMyHostName(void)
{
  char hostNameC[256];
  // null terminate this C string
  hostNameC[255] = 0;
  // set the string to 0 length if gethostname fails
  if(gethostname(hostNameC, 255))
    hostNameC[0] = 0;
  return QString::fromLocal8Bit(hostNameC);
}
}

static void checkConfigUpdates() {
#if KDE_VERSION >= 306
  KConfig * config = kapp->config();
  const QString updateFile = QString::fromLatin1("kmail.upd");
  QStringList updates;
  updates << "9"
	  << "3.1-update-identities"
	  << "3.1-use-identity-uoids"
          << "3.1-new-mail-notification";
  for ( QStringList::const_iterator it = updates.begin() ; it != updates.end() ; ++it )
    config->checkUpdate( *it, updateFile );
#endif
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".

  KAboutData about("kmail", I18N_NOOP("KMail"),
                   KMAIL_VERSION,
		   I18N_NOOP("The KDE Email client."),
		   KAboutData::License_GPL,
                   I18N_NOOP("(c) 1997-2002, The KMail developers"),
		   0,
		   "http://kmail.kde.org");
  about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "haeckel@kde.org" );
  about.addAuthor( "Don Sanders", I18N_NOOP("Core developer and maintainer"), "sanders@kde.org" );
  about.addAuthor( "Stefan Taferner ", I18N_NOOP("Original author"), "taferner@kde.org" );
  about.addAuthor( "Ingo Kl\303\266cker", I18N_NOOP("Encryption"), "kloecker@kde.de" );
  about.addAuthor( "Marc Mutz", I18N_NOOP("Core developer"), "mutz@kde.org" );
  about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "daniel.naber@t-online.de" );
  about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "a.gungl@gmx.de" );

  about.addAuthor( "Toyohiro Asukai", 0, "toyohiro@ksmplus.com" );
  about.addAuthor( "Waldo Bastian", 0, "bastian@kde.org" );
  about.addAuthor( "Carsten Burghardt", 0, "carsten.burghardt@web.de" );
  about.addAuthor( "Steven Brown", 0, "swbrown@ucsd.edu" );
  about.addAuthor( "Cristi Dumitrescu", 0, "cristid@chip.ro" );
  about.addAuthor( "Philippe Fremy", 0, "pfremy@chez.com" );
  about.addAuthor( "Kurt Granroth", 0, "granroth@kde.org" );
  about.addAuthor( "Heiko Hund", 0, "heiko@ist.eigentlich.net" );
  about.addAuthor( "Igor Janssen", 0, "rm@linux.ru.net" );
  about.addAuthor( "Matt Johnston", 0, "matt@caifex.org" );
  about.addAuthor( "Christer Kaivo-oja", 0, "whizkid@telia.com" );
  about.addAuthor( "Lars Knoll", 0, "knoll@kde.org" );
  about.addAuthor( "J. Nick Koston", 0, "bdraco@darkorb.net" );
  about.addAuthor( "Stephan Kulow", 0, "coolo@kde.org" );
  about.addAuthor( "Guillaume Laurent", 0, "glaurent@telegraph-road.org" );
  about.addAuthor( "Sam Magnuson", 0, "sam@trolltech.com" );
  about.addAuthor( "Laurent Montel", 0, "lmontel@mandrakesoft.com" );
  about.addAuthor( "Matt Newell", 0, "newellm@proaxis.com" );
  about.addAuthor( "Denis Perchine", 0, "dyp@perchine.com" );
  about.addAuthor( "Samuel Penn", 0, "sam@bifrost.demon.co.uk" );
  about.addAuthor( "Carsten Pfeiffer", 0, "pfeiffer@kde.org" );
  about.addAuthor( "Sven Radej", 0, "radej@kde.org" );
  about.addAuthor( "Mark Roberts", 0, "mark@taurine.demon.co.uk" );
  about.addAuthor( "Wolfgang Rohdewald", 0, "wrohdewald@dplanet.ch" );
  about.addAuthor( "Zack Rusin", 0, "zack@kde.org" );
  about.addAuthor( "Espen Sand", 0, "espen@kde.org" );
  about.addAuthor( "Aaron J. Seigo", 0, "aseigo@olympusproject.org" );
  about.addAuthor( "Jan Simonson", 0, "jan@simonson.pp.se" );
  about.addAuthor( "George Staikos", 0, "staikos@kde.org" );
  about.addAuthor( "Jason Stephenson", 0, "panda@mis.net" );
  about.addAuthor( "Jacek Stolarczyk", 0, "jacek@mer.chemia.polsl.gliwice.pl" );
  about.addAuthor( "Roberto S. Teixeira", 0, "maragato@kde.org" );
  about.addAuthor( "Ronen Tzur", 0, "rtzur@shani.net" );
  about.addAuthor( "Mario Weilguni", 0, "mweilguni@sime.com" );
  about.addAuthor( "Wynn Wilkes", 0, "wynnw@calderasystems.com" );
  about.addAuthor( "Robert D. Williams", 0, "rwilliams@kde.org" );
  about.addAuthor( "Markus Wuebben", 0, "markus.wuebben@kde.org" );
  about.addAuthor( "Thorsten Zachmann", 0, "t.zachmann@zagge.de" );
  about.addAuthor( "Karl-Heinz Zimmer", 0, "khz@kde.org" );

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options

  if (!KMailApplication::start())
     return 0;

  KMailApplication app;
  KGlobal::locale()->insertCatalogue("libkdenetwork");

  // Check that all updates have been run on the config file:
  checkConfigUpdates();

  // Check and create a lock file to prevent concurrent access to kmail files
  const QString lockLocation = locateLocal("appdata", "lock");
  KSimpleConfig config(lockLocation);
  int oldPid = config.readNumEntry("pid", -1);
  const QString oldHostName = config.readEntry("hostname");
  const QString hostName = getMyHostName();
  // proceed if there is no lock at present
  if (oldPid != -1 &&
  // proceed if the lock is our pid, or if the lock is from the same host
      oldPid != getpid() && hostName != oldHostName &&
  // proceed if the pid doesn't exist
      (kill(oldPid, 0) != -1 || errno != ESRCH))
  {
    QString msg = i18n("Only one instance of KMail can be run at "
      "any one time. It is already running on a different display "
      "with PID %1 on host %2 according to the lock file located "
      "at %3.").arg(oldPid).arg(oldHostName).arg(lockLocation);

    KNotifyClient::userEvent( msg,  KNotifyClient::Messagebox,
      KNotifyClient::Error );
    fprintf(stderr, "*** KMail is already running with PID %d on host %s\n",
            oldPid, oldHostName.local8Bit().data());
    return 1;
  }

  config.writeEntry("pid", getpid());
  config.writeEntry("hostname", hostName);
  config.sync();

  kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();
  kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  setSignalHandler(signalHandler);

  kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
  // Go!
  int ret = kapp->exec();

  // clean up
  kmailKernel.cleanup();
  config.writeEntry("pid", -1);
  config.sync();
  return ret;
}

<commit_msg>Hopefully this time it is accepted by everybody.<commit_after>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <errno.h>
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <qtimer.h>

#include <kuniqueapplication.h>
#include <klocale.h>
#include <kglobal.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>
#include <knotifyclient.h>
#include <dcopclient.h>
#include <kcrash.h>

#include "kmkernel.h" //control center

#undef Status // stupid X headers
#include "kmailIface_stub.h" // to call control center of master kmail

#include <kaboutdata.h>

#include "kmversion.h"

// OLD about text.  This is horrbly outdated.
/*const char* aboutText =
    "KMail [" KMAIL_VERSION "] by\n\n"
    "Stefan Taferner <taferner@kde.org>,\n"
    "Markus Wbben <markus.wuebben@kde.org>\n\n"
    "based on the work of:\n"
    "Lynx <lynx@topaz.hknet.com>,\n"
    "Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
    "and the above authors.\n\n"
    "This program is covered by the GPL.\n\n"
    "Please send bugreports to taferner@kde.org";
*/

static KCmdLineOptions kmoptions[] =
{
  { "s", 0 , 0 },
  { "subject <subject>",	I18N_NOOP("Set subject of message."), 0 },
  { "c", 0 , 0 },
  { "cc <address>",		I18N_NOOP("Send CC: to 'address'."), 0 },
  { "b", 0 , 0 },
  { "bcc <address>",		I18N_NOOP("Send BCC: to 'address'."), 0 },
  { "h", 0 , 0 },
  { "header <header>",		I18N_NOOP("Add 'header' to message."), 0 },
  { "msg <file>",		I18N_NOOP("Read message body from 'file'."), 0 },
  { "body <text>",              I18N_NOOP("Set body of message."), 0 },
  { "attach <url>",             I18N_NOOP("Add an attachment to the mail. This can be repeated."), 0 },
  { "check",			I18N_NOOP("Only check for new mail."), 0 },
  { "composer",			I18N_NOOP("Only open composer window."), 0 },
  { "+[address]",		I18N_NOOP("Send message to 'address'."), 0 },
//  { "+[file]",                  I18N_NOOP("Show message from file 'file'."), 0 },
  { 0, 0, 0}
};

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

extern "C" {

static void setSignalHandler(void (*handler)(int));

// Crash recovery signal handler
static void signalHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  ::exit(-1); //
}

// Crash recovery signal handler
static void crashHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  // Return to DrKonqi.
}
//-----------------------------------------------------------------------------

static void setSignalHandler(void (*handler)(int))
{
  signal(SIGKILL, handler);
  signal(SIGTERM, handler);
  signal(SIGHUP,  handler);
  KCrash::setEmergencySaveFunction(crashHandler);
}

}
//-----------------------------------------------------------------------------

class KMailApplication : public KUniqueApplication
{
public:
  KMailApplication() : KUniqueApplication() { };

  virtual int newInstance();

  void commitData(QSessionManager& sm) {
    kernel->notClosedByUser();
    KApplication::commitData( sm );
  }
};

int KMailApplication::newInstance()
{
  QString to, cc, bcc, subj, body;
  KURL messageFile = QString::null;
  KURL::List attachURLs;
  bool mailto = false;
  bool checkMail = false;
  //bool viewOnly = false;

  // process args:
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if (args->getOption("subject"))
  {
     mailto = true;
     subj = QString::fromLocal8Bit(args->getOption("subject"));
  }

  if (args->getOption("cc"))
  {
     mailto = true;
     cc = QString::fromLocal8Bit(args->getOption("cc"));
  }

  if (args->getOption("bcc"))
  {
     mailto = true;
     bcc = QString::fromLocal8Bit(args->getOption("bcc"));
  }

  if (args->getOption("msg"))
  {
     mailto = true;
     messageFile = QString::fromLocal8Bit(args->getOption("msg"));
  }

  if (args->getOption("body"))
  {
     mailto = true;
     body = QString::fromLocal8Bit(args->getOption("body"));
  }

  QCStringList attachList = args->getOptionList("attach");
  if (!attachList.isEmpty())
  {
     mailto = true;
     for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )
       if ( !(*it).isEmpty() )
         attachURLs += KURL( QString::fromLocal8Bit( *it ) );
  }

  if (args->isSet("composer"))
    mailto = true;

  if (args->isSet("check"))
    checkMail = true;

  for(int i= 0; i < args->count(); i++)
  {
    if (!to.isEmpty())
      to += ", ";
     if (strncasecmp(args->arg(i),"mailto:",7)==0)
       to += args->arg(i);
     else
       to += args->arg(i);
     mailto = true;
  }

  args->clear();

  if (!kernel->firstInstance() || !kapp->isRestored())
    kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);
  kernel->setFirstInstance(FALSE);
  return 0;
}

namespace
{
QString getMyHostName(void)
{
  char hostNameC[256];
  // null terminate this C string
  hostNameC[255] = 0;
  // set the string to 0 length if gethostname fails
  if(gethostname(hostNameC, 255))
    hostNameC[0] = 0;
  return QString::fromLocal8Bit(hostNameC);
}
}

static void checkConfigUpdates() {
#if KDE_VERSION >= 306
  KConfig * config = kapp->config();
  const QString updateFile = QString::fromLatin1("kmail.upd");
  QStringList updates;
  updates << "9"
	  << "3.1-update-identities"
	  << "3.1-use-identity-uoids"
          << "3.1-new-mail-notification";
  for ( QStringList::const_iterator it = updates.begin() ; it != updates.end() ; ++it )
    config->checkUpdate( *it, updateFile );
#endif
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".

  KAboutData about("kmail", I18N_NOOP("KMail"),
                   KMAIL_VERSION,
		   I18N_NOOP("The KDE Email client."),
		   KAboutData::License_GPL,
                   I18N_NOOP("(c) 1997-2002, The KMail developers"),
		   0,
		   "http://kmail.kde.org");
  about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current release coordinator"), "haeckel@kde.org" );
  about.addAuthor( "Don Sanders", I18N_NOOP("Core developer and former maintainer"), "sanders@kde.org" );
  about.addAuthor( "Stefan Taferner ", I18N_NOOP("Original author"), "taferner@kde.org" );
  about.addAuthor( "Ingo Kl\303\266cker", I18N_NOOP("Encryption"), "kloecker@kde.de" );
  about.addAuthor( "Marc Mutz", I18N_NOOP("Core developer"), "mutz@kde.org" );
  about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "daniel.naber@t-online.de" );
  about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "a.gungl@gmx.de" );

  about.addAuthor( "Toyohiro Asukai", 0, "toyohiro@ksmplus.com" );
  about.addAuthor( "Waldo Bastian", 0, "bastian@kde.org" );
  about.addAuthor( "Carsten Burghardt", 0, "carsten.burghardt@web.de" );
  about.addAuthor( "Steven Brown", 0, "swbrown@ucsd.edu" );
  about.addAuthor( "Cristi Dumitrescu", 0, "cristid@chip.ro" );
  about.addAuthor( "Philippe Fremy", 0, "pfremy@chez.com" );
  about.addAuthor( "Kurt Granroth", 0, "granroth@kde.org" );
  about.addAuthor( "Heiko Hund", 0, "heiko@ist.eigentlich.net" );
  about.addAuthor( "Igor Janssen", 0, "rm@linux.ru.net" );
  about.addAuthor( "Matt Johnston", 0, "matt@caifex.org" );
  about.addAuthor( "Christer Kaivo-oja", 0, "whizkid@telia.com" );
  about.addAuthor( "Lars Knoll", 0, "knoll@kde.org" );
  about.addAuthor( "J. Nick Koston", 0, "bdraco@darkorb.net" );
  about.addAuthor( "Stephan Kulow", 0, "coolo@kde.org" );
  about.addAuthor( "Guillaume Laurent", 0, "glaurent@telegraph-road.org" );
  about.addAuthor( "Sam Magnuson", 0, "sam@trolltech.com" );
  about.addAuthor( "Laurent Montel", 0, "lmontel@mandrakesoft.com" );
  about.addAuthor( "Matt Newell", 0, "newellm@proaxis.com" );
  about.addAuthor( "Denis Perchine", 0, "dyp@perchine.com" );
  about.addAuthor( "Samuel Penn", 0, "sam@bifrost.demon.co.uk" );
  about.addAuthor( "Carsten Pfeiffer", 0, "pfeiffer@kde.org" );
  about.addAuthor( "Sven Radej", 0, "radej@kde.org" );
  about.addAuthor( "Mark Roberts", 0, "mark@taurine.demon.co.uk" );
  about.addAuthor( "Wolfgang Rohdewald", 0, "wrohdewald@dplanet.ch" );
  about.addAuthor( "Zack Rusin", 0, "zack@kde.org" );
  about.addAuthor( "Espen Sand", 0, "espen@kde.org" );
  about.addAuthor( "Aaron J. Seigo", 0, "aseigo@olympusproject.org" );
  about.addAuthor( "Jan Simonson", 0, "jan@simonson.pp.se" );
  about.addAuthor( "George Staikos", 0, "staikos@kde.org" );
  about.addAuthor( "Jason Stephenson", 0, "panda@mis.net" );
  about.addAuthor( "Jacek Stolarczyk", 0, "jacek@mer.chemia.polsl.gliwice.pl" );
  about.addAuthor( "Roberto S. Teixeira", 0, "maragato@kde.org" );
  about.addAuthor( "Ronen Tzur", 0, "rtzur@shani.net" );
  about.addAuthor( "Mario Weilguni", 0, "mweilguni@sime.com" );
  about.addAuthor( "Wynn Wilkes", 0, "wynnw@calderasystems.com" );
  about.addAuthor( "Robert D. Williams", 0, "rwilliams@kde.org" );
  about.addAuthor( "Markus Wuebben", 0, "markus.wuebben@kde.org" );
  about.addAuthor( "Thorsten Zachmann", 0, "t.zachmann@zagge.de" );
  about.addAuthor( "Karl-Heinz Zimmer", 0, "khz@kde.org" );

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options

  if (!KMailApplication::start())
     return 0;

  KMailApplication app;
  KGlobal::locale()->insertCatalogue("libkdenetwork");

  // Check that all updates have been run on the config file:
  checkConfigUpdates();

  // Check and create a lock file to prevent concurrent access to kmail files
  const QString lockLocation = locateLocal("appdata", "lock");
  KSimpleConfig config(lockLocation);
  int oldPid = config.readNumEntry("pid", -1);
  const QString oldHostName = config.readEntry("hostname");
  const QString hostName = getMyHostName();
  // proceed if there is no lock at present
  if (oldPid != -1 &&
  // proceed if the lock is our pid, or if the lock is from the same host
      oldPid != getpid() && hostName != oldHostName &&
  // proceed if the pid doesn't exist
      (kill(oldPid, 0) != -1 || errno != ESRCH))
  {
    QString msg = i18n("Only one instance of KMail can be run at "
      "any one time. It is already running on a different display "
      "with PID %1 on host %2 according to the lock file located "
      "at %3.").arg(oldPid).arg(oldHostName).arg(lockLocation);

    KNotifyClient::userEvent( msg,  KNotifyClient::Messagebox,
      KNotifyClient::Error );
    fprintf(stderr, "*** KMail is already running with PID %d on host %s\n",
            oldPid, oldHostName.local8Bit().data());
    return 1;
  }

  config.writeEntry("pid", getpid());
  config.writeEntry("hostname", hostName);
  config.sync();

  kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();
  kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  setSignalHandler(signalHandler);

  kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
  // Go!
  int ret = kapp->exec();

  // clean up
  kmailKernel.cleanup();
  config.writeEntry("pid", -1);
  config.sync();
  return ret;
}

<|endoftext|>


<commit_before>#include "pb2json.h"

using std::string;
char * pb2json(const Message &msg)
{
	json_t *root = parse_msg(&msg);
	char *json = json_dumps(root,0);
	json_decref(root);
	return json; // should be freed by caller
}
char * pb2json( Message *msg,const char *buf ,int len)
{
	string s (buf,len);
	msg->ParseFromString(s);
	json_t *root = parse_msg(msg);
	char *json = json_dumps(root,0);
	json_decref(root);
	return json; // should be freed by caller
}
static json_t *parse_repeated_field(const Message *msg,const Reflection * ref,const FieldDescriptor *field)
{
	size_t count = ref->FieldSize(*msg,field);
	json_t *arr = json_array();
	if(!arr)return NULL;
	switch(field->cpp_type())
	{
		case FieldDescriptor::CPPTYPE_DOUBLE:
			for(size_t i = 0 ; i != count ; ++i)
			{
				double	value1 = ref->GetRepeatedDouble(*msg,field,i);
				json_array_append_new(arr,json_real(value1));
			}
			break;
		case FieldDescriptor::CPPTYPE_FLOAT:
			for(size_t i = 0 ; i != count ; ++i)
			{
				float value2 = ref->GetRepeatedFloat(*msg,field,i);
				json_array_append_new(arr,json_real(value2));
			}
			break;
		case FieldDescriptor::CPPTYPE_INT64:
			for(size_t i = 0 ; i != count ; ++i)
			{
				int64_t value3 = ref->GetRepeatedInt64(*msg,field,i);
				json_array_append_new(arr,json_integer(value3))	;
			}
			break;
		case FieldDescriptor::CPPTYPE_UINT64:
			for(size_t i = 0 ; i != count ; ++i)
			{
				uint64_t value4 = ref->GetRepeatedUInt64(*msg,field,i);
				json_array_append_new(arr,json_integer(value4));
			}
			break;
		case FieldDescriptor::CPPTYPE_INT32:
			for(size_t i = 0 ; i != count ; ++i)
			{
				int32_t value5 = ref->GetRepeatedInt32(*msg,field,i);
				json_array_append_new(arr,json_integer(value5));
			}
			break;
		case FieldDescriptor::CPPTYPE_UINT32:
			for(size_t i = 0 ; i != count ; ++i)
			{
				uint32_t value6 = ref->GetRepeatedUInt32(*msg,field,i);
				json_array_append_new(arr,json_integer(value6));
			}
			break;
		case FieldDescriptor::CPPTYPE_BOOL:
			for(size_t i = 0 ; i != count ; ++i)
			{
				bool value7 = ref->GetRepeatedBool(*msg,field,i);
				json_array_append_new(arr,value7?json_true():json_false())	;
			}
			break;
		case FieldDescriptor::CPPTYPE_STRING:
			for(size_t i = 0 ; i != count ; ++i)
			{
				string value8 = ref->GetRepeatedString(*msg,field,i);
				json_array_append_new(arr,json_string(value8.c_str()));
			}
			break;
		case FieldDescriptor::CPPTYPE_MESSAGE:
			for(size_t i = 0 ; i != count ; ++i)
			{
				const Message *value9 = &(ref->GetRepeatedMessage(*msg,field,i));
				json_array_append_new(arr,parse_msg(value9));
			}
			break;
		case FieldDescriptor::CPPTYPE_ENUM:
			for(size_t i = 0 ; i != count ; ++i)
			{
				const EnumValueDescriptor* value10 = ref->GetRepeatedEnum(*msg,field,i);
				json_array_append_new(arr,json_integer(value10->number()));
			}
			break;
		default:
			break;
	}
	return arr;
}
static json_t *parse_msg(const Message *msg)
{
	const Descriptor *d = msg->GetDescriptor();
	if(!d)return NULL;
	size_t count = d->field_count();
	json_t *root = json_object();
	if(!root)return NULL;
	for (size_t i = 0; i != count ; ++i)
	{
		const FieldDescriptor *field = d->field(i);
		if(!field)return NULL;

		const Reflection *ref = msg->GetReflection();
		if(!ref)return NULL;
		const char *name = field->name().c_str();
		if(field->is_repeated())
			json_object_set_new(root,name,parse_repeated_field(msg,ref,field));
		if(!field->is_repeated() && ref->HasField(*msg,field))
		{

			double value1;
			float value2;
			int64_t value3;
			uint64_t value4;
			int32_t value5;
			uint32_t value6;
			bool value7;
			string value8;
			const Message *value9;
			const EnumValueDescriptor *value10;

			switch (field->cpp_type())
			{
				case FieldDescriptor::CPPTYPE_DOUBLE:
					value1 = ref->GetDouble(*msg,field);
					json_object_set_new(root,name,json_real(value1));
					break;
				case FieldDescriptor::CPPTYPE_FLOAT:
					value2 = ref->GetFloat(*msg,field);
					json_object_set_new(root,name,json_real(value2));
					break;
				case FieldDescriptor::CPPTYPE_INT64:
					value3 = ref->GetInt64(*msg,field);
					json_object_set_new(root,name,json_integer(value3))	;
					break;
				case FieldDescriptor::CPPTYPE_UINT64:
					value4 = ref->GetUInt64(*msg,field);
					json_object_set_new(root,name,json_integer(value4));
					break;
				case FieldDescriptor::CPPTYPE_INT32:
					value5 = ref->GetInt32(*msg,field);
					json_object_set_new(root,name,json_integer(value5));
					break;
				case FieldDescriptor::CPPTYPE_UINT32:
					value6 = ref->GetUInt32(*msg,field);
					json_object_set_new(root,name,json_integer(value6));
					break;
				case FieldDescriptor::CPPTYPE_BOOL:
					value7 = ref->GetBool(*msg,field);

					json_object_set_new(root,name,value7?json_true():json_false())	;
					break;
				case FieldDescriptor::CPPTYPE_STRING:
					value8 = ref->GetString(*msg,field);
					json_object_set_new(root,name,json_string(value8.c_str()));
					break;
				case FieldDescriptor::CPPTYPE_MESSAGE:
					value9 = &(ref->GetMessage(*msg,field));
					json_object_set_new(root,name,parse_msg(value9));
					break;//FIXME : parse Message
				case FieldDescriptor::CPPTYPE_ENUM:
					value10 = ref->GetEnum(*msg,field);
					json_object_set_new(root,name,json_integer(value10->number()));
					break;
				default:
					break;
			}

		}

	}
	return root;

}
<commit_msg>Add support for "bytes" fields (hex-encoding them for printability).<commit_after>#include "pb2json.h"

using std::string;
string hex_encode(const string& input)
{
	static const char* const lut = "0123456789abcdef";
	size_t len = input.length();

	std::string output;
	output.reserve(2 * len);
	for (size_t i = 0; i < len; ++i)
	{
		const unsigned char c = input[i];
		output.push_back(lut[c >> 4]);
		output.push_back(lut[c & 15]);
	}
	return output;
}
char * pb2json(const Message &msg)
{
	json_t *root = parse_msg(&msg);
	char *json = json_dumps(root,0);
	json_decref(root);
	return json; // should be freed by caller
}
char * pb2json( Message *msg,const char *buf ,int len)
{
	string s (buf,len);
	msg->ParseFromString(s);
	json_t *root = parse_msg(msg);
	char *json = json_dumps(root,0);
	json_decref(root);
	return json; // should be freed by caller
}
static json_t *parse_repeated_field(const Message *msg,const Reflection * ref,const FieldDescriptor *field)
{
	size_t count = ref->FieldSize(*msg,field);
	json_t *arr = json_array();
	if(!arr)return NULL;
	switch(field->cpp_type())
	{
		case FieldDescriptor::CPPTYPE_DOUBLE:
			for(size_t i = 0 ; i != count ; ++i)
			{
				double	value1 = ref->GetRepeatedDouble(*msg,field,i);
				json_array_append_new(arr,json_real(value1));
			}
			break;
		case FieldDescriptor::CPPTYPE_FLOAT:
			for(size_t i = 0 ; i != count ; ++i)
			{
				float value2 = ref->GetRepeatedFloat(*msg,field,i);
				json_array_append_new(arr,json_real(value2));
			}
			break;
		case FieldDescriptor::CPPTYPE_INT64:
			for(size_t i = 0 ; i != count ; ++i)
			{
				int64_t value3 = ref->GetRepeatedInt64(*msg,field,i);
				json_array_append_new(arr,json_integer(value3))	;
			}
			break;
		case FieldDescriptor::CPPTYPE_UINT64:
			for(size_t i = 0 ; i != count ; ++i)
			{
				uint64_t value4 = ref->GetRepeatedUInt64(*msg,field,i);
				json_array_append_new(arr,json_integer(value4));
			}
			break;
		case FieldDescriptor::CPPTYPE_INT32:
			for(size_t i = 0 ; i != count ; ++i)
			{
				int32_t value5 = ref->GetRepeatedInt32(*msg,field,i);
				json_array_append_new(arr,json_integer(value5));
			}
			break;
		case FieldDescriptor::CPPTYPE_UINT32:
			for(size_t i = 0 ; i != count ; ++i)
			{
				uint32_t value6 = ref->GetRepeatedUInt32(*msg,field,i);
				json_array_append_new(arr,json_integer(value6));
			}
			break;
		case FieldDescriptor::CPPTYPE_BOOL:
			for(size_t i = 0 ; i != count ; ++i)
			{
				bool value7 = ref->GetRepeatedBool(*msg,field,i);
				json_array_append_new(arr,value7?json_true():json_false())	;
			}
			break;
		case FieldDescriptor::CPPTYPE_STRING:
			for(size_t i = 0 ; i != count ; ++i)
			{
				string value8 = ref->GetRepeatedString(*msg,field,i);
				json_array_append_new(arr,json_string(value8.c_str()));
			}
			break;
		case FieldDescriptor::CPPTYPE_MESSAGE:
			for(size_t i = 0 ; i != count ; ++i)
			{
				const Message *value9 = &(ref->GetRepeatedMessage(*msg,field,i));
				json_array_append_new(arr,parse_msg(value9));
			}
			break;
		case FieldDescriptor::CPPTYPE_ENUM:
			for(size_t i = 0 ; i != count ; ++i)
			{
				const EnumValueDescriptor* value10 = ref->GetRepeatedEnum(*msg,field,i);
				json_array_append_new(arr,json_integer(value10->number()));
			}
			break;
		default:
			break;
	}
	return arr;
}
static json_t *parse_msg(const Message *msg)
{
	const Descriptor *d = msg->GetDescriptor();
	if(!d)return NULL;
	size_t count = d->field_count();
	json_t *root = json_object();
	if(!root)return NULL;
	for (size_t i = 0; i != count ; ++i)
	{
		const FieldDescriptor *field = d->field(i);
		if(!field)return NULL;

		const Reflection *ref = msg->GetReflection();
		if(!ref)return NULL;
		const char *name = field->name().c_str();
		if(field->is_repeated())
			json_object_set_new(root,name,parse_repeated_field(msg,ref,field));
		if(!field->is_repeated() && ref->HasField(*msg,field))
		{

			double value1;
			float value2;
			int64_t value3;
			uint64_t value4;
			int32_t value5;
			uint32_t value6;
			bool value7;
			string value8;
			const Message *value9;
			const EnumValueDescriptor *value10;

			switch (field->cpp_type())
			{
				case FieldDescriptor::CPPTYPE_DOUBLE:
					value1 = ref->GetDouble(*msg,field);
					json_object_set_new(root,name,json_real(value1));
					break;
				case FieldDescriptor::CPPTYPE_FLOAT:
					value2 = ref->GetFloat(*msg,field);
					json_object_set_new(root,name,json_real(value2));
					break;
				case FieldDescriptor::CPPTYPE_INT64:
					value3 = ref->GetInt64(*msg,field);
					json_object_set_new(root,name,json_integer(value3))	;
					break;
				case FieldDescriptor::CPPTYPE_UINT64:
					value4 = ref->GetUInt64(*msg,field);
					json_object_set_new(root,name,json_integer(value4));
					break;
				case FieldDescriptor::CPPTYPE_INT32:
					value5 = ref->GetInt32(*msg,field);
					json_object_set_new(root,name,json_integer(value5));
					break;
				case FieldDescriptor::CPPTYPE_UINT32:
					value6 = ref->GetUInt32(*msg,field);
					json_object_set_new(root,name,json_integer(value6));
					break;
				case FieldDescriptor::CPPTYPE_BOOL:
					value7 = ref->GetBool(*msg,field);
					json_object_set_new(root,name,value7?json_true():json_false())	;
					break;
				case FieldDescriptor::CPPTYPE_STRING:
					if (field->type() == FieldDescriptor::TYPE_BYTES) {
						value8 = hex_encode(ref->GetString(*msg,field));
					} else {
						value8 = ref->GetString(*msg,field);
					}
					json_object_set_new(root,name,json_string(value8.c_str()));
					break;
				case FieldDescriptor::CPPTYPE_MESSAGE:
					value9 = &(ref->GetMessage(*msg,field));
					json_object_set_new(root,name,parse_msg(value9));
					break;//FIXME : parse Message
				case FieldDescriptor::CPPTYPE_ENUM:
					value10 = ref->GetEnum(*msg,field);
					json_object_set_new(root,name,json_integer(value10->number()));
					break;
				default:
					break;
			}

		}

	}
	return root;

}
<|endoftext|>


<commit_before>#ifndef FORMAST_HPP_INCLUDED
#define FORMAST_HPP_INCLUDED

#ifdef FORMAST_STATIC
// formast static library
#  define FORMAST_API
#  define FORMAST_HIDDEN
#else
// formast shared library
#  if defined _WIN32 || defined __CYGWIN__
// Windows
#    ifdef formastlib_EXPORTS
// formast is being compiled: export API to dll
#      define FORMAST_API __declspec(dllexport)
#    else
// other code is being compiled, using formast.dll: import API from dll
#      define FORMAST_API __declspec(dllimport)
#    endif
#    define FORMAST_HIDDEN
#  elif __GNUC__ >= 4
// GNU Linux: set visibility of symbols
#    define FORMAST_API    __attribute__ ((visibility ("default")))
#    define FORMAST_HIDDEN __attribute__ ((visibility ("hidden")))
#  else
// unknown
#    define FORMAST_API
#    define FORMAST_HIDDEN
#  endif
#endif

#include <boost/cstdint.hpp>
#include <boost/optional.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
#include <vector>

#include "formast/detail/ast.hpp"

namespace formast
{

typedef formast::detail::ast::Top Top;
typedef formast::detail::ast::Stats Stats;
typedef formast::detail::ast::Expr Expr;

typedef std::string Doc;

struct Attr {
    std::string class_name;
    std::string name;
    boost::optional<Doc> doc;
};

struct Class {
    std::string name;
    boost::optional<std::string> base_name;
    boost::optional<Doc> doc;
    boost::optional<Stats> stats;
};

struct If {
    Expr expr;
    Stats then;
    boost::optional<Stats> else_;
};

class Parser
{
public:
    FORMAST_API Parser();
    FORMAST_API virtual void parse_stream(std::istream & is, Top & top) = 0;
    FORMAST_API void parse_string(std::string const & s, Top & top);
};

class XmlParser : public Parser
{
public:
    FORMAST_API XmlParser();
    FORMAST_API virtual void parse_stream(std::istream & is, Top & top);
};

class Visitor
{
public:
    FORMAST_API Visitor();
    FORMAST_API virtual ~Visitor();

    FORMAST_API virtual void top(Top const & top);
    FORMAST_API virtual void top_class(Class const & class_);

    FORMAST_API virtual void stats(Stats const & stats);
    FORMAST_API virtual void stats_attr(Attr const & attr);
    FORMAST_API virtual void stats_if(If const & if_);

    FORMAST_API virtual void expr(Expr const & e);
    FORMAST_API virtual void expr_uint(boost::uint64_t const & n);
    FORMAST_API virtual void expr_id(std::string const & i);
    FORMAST_API virtual void expr_pos(Expr const & right);
    FORMAST_API virtual void expr_neg(Expr const & right);
    FORMAST_API virtual void expr_add(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_sub(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_mul(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_div(Expr const & left, Expr const & right);
private:
    // pimpl idiom
    FORMAST_HIDDEN class ExprVisitor;
    boost::shared_ptr<ExprVisitor> _expr_visitor;
    FORMAST_HIDDEN class TopVisitor;
    boost::shared_ptr<TopVisitor> _top_visitor;
    FORMAST_HIDDEN class StatsVisitor;
    boost::shared_ptr<StatsVisitor> _stats_visitor;
};

} // namespace formast

#endif
<commit_msg>Add visitor names for the new expression operators.<commit_after>#ifndef FORMAST_HPP_INCLUDED
#define FORMAST_HPP_INCLUDED

#ifdef FORMAST_STATIC
// formast static library
#  define FORMAST_API
#  define FORMAST_HIDDEN
#else
// formast shared library
#  if defined _WIN32 || defined __CYGWIN__
// Windows
#    ifdef formastlib_EXPORTS
// formast is being compiled: export API to dll
#      define FORMAST_API __declspec(dllexport)
#    else
// other code is being compiled, using formast.dll: import API from dll
#      define FORMAST_API __declspec(dllimport)
#    endif
#    define FORMAST_HIDDEN
#  elif __GNUC__ >= 4
// GNU Linux: set visibility of symbols
#    define FORMAST_API    __attribute__ ((visibility ("default")))
#    define FORMAST_HIDDEN __attribute__ ((visibility ("hidden")))
#  else
// unknown
#    define FORMAST_API
#    define FORMAST_HIDDEN
#  endif
#endif

#include <boost/cstdint.hpp>
#include <boost/optional.hpp>
#include <boost/shared_ptr.hpp>
#include <string>
#include <vector>

#include "formast/detail/ast.hpp"

namespace formast
{

typedef formast::detail::ast::Top Top;
typedef formast::detail::ast::Stats Stats;
typedef formast::detail::ast::Expr Expr;

typedef std::string Doc;

struct Attr {
    std::string class_name;
    std::string name;
    boost::optional<Doc> doc;
};

struct Class {
    std::string name;
    boost::optional<std::string> base_name;
    boost::optional<Doc> doc;
    boost::optional<Stats> stats;
};

struct If {
    Expr expr;
    Stats then;
    boost::optional<Stats> else_;
};

class Parser
{
public:
    FORMAST_API Parser();
    FORMAST_API virtual void parse_stream(std::istream & is, Top & top) = 0;
    FORMAST_API void parse_string(std::string const & s, Top & top);
};

class XmlParser : public Parser
{
public:
    FORMAST_API XmlParser();
    FORMAST_API virtual void parse_stream(std::istream & is, Top & top);
};

class Visitor
{
public:
    FORMAST_API Visitor();
    FORMAST_API virtual ~Visitor();

    FORMAST_API virtual void top(Top const & top);
    FORMAST_API virtual void top_class(Class const & class_);

    FORMAST_API virtual void stats(Stats const & stats);
    FORMAST_API virtual void stats_attr(Attr const & attr);
    FORMAST_API virtual void stats_if(If const & if_);

    FORMAST_API virtual void expr(Expr const & e);
    FORMAST_API virtual void expr_uint(boost::uint64_t const & n);
    FORMAST_API virtual void expr_id(std::string const & i);
    FORMAST_API virtual void expr_pos(Expr const & right);
    FORMAST_API virtual void expr_neg(Expr const & right);
    FORMAST_API virtual void expr_add(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_sub(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_mul(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_div(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_mod(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_pow(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_logical_and(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_logical_or(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_logical_not(Expr const & right);
    FORMAST_API virtual void expr_bitwise_and(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_bitwise_or(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_bitwise_xor(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_compare_eq(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_compare_ne(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_compare_gt(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_compare_lt(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_compare_ge(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_compare_le(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_shift_left(Expr const & left, Expr const & right);
    FORMAST_API virtual void expr_shift_right(Expr const & left, Expr const & right);
private:
    // pimpl idiom
    FORMAST_HIDDEN class ExprVisitor;
    boost::shared_ptr<ExprVisitor> _expr_visitor;
    FORMAST_HIDDEN class TopVisitor;
    boost::shared_ptr<TopVisitor> _top_visitor;
    FORMAST_HIDDEN class StatsVisitor;
    boost::shared_ptr<StatsVisitor> _stats_visitor;
};

} // namespace formast

#endif
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. *
 *                                                                         *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/* $Id$  */

#include "AliITSCalibrationSSD.h"
//////////////////////////////////////////////////////
//  Calibration class for set:ITS                   //
//  Specific subdetector implementation             //
//  for silicon strips detectors                    //
//                                                  //
//                                                  //
//////////////////////////////////////////////////////

const Double_t AliITSCalibrationSSD::fgkNoiseNDefault = 625.;
const Double_t AliITSCalibrationSSD::fgkNoisePDefault = 420.;
const Int_t AliITSCalibrationSSD::fgkNParDefault = 6;
const Double_t AliITSCalibrationSSD::fgkSigmaPDefault = 3.;
const Double_t AliITSCalibrationSSD::fgkSigmaNDefault = 2.;

ClassImp(AliITSCalibrationSSD)

//______________________________________________________________________
AliITSCalibrationSSD::AliITSCalibrationSSD():
fNPar(0),
fDetPar(0),
fNoiseP(0),
fNoiseN(0),
fSigmaP(0),
fSigmaN(0),
fNoise(0),
fGain(0),
fBadChannels(0),
fGainP(0),
fGainN(0),
fNoisP(0),
fNoisN(0),
fNoisePThreshold(0),
fNoisyPChannelsList(0),
fNoiseNThreshold(0),
fNoisyNChannelsList(0),
fDeadNChannelsList(0),
fDeadPChannelsList(0){
    // Default Constructor

    SetNoiseParam(fgkNoisePDefault,fgkNoiseNDefault);
}
//______________________________________________________________________
AliITSCalibrationSSD::AliITSCalibrationSSD(const char *dataType):
fNPar(0),
fDetPar(0),
fNoiseP(0),
fNoiseN(0),
fSigmaP(0),
fSigmaN(0),
fNoise(0),
fPedestal(0),
fGain(0),
fBadChannels(0),
fGainP(0),
fGainN(0),
fNoisP(0),
fNoisN(0),
fPedP(0),
fPedN(0),
fNoisePThreshold(0),
fNoisyPChannelsList(0),
fNoiseNThreshold(0),
fNoisyNChannelsList(0),
fDeadNChannelsList(0),
fDeadPChannelsList(0){
    // constructor

    SetNoiseParam(fgkNoisePDefault,fgkNoiseNDefault);
    SetDataType(dataType);
    SetSigmaSpread(fgkSigmaPDefault,fgkSigmaNDefault);
    SetNDetParam(fgkNParDefault);   // Sets fNPar=6 by default.
    fDetPar = new Double_t[fNPar];
    if (fNPar==6) {
	fDetPar[0]=10.;
	fDetPar[1]=5.;
	fDetPar[2]=0.02;
	fDetPar[3]=0.02;
	fDetPar[4]=0.02;
	fDetPar[5]=0.03;
    } // end if
}
//______________________________________________________________________
AliITSCalibrationSSD::~AliITSCalibrationSSD(){
    // destructor

    delete [] fDetPar;
}
//______________________________________________________________________
void AliITSCalibrationSSD::SetDetParam(Double_t  *par){
    // set det param
    Int_t i;

    for (i=0; i<fNPar; i++) {
	fDetPar[i]=par[i];
	//printf("\n CompressPar %d %d \n",i,fCPar[i]);
    } // end for i
}
//______________________________________________________________________
void AliITSCalibrationSSD::GetDetParam(Double_t  *par) const {
    // get det param
    Int_t i;

    for (i=0; i<fNPar; i++) {
	par[i]=fDetPar[i];
    } // end for i
}
<commit_msg>Changes to remove Effective C++ warnings<commit_after>/**************************************************************************
 * Copyright(c) 2007-2009, ALICE Experiment at CERN, All rights reserved. *
 *                                                                         *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/* $Id$  */

#include "AliITSCalibrationSSD.h"
//////////////////////////////////////////////////////
//  Calibration class for set:ITS                   //
//  Specific subdetector implementation             //
//  for silicon strips detectors                    //
//                                                  //
//                                                  //
//////////////////////////////////////////////////////

const Double_t AliITSCalibrationSSD::fgkNoiseNDefault = 625.;
const Double_t AliITSCalibrationSSD::fgkNoisePDefault = 420.;
const Int_t AliITSCalibrationSSD::fgkNParDefault = 6;
const Double_t AliITSCalibrationSSD::fgkSigmaPDefault = 3.;
const Double_t AliITSCalibrationSSD::fgkSigmaNDefault = 2.;

ClassImp(AliITSCalibrationSSD)

//______________________________________________________________________
AliITSCalibrationSSD::AliITSCalibrationSSD():
fNPar(0),
fDetPar(0),
fNoiseP(0),
fNoiseN(0),
fSigmaP(0),
fSigmaN(0),
fNoise(0),
fPedestal(),
fGain(0),
fBadChannels(0),
fGainP(0),
fGainN(0),
fNoisP(0),
fNoisN(0),
fPedP(),
fPedN(),
fNoisePThreshold(0),
fNoisyPChannelsList(0),
fNoiseNThreshold(0),
fNoisyNChannelsList(0),
fDeadNChannelsList(0),
fDeadPChannelsList(0){
    // Default Constructor

    SetNoiseParam(fgkNoisePDefault,fgkNoiseNDefault);
}
//______________________________________________________________________
AliITSCalibrationSSD::AliITSCalibrationSSD(const char *dataType):
fNPar(0),
fDetPar(0),
fNoiseP(0),
fNoiseN(0),
fSigmaP(0),
fSigmaN(0),
fNoise(0),
fPedestal(0),
fGain(0),
fBadChannels(0),
fGainP(0),
fGainN(0),
fNoisP(0),
fNoisN(0),
fPedP(0),
fPedN(0),
fNoisePThreshold(0),
fNoisyPChannelsList(0),
fNoiseNThreshold(0),
fNoisyNChannelsList(0),
fDeadNChannelsList(0),
fDeadPChannelsList(0){
    // constructor

    SetNoiseParam(fgkNoisePDefault,fgkNoiseNDefault);
    SetDataType(dataType);
    SetSigmaSpread(fgkSigmaPDefault,fgkSigmaNDefault);
    SetNDetParam(fgkNParDefault);   // Sets fNPar=6 by default.
    fDetPar = new Double_t[fNPar];
    if (fNPar==6) {
	fDetPar[0]=10.;
	fDetPar[1]=5.;
	fDetPar[2]=0.02;
	fDetPar[3]=0.02;
	fDetPar[4]=0.02;
	fDetPar[5]=0.03;
    } // end if
}
//______________________________________________________________________
AliITSCalibrationSSD::~AliITSCalibrationSSD(){
    // destructor

    delete [] fDetPar;
}
//______________________________________________________________________
void AliITSCalibrationSSD::SetDetParam(Double_t  *par){
    // set det param
    Int_t i;

    for (i=0; i<fNPar; i++) {
	fDetPar[i]=par[i];
	//printf("\n CompressPar %d %d \n",i,fCPar[i]);
    } // end for i
}
//______________________________________________________________________
void AliITSCalibrationSSD::GetDetParam(Double_t  *par) const {
    // get det param
    Int_t i;

    for (i=0; i<fNPar; i++) {
	par[i]=fDetPar[i];
    } // end for i
}
<|endoftext|>


<commit_before>#pragma once

#include "types/absolute_time_duration.hpp"
#include <pqrs/osx/chrono.hpp>

namespace krbn {
namespace manipulator {
namespace manipulators {
namespace mouse_motion_to_scroll {
struct counter_parameters final {
public:
  static constexpr double speed_multiplier_default_value = 1.0;
  static constexpr std::chrono::milliseconds recent_time_duration_milliseconds_default_value =
      std::chrono::milliseconds(100);
  static constexpr int threshold_default_value = 128;
  static constexpr int direction_lock_threshold_default_value = 4;
  static constexpr std::chrono::milliseconds scroll_event_interval_milliseconds_threshold_default_value =
      std::chrono::milliseconds(100);

  counter_parameters(void) : speed_multiplier_(speed_multiplier_default_value),
                             recent_time_duration_milliseconds_(recent_time_duration_milliseconds_default_value),
                             threshold_(threshold_default_value),
                             direction_lock_threshold_(direction_lock_threshold_default_value),
                             scroll_event_interval_milliseconds_threshold_(scroll_event_interval_milliseconds_threshold_default_value) {
  }

  double get_speed_multiplier(void) const {
    return speed_multiplier_;
  }

  void set_speed_multiplier(double value) {
    if (value <= 0.0) {
      value = speed_multiplier_default_value;
    }

    speed_multiplier_ = value;
  }

  std::chrono::milliseconds get_recent_time_duration_milliseconds(void) const {
    return recent_time_duration_milliseconds_;
  }

  void set_recent_time_duration_milliseconds(std::chrono::milliseconds value) {
    if (value < std::chrono::milliseconds(1)) {
      value = recent_time_duration_milliseconds_default_value;
    }

    recent_time_duration_milliseconds_ = value;
  }

  int get_threshold(void) const {
    return threshold_;
  }

  void set_threshold(int value) {
    if (value <= 0) {
      value = threshold_default_value;
    }

    threshold_ = value;
  }

  int get_direction_lock_threshold(void) const {
    return direction_lock_threshold_;
  }

  void set_direction_lock_threshold(int value) {
    if (value <= 0) {
      value = direction_lock_threshold_default_value;
    }

    direction_lock_threshold_ = value;
  }

  std::chrono::milliseconds get_scroll_event_interval_milliseconds_threshold(void) const {
    return scroll_event_interval_milliseconds_threshold_;
  }

  void set_scroll_event_interval_milliseconds_threshold(std::chrono::milliseconds value) {
    if (value < std::chrono::milliseconds(1)) {
      value = scroll_event_interval_milliseconds_threshold_default_value;
    }

    scroll_event_interval_milliseconds_threshold_ = value;
  }

private:
  double speed_multiplier_;
  std::chrono::milliseconds recent_time_duration_milliseconds_;
  int threshold_;
  int direction_lock_threshold_;
  std::chrono::milliseconds scroll_event_interval_milliseconds_threshold_;
};
} // namespace mouse_motion_to_scroll
} // namespace manipulators
} // namespace manipulator
} // namespace krbn
<commit_msg>add momentum_scroll_enabled_<commit_after>#pragma once

#include "types/absolute_time_duration.hpp"
#include <pqrs/osx/chrono.hpp>

namespace krbn {
namespace manipulator {
namespace manipulators {
namespace mouse_motion_to_scroll {
struct counter_parameters final {
public:
  static constexpr double speed_multiplier_default_value = 1.0;
  static constexpr std::chrono::milliseconds recent_time_duration_milliseconds_default_value =
      std::chrono::milliseconds(100);
  static constexpr int threshold_default_value = 128;
  static constexpr int direction_lock_threshold_default_value = 4;
  static constexpr std::chrono::milliseconds scroll_event_interval_milliseconds_threshold_default_value =
      std::chrono::milliseconds(100);

  counter_parameters(void) : momentum_scroll_enabled_(true),
                             speed_multiplier_(speed_multiplier_default_value),
                             recent_time_duration_milliseconds_(recent_time_duration_milliseconds_default_value),
                             threshold_(threshold_default_value),
                             direction_lock_threshold_(direction_lock_threshold_default_value),
                             scroll_event_interval_milliseconds_threshold_(scroll_event_interval_milliseconds_threshold_default_value) {
  }

  bool get_momentum_scroll_enabled(void) const {
    return momentum_scroll_enabled_;
  }

  void set_momentum_scroll_enabled(bool value) {
    momentum_scroll_enabled_ = value;
  }

  double get_speed_multiplier(void) const {
    return speed_multiplier_;
  }

  void set_speed_multiplier(double value) {
    if (value <= 0.0) {
      value = speed_multiplier_default_value;
    }

    speed_multiplier_ = value;
  }

  std::chrono::milliseconds get_recent_time_duration_milliseconds(void) const {
    return recent_time_duration_milliseconds_;
  }

  void set_recent_time_duration_milliseconds(std::chrono::milliseconds value) {
    if (value < std::chrono::milliseconds(1)) {
      value = recent_time_duration_milliseconds_default_value;
    }

    recent_time_duration_milliseconds_ = value;
  }

  int get_threshold(void) const {
    return threshold_;
  }

  void set_threshold(int value) {
    if (value <= 0) {
      value = threshold_default_value;
    }

    threshold_ = value;
  }

  int get_direction_lock_threshold(void) const {
    return direction_lock_threshold_;
  }

  void set_direction_lock_threshold(int value) {
    if (value <= 0) {
      value = direction_lock_threshold_default_value;
    }

    direction_lock_threshold_ = value;
  }

  std::chrono::milliseconds get_scroll_event_interval_milliseconds_threshold(void) const {
    return scroll_event_interval_milliseconds_threshold_;
  }

  void set_scroll_event_interval_milliseconds_threshold(std::chrono::milliseconds value) {
    if (value < std::chrono::milliseconds(1)) {
      value = scroll_event_interval_milliseconds_threshold_default_value;
    }

    scroll_event_interval_milliseconds_threshold_ = value;
  }

private:
  bool momentum_scroll_enabled_;
  double speed_multiplier_;
  std::chrono::milliseconds recent_time_duration_milliseconds_;
  int threshold_;
  int direction_lock_threshold_;
  std::chrono::milliseconds scroll_event_interval_milliseconds_threshold_;
};
} // namespace mouse_motion_to_scroll
} // namespace manipulators
} // namespace manipulator
} // namespace krbn
<|endoftext|>


<commit_before>// Aseprite FLIC Library
// Copyright (c) 2015 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.

#include "flic/flic.h"
#include "flic/flic_details.h"

#include <cassert>

namespace flic {

Decoder::Decoder(FileInterface* file)
  : m_file(file)
  , m_frameCount(0)
  , m_offsetFrame1(0)
  , m_offsetFrame2(0)
{
}

bool Decoder::readHeader(Header& header)
{
  uint32_t fileSize = read32();
  uint16_t magic = read16();

  assert(magic == FLI_MAGIC_NUMBER || magic == FLC_MAGIC_NUMBER);
  if (magic != FLI_MAGIC_NUMBER &&
      magic != FLC_MAGIC_NUMBER)
    return false;

  header.frames = read16();
  header.width  = read16();
  header.height = read16();
  read16();                     // Color depth (it is interpreted as 8bpp anyway)
  read16();                     // Skip flags
  header.speed = read32();
  if (magic == FLI_MAGIC_NUMBER) {
    if (header.speed == 0)
      header.speed = 70;
    else
      header.speed = 1000 * header.speed / 70;
  }

  if (magic == FLC_MAGIC_NUMBER) {
    // Offset to the first and second frame
    m_file->seek(80);
    m_offsetFrame1 = read32();
    m_offsetFrame2 = read32();
  }

  if (header.width == 0) header.width = 320;
  if (header.height == 0) header.width = 200;

  m_width = header.width;
  m_height = header.height;

  // Skip padding
  m_file->seek(128);
  return true;
}

bool Decoder::readFrame(Frame& frame)
{
  switch (m_frameCount) {
    case 0:
      if (m_offsetFrame1)
        m_file->seek(m_offsetFrame1);
      break;
    case 1:
      if (m_offsetFrame2)
        m_file->seek(m_offsetFrame2);
      break;
  }

  uint32_t frameStartPos = m_file->tell();
  uint32_t frameSize = read32();
  uint16_t magic = read16();
  assert(magic == FLI_FRAME_MAGIC_NUMBER);

  uint16_t chunks = read16();
  for (int i=0; i<8; ++i)       // Padding
    m_file->read8();

  for (uint16_t i=0; i!=chunks; ++i)
    readChunk(frame);

  m_file->seek(frameStartPos+frameSize);
  ++m_frameCount;
  return true;
}

void Decoder::readChunk(Frame& frame)
{
  uint32_t chunkStartPos = m_file->tell();
  uint32_t chunkSize = read32();
  uint16_t type = read16();

  switch (type) {
    case FLI_COLOR_256_CHUNK: readColorChunk(frame, false); break;
    case FLI_DELTA_CHUNK:     readDeltaChunk(frame);        break;
    case FLI_COLOR_64_CHUNK:  readColorChunk(frame, true);  break;
    case FLI_LC_CHUNK:        readLcChunk(frame);           break;
    case FLI_BLACK_CHUNK:     readBlackChunk(frame);        break;
    case FLI_BRUN_CHUNK:      readBrunChunk(frame);         break;
    case FLI_COPY_CHUNK:      readCopyChunk(frame);         break;
    default:
      // Ignore all other kind of chunks
      break;
  }

  m_file->seek(chunkStartPos+chunkSize);
}

void Decoder::readBlackChunk(Frame& frame)
{
  std::fill(frame.pixels,
            frame.pixels+frame.rowstride*m_height, 0);
}

void Decoder::readCopyChunk(Frame& frame)
{
  assert(m_width == 320 && m_height == 200);
  if (m_width == 320 && m_height == 200) {
    for (int y=0; y<200; ++y) {
      auto it = frame.pixels + y*frame.rowstride;
      for (int x=0; x<320; ++x, ++it)
        *it = m_file->read8();
    }
  }
}

void Decoder::readColorChunk(Frame& frame, bool oldColorChunk)
{
  int npackets = read16();

  // For each packet
  int i = 0;
  while (npackets--) {
    i += m_file->read8();       // Colors to skip

    int colors = m_file->read8();
    if (colors == 0)
      colors = 256;

    for (int j=0; j<colors; ++j) {
      Color& color = frame.colormap[i+j];
      color.r = m_file->read8();
      color.g = m_file->read8();
      color.b = m_file->read8();
      if (oldColorChunk) {
        color.r = 255 * int(color.r) / 63;
        color.g = 255 * int(color.g) / 63;
        color.b = 255 * int(color.b) / 63;
      }
    }
  }
}

void Decoder::readBrunChunk(Frame& frame)
{
  for (int y=0; y<m_height; ++y) {
    auto it = frame.pixels+frame.rowstride*y;
    int x = 0;
    int npackets = m_file->read8();
    while (m_file->ok() && x < m_width) {
      int count = int(int8_t(m_file->read8()));
      if (count >= 0) {
        uint8_t color = m_file->read8();
        while (count-- != 0 && x < m_width) {
          *it = color;
          ++it;
          ++x;
        }
      }
      else {
        while (count++ != 0) {
          *it = m_file->read8();
          ++it;
          ++x;
        }
      }
    }
  }
}

void Decoder::readLcChunk(Frame& frame)
{
  int skipLines = read16();
  int nlines = read16();

  for (int y=skipLines; y<skipLines+nlines; ++y) {
    auto it = frame.pixels+frame.rowstride*y;
    int x = 0;
    int npackets = m_file->read8();
    while (npackets-- && x < m_width) {
      int skip = m_file->read8();

      x += skip;
      it += skip;

      int count = int(int8_t(m_file->read8()));
      if (count >= 0) {
        while (count-- != 0) {
          *it = m_file->read8();
          ++it;
          ++x;
        }
      }
      else {
        uint8_t color = m_file->read8();
        while (count++ != 0 && x < m_width) {
          *it = color;
          ++it;
          ++x;
        }
      }
    }
  }
}

void Decoder::readDeltaChunk(Frame& frame)
{
  int nlines = read16();
  int y = 0;
  while (nlines-- != 0) {
    int npackets = 0;

    while (m_file->ok()) {
      int16_t word = read16();
      if (word < 0) {          // Has bit 15 (0x8000)
        if (word & 0x4000) {   // Has bit 14 (0x4000)
          y += -word;          // Skip lines
        }
        // Only last pixel has changed
        else {
          assert(y >= 0 && y < m_height);
          if (y >= 0 && y < m_height) {
            auto it = frame.pixels + y*frame.rowstride + m_width - 1;
            *it = (word & 0xff);
          }
          ++y;
          if (nlines-- == 0)
            goto done;
        }
      }
      else {
        npackets = word;
        break;
      }
    }

    int x = 0;
    while (npackets-- != 0) {
      x += m_file->read8();           // Skip pixels
      int8_t count = m_file->read8(); // Number of words

      assert(y >= 0 && y < m_height &&
             x >= 0 && x < m_width);
      auto it = frame.pixels + y*frame.rowstride + x;

      if (count >= 0) {
        while (count-- != 0 && x < m_width) {
          int color1 = m_file->read8();
          int color2 = m_file->read8();

          *it = color1;
          ++it;
          ++x;

          if (x < m_width) {
            *it = color2;
            ++it;
            ++x;
          }
        }
      }
      else {
        int color1 = m_file->read8();
        int color2 = m_file->read8();

        while (count++ != 0 && x < m_width) {
          *it = color1;
          ++it;
          ++x;

          if (x < m_width) {
            *it = color2;
            ++it;
            ++x;
          }
        }
      }
    }

    ++y;
  }
done:;
}

uint16_t Decoder::read16()
{
  int b1 = m_file->read8();
  int b2 = m_file->read8();

  if (m_file->ok()) {
    return ((b2 << 8) | b1); // Little endian
  }
  else
    return 0;
}

uint32_t Decoder::read32()
{
  int b1 = m_file->read8();
  int b2 = m_file->read8();
  int b3 = m_file->read8();
  int b4 = m_file->read8();

  if (m_file->ok()) {
    // Little endian
    return ((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
  }
  else
    return 0;
}

} // namespace flic
<commit_msg>Remove unused variables<commit_after>// Aseprite FLIC Library
// Copyright (c) 2015 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.

#include "flic/flic.h"
#include "flic/flic_details.h"

#include <cassert>

namespace flic {

Decoder::Decoder(FileInterface* file)
  : m_file(file)
  , m_frameCount(0)
  , m_offsetFrame1(0)
  , m_offsetFrame2(0)
{
}

bool Decoder::readHeader(Header& header)
{
  read32(); // file size
  uint16_t magic = read16();

  assert(magic == FLI_MAGIC_NUMBER || magic == FLC_MAGIC_NUMBER);
  if (magic != FLI_MAGIC_NUMBER &&
      magic != FLC_MAGIC_NUMBER)
    return false;

  header.frames = read16();
  header.width  = read16();
  header.height = read16();
  read16();                     // Color depth (it is interpreted as 8bpp anyway)
  read16();                     // Skip flags
  header.speed = read32();
  if (magic == FLI_MAGIC_NUMBER) {
    if (header.speed == 0)
      header.speed = 70;
    else
      header.speed = 1000 * header.speed / 70;
  }

  if (magic == FLC_MAGIC_NUMBER) {
    // Offset to the first and second frame
    m_file->seek(80);
    m_offsetFrame1 = read32();
    m_offsetFrame2 = read32();
  }

  if (header.width == 0) header.width = 320;
  if (header.height == 0) header.width = 200;

  m_width = header.width;
  m_height = header.height;

  // Skip padding
  m_file->seek(128);
  return true;
}

bool Decoder::readFrame(Frame& frame)
{
  switch (m_frameCount) {
    case 0:
      if (m_offsetFrame1)
        m_file->seek(m_offsetFrame1);
      break;
    case 1:
      if (m_offsetFrame2)
        m_file->seek(m_offsetFrame2);
      break;
  }

  uint32_t frameStartPos = m_file->tell();
  uint32_t frameSize = read32();
  uint16_t magic = read16();
  assert(magic == FLI_FRAME_MAGIC_NUMBER);
  (void)magic;

  uint16_t chunks = read16();
  for (int i=0; i<8; ++i)       // Padding
    m_file->read8();

  for (uint16_t i=0; i!=chunks; ++i)
    readChunk(frame);

  m_file->seek(frameStartPos+frameSize);
  ++m_frameCount;
  return true;
}

void Decoder::readChunk(Frame& frame)
{
  uint32_t chunkStartPos = m_file->tell();
  uint32_t chunkSize = read32();
  uint16_t type = read16();

  switch (type) {
    case FLI_COLOR_256_CHUNK: readColorChunk(frame, false); break;
    case FLI_DELTA_CHUNK:     readDeltaChunk(frame);        break;
    case FLI_COLOR_64_CHUNK:  readColorChunk(frame, true);  break;
    case FLI_LC_CHUNK:        readLcChunk(frame);           break;
    case FLI_BLACK_CHUNK:     readBlackChunk(frame);        break;
    case FLI_BRUN_CHUNK:      readBrunChunk(frame);         break;
    case FLI_COPY_CHUNK:      readCopyChunk(frame);         break;
    default:
      // Ignore all other kind of chunks
      break;
  }

  m_file->seek(chunkStartPos+chunkSize);
}

void Decoder::readBlackChunk(Frame& frame)
{
  std::fill(frame.pixels,
            frame.pixels+frame.rowstride*m_height, 0);
}

void Decoder::readCopyChunk(Frame& frame)
{
  assert(m_width == 320 && m_height == 200);
  if (m_width == 320 && m_height == 200) {
    for (int y=0; y<200; ++y) {
      auto it = frame.pixels + y*frame.rowstride;
      for (int x=0; x<320; ++x, ++it)
        *it = m_file->read8();
    }
  }
}

void Decoder::readColorChunk(Frame& frame, bool oldColorChunk)
{
  int npackets = read16();

  // For each packet
  int i = 0;
  while (npackets--) {
    i += m_file->read8();       // Colors to skip

    int colors = m_file->read8();
    if (colors == 0)
      colors = 256;

    for (int j=0; j<colors; ++j) {
      Color& color = frame.colormap[i+j];
      color.r = m_file->read8();
      color.g = m_file->read8();
      color.b = m_file->read8();
      if (oldColorChunk) {
        color.r = 255 * int(color.r) / 63;
        color.g = 255 * int(color.g) / 63;
        color.b = 255 * int(color.b) / 63;
      }
    }
  }
}

void Decoder::readBrunChunk(Frame& frame)
{
  for (int y=0; y<m_height; ++y) {
    auto it = frame.pixels+frame.rowstride*y;
    int x = 0;
    m_file->read8(); // Ignore number of packets (we read until x == m_width)
    while (m_file->ok() && x < m_width) {
      int count = int(int8_t(m_file->read8()));
      if (count >= 0) {
        uint8_t color = m_file->read8();
        while (count-- != 0 && x < m_width) {
          *it = color;
          ++it;
          ++x;
        }
      }
      else {
        while (count++ != 0) {
          *it = m_file->read8();
          ++it;
          ++x;
        }
      }
    }
  }
}

void Decoder::readLcChunk(Frame& frame)
{
  int skipLines = read16();
  int nlines = read16();

  for (int y=skipLines; y<skipLines+nlines; ++y) {
    auto it = frame.pixels+frame.rowstride*y;
    int x = 0;
    int npackets = m_file->read8();
    while (npackets-- && x < m_width) {
      int skip = m_file->read8();

      x += skip;
      it += skip;

      int count = int(int8_t(m_file->read8()));
      if (count >= 0) {
        while (count-- != 0) {
          *it = m_file->read8();
          ++it;
          ++x;
        }
      }
      else {
        uint8_t color = m_file->read8();
        while (count++ != 0 && x < m_width) {
          *it = color;
          ++it;
          ++x;
        }
      }
    }
  }
}

void Decoder::readDeltaChunk(Frame& frame)
{
  int nlines = read16();
  int y = 0;
  while (nlines-- != 0) {
    int npackets = 0;

    while (m_file->ok()) {
      int16_t word = read16();
      if (word < 0) {          // Has bit 15 (0x8000)
        if (word & 0x4000) {   // Has bit 14 (0x4000)
          y += -word;          // Skip lines
        }
        // Only last pixel has changed
        else {
          assert(y >= 0 && y < m_height);
          if (y >= 0 && y < m_height) {
            auto it = frame.pixels + y*frame.rowstride + m_width - 1;
            *it = (word & 0xff);
          }
          ++y;
          if (nlines-- == 0)
            goto done;
        }
      }
      else {
        npackets = word;
        break;
      }
    }

    int x = 0;
    while (npackets-- != 0) {
      x += m_file->read8();           // Skip pixels
      int8_t count = m_file->read8(); // Number of words

      assert(y >= 0 && y < m_height &&
             x >= 0 && x < m_width);
      auto it = frame.pixels + y*frame.rowstride + x;

      if (count >= 0) {
        while (count-- != 0 && x < m_width) {
          int color1 = m_file->read8();
          int color2 = m_file->read8();

          *it = color1;
          ++it;
          ++x;

          if (x < m_width) {
            *it = color2;
            ++it;
            ++x;
          }
        }
      }
      else {
        int color1 = m_file->read8();
        int color2 = m_file->read8();

        while (count++ != 0 && x < m_width) {
          *it = color1;
          ++it;
          ++x;

          if (x < m_width) {
            *it = color2;
            ++it;
            ++x;
          }
        }
      }
    }

    ++y;
  }
done:;
}

uint16_t Decoder::read16()
{
  int b1 = m_file->read8();
  int b2 = m_file->read8();

  if (m_file->ok()) {
    return ((b2 << 8) | b1); // Little endian
  }
  else
    return 0;
}

uint32_t Decoder::read32()
{
  int b1 = m_file->read8();
  int b2 = m_file->read8();
  int b3 = m_file->read8();
  int b4 = m_file->read8();

  if (m_file->ok()) {
    // Little endian
    return ((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
  }
  else
    return 0;
}

} // namespace flic
<|endoftext|>


<commit_before>#pragma once

#include "tensor.hpp"

namespace sor {

	/* Vector & matrix nagation.
	*/
	template<typename Type, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto operator-(tensor<Type, Dims...> lhs) {
		std::transform(lhs.begin(), lhs.end(), lhs.begin(), std::negate<void>());
		return lhs;
	}

	/* Vector & matrix sum.
	*/
	template<typename LhsType, typename RhsType, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto& operator+=(tensor<LhsType, Dims...>& lhs, tensor<RhsType, Dims...> const& rhs) {
		std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(), std::plus<void>());
		return lhs;
	}

	template<typename LhsType, typename RhsType, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto operator+(tensor<LhsType, Dims...> const& lhs, tensor<RhsType, Dims...> const& rhs) {
		using result_type = tensor<typename std::common_type<LhsType, RhsType>::type, Dims...>;
		result_type result(lhs);
		result += rhs;
		return result;
	}

	/* Vector & matrix subtraction.
	*/
	template<typename LhsType, typename RhsType, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto& operator-=(tensor<LhsType, Dims...>& lhs, tensor<RhsType, Dims...> const& rhs) {
		std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(), std::minus<void>());
		return lhs;
	}

	template<typename LhsType, typename RhsType, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto operator-(tensor<LhsType, Dims...> const& lhs, tensor<RhsType, Dims...> const& rhs) {
		using result_type = tensor<typename std::common_type<LhsType, RhsType>::type, Dims...>;
		result_type result(lhs);
		result -= rhs;
		return result;
	}

	/* Vector & matrix scalar multiplication.
	*/
	template<typename LhsType, std::size_t... Dims, typename RhsType,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto& operator*=(tensor<LhsType, Dims...>& lhs, RhsType const& rhs) {
		for (auto& i : lhs) { i *= rhs; }
		return rhs;
	}

	template<typename LhsType, std::size_t... Dims, typename RhsType,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto operator*(tensor<LhsType, Dims...> const& lhs, RhsType const& rhs) {
		using result_type = tensor<typename std::common_type<LhsType, RhsType>::type, Dims...>;
		result_type result(lhs);
		result *= rhs;
		return result;
	}

	template<typename LhsType, typename RhsType, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto operator*(LhsType const& lhs, tensor<RhsType, Dims...> const& rhs) {
		using result_type = tensor<typename std::common_type<LhsType, RhsType>::type, Dims...>;
		result_type result(rhs);
		result *= lhs;
		return result;
	}

	/* Vector & matrix scalar division.
	 * Notice: `scalar / vector` is intentionally not provided given that it doesn't
	 * have clear semantic in this context.
	*/
	template<typename LhsType, std::size_t... Dims, typename RhsType,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto& operator/=(tensor<LhsType, Dims...>& lhs, RhsType const& rhs) {
		for (auto& i : lhs) { i /= rhs; }
		return rhs;
	}

	template<typename LhsType, std::size_t... Dims, typename RhsType,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto operator/(tensor<LhsType, Dims...> const& lhs, RhsType const& rhs) {
		using result_type = tensor<typename std::common_type<LhsType, RhsType>::type, Dims...>;
		result_type result(lhs);
		result /= rhs;
		return result;
	}

}<commit_msg>Restricted algebraic scalar operators to all types that are not tensors<commit_after>#pragma once

#include "tensor.hpp"

namespace sor {

	/* Vector & matrix nagation.
	*/
	template<typename Type, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto operator-(tensor<Type, Dims...> lhs) {
		std::transform(lhs.begin(), lhs.end(), lhs.begin(), std::negate<void>());
		return lhs;
	}

	/* Vector & matrix sum.
	*/
	template<typename LhsType, typename RhsType, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto& operator+=(tensor<LhsType, Dims...>& lhs, tensor<RhsType, Dims...> const& rhs) {
		std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(), std::plus<void>());
		return lhs;
	}

	template<typename LhsType, typename RhsType, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto operator+(tensor<LhsType, Dims...> const& lhs, tensor<RhsType, Dims...> const& rhs) {
		using result_type = tensor<typename std::common_type<LhsType, RhsType>::type, Dims...>;
		result_type result(lhs);
		result += rhs;
		return result;
	}

	/* Vector & matrix subtraction.
	*/
	template<typename LhsType, typename RhsType, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto& operator-=(tensor<LhsType, Dims...>& lhs, tensor<RhsType, Dims...> const& rhs) {
		std::transform(lhs.begin(), lhs.end(), rhs.begin(), lhs.begin(), std::minus<void>());
		return lhs;
	}

	template<typename LhsType, typename RhsType, std::size_t... Dims,
		typename std::enable_if<sizeof...(Dims) < 3, int>::type = 0>
	auto operator-(tensor<LhsType, Dims...> const& lhs, tensor<RhsType, Dims...> const& rhs) {
		using result_type = tensor<typename std::common_type<LhsType, RhsType>::type, Dims...>;
		result_type result(lhs);
		result -= rhs;
		return result;
	}

	/* Vector & matrix scalar multiplication.
	*/
	template<typename LhsType, std::size_t... Dims, typename RhsType,
		typename std::enable_if<
			sizeof...(Dims) < 3 && !sor::is_tensor<RhsType>::value,
			int
		>::type = 0>
	auto& operator*=(tensor<LhsType, Dims...>& lhs, RhsType const& rhs) {
		for (auto& i : lhs) { i *= rhs; }
		return rhs;
	}

	template<typename LhsType, std::size_t... Dims, typename RhsType,
		typename std::enable_if<
			sizeof...(Dims) < 3 && !sor::is_tensor<RhsType>::value,
			int
		>::type = 0>
	auto operator*(tensor<LhsType, Dims...> const& lhs, RhsType const& rhs) {
		using result_type = tensor<typename std::common_type<LhsType, RhsType>::type, Dims...>;
		result_type result(lhs);
		result *= rhs;
		return result;
	}

	template<typename LhsType, typename RhsType, std::size_t... Dims,
		typename std::enable_if<
			sizeof...(Dims) < 3 && !sor::is_tensor<LhsType>::value,
			int
		>::type = 0>
	auto operator*(LhsType const& lhs, tensor<RhsType, Dims...> const& rhs) {
		using result_type = tensor<typename std::common_type<LhsType, RhsType>::type, Dims...>;
		result_type result(rhs);
		result *= lhs;
		return result;
	}

	/* Vector & matrix scalar division.
	 * Notice: `scalar / vector` is intentionally not provided given that it doesn't
	 * have clear semantic in this context.
	*/
	template<typename LhsType, std::size_t... Dims, typename RhsType,
		typename std::enable_if<
			sizeof...(Dims) < 3 && !sor::is_tensor<RhsType>::value,
			int
		>::type = 0>
	auto& operator/=(tensor<LhsType, Dims...>& lhs, RhsType const& rhs) {
		for (auto& i : lhs) { i /= rhs; }
		return rhs;
	}

	template<typename LhsType, std::size_t... Dims, typename RhsType,
		typename std::enable_if<
			sizeof...(Dims) < 3 && !sor::is_tensor<RhsType>::value,
			int
		>::type = 0>
	auto operator/(tensor<LhsType, Dims...> const& lhs, RhsType const& rhs) {
		using result_type = tensor<typename std::common_type<LhsType, RhsType>::type, Dims...>;
		result_type result(lhs);
		result /= rhs;
		return result;
	}

}<|endoftext|>


<commit_before>/*************************************************************************
 * Copyright (c) 2014 eProsima. All rights reserved.
 *
 * This copy of eProsima RTPS is licensed to you under the terms described in the
 * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution.
 *
 *************************************************************************/

/**
 * @file eClock.cpp
 *
 */
#include <cmath>
#include <iostream>
#include "eprosimartps/utils/eClock.h"
namespace eprosima {
namespace rtps {
	//FIXME: UTC SECONDS AUTOMATICALLY
eClock::eClock():
		m_seconds_from_1900_to_1970(2208988800),
		m_utc_seconds_diff(2*60*60)
{
#if defined(_WIN32)
	QueryPerformanceFrequency(&freq);
#endif
}

eClock::~eClock() {

}

#if defined(_WIN32)
#include <cstdint>

bool eClock::setTimeNow(Time_t* tnow)
{

    GetSystemTimeAsFileTime(&ft);
    ftlong = ft.dwHighDateTime;
    ftlong <<=32;
    ftlong |= ft.dwLowDateTime;
    ftlong /=10;
    ftlong -= 11644473600000000ULL;
	tnow->seconds = (int32_t)((ftlong/1000000)+(long)m_seconds_from_1900_to_1970+(long)m_utc_seconds_diff);
	//std::cout<<std::fixed<< "fraction bf and aft  " << (tt%1000000) << " ** " << ((tt%1000000)*pow(10.0,-6)*pow(2.0,32)) << " ++ "<<((uint32_t)((tt%1000000)*pow(10.0,-6)*pow(2.0,32)))/pow(2.0,32)*pow(10.0,6)<< std::endl;
	tnow->fraction = (uint32_t)((ftlong%1000000)*pow(10.0,-6)*pow(2.0,32));
	return true;
}

void eClock::my_sleep(uint32_t milliseconds)
{
	#pragma warning(disable: 4430)
	Sleep(milliseconds);
	return;
}

void eClock::intervalStart()
{
	  GetSystemTimeAsFileTime(&ft1);
	  QueryPerformanceCounter(&li1);
}
uint64_t eClock::intervalEnd()
{
	GetSystemTimeAsFileTime(&ft2);
	QueryPerformanceCounter(&li2);
	return 0;

}

#else //UNIX VERSION
#include <unistd.h>

bool eClock::setTimeNow(Time_t* tnow)
{
	gettimeofday(&m_now,NULL);
	tnow->seconds = m_now.tv_sec+m_seconds_from_1900_to_1970+m_utc_seconds_diff;
	tnow->fraction = (uint32_t)(m_now.tv_usec*pow(2.0,32)*pow(10.0,-6));
	return true;
}

void eClock::my_sleep(uint32_t milliseconds)
{
	usleep(milliseconds*1000);
	return;
}

void eClock::intervalStart()
{
	gettimeofday(&m_interval1,NULL);
}

uint64_t eClock::intervalEnd()
{
	gettimeofday(&m_interval2,NULL);
	return (m_interval2.tv_sec-m_interval1.tv_sec)*1000000+m_interval2.tv_usec-m_interval1-tv_usec;
}

#endif

} /* namespace rtps */
} /* namespace eprosima */
<commit_msg>Fixed clock for unix<commit_after>/*************************************************************************
 * Copyright (c) 2014 eProsima. All rights reserved.
 *
 * This copy of eProsima RTPS is licensed to you under the terms described in the
 * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution.
 *
 *************************************************************************/

/**
 * @file eClock.cpp
 *
 */
#include <cmath>
#include <iostream>
#include "eprosimartps/utils/eClock.h"
namespace eprosima {
namespace rtps {
	//FIXME: UTC SECONDS AUTOMATICALLY
eClock::eClock():
		m_seconds_from_1900_to_1970(2208988800),
		m_utc_seconds_diff(2*60*60)
{
#if defined(_WIN32)
	QueryPerformanceFrequency(&freq);
#endif
}

eClock::~eClock() {

}

#if defined(_WIN32)
#include <cstdint>

bool eClock::setTimeNow(Time_t* tnow)
{

    GetSystemTimeAsFileTime(&ft);
    ftlong = ft.dwHighDateTime;
    ftlong <<=32;
    ftlong |= ft.dwLowDateTime;
    ftlong /=10;
    ftlong -= 11644473600000000ULL;
	tnow->seconds = (int32_t)((ftlong/1000000)+(long)m_seconds_from_1900_to_1970+(long)m_utc_seconds_diff);
	//std::cout<<std::fixed<< "fraction bf and aft  " << (tt%1000000) << " ** " << ((tt%1000000)*pow(10.0,-6)*pow(2.0,32)) << " ++ "<<((uint32_t)((tt%1000000)*pow(10.0,-6)*pow(2.0,32)))/pow(2.0,32)*pow(10.0,6)<< std::endl;
	tnow->fraction = (uint32_t)((ftlong%1000000)*pow(10.0,-6)*pow(2.0,32));
	return true;
}

void eClock::my_sleep(uint32_t milliseconds)
{
	#pragma warning(disable: 4430)
	Sleep(milliseconds);
	return;
}

void eClock::intervalStart()
{
	  GetSystemTimeAsFileTime(&ft1);
	  QueryPerformanceCounter(&li1);
}
uint64_t eClock::intervalEnd()
{
	GetSystemTimeAsFileTime(&ft2);
	QueryPerformanceCounter(&li2);
	return 0;

}

#else //UNIX VERSION
#include <unistd.h>

bool eClock::setTimeNow(Time_t* tnow)
{
	gettimeofday(&m_now,NULL);
	tnow->seconds = m_now.tv_sec+m_seconds_from_1900_to_1970+m_utc_seconds_diff;
	tnow->fraction = (uint32_t)(m_now.tv_usec*pow(2.0,32)*pow(10.0,-6));
	return true;
}

void eClock::my_sleep(uint32_t milliseconds)
{
	usleep(milliseconds*1000);
	return;
}

void eClock::intervalStart()
{
	gettimeofday(&m_interval1,NULL);
}

uint64_t eClock::intervalEnd()
{
	gettimeofday(&m_interval2,NULL);
	return (m_interval2.tv_sec-m_interval1.tv_sec)*1000000+m_interval2.tv_usec-m_interval1.tv_usec;
}

#endif

} /* namespace rtps */
} /* namespace eprosima */
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *  @file main.cpp
 */

#include "JPetManager/JPetManager.h"
#include "ImageReco.h"
#include "SinogramCreator.h"
#include "SinogramCreatorMC.h"
#include "MLEMRunner.h"
using namespace std;

int main(int argc, const char *argv[])
{
  JPetManager &manager = JPetManager::getManager();

  manager.registerTask<ImageReco>("ImageReco");
  manager.registerTask<SinogramCreator>("SinogramCreator");
  manager.registerTask<SinogramCreatorMC>("SinogramCreatorMC");
  manager.registerTask<MLEMRunner>("MLEMRunner");

  manager.useTask("MLEMRunner", "reco.unk.evt", "mlem");
  manager.useTask("ImageReco", "unk.evt", "reco");
  manager.useTask("SinogramCreator", "unk.evt", "sino");
  manager.useTask("SinogramCreatorMC", "unk.evt", "sino.mc");

  manager.run(argc, argv);
}
<commit_msg>Add try/catch to main, change output to empty<commit_after>/**
 *  @copyright Copyright 2017 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *  @file main.cpp
 */

#include "ImageReco.h"
#include "JPetManager/JPetManager.h"
#include "MLEMRunner.h"
#include "SinogramCreator.h"
#include "SinogramCreatorMC.h"
using namespace std;

int main(int argc, const char* argv[]) {
  try {
    JPetManager& manager = JPetManager::getManager();

    manager.registerTask<ImageReco>("ImageReco");
    manager.registerTask<SinogramCreator>("SinogramCreator");
    manager.registerTask<SinogramCreatorMC>("SinogramCreatorMC");
    manager.registerTask<MLEMRunner>("MLEMRunner");

    manager.useTask("MLEMRunner", "reco.unk.evt", "");
    // manager.useTask("ImageReco", "unk.evt", "reco");
    // manager.useTask("SinogramCreator", "unk.evt", "sino");
    // manager.useTask("SinogramCreatorMC", "unk.evt", "sino.mc");

    manager.run(argc, argv);
  } catch (const std::exception& except) {
    std::cerr << "Unrecoverable error occured:" << except.what() << "Exiting the program!" << std::endl;
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}
<|endoftext|>