<commit_before>
// (c) COPYRIGHT URI/MIT 1994-1996
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
//      jhrg,jimg       James Gallagher (jgallagher@gso.uri.edu)
//      reza            Reza Nekovei (reza@intcomm.net)

// A few useful routines which are used in CGI programs.
//
// ReZa 9/30/94

// $Log: cgi_util.cc,v $
// Revision 1.14  1996/06/08 00:16:42  jimg
// Fixed a bug in name_path().
// Added compression functions which create filter processes which automatically
// compress stdio file streams.
// Added to set_mime_text() and set_mime_binary() support for compression. These
// now correctly set the content-encoding field of the mime header.
// Fixed ErrMsgT so that it says `DODS server' when the name of the server is
// not known.
//
// Revision 1.13  1996/06/04 21:33:53  jimg
// Multiple connections are now possible. It is now possible to open several
// URLs at the same time and read from them in a round-robin fashion. To do
// this I added data source and sink parameters to the serialize and
// deserialize mfuncs. Connect was also modified so that it manages the data
// source `object' (which is just an XDR pointer).
//
// Revision 1.12  1996/05/31 23:30:46  jimg
// Updated copyright notice.
//
// Revision 1.11  1996/05/21 23:52:42  jimg
// Changed include netio.h to cgi_util.h.
//
// Revision 1.10  1996/03/05 23:22:06  jimg
// Addedconst to the char * function definitions.
//
// Revision 1.9  1995/07/09  21:20:42  jimg
// Fixed date in copyright (it now reads `Copyright 1995 ...').
//
// Revision 1.8  1995/07/09  21:14:43  jimg
// Added copyright.
//
// Revision 1.7  1995/06/27  17:38:43  jimg
// Modified the cgi-util-test code so that it correctly uses name_path(); the
// pointer returned by that function must be delteted.
//
// Revision 1.6  1995/05/30  18:28:59  jimg
// Added const to ErrMsgT prototype.
//
// Revision 1.5  1995/05/22  20:36:10  jimg
// Added #include "config_netio.h"
// Removed old code.
//
// Revision 1.4  1995/03/16  16:29:24  reza
// Fixed bugs in ErrMsgT and mime type.
//
// Revision 1.3  1995/02/22  21:03:59  reza
// Added version number capability using CGI status_line.
//
// Revision 1.2  1995/02/22  19:53:32  jimg
// Fixed usage of time functions in ErrMsgT; use ctime instead of localtime
// and asctime.
// Fixed TimStr bug in ErrMsgT.
// Fixed dynamic memory bugs in name_path and fmakeword.
// Replaced malloc calls with calls to new char[]; C++ code will expect to
// be able to use delete.
// Fixed memory overrun error in fmakeword.
// Fixed potential bug in name_path (when called with null argument).
// Added assetions.
//
// Revision 1.1  1995/01/10  16:23:01  jimg
// Created new `common code' library for the net I/O stuff.
//
// Revision 1.1  1994/10/28  14:34:01  reza
// First version

static char rcsid[]={"$Id: cgi_util.cc,v 1.14 1996/06/08 00:16:42 jimg Exp $"};

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>

#include <iostream.h>
#include <String.h>

#include "config_dap.h"
#include "cgi_util.h"

#ifdef TRACE_NEW
#include "trace_new.h"
#endif

#ifndef FILE_DELIMITER		// default to unix
#define FILE_DELIMITER '/'
#endif

#define TimLen 26		// length of string from asctime()
#define CLUMP_SIZE 1024		// size of clumps to new in fmakeword()

// An error handling routine to append the error messege from CGI programs,
// a time stamp, and the client host name (or address) to HTTPD error-log.
// Use this instead of the functions in liberrmsg.a in the programs run by
// the CGIs to report errors so those errors show up in HTTPD's log files.
//
// Returns: void

void
ErrMsgT(const char *Msgt)
{
    time_t TimBin;
    char TimStr[TimLen];

    if (time(&TimBin) == (time_t)-1)
	strcpy(TimStr, "time() error           ");
    else {
	strcpy(TimStr, ctime(&TimBin));
	TimStr[TimLen - 2] = '\0'; // overwrite the \n
    }

    char *host_or_addr = getenv("REMOTE_HOST") ? getenv("REMOTE_HOST") :
	getenv("REMOTE_ADDR");
    char *script = getenv("SCRIPT_NAME") ? getenv("SCRIPT_NAME") :
	"DODS server";

    cerr << "[" << TimStr << "] CGI: " << script << " faild for "
	 << host_or_addr << " reason: "<< Msgt << endl;
}

// Given an open FILE *IN, a separator character (in STOP) and the number of
// characters in the thing referenced by IN, return characters upto the
// STOP. The STOP character itself is discarded. Memory for the new word is
// dynamically allocated using C++'s new facility. In addition, the count of
// characters in the input source (CL; content length) is decremented.
//
// Once CL is zero, do not continue calling this function!
//
// Returns: a newly allocated string.

char *
fmakeword(FILE *f, const char stop, int *cl)
{
    assert(f && stop && *cl);

    int wsize = CLUMP_SIZE;
    int ll = 0;
    char *word = new char[wsize + 1];

    while(1) {
	assert(ll <= wsize);

        word[ll] = (char)fgetc(f);

	// If the word size is exceeded, allocate more space. What a kluge.
        if(ll == wsize) {
            wsize += CLUMP_SIZE;
	    char *tmp_word_buf = new char[wsize + 1];
	    memcpy(tmp_word_buf, word, wsize - (CLUMP_SIZE - 1));
	    delete word;
	    word = tmp_word_buf;
	}

        --(*cl);

        if((word[ll] == stop) || (feof(f)) || (!(*cl))) {
            if(word[ll] != stop)
		ll++;
	    assert(ll <= wsize);
            word[ll] = '\0';
            return word;
	}

        ++ll;
    }
}

// Given a pathname, return just the filename component with any extension
// removed. The new string resides in newly allocated memory; the caller must
// delete it when done using the filename.
// Originally from the netcdf distribution (ver 2.3.2).
//
// *** Change to String class argument and return type. jhrg
//
// Returns: A filename, with path and extension information removed. If
// memory for the new name cannot be allocated, does not return!

char *
name_path(const char *path)
{
    if (!path)
	return NULL;

    char *cp = strrchr(path, FILE_DELIMITER);
    if (cp == 0)                // no delimiter
	cp = (char *)path;
    else                        // skip delimeter
	cp++;

    char *newp = new char[strlen(cp)+1];

    (void) strcpy(newp, cp);	// copy last component of path
    if ((cp = strrchr(newp, '.')) != NULL)
      *cp = '\0';               /* strip off any extension */

    return newp;
}

// Send string to set the transfer (mime) type and server version
// Note that the content description filed is used to indicate whether valid
// information of an error message is contained in the document and the
// content-encoding field is used to indicate whether the data is compressed.
// If the data stream is to be compressed, arrange for a compression output
// filter so that all information sent after the header will be compressed.
//
// Returns: false if the compression output filter was to be used but could
// not be started, true otherwise.

static char *descrip[]={"unknown", "dods_das", "dods_dds", "dods_data",
			"dods_error"};
static char *encoding[]={"unknown", "x-plain", "x-gzip"};

void
set_mime_text(ObjectType type = unknown_type, EncodingType enc = x_plain)
{
    cout << "Status: 200 " << DVR << endl; // Send server version
    cout << "Content-type: text/plain" << endl;
    cout << "Content-Description: " << descrip[type] << endl;
    cout << "Content-Encoding: " << encoding[enc] << endl;
    cout << endl;			// MIME header ends with a blank line
}

void
set_mime_binary(ObjectType type = unknown_type, EncodingType enc = x_plain)
{
    cout << "Status: 200 " << DVR << endl;
    cout << "Content-type: application/octet-stream" << endl;
    cout << "Content-Description: " << descrip[type] << endl;
    cout << "Content-Encoding: " << encoding[enc] << endl;
    cout << endl;		// MIME header ends with a blank line
}

// Open a pipe to a filter process which will compress this process' stdout.
//
// NB: You must use pclose to close the FILE *.
//
// Returns: false if the pipe or child process could not be created, true
// otherwise.

FILE *
compress_stdout()
{
    String cmd = "gzip -cf";	// c: write to stdout, f: ...even if a tty

    FILE *infile = popen((const char *)cmd, "w");
    if (infile == NULL) {
	cerr << "Could not open compression output filter." << endl;
	return NULL;
    }

    return infile;
}

FILE *
decompress_stdin()
{
    String cmd = "gzip -cdf";	// c: read from stdin, f: ...even if a tty
				// d: decompress
    FILE *infile = popen((const char *)cmd, "r");
    if (infile == NULL) {
	cerr << "Could not open compression output filter." << endl;
	return NULL;
    }

    return infile;
}

#ifdef TEST_CGI_UTIL

int
main(int argc, char *argv[])
{
    // test ErrMsgT
    ErrMsgT("Error");
    String smsg = "String Error";
    ErrMsgT(smsg);
    char *cmsg = "char * error";
    ErrMsgT(cmsg);
    ErrMsgT("");
    ErrMsgT(NULL);

    // test fmakeword
    FILE *in = fopen("./cgi-util-tests/fmakeword.input", "r");
    char stop = ' ';
    int content_len = 68;
    while (content_len) {
	char *word = fmakeword(in, stop, &content_len);
	cout << "Word: " << word << endl;
	delete word;
    }
    fclose(in);

    // this tests buffer extension in fmakeword, two words are 1111 and 11111
    // char respectively.
    in = fopen("./cgi-util-tests/fmakeword2.input", "r");
    stop = ' ';
    content_len = 12467;
    while (content_len) {
	char *word = fmakeword(in, stop, &content_len);
	cout << "Word: " << word << endl;
	delete word;
    }
    fclose(in);

    // test name_path
    char *name_path_p;
    char *name = "stuff";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = "stuff.Z";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = "/usr/local/src/stuff.Z";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = "/usr/local/src/stuff.tar.Z";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = "/usr/local/src/stuff";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = "";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = 0;
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    // Test mime header generators and compressed output

    cout << "MIME text header:" << endl;
    set_mime_text(dods_das);

    cout << "MIME binary header:" << endl;
    set_mime_binary(dods_data);
    cout << "Some data..." << endl;

    cout << "MIME binary header and compressed data:" << endl;
    set_mime_binary(dods_data, x_gzip);
    FILE *out = compress_stdout();
    fprintf(out, "Compresses data...\n");
    fflush(out);
    pclose(out);
}

#endif

<commit_msg>Modified so that the compress/decompress functions use the DODS_ROOT enviroment-variable/define or the user's PATH to find gzip.<commit_after>
// (c) COPYRIGHT URI/MIT 1994-1996
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
//      jhrg,jimg       James Gallagher (jgallagher@gso.uri.edu)
//      reza            Reza Nekovei (reza@intcomm.net)

// A few useful routines which are used in CGI programs.
//
// ReZa 9/30/94

// $Log: cgi_util.cc,v $
// Revision 1.15  1996/06/18 23:48:46  jimg
// Modified so that the compress/decompress functions use the DODS_ROOT
// enviroment-variable/define or the user's PATH to find gzip.
//
// Revision 1.14  1996/06/08 00:16:42  jimg
// Fixed a bug in name_path().
// Added compression functions which create filter processes which automatically
// compress stdio file streams.
// Added to set_mime_text() and set_mime_binary() support for compression. These
// now correctly set the content-encoding field of the mime header.
// Fixed ErrMsgT so that it says `DODS server' when the name of the server is
// not known.
//
// Revision 1.13  1996/06/04 21:33:53  jimg
// Multiple connections are now possible. It is now possible to open several
// URLs at the same time and read from them in a round-robin fashion. To do
// this I added data source and sink parameters to the serialize and
// deserialize mfuncs. Connect was also modified so that it manages the data
// source `object' (which is just an XDR pointer).
//
// Revision 1.12  1996/05/31 23:30:46  jimg
// Updated copyright notice.
//
// Revision 1.11  1996/05/21 23:52:42  jimg
// Changed include netio.h to cgi_util.h.
//
// Revision 1.10  1996/03/05 23:22:06  jimg
// Addedconst to the char * function definitions.
//
// Revision 1.9  1995/07/09  21:20:42  jimg
// Fixed date in copyright (it now reads `Copyright 1995 ...').
//
// Revision 1.8  1995/07/09  21:14:43  jimg
// Added copyright.
//
// Revision 1.7  1995/06/27  17:38:43  jimg
// Modified the cgi-util-test code so that it correctly uses name_path(); the
// pointer returned by that function must be delteted.
//
// Revision 1.6  1995/05/30  18:28:59  jimg
// Added const to ErrMsgT prototype.
//
// Revision 1.5  1995/05/22  20:36:10  jimg
// Added #include "config_netio.h"
// Removed old code.
//
// Revision 1.4  1995/03/16  16:29:24  reza
// Fixed bugs in ErrMsgT and mime type.
//
// Revision 1.3  1995/02/22  21:03:59  reza
// Added version number capability using CGI status_line.
//
// Revision 1.2  1995/02/22  19:53:32  jimg
// Fixed usage of time functions in ErrMsgT; use ctime instead of localtime
// and asctime.
// Fixed TimStr bug in ErrMsgT.
// Fixed dynamic memory bugs in name_path and fmakeword.
// Replaced malloc calls with calls to new char[]; C++ code will expect to
// be able to use delete.
// Fixed memory overrun error in fmakeword.
// Fixed potential bug in name_path (when called with null argument).
// Added assetions.
//
// Revision 1.1  1995/01/10  16:23:01  jimg
// Created new `common code' library for the net I/O stuff.
//
// Revision 1.1  1994/10/28  14:34:01  reza
// First version

static char rcsid[]={"$Id: cgi_util.cc,v 1.15 1996/06/18 23:48:46 jimg Exp $"};

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>

#include <iostream.h>
#include <String.h>

#include "config_dap.h"
#include "cgi_util.h"

#ifdef TRACE_NEW
#include "trace_new.h"
#endif

#ifndef FILE_DELIMITER		// default to unix
#define FILE_DELIMITER '/'
#endif

static const char *dods_root = getenv("DODS_ROOT") ? getenv("DODS_ROOT")
    : DODS_ROOT;

static const int TimLen = 26;	// length of string from asctime()
static const int CLUMP_SIZE = 1024; // size of clumps to new in fmakeword()

// An error handling routine to append the error messege from CGI programs,
// a time stamp, and the client host name (or address) to HTTPD error-log.
// Use this instead of the functions in liberrmsg.a in the programs run by
// the CGIs to report errors so those errors show up in HTTPD's log files.
//
// Returns: void

void
ErrMsgT(const char *Msgt)
{
    time_t TimBin;
    char TimStr[TimLen];

    if (time(&TimBin) == (time_t)-1)
	strcpy(TimStr, "time() error           ");
    else {
	strcpy(TimStr, ctime(&TimBin));
	TimStr[TimLen - 2] = '\0'; // overwrite the \n
    }

    char *host_or_addr = getenv("REMOTE_HOST") ? getenv("REMOTE_HOST") :
	getenv("REMOTE_ADDR");
    char *script = getenv("SCRIPT_NAME") ? getenv("SCRIPT_NAME") :
	"DODS server";

    cerr << "[" << TimStr << "] CGI: " << script << " faild for "
	 << host_or_addr << " reason: "<< Msgt << endl;
}

// Given an open FILE *IN, a separator character (in STOP) and the number of
// characters in the thing referenced by IN, return characters upto the
// STOP. The STOP character itself is discarded. Memory for the new word is
// dynamically allocated using C++'s new facility. In addition, the count of
// characters in the input source (CL; content length) is decremented.
//
// Once CL is zero, do not continue calling this function!
//
// Returns: a newly allocated string.

char *
fmakeword(FILE *f, const char stop, int *cl)
{
    assert(f && stop && *cl);

    int wsize = CLUMP_SIZE;
    int ll = 0;
    char *word = new char[wsize + 1];

    while(1) {
	assert(ll <= wsize);

        word[ll] = (char)fgetc(f);

	// If the word size is exceeded, allocate more space. What a kluge.
        if(ll == wsize) {
            wsize += CLUMP_SIZE;
	    char *tmp_word_buf = new char[wsize + 1];
	    memcpy(tmp_word_buf, word, wsize - (CLUMP_SIZE - 1));
	    delete word;
	    word = tmp_word_buf;
	}

        --(*cl);

        if((word[ll] == stop) || (feof(f)) || (!(*cl))) {
            if(word[ll] != stop)
		ll++;
	    assert(ll <= wsize);
            word[ll] = '\0';
            return word;
	}

        ++ll;
    }
}

// Given a pathname, return just the filename component with any extension
// removed. The new string resides in newly allocated memory; the caller must
// delete it when done using the filename.
// Originally from the netcdf distribution (ver 2.3.2).
//
// *** Change to String class argument and return type. jhrg
//
// Returns: A filename, with path and extension information removed. If
// memory for the new name cannot be allocated, does not return!

char *
name_path(const char *path)
{
    if (!path)
	return NULL;

    char *cp = strrchr(path, FILE_DELIMITER);
    if (cp == 0)                // no delimiter
	cp = (char *)path;
    else                        // skip delimeter
	cp++;

    char *newp = new char[strlen(cp)+1];

    (void) strcpy(newp, cp);	// copy last component of path
    if ((cp = strrchr(newp, '.')) != NULL)
      *cp = '\0';               /* strip off any extension */

    return newp;
}

// Send string to set the transfer (mime) type and server version
// Note that the content description filed is used to indicate whether valid
// information of an error message is contained in the document and the
// content-encoding field is used to indicate whether the data is compressed.
// If the data stream is to be compressed, arrange for a compression output
// filter so that all information sent after the header will be compressed.
//
// Returns: false if the compression output filter was to be used but could
// not be started, true otherwise.

static char *descrip[]={"unknown", "dods_das", "dods_dds", "dods_data",
			"dods_error"};
static char *encoding[]={"unknown", "x-plain", "x-gzip"};

void
set_mime_text(ObjectType type = unknown_type, EncodingType enc = x_plain)
{
    cout << "Status: 200 " << DVR << endl; // Send server version
    cout << "Content-type: text/plain" << endl;
    cout << "Content-Description: " << descrip[type] << endl;
    cout << "Content-Encoding: " << encoding[enc] << endl;
    cout << endl;			// MIME header ends with a blank line
}

void
set_mime_binary(ObjectType type = unknown_type, EncodingType enc = x_plain)
{
    cout << "Status: 200 " << DVR << endl;
    cout << "Content-type: application/octet-stream" << endl;
    cout << "Content-Description: " << descrip[type] << endl;
    cout << "Content-Encoding: " << encoding[enc] << endl;
    cout << endl;		// MIME header ends with a blank line
}

// Open a pipe to a filter process which will compress this process' stdout.
//
// NB: You must use pclose to close the FILE *.
//
// Returns: false if the pipe or child process could not be created, true
// otherwise.

FILE *
compress_stdout()
{
    String cmd = "gzip -cf";	// c: write to stdout, f: ...even if a tty
    String path = (String)dods_root + "/etc/" + cmd;

    // First try to find gzip at DODS_ROOT/etc. If that fials use the user's
    // PATH.
    FILE *infile = popen((const char *)path, "w");
    if (!infile) {
	infile = popen((const char *)cmd, "w");
	if (infile == NULL) {
	    cerr << "Could not open compression output filter." << endl;
	    return NULL;
	}
    }

    return infile;
}

// NB: the Connect class does not use this.

FILE *
decompress_stdin()
{
    String cmd = "gzip -cdf";	// c: read from stdin, f: ...even if a tty
				// d: decompress
    String path = (String)dods_root + "/etc/" + cmd;

    // First try to find gzip at DODS_ROOT/etc. If that fials use the user's
    // PATH.
    FILE *infile = popen((const char *)path, "r");
    if (!infile) {
	infile = popen((const char *)cmd, "r");
	if (infile == NULL) {
	    cerr << "Could not open compression input filter." << endl;
	    return NULL;
	}
    }

    return infile;
}

#ifdef TEST_CGI_UTIL

int
main(int argc, char *argv[])
{
    // test ErrMsgT
    ErrMsgT("Error");
    String smsg = "String Error";
    ErrMsgT(smsg);
    char *cmsg = "char * error";
    ErrMsgT(cmsg);
    ErrMsgT("");
    ErrMsgT(NULL);

    // test fmakeword
    FILE *in = fopen("./cgi-util-tests/fmakeword.input", "r");
    char stop = ' ';
    int content_len = 68;
    while (content_len) {
	char *word = fmakeword(in, stop, &content_len);
	cout << "Word: " << word << endl;
	delete word;
    }
    fclose(in);

    // this tests buffer extension in fmakeword, two words are 1111 and 11111
    // char respectively.
    in = fopen("./cgi-util-tests/fmakeword2.input", "r");
    stop = ' ';
    content_len = 12467;
    while (content_len) {
	char *word = fmakeword(in, stop, &content_len);
	cout << "Word: " << word << endl;
	delete word;
    }
    fclose(in);

    // test name_path
    char *name_path_p;
    char *name = "stuff";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = "stuff.Z";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = "/usr/local/src/stuff.Z";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = "/usr/local/src/stuff.tar.Z";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = "/usr/local/src/stuff";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = "";
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    name = 0;
    name_path_p = name_path(name);
    cout << name << ": " << name_path_p << endl;
    delete name_path_p;

    // Test mime header generators and compressed output

    cout << "MIME text header:" << endl;
    set_mime_text(dods_das);

    cout << "MIME binary header:" << endl;
    set_mime_binary(dods_data);
    cout << "Some data..." << endl;

    cout << "MIME binary header and compressed data:" << endl;
    set_mime_binary(dods_data, x_gzip);
    FILE *out = compress_stdout();
    fprintf(out, "Compresses data...\n");
    fflush(out);
    pclose(out);
}

#endif

<|endoftext|>


<commit_before>// Arguments: Doubles, Doubles, Doubles
#include <stan/math/prim.hpp>

using stan::math::square;
using stan::math::var;
using std::numeric_limits;
using std::vector;

class AgradCdfLogNormal : public AgradCdfLogTest {
 public:
  void valid_values(vector<vector<double> >& parameters,
                    vector<double>& cdf_log) {
    vector<double> param(3);

    param[0] = 0;  // y
    param[1] = 0;  // mu
    param[2] = 1;  // sigma
    parameters.push_back(param);
    cdf_log.push_back(-0.6931471805599452862268);  // expected cdf_log

    param[0] = 1;  // y
    param[1] = 0;  // mu
    param[2] = 1;  // sigma
    parameters.push_back(param);
    cdf_log.push_back(-0.1727537790234499326392);  // expected cdf_log

    param[0] = -2;  // y
    param[1] = 0;   // mu
    param[2] = 1.5;   // sigma
    parameters.push_back(param);
    cdf_log.push_back(-2.3945773661586438052);  // expected cdf_log

    param[0] = -3.5;  // y
    param[1] = 1.9;   // mu
    param[2] = 7.2;   // sigma
    parameters.push_back(param);
    cdf_log.push_back(-1.484448229919656192521);  // expected cdf_log

    param[0] = 7.5;  // y
    param[1] = 0;    // mu
    param[2] = 1;    // sigma
    parameters.push_back(param);
    cdf_log.push_back(-3.1908916729109475e-14);  // expected cdf_log
  }

  void invalid_values(vector<size_t>& index, vector<double>& value) {
    // y

    // mu
    index.push_back(1U);
    value.push_back(numeric_limits<double>::infinity());

    index.push_back(1U);
    value.push_back(-numeric_limits<double>::infinity());

    // sigma
    index.push_back(2U);
    value.push_back(0.0);

    index.push_back(2U);
    value.push_back(-1.0);

    index.push_back(2U);
    value.push_back(-numeric_limits<double>::infinity());
  }

  bool has_lower_bound() { return false; }

  bool has_upper_bound() { return false; }

  template <typename T_y, typename T_loc, typename T_scale, typename T3,
            typename T4, typename T5>
  stan::return_type_t<T_y, T_loc, T_scale> cdf_log(const T_y& y,
                                                   const T_loc& mu,
                                                   const T_scale& sigma,
                                                   const T3&, const T4&,
                                                   const T5&) {
    return stan::math::normal_cdf_log(y, mu, sigma);
  }

  template <typename T_y, typename T_loc, typename T_scale, typename T3,
            typename T4, typename T5>
  stan::return_type_t<T_y, T_loc, T_scale> cdf_log_function(
      const T_y& y, const T_loc& mu, const T_scale& sigma, const T3&, const T4&,
      const T5&) {
    using stan::math::LOG_HALF;
    using stan::math::SQRT_PI;
    using stan::math::SQRT_TWO;
    using std::exp;
    using std::log;
    using std::log1p;
    using std::pow;

    stan::return_type_t<T_y, T_loc, T_scale> cdf_log(0.0);

    // define constants used in numerical approximation of log(CDF) for x<-20
    stan::return_type_t<T_y, T_loc, T_scale> p[6]
        = {-0.000658749161529837803157, -0.0160837851487422766278,
           -0.125781726111229246204,    -0.360344899949804439429,
           -0.305326634961232344035,    -0.0163153871373020978498};
    stan::return_type_t<T_y, T_loc, T_scale> q[6]
        = {0.00233520497626869185443, 0.0605183413124413191178,
           0.527905102951428412248,   1.87295284992346047209,
           2.56852019228982242072,    1.0};
    stan::return_type_t<T_y, T_loc, T_scale> scaled_diff(0.0);
    scaled_diff += (y - mu) / (sigma * SQRT_TWO);
    stan::return_type_t<T_y, T_loc, T_scale> sigma2pi(0.0);
    sigma2pi += sigma * SQRT_TWO;

    // use erfc() instead of erf() in order to retain precision since for x>0
    // erfc()->0
    if (scaled_diff > 0.0) {
      // CDF(x) = 1/2 + 1/2erf(x) = 1 - 1/2erfc(x)
      cdf_log += log1p(-0.5 * erfc(scaled_diff));
    } else if (scaled_diff > -20.0) {
      // CDF(x) = 1/2 - 1/2erf(-x) = 1/2erfc(-x)
      cdf_log += log(erfc(-scaled_diff)) + LOG_HALF;
    } else {
      // check whether scaled_diff^10 term will overflow
      if (10.0 * log(-scaled_diff) < log(std::numeric_limits<double>::max())) {
        // entering territory where erfc(-x)~0
        // need to use direct numerical approximation of cdf_log instead
        // the following based on W. J. Cody, Math. Comp. 23(107):631-638 (1969)
        // CDF(x) = 1/2erfc(-x)
        stan::return_type_t<T_y, T_loc, T_scale> temp_p = 0.0;
        stan::return_type_t<T_y, T_loc, T_scale> temp_q = 0.0;
        stan::return_type_t<T_y, T_loc, T_scale> x2 = square(scaled_diff);
        stan::return_type_t<T_y, T_loc, T_scale> pow_x = 0.0;
        for (int j = 0; j < 6; j++) {
          pow_x = pow(scaled_diff, -2 * j);
          temp_p = temp_p - p[j] * pow_x;
          temp_q = temp_q - q[j] * pow_x;
        }
        cdf_log += log(0.5) + log(1.0 / SQRT_PI + (temp_p / temp_q) / x2)
                   - log(-scaled_diff) - x2;
      } else {
        cdf_log += stan::math::negative_infinity();
      }
    }
    return cdf_log;
  }
};
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.1-14 (tags/RELEASE_601/final)<commit_after>// Arguments: Doubles, Doubles, Doubles
#include <stan/math/prim.hpp>

using stan::math::square;
using stan::math::var;
using std::numeric_limits;
using std::vector;

class AgradCdfLogNormal : public AgradCdfLogTest {
 public:
  void valid_values(vector<vector<double> >& parameters,
                    vector<double>& cdf_log) {
    vector<double> param(3);

    param[0] = 0;  // y
    param[1] = 0;  // mu
    param[2] = 1;  // sigma
    parameters.push_back(param);
    cdf_log.push_back(-0.6931471805599452862268);  // expected cdf_log

    param[0] = 1;  // y
    param[1] = 0;  // mu
    param[2] = 1;  // sigma
    parameters.push_back(param);
    cdf_log.push_back(-0.1727537790234499326392);  // expected cdf_log

    param[0] = -2;   // y
    param[1] = 0;    // mu
    param[2] = 1.5;  // sigma
    parameters.push_back(param);
    cdf_log.push_back(-2.3945773661586438052);  // expected cdf_log

    param[0] = -3.5;  // y
    param[1] = 1.9;   // mu
    param[2] = 7.2;   // sigma
    parameters.push_back(param);
    cdf_log.push_back(-1.484448229919656192521);  // expected cdf_log

    param[0] = 7.5;  // y
    param[1] = 0;    // mu
    param[2] = 1;    // sigma
    parameters.push_back(param);
    cdf_log.push_back(-3.1908916729109475e-14);  // expected cdf_log
  }

  void invalid_values(vector<size_t>& index, vector<double>& value) {
    // y

    // mu
    index.push_back(1U);
    value.push_back(numeric_limits<double>::infinity());

    index.push_back(1U);
    value.push_back(-numeric_limits<double>::infinity());

    // sigma
    index.push_back(2U);
    value.push_back(0.0);

    index.push_back(2U);
    value.push_back(-1.0);

    index.push_back(2U);
    value.push_back(-numeric_limits<double>::infinity());
  }

  bool has_lower_bound() { return false; }

  bool has_upper_bound() { return false; }

  template <typename T_y, typename T_loc, typename T_scale, typename T3,
            typename T4, typename T5>
  stan::return_type_t<T_y, T_loc, T_scale> cdf_log(const T_y& y,
                                                   const T_loc& mu,
                                                   const T_scale& sigma,
                                                   const T3&, const T4&,
                                                   const T5&) {
    return stan::math::normal_cdf_log(y, mu, sigma);
  }

  template <typename T_y, typename T_loc, typename T_scale, typename T3,
            typename T4, typename T5>
  stan::return_type_t<T_y, T_loc, T_scale> cdf_log_function(
      const T_y& y, const T_loc& mu, const T_scale& sigma, const T3&, const T4&,
      const T5&) {
    using stan::math::LOG_HALF;
    using stan::math::SQRT_PI;
    using stan::math::SQRT_TWO;
    using std::exp;
    using std::log;
    using std::log1p;
    using std::pow;

    stan::return_type_t<T_y, T_loc, T_scale> cdf_log(0.0);

    // define constants used in numerical approximation of log(CDF) for x<-20
    stan::return_type_t<T_y, T_loc, T_scale> p[6]
        = {-0.000658749161529837803157, -0.0160837851487422766278,
           -0.125781726111229246204,    -0.360344899949804439429,
           -0.305326634961232344035,    -0.0163153871373020978498};
    stan::return_type_t<T_y, T_loc, T_scale> q[6]
        = {0.00233520497626869185443, 0.0605183413124413191178,
           0.527905102951428412248,   1.87295284992346047209,
           2.56852019228982242072,    1.0};
    stan::return_type_t<T_y, T_loc, T_scale> scaled_diff(0.0);
    scaled_diff += (y - mu) / (sigma * SQRT_TWO);
    stan::return_type_t<T_y, T_loc, T_scale> sigma2pi(0.0);
    sigma2pi += sigma * SQRT_TWO;

    // use erfc() instead of erf() in order to retain precision since for x>0
    // erfc()->0
    if (scaled_diff > 0.0) {
      // CDF(x) = 1/2 + 1/2erf(x) = 1 - 1/2erfc(x)
      cdf_log += log1p(-0.5 * erfc(scaled_diff));
    } else if (scaled_diff > -20.0) {
      // CDF(x) = 1/2 - 1/2erf(-x) = 1/2erfc(-x)
      cdf_log += log(erfc(-scaled_diff)) + LOG_HALF;
    } else {
      // check whether scaled_diff^10 term will overflow
      if (10.0 * log(-scaled_diff) < log(std::numeric_limits<double>::max())) {
        // entering territory where erfc(-x)~0
        // need to use direct numerical approximation of cdf_log instead
        // the following based on W. J. Cody, Math. Comp. 23(107):631-638 (1969)
        // CDF(x) = 1/2erfc(-x)
        stan::return_type_t<T_y, T_loc, T_scale> temp_p = 0.0;
        stan::return_type_t<T_y, T_loc, T_scale> temp_q = 0.0;
        stan::return_type_t<T_y, T_loc, T_scale> x2 = square(scaled_diff);
        stan::return_type_t<T_y, T_loc, T_scale> pow_x = 0.0;
        for (int j = 0; j < 6; j++) {
          pow_x = pow(scaled_diff, -2 * j);
          temp_p = temp_p - p[j] * pow_x;
          temp_q = temp_q - q[j] * pow_x;
        }
        cdf_log += log(0.5) + log(1.0 / SQRT_PI + (temp_p / temp_q) / x2)
                   - log(-scaled_diff) - x2;
      } else {
        cdf_log += stan::math::negative_infinity();
      }
    }
    return cdf_log;
  }
};
<|endoftext|>


<commit_before>#include <qlayout.h>
#include <qlabel.h>
#include <qcombobox.h>
#include <kdialog.h>
#include <kdebug.h>
#include <klineedit.h>
#include "incsearchwidget.h"

IncSearchWidget::IncSearchWidget(QWidget *parent, const char* /*name*/)
    : IncSearchWidgetBase(parent, "kde toolbar widget")
{
    // style the label too
    labelIncSearch->setName("kde toolbar widget");
    layout()->setMargin(KDialog::marginHint());
    layout()->setSpacing(KDialog::spacingHint());
    connect(leIncSearch, SIGNAL(textChanged(const QString&)),
            SLOT(incSearchTextChanged(const QString&)));
    connect(leIncSearch, SIGNAL(returnPressed()),
            SLOT(incSearchTextReturnPressed()));
    connect(cbIncSearch, SIGNAL(activated(const QString&)),
            SLOT(incSearchComboActivated(const QString&)));
}

IncSearchWidget::~IncSearchWidget()
{
}

void IncSearchWidget::incSearchTextChanged(const QString&)
{
    announce();
}

void IncSearchWidget::incSearchTextReturnPressed()
{
    announce();
}

void IncSearchWidget::incSearchComboActivated(const QString&)
{
    announce();
}

void IncSearchWidget::announce()
{
    kdDebug() << "IncSearchWidget::announce: looking up "
              << leIncSearch->text() << " in "
              << cbIncSearch->currentItem() << endl;
    emit(incSearch(leIncSearch->text(), cbIncSearch->currentItem()));
}

void IncSearchWidget::setFields(const QStringList& fields)
{
    cbIncSearch->clear();
    cbIncSearch->insertStringList(fields);
}

#include "incsearchwidget.moc"
<commit_msg>- updated Galliums changes in the toolbar style, then resolved the   commit conflicts because he did it as well and now committing, this   should solve the different tool bar sizes as well as the non-styled   widgets in the toolbars --Mirko.<commit_after>#include <qlayout.h>
#include <qcombobox.h>
#include <qlabel.h>
#include <kdialog.h>
#include <kdebug.h>
#include <klineedit.h>
#include "incsearchwidget.h"

IncSearchWidget::IncSearchWidget(QWidget *parent, const char* /*name*/)
    : IncSearchWidgetBase(parent, "kde toolbar widget")
{
    setName("kde toolbar widget");
    labelIncSearch->setName("kde toolbar widget");
    layout()->setMargin(0);
    layout()->setSpacing(KDialog::spacingHint());
    connect(leIncSearch, SIGNAL(textChanged(const QString&)),
            SLOT(incSearchTextChanged(const QString&)));
    connect(leIncSearch, SIGNAL(returnPressed()),
            SLOT(incSearchTextReturnPressed()));
    connect(cbIncSearch, SIGNAL(activated(const QString&)),
            SLOT(incSearchComboActivated(const QString&)));
}

IncSearchWidget::~IncSearchWidget()
{
}

void IncSearchWidget::incSearchTextChanged(const QString&)
{
    announce();
}

void IncSearchWidget::incSearchTextReturnPressed()
{
    announce();
}

void IncSearchWidget::incSearchComboActivated(const QString&)
{
    announce();
}

void IncSearchWidget::announce()
{
    kdDebug() << "IncSearchWidget::announce: looking up "
              << leIncSearch->text() << " in "
              << cbIncSearch->currentItem() << endl;
    emit(incSearch(leIncSearch->text(), cbIncSearch->currentItem()));
}

void IncSearchWidget::setFields(const QStringList& fields)
{
    cbIncSearch->clear();
    cbIncSearch->insertStringList(fields);
}

#include "incsearchwidget.moc"
<|endoftext|>


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

#include "NoteNodeChange.h"

#include "../nodes/Node.h"

namespace Model {

NoteNodeChange::NoteNodeChange(QSet<Node*>& modifiedTargets, QSet<Node*>& removedTargets, const UndoCommand* command)
	: UndoCommand{nullptr, "Note node changes"}, modifiedTargets_{modifiedTargets}, removedTargets_{removedTargets},
	  target_{command->target()}, insertedNode_{command->insertedNode()}, removedNode_{command->removedNode()}
{
}

void NoteNodeChange::redo()
{
	if ( target_ ) modifiedTargets_.insert(target_);
	if ( insertedNode_ ) unmarkRemovals(insertedNode_);
	if ( removedNode_  ) markNodeAndChildrenAsRemoved( removedNode_ );
	UndoCommand::redo();
}

void NoteNodeChange::undo()
{
	if ( target_ ) modifiedTargets_.insert(target_);
	if ( removedNode_ ) unmarkRemovals(removedNode_);
	if ( insertedNode_ ) markNodeAndChildrenAsRemoved( insertedNode_ );
	UndoCommand::undo();
}

void NoteNodeChange::markNodeAndChildrenAsRemoved(Node* node) const
{
	QList<Node*> stack {node};
	while (!stack.isEmpty())
	{
		Node* child = stack.takeLast();
		removedTargets_.insert(child);
		stack.append( child->children() );
	}
}

void NoteNodeChange::unmarkRemovals(Node*) const
{
}

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

#include "NoteNodeChange.h"

#include "../nodes/Node.h"

namespace Model {

NoteNodeChange::NoteNodeChange(QSet<Node*>& modifiedTargets, QSet<Node*>& removedTargets, const UndoCommand* command)
	: UndoCommand{nullptr, "Note node changes"}, modifiedTargets_{modifiedTargets}, removedTargets_{removedTargets},
		target_{command->target() && command->target()->manager() ? command->target() : nullptr},
		insertedNode_{command->insertedNode()}, removedNode_{command->removedNode()}
{
}

void NoteNodeChange::redo()
{
	if ( target_ ) modifiedTargets_.insert(target_);
	if ( insertedNode_ ) unmarkRemovals(insertedNode_);
	if ( removedNode_  ) markNodeAndChildrenAsRemoved( removedNode_ );
	UndoCommand::redo();
}

void NoteNodeChange::undo()
{
	if ( target_ ) modifiedTargets_.insert(target_);
	if ( removedNode_ ) unmarkRemovals(removedNode_);
	if ( insertedNode_ ) markNodeAndChildrenAsRemoved( insertedNode_ );
	UndoCommand::undo();
}

void NoteNodeChange::markNodeAndChildrenAsRemoved(Node* node) const
{
	QList<Node*> stack {node};
	while (!stack.isEmpty())
	{
		Node* child = stack.takeLast();
		removedTargets_.insert(child);
		stack.append( child->children() );
	}
}

void NoteNodeChange::unmarkRemovals(Node*) const
{
}

}
<|endoftext|>


<commit_before>/******************************************************************************\
* Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.               *
* Leap Motion proprietary and confidential. Not for distribution.              *
* Use subject to the terms of the Leap Motion SDK Agreement available at       *
* https://developer.leapmotion.com/sdk_agreement, or another agreement         *
* between Leap Motion and you, your company or other organization.             *
\******************************************************************************/

#include <iostream>
#include <string.h>
#include "Leap.h"

using namespace Leap;

int seconds = 0;
int cnt_A = 0;

class SampleListener : public Listener {
  public:
    virtual void onInit(const Controller&);
    virtual void onConnect(const Controller&);
    virtual void onDisconnect(const Controller&);
    virtual void onExit(const Controller&);
    virtual void onFrame(const Controller&);
    virtual void onFocusGained(const Controller&);
    virtual void onFocusLost(const Controller&);
    virtual void onDeviceChange(const Controller&);
    virtual void onServiceConnect(const Controller&);
    virtual void onServiceDisconnect(const Controller&);

  private:

};

const std::string fingerNames[] = {"Thumb", "Index", "Middle", "Ring", "Pinky"};
const std::string boneNames[] = {"Metacarpal", "Proximal", "Middle", "Distal"};
const std::string stateNames[] = {"STATE_INVALID", "STATE_START", "STATE_UPDATE", "STATE_END"};

void SampleListener::onInit(const Controller& controller) {
  std::cout << "Initialized" << std::endl;
}

void SampleListener::onConnect(const Controller& controller) {
  std::cout << "Connected" << std::endl;
  controller.enableGesture(Gesture::TYPE_CIRCLE);
  controller.enableGesture(Gesture::TYPE_KEY_TAP);
  controller.enableGesture(Gesture::TYPE_SCREEN_TAP);
  controller.enableGesture(Gesture::TYPE_SWIPE);
}

void SampleListener::onDisconnect(const Controller& controller) {
  // Note: not dispatched when running in a debugger.
  std::cout << "Disconnected" << std::endl;
}

void SampleListener::onExit(const Controller& controller) {
  std::cout << "Exited" << std::endl;
}

void SampleListener::onFrame(const Controller& controller) {
	seconds ++;
	seconds = seconds % 20;
  // Get the most recent frame and report some basic information
  const Frame frame = controller.frame();
  /*
  std::cout << ", hands: " << frame.hands().count()
            << ", extended fingers: " << frame.fingers().extended().count();
			*/
  HandList hands = frame.hands();

  for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) {
    // Get the first hand
    const Hand hand = *hl;
	/*
    std::string handType = hand.isLeft() ? "Left hand" : "Right hand";
    std::cout << std::string(2, ' ') << handType << ", id: " << hand.id()
              << ", palm position: " << hand.palmPosition() << std::endl;
			  */
    // Get the hand's normal vector and direction
    const Vector normal = hand.palmNormal();
    const Vector direction = hand.direction();

	/*
    // Calculate the hand's pitch, roll, and yaw angles
    std::cout << std::string(2, ' ') <<  "pitch: " << direction.pitch() * RAD_TO_DEG << " degrees, "
              << "roll: " << normal.roll() * RAD_TO_DEG << " degrees, "
              << "yaw: " << direction.yaw() * RAD_TO_DEG << " degrees" << std::endl;

    // Get the Arm bone
    Arm arm = hand.arm();
    std::cout << std::string(2, ' ') <<  "Arm direction: " << arm.direction()
              << " wrist position: " << arm.wristPosition()
              << " elbow position: " << arm.elbowPosition() << std::endl;
		*/
    // Get fingers
	/*
    const FingerList fingers = hand.fingers();

    for (FingerList::const_iterator fl = fingers.begin(); fl != fingers.end(); ++fl) {
      const Finger finger = *fl;
      std::cout << std::string(4, ' ') <<  fingerNames[finger.type()]
                << ", length: " << finger.length()
                //<< "mm, width: " << finger.width()
				<<"XXXXXXXXXXXXX"<<finger.tipPosition()<< std::endl;
	}}

	*/
  // test code

	const FingerList testFingers = hand.fingers();
	int fingerNumbers[5];
	int cnt = 0;
	for (FingerList::const_iterator fl = testFingers.begin(); fl != testFingers.end(); ++fl) {
		const Finger finger = *fl;
		fingerNumbers[cnt] = finger.tipPosition()[1];
		cnt++;
	}
	/*
	std::cout <<"th" << fingerNumbers[0] << std::endl;
	std::cout << "ind" << fingerNumbers[1] << std::endl;
	std::cout << "mid"<< fingerNumbers[2] << std::endl;
	std::cout << "ring" << fingerNumbers[3] << std::endl;
	std::cout << "pinky" << fingerNumbers[4] << std::endl;
	*/
	if(fingerNumbers[0] - fingerNumbers[1] > 16 ) {
		if(seconds != 0) {
			return;
		}
		cnt_A++;
		std::cout << "NEW LETTER" << std::endl;
		std::cout << "A" << std::endl;
		std::cout << cnt_A << std::endl;
		std::cout << std::endl << std::endl;
	}
  }

	/*
      // Get finger bones
      for (int b = 0; b < 4; ++b) {
        Bone::Type boneType = static_cast<Bone::Type>(b);
        Bone bone = finger.bone(boneType);
        std::cout << std::string(6, ' ') <<  boneNames[boneType]
                  << " bone, start: " << bone.prevJoint()
                  << ", end: " << bone.nextJoint()
                  << ", direction: " << bone.direction() << std::endl;
      }
    }
  }
  /*
  // Get tools
  const ToolList tools = frame.tools();
  for (ToolList::const_iterator tl = tools.begin(); tl != tools.end(); ++tl) {
    const Tool tool = *tl;
    std::cout << std::string(2, ' ') <<  "Tool, id: " << tool.id()
              << ", position: " << tool.tipPosition()
              << ", direction: " << tool.direction() << std::endl;
  }

  // Get gestures
  const GestureList gestures = frame.gestures();
  for (int g = 0; g < gestures.count(); ++g) {
    Gesture gesture = gestures[g];

    switch (gesture.type()) {
      case Gesture::TYPE_CIRCLE:
      {
        CircleGesture circle = gesture;
        std::string clockwiseness;

        if (circle.pointable().direction().angleTo(circle.normal()) <= PI/2) {
          clockwiseness = "clockwise";
        } else {
          clockwiseness = "counterclockwise";
        }

        // Calculate angle swept since last frame
        float sweptAngle = 0;
        if (circle.state() != Gesture::STATE_START) {
          CircleGesture previousUpdate = CircleGesture(controller.frame(1).gesture(circle.id()));
          sweptAngle = (circle.progress() - previousUpdate.progress()) * 2 * PI;
        }
        std::cout << std::string(2, ' ')
                  << "Circle id: " << gesture.id()
                  << ", state: " << stateNames[gesture.state()]
                  << ", progress: " << circle.progress()
                  << ", radius: " << circle.radius()
                  << ", angle " << sweptAngle * RAD_TO_DEG
                  <<  ", " << clockwiseness << std::endl;
        break;
      }
      case Gesture::TYPE_SWIPE:
      {
        SwipeGesture swipe = gesture;
        std::cout << std::string(2, ' ')
          << "Swipe id: " << gesture.id()
          << ", state: " << stateNames[gesture.state()]
          << ", direction: " << swipe.direction()
          << ", speed: " << swipe.speed() << std::endl;
        break;
      }
      case Gesture::TYPE_KEY_TAP:
      {
        KeyTapGesture tap = gesture;
        std::cout << std::string(2, ' ')
          << "Key Tap id: " << gesture.id()
          << ", state: " << stateNames[gesture.state()]
          << ", position: " << tap.position()
          << ", direction: " << tap.direction()<< std::endl;
        break;
      }
      case Gesture::TYPE_SCREEN_TAP:
      {
        ScreenTapGesture screentap = gesture;
        std::cout << std::string(2, ' ')
          << "Screen Tap id: " << gesture.id()
          << ", state: " << stateNames[gesture.state()]
          << ", position: " << screentap.position()
          << ", direction: " << screentap.direction()<< std::endl;
        break;
      }
      default:
        std::cout << std::string(2, ' ')  << "Unknown gesture type." << std::endl;
        break;
    }
  }

  //if (!frame.hands().isEmpty() || !gestures.isEmpty()) {
    //std::cout << std::endl;
  //}
}*/
}
void SampleListener::onFocusGained(const Controller& controller) {
  std::cout << "Focus Gained" << std::endl;
}

void SampleListener::onFocusLost(const Controller& controller) {
  std::cout << "Focus Lost" << std::endl;
}

void SampleListener::onDeviceChange(const Controller& controller) {
  std::cout << "Device Changed" << std::endl;
  const DeviceList devices = controller.devices();

  for (int i = 0; i < devices.count(); ++i) {
    std::cout << "id: " << devices[i].toString() << std::endl;
    std::cout << "  isStreaming: " << (devices[i].isStreaming() ? "true" : "false") << std::endl;
  }
}

void SampleListener::onServiceConnect(const Controller& controller) {
  std::cout << "Service Connected" << std::endl;
}

void SampleListener::onServiceDisconnect(const Controller& controller) {
  std::cout << "Service Disconnected" << std::endl;
}

int main(int argc, char** argv) {
  // Create a sample listener and controller
  SampleListener listener;
  Controller controller;

  // Have the sample listener receive events from the controller
  controller.addListener(listener);

  if (argc > 1 && strcmp(argv[1], "--bg") == 0)
    controller.setPolicy(Leap::Controller::POLICY_BACKGROUND_FRAMES);

  // Keep this process running until Enter is pressed
  std::cout << "Press Enter to quit..." << std::endl;
  std::cin.get();

  // Remove the sample listener when done
  controller.removeListener(listener);

  return 0;
}
<commit_msg>kris min elemnt<commit_after>/******************************************************************************\
* Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.               *
* Leap Motion proprietary and confidential. Not for distribution.              *
* Use subject to the terms of the Leap Motion SDK Agreement available at       *
* https://developer.leapmotion.com/sdk_agreement, or another agreement         *
* between Leap Motion and you, your company or other organization.             *
\******************************************************************************/

#include <iostream>
#include <string.h>
#include "Leap.h"

using namespace Leap;

int seconds = 0;
int cnt_A = 0;
const char  letts[]  = { 'a', 'b' , 'c' , 'd' , 'e' } ;

class SampleListener : public Listener {
  public:
    virtual void onInit(const Controller&);
    virtual void onConnect(const Controller&);
    virtual void onDisconnect(const Controller&);
    virtual void onExit(const Controller&);
    virtual void onFrame(const Controller&);
    virtual void onFocusGained(const Controller&);
    virtual void onFocusLost(const Controller&);
    virtual void onDeviceChange(const Controller&);
    virtual void onServiceConnect(const Controller&);
    virtual void onServiceDisconnect(const Controller&);

  private:
	  char getLetter(int arr[], int size);
};

const std::string fingerNames[] = {"Thumb", "Index", "Middle", "Ring", "Pinky"};
const std::string boneNames[] = {"Metacarpal", "Proximal", "Middle", "Distal"};
const std::string stateNames[] = {"STATE_INVALID", "STATE_START", "STATE_UPDATE", "STATE_END"};

void SampleListener::onInit(const Controller& controller) {
  std::cout << "Initialized" << std::endl;
}

void SampleListener::onConnect(const Controller& controller) {
  std::cout << "Connected" << std::endl;
  controller.enableGesture(Gesture::TYPE_CIRCLE);
  controller.enableGesture(Gesture::TYPE_KEY_TAP);
  controller.enableGesture(Gesture::TYPE_SCREEN_TAP);
  controller.enableGesture(Gesture::TYPE_SWIPE);
}

void SampleListener::onDisconnect(const Controller& controller) {
  // Note: not dispatched when running in a debugger.
  std::cout << "Disconnected" << std::endl;
}

void SampleListener::onExit(const Controller& controller) {
  std::cout << "Exited" << std::endl;
}

char SampleListener::getLetter(int arr[] , int size ) {
	/*

	std::cout <<"th" << arr[0] << std::endl;
	std::cout << "ind" << arr[1] << std::endl;
	std::cout << "mid"<< arr[2] << std::endl;
	std::cout << "ring" << arr[3] << std::endl;
	std::cout << "pinky" << arr[4] << std::endl;

	*/
	int f_pos = -1;
	int min = arr[0];
	int min_index = 0;
	for(int i = 1; i < size; i++) {
		if( min > arr[i] ) {
			min = arr[i];
			min_index = i;

		}
	}
	//std::cout << min_index << std::endl;
	//std::cout << min << std::endl;
	if( min_index + 1 == size ) {
		if(arr[min_index - 1] - arr[min_index] > 30) {
			return letts[min_index];
		}
	}
	else{
		if(arr[min_index +1] - arr[min_index] > 30) {
			return letts[min_index];
		}
	}
	return NULL;
}

void SampleListener::onFrame(const Controller& controller) {
	seconds ++;
	seconds = seconds % 20;
  // Get the most recent frame and report some basic information
  const Frame frame = controller.frame();
  /*
  std::cout << ", hands: " << frame.hands().count()
            << ", extended fingers: " << frame.fingers().extended().count();
			*/
  HandList hands = frame.hands();

  for (HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) {
    // Get the first hand
    const Hand hand = *hl;
	/*
    std::string handType = hand.isLeft() ? "Left hand" : "Right hand";
    std::cout << std::string(2, ' ') << handType << ", id: " << hand.id()
              << ", palm position: " << hand.palmPosition() << std::endl;
			  */
    // Get the hand's normal vector and direction
    const Vector normal = hand.palmNormal();
    const Vector direction = hand.direction();

	/*
    // Calculate the hand's pitch, roll, and yaw angles
    std::cout << std::string(2, ' ') <<  "pitch: " << direction.pitch() * RAD_TO_DEG << " degrees, "
              << "roll: " << normal.roll() * RAD_TO_DEG << " degrees, "
              << "yaw: " << direction.yaw() * RAD_TO_DEG << " degrees" << std::endl;

    // Get the Arm bone
    Arm arm = hand.arm();
    std::cout << std::string(2, ' ') <<  "Arm direction: " << arm.direction()
              << " wrist position: " << arm.wristPosition()
              << " elbow position: " << arm.elbowPosition() << std::endl;
		*/
    // Get fingers
	/*
    const FingerList fingers = hand.fingers();

    for (FingerList::const_iterator fl = fingers.begin(); fl != fingers.end(); ++fl) {
      const Finger finger = *fl;
      std::cout << std::string(4, ' ') <<  fingerNames[finger.type()]
                << ", length: " << finger.length()
                //<< "mm, width: " << finger.width()
				<<"XXXXXXXXXXXXX"<<finger.tipPosition()<< std::endl;
	}}

	*/
  // test code

	const FingerList testFingers = hand.fingers();
	int fingerNumbers[5];
	int cnt = 0;
	for (FingerList::const_iterator fl = testFingers.begin(); fl != testFingers.end(); ++fl) {
		const Finger finger = *fl;
		fingerNumbers[cnt] = finger.tipPosition()[1];
		cnt++;
	}
	/*
	std::cout <<"th" << fingerNumbers[0] << std::endl;
	std::cout << "ind" << fingerNumbers[1] << std::endl;
	std::cout << "mid"<< fingerNumbers[2] << std::endl;
	std::cout << "ring" << fingerNumbers[3] << std::endl;
	std::cout << "pinky" << fingerNumbers[4] << std::endl;
	*/
		if(seconds != 0) {
			return;
		}
		if(getLetter(fingerNumbers , 5 ) == NULL) {
			return;
		}
		std::cout << getLetter(fingerNumbers , 5 );

  }

	/*
      // Get finger bones
      for (int b = 0; b < 4; ++b) {
        Bone::Type boneType = static_cast<Bone::Type>(b);
        Bone bone = finger.bone(boneType);
        std::cout << std::string(6, ' ') <<  boneNames[boneType]
                  << " bone, start: " << bone.prevJoint()
                  << ", end: " << bone.nextJoint()
                  << ", direction: " << bone.direction() << std::endl;
      }
    }
  }
  /*
  // Get tools
  const ToolList tools = frame.tools();
  for (ToolList::const_iterator tl = tools.begin(); tl != tools.end(); ++tl) {
    const Tool tool = *tl;
    std::cout << std::string(2, ' ') <<  "Tool, id: " << tool.id()
              << ", position: " << tool.tipPosition()
              << ", direction: " << tool.direction() << std::endl;
  }

  // Get gestures
  const GestureList gestures = frame.gestures();
  for (int g = 0; g < gestures.count(); ++g) {
    Gesture gesture = gestures[g];

    switch (gesture.type()) {
      case Gesture::TYPE_CIRCLE:
      {
        CircleGesture circle = gesture;
        std::string clockwiseness;

        if (circle.pointable().direction().angleTo(circle.normal()) <= PI/2) {
          clockwiseness = "clockwise";
        } else {
          clockwiseness = "counterclockwise";
        }

        // Calculate angle swept since last frame
        float sweptAngle = 0;
        if (circle.state() != Gesture::STATE_START) {
          CircleGesture previousUpdate = CircleGesture(controller.frame(1).gesture(circle.id()));
          sweptAngle = (circle.progress() - previousUpdate.progress()) * 2 * PI;
        }
        std::cout << std::string(2, ' ')
                  << "Circle id: " << gesture.id()
                  << ", state: " << stateNames[gesture.state()]
                  << ", progress: " << circle.progress()
                  << ", radius: " << circle.radius()
                  << ", angle " << sweptAngle * RAD_TO_DEG
                  <<  ", " << clockwiseness << std::endl;
        break;
      }
      case Gesture::TYPE_SWIPE:
      {
        SwipeGesture swipe = gesture;
        std::cout << std::string(2, ' ')
          << "Swipe id: " << gesture.id()
          << ", state: " << stateNames[gesture.state()]
          << ", direction: " << swipe.direction()
          << ", speed: " << swipe.speed() << std::endl;
        break;
      }
      case Gesture::TYPE_KEY_TAP:
      {
        KeyTapGesture tap = gesture;
        std::cout << std::string(2, ' ')
          << "Key Tap id: " << gesture.id()
          << ", state: " << stateNames[gesture.state()]
          << ", position: " << tap.position()
          << ", direction: " << tap.direction()<< std::endl;
        break;
      }
      case Gesture::TYPE_SCREEN_TAP:
      {
        ScreenTapGesture screentap = gesture;
        std::cout << std::string(2, ' ')
          << "Screen Tap id: " << gesture.id()
          << ", state: " << stateNames[gesture.state()]
          << ", position: " << screentap.position()
          << ", direction: " << screentap.direction()<< std::endl;
        break;
      }
      default:
        std::cout << std::string(2, ' ')  << "Unknown gesture type." << std::endl;
        break;
    }
  }

  //if (!frame.hands().isEmpty() || !gestures.isEmpty()) {
    //std::cout << std::endl;
  //}
}*/
}
void SampleListener::onFocusGained(const Controller& controller) {
  std::cout << "Focus Gained" << std::endl;
}

void SampleListener::onFocusLost(const Controller& controller) {
  std::cout << "Focus Lost" << std::endl;
}

void SampleListener::onDeviceChange(const Controller& controller) {
  std::cout << "Device Changed" << std::endl;
  const DeviceList devices = controller.devices();

  for (int i = 0; i < devices.count(); ++i) {
    std::cout << "id: " << devices[i].toString() << std::endl;
    std::cout << "  isStreaming: " << (devices[i].isStreaming() ? "true" : "false") << std::endl;
  }
}

void SampleListener::onServiceConnect(const Controller& controller) {
  std::cout << "Service Connected" << std::endl;
}

void SampleListener::onServiceDisconnect(const Controller& controller) {
  std::cout << "Service Disconnected" << std::endl;
}

int main(int argc, char** argv) {
  // Create a sample listener and controller
  SampleListener listener;
  Controller controller;

  // Have the sample listener receive events from the controller
  controller.addListener(listener);

  if (argc > 1 && strcmp(argv[1], "--bg") == 0)
    controller.setPolicy(Leap::Controller::POLICY_BACKGROUND_FRAMES);

  // Keep this process running until Enter is pressed
  std::cout << "Press Enter to quit..." << std::endl;
  std::cin.get();

  // Remove the sample listener when done
  controller.removeListener(listener);

  return 0;
}
<|endoftext|>


<commit_before>#ifndef MANIFOLDS_POLYNOMIAL_HH
#define MANIFOLDS_POLYNOMIAL_HH

#include "full_function_defs.hh"
#include "function.hh"
#include <array>
#include <type_traits>
#include <ostream>
#include <iostream>
#include <algorithm>
#include "typename.hh"

namespace manifolds {
// Somewhat confusingly,
// order here refers to the number of coefficients
template <class CoeffType, class Order>
struct Polynomial : Function<int_<6>, 1, 1>,
                    FunctionCommon<Polynomial<CoeffType, Order> > {
  using FunctionCommon<Polynomial>::operator();
  static const int num_coeffs = Order::value;
  static const bool stateless = false;
  static const ComplexOutputBehaviour complex_output =
      is_complex<CoeffType>::value ? AlwaysComplex : SameAsInput;

  template <class Type, std::size_t N>
  Polynomial(std::array<Type, N> t)
      : coeffs(t) {}

  template <class Type, class N> Polynomial(const Polynomial<Type, N> &t) {
    std::copy(t.GetCoeffs().begin(), t.GetCoeffs().end(), coeffs.begin());
  }

  template <class T, class... Ts> auto eval(T t, Ts...) const {
    static_assert(sizeof...(Ts) == 0 || Order::value == 1,
                  "Can only call polynomial "
                  "with multiple arguments when "
                  "polynomial is a constant");
    typename common_type<T, CoeffType>::type result = 0, t2 = t;
    for (auto i = coeffs.rbegin(); i != coeffs.rend(); i++) {
      result = result * t2 + *i;
    }
    return result;
  }

  const auto &GetCoeffs() const { return coeffs; }

  void Print(std::ostream &s) const {
    s << "Polynomial" << Order::value << "(";
    for (int i = 0; i < Order::value; i++) {
      s << coeffs[i];
      if (i != Order::value - 1)
        s << ' ';
    }
    s << ")";
  }

  const auto &operator[](std::size_t i) const { return coeffs[i]; }

private:
  std::array<CoeffType, Order::value> coeffs;
};

template <class> struct is_polynomial : std::false_type {};

template <class C, class O>
struct is_polynomial<Polynomial<C, O> > : std::true_type {};

template <class> struct PolynomialOrder : int_<-1> {};

template <class C, class O> struct PolynomialOrder<Polynomial<C, O> > : O {};

inline Polynomial<long double, int_<1> > operator"" _c(long double x) {
  std::array<long double, 1> a{ { x } };
  return { a };
}

inline Polynomial<long long, int_<1> > operator"" _c(long long unsigned x) {
  std::array<long long, 1> a{ {(long long)x } };
  return { a };
}

template <class... InputTypes> auto GetPolynomial(InputTypes... coeffs) {
  typedef typename std::common_type<InputTypes...>::type coeff_type;
  std::array<coeff_type, sizeof...(InputTypes)> coeff_arr{ { coeff_type(
      coeffs)... } };
  return Polynomial<coeff_type, int_<sizeof...(InputTypes)> >(coeff_arr);
}

template <class T, class C, class U>
bool operator==(const Polynomial<T, C> &p1, const Polynomial<U, C> &p2) {
  return std::equal(p1.GetCoeffs().begin(), p1.GetCoeffs().end(),
                    p2.GetCoeffs().begin(), p2.GetCoeffs().end());
}
}

#endif
<commit_msg>Adding support for evaluating with type combos that don't support std::common_type, such as Matrix and double<commit_after>#ifndef MANIFOLDS_POLYNOMIAL_HH
#define MANIFOLDS_POLYNOMIAL_HH

#include "full_function_defs.hh"
#include "function.hh"
#include <array>
#include <type_traits>
#include <ostream>
#include <iostream>
#include <algorithm>
#include "typename.hh"

namespace manifolds {
// Somewhat confusingly,
// order here refers to the number of coefficients
template <class CoeffType, class Order>
struct Polynomial : Function<int_<6>, 1, 1>,
                    FunctionCommon<Polynomial<CoeffType, Order> > {
  using FunctionCommon<Polynomial>::operator();
  static const int num_coeffs = Order::value;
  static const bool stateless = false;
  static const ComplexOutputBehaviour complex_output =
      is_complex<CoeffType>::value ? AlwaysComplex : SameAsInput;

  template <class Type, std::size_t N>
  Polynomial(std::array<Type, N> t)
      : coeffs(t) {}

  template <class Type, class N> Polynomial(const Polynomial<Type, N> &t) {
    std::copy(t.GetCoeffs().begin(), t.GetCoeffs().end(), coeffs.begin());
  }

    template <class T> auto eval2impl(T t, int_<1>) const {
        return coeffs[Order::value-1];
    }

    template <class T, int i> auto eval2impl(T t, int_<i>) const {
        static const int index = Order::value - i;
        return eval2impl(t, int_<i-1>{}) * t + coeffs[index];
    }

    template <class T, class... Ts> auto eval(T t, Ts...) const {
        static_assert(sizeof...(Ts) == 0 || Order::value == 1,
                      "Can only call polynomial "
                      "with multiple arguments when "
                      "polynomial is a constant");
        return eval2impl(t, int_<Order::value>{});
    }

  const auto &GetCoeffs() const { return coeffs; }

  void Print(std::ostream &s) const {
    s << "Polynomial" << Order::value << "(";
    for (int i = 0; i < Order::value; i++) {
      s << coeffs[i];
      if (i != Order::value - 1)
        s << ' ';
    }
    s << ")";
  }

  const auto &operator[](std::size_t i) const { return coeffs[i]; }

private:
  std::array<CoeffType, Order::value> coeffs;
};

template <class> struct is_polynomial : std::false_type {};

template <class C, class O>
struct is_polynomial<Polynomial<C, O> > : std::true_type {};

template <class> struct PolynomialOrder : int_<-1> {};

template <class C, class O> struct PolynomialOrder<Polynomial<C, O> > : O {};

inline Polynomial<long double, int_<1> > operator"" _c(long double x) {
  std::array<long double, 1> a{ { x } };
  return { a };
}

inline Polynomial<long long, int_<1> > operator"" _c(long long unsigned x) {
  std::array<long long, 1> a{ {(long long)x } };
  return { a };
}

template <class... InputTypes> auto GetPolynomial(InputTypes... coeffs) {
  typedef typename std::common_type<InputTypes...>::type coeff_type;
  std::array<coeff_type, sizeof...(InputTypes)> coeff_arr{ { coeff_type(
      coeffs)... } };
  return Polynomial<coeff_type, int_<sizeof...(InputTypes)> >(coeff_arr);
}

template <class T, class C, class U>
bool operator==(const Polynomial<T, C> &p1, const Polynomial<U, C> &p2) {
  return std::equal(p1.GetCoeffs().begin(), p1.GetCoeffs().end(),
                    p2.GetCoeffs().begin(), p2.GetCoeffs().end());
}
}

#endif
<|endoftext|>


<commit_before>#include <stan/math/rev.hpp>
#include <gtest/gtest.h>
#include <vector>

TEST(MathPrimFun, size_mvt_scalar) {
  using stan::math::size_mvt;

  stan::math::var x1;
  EXPECT_THROW(size_mvt(x1), std::invalid_argument);
}

TEST(MathPrimFun, size_mvt_matrices_vectors) {
  using stan::math::size_mvt;

  stan::math::var_value<Eigen::MatrixXd> x1 = Eigen::MatrixXd(2, 3);
  EXPECT_EQ(1U, size_mvt(x1));

  std::vector<stan::math::var_value<Eigen::MatrixXd>> x2(3);
  EXPECT_EQ(3U, size_mvt(x2));

  std::vector<stan::math::var_value<Eigen::RowVectorXd>> x3(7);
  EXPECT_EQ(7U, size_mvt(x3));

  std::vector<stan::math::var_value<Eigen::VectorXd>> x4(7);
  EXPECT_EQ(7U, size_mvt(x4));
}
<commit_msg>Updated test names (Issue #2101)<commit_after>#include <stan/math/rev.hpp>
#include <gtest/gtest.h>
#include <vector>

TEST(AgradRev, size_mvt_scalar) {
  using stan::math::size_mvt;

  stan::math::var x1;
  EXPECT_THROW(size_mvt(x1), std::invalid_argument);
}

TEST(AgradRev, size_mvt_matrices_vectors) {
  using stan::math::size_mvt;

  stan::math::var_value<Eigen::MatrixXd> x1 = Eigen::MatrixXd(2, 3);
  EXPECT_EQ(1U, size_mvt(x1));

  std::vector<stan::math::var_value<Eigen::MatrixXd>> x2(3);
  EXPECT_EQ(3U, size_mvt(x2));

  std::vector<stan::math::var_value<Eigen::RowVectorXd>> x3(7);
  EXPECT_EQ(7U, size_mvt(x3));

  std::vector<stan::math::var_value<Eigen::VectorXd>> x4(7);
  EXPECT_EQ(7U, size_mvt(x4));
}
<|endoftext|>


<commit_before>#include "realm/realm.h"

#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <csignal>

#include <time.h>
#include <unistd.h>

using namespace Realm;

// Task IDs, some IDs are reserved so start at first available number
enum {
  TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0,
  CHILD_TASK     = Processor::TASK_ID_FIRST_AVAILABLE+1,
};

// each child needs to know how high to count, which reservation to wait
//  on and which to use to signal the next child
struct ChildArgs {
  int iterations;
  bool release_first;
  Reservation acquire_me;
  Reservation release_me;
};

// we're going to use alarm() as a watchdog to detect deadlocks
void sigalrm_handler(int sig)
{
  fprintf(stderr, "HELP!  Alarm triggered - likely deadlock!\n");
  exit(1);
}

void child_task(const void *args, size_t arglen, Processor p)
{
  assert(arglen == sizeof(ChildArgs));
  const ChildArgs& c_args = *(const ChildArgs *)args;

#ifdef DEBUG_CHILDREN
  printf("starting child task on processor " IDFMT "\n", p.id);
#endif

  for(int count = 0; count < c_args.iterations; count++) {
    if(c_args.release_first)
      c_args.release_me.release();

    Event e = c_args.acquire_me.acquire();
#ifdef DEBUG_CHILDREN
    printf("acquire %d of " IDFMT " -> " IDFMT "/%d\n",
	   count, c_args.acquire_me.id, e.id, e.gen);
#endif
    e.wait();

    if(!c_args.release_first)
      c_args.release_me.release();
  }

#ifdef DEBUG_CHILDREN
  printf("ending task on processor " IDFMT "\n", p.id);
#endif
}

static int num_children = 4;
static int num_iterations = 100000;
static int timeout_seconds = 10;

void top_level_task(const void *args, size_t arglen, Processor p)
{
  printf("Realm context switching test - %d children, %d iterations, %ds timeout\n",
	 num_children, num_iterations, timeout_seconds);

  // iterate over all the CPU kinds we can find - test each kind once
  Machine machine = Machine::get_machine();
  std::set<Processor::Kind> seen;
  {
    std::set<Processor> all_processors;
    machine.get_all_processors(all_processors);
    for(std::set<Processor>::const_iterator it = all_processors.begin();
	it != all_processors.end();
	it++) {
      Processor pp = (*it);
      Processor::Kind k = pp.kind();
      if(seen.count(k) > 0) continue;

      printf("testing processor " IDFMT " (kind=%d)\n", pp.id, k);
      seen.insert(k);

      // set the watchdog timeout before we do anything that could get stuck
      alarm(timeout_seconds);

      // we're going to need a reservation per child - all start out acquired
      std::vector<Reservation> rsrvs(num_children);
      for(int i = 0; i < num_children; i++) {
	rsrvs[i] = Reservation::create_reservation();
	Event e = rsrvs[i].acquire();
	// uncontended, so this should be immediate
	assert(!e.exists());
      }

      // create the child tasks
      std::set<Event> finish_events;
      for(int i = 0; i < num_children; i++) {
	ChildArgs c_args;
	c_args.iterations = num_iterations;
	c_args.release_first = (i == (num_children - 1));
	c_args.acquire_me = rsrvs[i];
	c_args.release_me = rsrvs[(i + 1) % num_children];

	finish_events.insert(pp.spawn(CHILD_TASK, &c_args, sizeof(c_args)));
      }

      // now merge them and see how long it takes them to complete
      double t_start = Clock::current_time();
      Event e = Event::merge_events(finish_events);
      e.wait();
      double t_end = Clock::current_time();

      // turn off the watchdog timer
      alarm(0);

      double elapsed = t_end - t_start;
      double ns_per_switch = 1e9 * elapsed / num_iterations / num_children;
      printf("proc " IDFMT " (kind=%d) finished: elapsed=%5.2fs time/switch=%6.0fns\n",
	     pp.id, k, elapsed, ns_per_switch);
    }
  }

  printf("all done!\n");

  sleep(1);
  // shutdown the runtime - this should implicitly wait for the report task to run
  {
    std::set<Processor> all_procs;
    machine.get_all_processors(all_procs);
    for (std::set<Processor>::const_iterator it = all_procs.begin();
          it != all_procs.end(); it++)
    {
      // Damn you C++ and your broken const qualifiers
      Processor handle_copy = *it;
      // Send the kill pill
      handle_copy.spawn(0,NULL,0);
    }
  }
}

int main(int argc, char **argv)
{
  Runtime rt;

  rt.init(&argc, &argv);

  for(int i = 1; i < argc; i++) {
    if(!strcmp(argv[i], "-c")) {
      num_children = atoi(argv[++i]);
      continue;
    }

    if(!strcmp(argv[i], "-i")) {
      num_iterations = atoi(argv[++i]);
      continue;
    }

    if(!strcmp(argv[i], "-t")) {
      timeout_seconds = atoi(argv[++i]);
      continue;
    }
  }

  rt.register_task(TOP_LEVEL_TASK, top_level_task);
  rt.register_task(CHILD_TASK, child_task);

  signal(SIGALRM, sigalrm_handler);

  // Start the machine running
  // Control never returns from this call
  // Note we only run the top level task on one processor
  // You can also run the top level task on all processors or one processor per node
  rt.run(TOP_LEVEL_TASK, Runtime::ONE_TASK_ONLY);

  rt.shutdown();
  return 0;
}
<commit_msg>add a "sleep" test for overlapping (or not) of active threads<commit_after>#include "realm/realm.h"

#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <csignal>

#include <time.h>
#include <unistd.h>

using namespace Realm;

// Task IDs, some IDs are reserved so start at first available number
enum {
  TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0,
  SWITCH_TEST_TASK,
  SLEEP_TEST_TASK,
};

// we're going to use alarm() as a watchdog to detect deadlocks
void sigalrm_handler(int sig)
{
  fprintf(stderr, "HELP!  Alarm triggered - likely deadlock!\n");
  exit(1);
}

// each child needs to know how high to count, which reservation to wait
//  on and which to use to signal the next child
struct SwitchTestArgs {
  int iterations;
  bool release_first;
  Reservation acquire_me;
  Reservation release_me;
};

void switch_task(const void *args, size_t arglen, Processor p)
{
  assert(arglen == sizeof(SwitchTestArgs));
  const SwitchTestArgs& c_args = *(const SwitchTestArgs *)args;

#ifdef DEBUG_CHILDREN
  printf("starting child task on processor " IDFMT "\n", p.id);
#endif

  for(int count = 0; count < c_args.iterations; count++) {
    if(c_args.release_first)
      c_args.release_me.release();

    Event e = c_args.acquire_me.acquire();
#ifdef DEBUG_CHILDREN
    printf("acquire %d of " IDFMT " -> " IDFMT "/%d\n",
	   count, c_args.acquire_me.id, e.id, e.gen);
#endif
    e.wait();

    if(!c_args.release_first)
      c_args.release_me.release();
  }

#ifdef DEBUG_CHILDREN
  printf("ending switch task on processor " IDFMT "\n", p.id);
#endif
}

struct SleepTestArgs {
  int sleep_seconds;
};

void sleep_task(const void *args, size_t arglen, Processor p)
{
  assert(arglen == sizeof(SleepTestArgs));
  const SleepTestArgs& c_args = *(const SleepTestArgs *)args;

#ifdef DEBUG_CHILDREN
  printf("starting sleep task on processor " IDFMT "\n", p.id);
#endif

  sleep(c_args.sleep_seconds);

#ifdef DEBUG_CHILDREN
  printf("ending sleep task on processor " IDFMT "\n", p.id);
#endif
}

static int num_children = 4;
static int num_iterations = 100000;
static int timeout_seconds = 10;
static int sleep_seconds = 2;

void top_level_task(const void *args, size_t arglen, Processor p)
{
  printf("Realm context switching test - %d children, %d iterations, %ds timeout\n",
	 num_children, num_iterations, timeout_seconds);

  // iterate over all the CPU kinds we can find - test each kind once
  Machine machine = Machine::get_machine();
  std::set<Processor::Kind> seen;
  {
    std::set<Processor> all_processors;
    machine.get_all_processors(all_processors);
    for(std::set<Processor>::const_iterator it = all_processors.begin();
	it != all_processors.end();
	it++) {
      Processor pp = (*it);
      Processor::Kind k = pp.kind();
      if(seen.count(k) > 0) continue;

      printf("testing processor " IDFMT " (kind=%d)\n", pp.id, k);
      seen.insert(k);

      // first, the switching test
      if(num_iterations > 0) {
        // set the watchdog timeout before we do anything that could get stuck
        alarm(timeout_seconds);

	// we're going to need a reservation per child - all start out acquired
	std::vector<Reservation> rsrvs(num_children);
	for(int i = 0; i < num_children; i++) {
          rsrvs[i] = Reservation::create_reservation();
	  Event e = rsrvs[i].acquire();
	  // uncontended, so this should be immediate
	  assert(!e.exists());
        }

        // create the child tasks
        std::set<Event> finish_events;
	for(int i = 0; i < num_children; i++) {
	  SwitchTestArgs c_args;
	  c_args.iterations = num_iterations;
	  c_args.release_first = (i == (num_children - 1));
	  c_args.acquire_me = rsrvs[i];
	  c_args.release_me = rsrvs[(i + 1) % num_children];

	  finish_events.insert(pp.spawn(SWITCH_TEST_TASK, &c_args, sizeof(c_args)));
        }

        // now merge them and see how long it takes them to complete
	double t_start = Clock::current_time();
	Event e = Event::merge_events(finish_events);
	e.wait();
	double t_end = Clock::current_time();

	// turn off the watchdog timer
	alarm(0);

	double elapsed = t_end - t_start;
	double ns_per_switch = 1e9 * elapsed / num_iterations / num_children;
	printf("switch: proc " IDFMT " (kind=%d) finished: elapsed=%5.2fs time/switch=%6.0fns\n",
               pp.id, k, elapsed, ns_per_switch);
      }

      // now the sleep (i.e. kernel-level switching, if possible) test
      if(sleep_seconds > 0) {
        int exp_time = sleep_seconds;
	if(k != Processor::IO_PROC)
	  exp_time *= num_children;  // no overlapping of tasks

        // set the watchdog timeout before we do anything that could get stuck
        alarm(sleep_seconds * num_children * 2);

        // create the child tasks
        std::set<Event> finish_events;
	for(int i = 0; i < num_children; i++) {
	  SleepTestArgs c_args;
	  c_args.sleep_seconds = sleep_seconds;

	  finish_events.insert(pp.spawn(SLEEP_TEST_TASK, &c_args, sizeof(c_args)));
        }

        // now merge them and see how long it takes them to complete
	double t_start = Clock::current_time();
	Event e = Event::merge_events(finish_events);
	e.wait();
	double t_end = Clock::current_time();

	// turn off the watchdog timer
	alarm(0);

	double elapsed = t_end - t_start;
	printf("sleep: proc " IDFMT " (kind=%d) finished: elapsed=%5.2fs expected=%3ds\n",
               pp.id, k, elapsed, exp_time);
      }
    }
  }

  printf("all done!\n");
  sleep(1);

  Runtime::get_runtime().shutdown();
}

int main(int argc, char **argv)
{
  Runtime rt;

  rt.init(&argc, &argv);

  for(int i = 1; i < argc; i++) {
    if(!strcmp(argv[i], "-c")) {
      num_children = atoi(argv[++i]);
      continue;
    }

    if(!strcmp(argv[i], "-i")) {
      num_iterations = atoi(argv[++i]);
      continue;
    }

    if(!strcmp(argv[i], "-t")) {
      timeout_seconds = atoi(argv[++i]);
      continue;
    }

    if(!strcmp(argv[i], "-s")) {
      sleep_seconds = atoi(argv[++i]);
      continue;
    }
  }

  rt.register_task(TOP_LEVEL_TASK, top_level_task);
  rt.register_task(SWITCH_TEST_TASK, switch_task);
  rt.register_task(SLEEP_TEST_TASK, sleep_task);

  signal(SIGALRM, sigalrm_handler);

  // Start the machine running
  // Control never returns from this call
  // Note we only run the top level task on one processor
  // You can also run the top level task on all processors or one processor per node
  rt.run(TOP_LEVEL_TASK, Runtime::ONE_TASK_ONLY);

  //rt.shutdown();
  return 0;
}
<|endoftext|>


<commit_before>#include "Scenes\InitialScene.h"
#include "XEngine.h"
#include "Managers\AnimationManager.h"
#include "Managers\InputManager.h"
#include "Utils\Animation.h"
#include "Utils\MathUtils.h"
#include "GameObjects\Sprite.h"
#include "GameObjects\Rect.h"
#include "GameObjects\Circle.h"
#include "Renderer\Camera.h"
#include "Component\TilledImageRenderer.h"

Sprite* sprite;
Rect* rect;

InitialScene::InitialScene(XEngine& ref) : EngineScene(ref) {
}

Sprite* Mario;

DEFINE_DELEGATE(newDel, void(unsigned int));
void InitialScene::OnKeyDown(unsigned int keyCode)
{
	unsigned int test = VK_SPACE;
	if (keyCode == VK_SPACE) {
 		Mario->rigidBody->ApplyForce(b2Vec2(0.0f, 150.f), Mario->rigidBody->GetWorldCenter(), true);
	}

	if (keyCode == VK_ESCAPE) {
		Mario->Destroy();
	}

	if (keyCode == VK_D) {
		coreRef.physics->isDebug = !coreRef.physics->isDebug;
	}
}

void InitialScene::Start()
{
	newDel = CREATE_MULTICAST_DELEGATE(coreRef.inputManager->OnMouseDown, InitialScene, &InitialScene::OnKeyDown, this);
	coreRef.inputManager->OnKeyDown += newDel;
	CachedImage* image = CacheManager::GetInstance()->AddImage(TEXT("Resources/Mario-Idle-Walk.png"));
	Mario = new Sprite(Vector2(50, 200.f), coreRef, *image);
	Mario->SetSpriteSheet(17, 33);

	//SET MARIO ANIM
	int idle[1] = { 0 };
	int walk[4] = { 1, 2, 3, 4 };
	Mario->animationManager.AddAnim(TEXT("idle"), new Animation(idle, 150, 1, true));
	Mario->animationManager.AddAnim(TEXT("walk"), new Animation(walk, 150, 4, true));

	//SET MARIO PHYSICS
	Mario->SetPhysics(true, PhysicShape::Circle, PhysicBodyType::Kinematic, false, 0.0f, 8.f);
	Mario->anchor.y = 26.f;
	b2MassData massData;
	Mario->rigidBody->GetMassData(&massData);
	massData.center = Renderer::PixelsToWorldUnits(Mario->anchor);
	Mario->rigidBody->SetMassData(&massData);
	Mario->rigidBody->SetFixedRotation(true);
	coreRef.physics->AddBoxFixture(Mario->rigidBody, Vector2(0.f, Mario->anchor.y - (Mario->frameHeight / 2.f)), Vector2(Mario->frameWidth / 2.f, Mario->frameHeight / 2.f), 0.0f, 0.0f, true);

	GameObject* emptyObject = new GameObject(Vector2(10.f, 10.f), coreRef);
	AddGameObject(emptyObject);
	TilledImageRenderer& tilledRenderer = emptyObject->AddComponent<TilledImageRenderer>(false, true);

	tilledRenderer.SetImage(image);
	tilledRenderer.SetSpriteSheet(17, 33);
	tilledRenderer.SetTilleSize(Vector2(50.f, 50.f));
	//OTHER PHYSICS OBJECTS (no need to add this objects to update list or render list, there are only present in the physics engine)
	/*coreRef.physics->CreateBoxBody(Vector2(40.f, 720.f / 2.f), Vector2(30.f, 720.f), 0.0f, 1.0f, PhysicBodyType::Static, false);
	coreRef.physics->CreateBoxBody(Vector2(1230.f, 720.f / 2.f), Vector2(30.f, 720.f), 0.0f, 1.0f, PhysicBodyType::Static, false);

	Rect* rect = new Rect(Vector2(1280.f / 2.f, 50.f), coreRef, 1280, 100, D2D1::ColorF(0.5f, 0.f, 0.5f));
	rect->SetPhysics(true, PhysicBodyType::Kinematic);

	for (int i = 0; i < 40; i++) {
		Circle* rectDyn = new Circle(Vector2(i * 25.f + 100.f, 400.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 110.f, 460.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 100.f, 490.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 110.f, 520.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 100.f, 550.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 100.f, 580.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 100.f, 610.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);
	}*/
	//AddGameObject(rect);
	AddGameObject(Mario);
}

void InitialScene::OnDestroy() {
	coreRef.inputManager->OnKeyDown -= newDel;
}

void InitialScene::Update(float deltaTime)
{
	EngineScene::Update(deltaTime);
	b2Vec2 currentVel = Mario->rigidBody->GetLinearVelocity();
	if (coreRef.inputManager->IsDown(VK_RIGHT)) {
		if (!Mario->animationManager.IsPlaying(TEXT("walk"))) {
			Mario->animationManager.PlayAnim(TEXT("walk"));
		}

		Mario->rigidBody->SetLinearVelocity(b2Vec2(5.f, currentVel.y));

		Mario->scale.width = 1;
	}else if (coreRef.inputManager->IsDown(VK_LEFT)) {
		if (!Mario->animationManager.IsPlaying(TEXT("walk"))) {
			Mario->animationManager.PlayAnim(TEXT("walk"));
		}
		Mario->rigidBody->SetLinearVelocity(b2Vec2(-5.f, currentVel.y));

		Mario->scale.width = -1;
	}
	else {
		if (!Mario->animationManager.IsPlaying(TEXT("idle"))) {
			Mario->animationManager.PlayAnim(TEXT("idle"));
		}
		Mario->rigidBody->SetLinearVelocity(b2Vec2(0.f, currentVel.y));
	}

	currentVel = Mario->rigidBody->GetLinearVelocity();

	if (coreRef.inputManager->IsDown(VK_UP)) {
		Mario->rigidBody->SetLinearVelocity(b2Vec2(currentVel.x, 5.f));
		b2Vec2 vel = Mario->rigidBody->GetLinearVelocity();
		if (vel.x > 5.f) {
			vel.x = 5.f;
			Mario->rigidBody->SetLinearVelocity(vel);
		}
	}
	else if (coreRef.inputManager->IsDown(VK_DOWN)) {
		Mario->rigidBody->SetLinearVelocity(b2Vec2(currentVel.x, -5.f));
		b2Vec2 vel = Mario->rigidBody->GetLinearVelocity();
		if (vel.x < -5.f) {
			vel.x = -5.f;
			Mario->rigidBody->SetLinearVelocity(vel);
		}

	}
	else {
		Mario->rigidBody->SetLinearVelocity(b2Vec2(currentVel.x, 0.f));
	}

	if (coreRef.inputManager->IsDown(VK_L)) {
		coreRef.camera->position.y += 20.f * deltaTime;
	}

}
<commit_msg>All together!<commit_after>#include "Scenes\InitialScene.h"
#include "XEngine.h"
#include "Managers\AnimationManager.h"
#include "Managers\InputManager.h"
#include "Utils\Animation.h"
#include "Utils\MathUtils.h"
#include "GameObjects\Sprite.h"
#include "GameObjects\Rect.h"
#include "GameObjects\Circle.h"
#include "Renderer\Camera.h"
#include "Component\TilledImageRenderer.h"

Sprite* sprite;
Rect* rect;
GameObject* tilledImage;
InitialScene::InitialScene(XEngine& ref) : EngineScene(ref) {
}

Sprite* Mario;

DEFINE_DELEGATE(newDel, void(unsigned int));
void InitialScene::OnKeyDown(unsigned int keyCode)
{
	unsigned int test = VK_SPACE;
	if (keyCode == VK_SPACE) {
 		Mario->rigidBody->ApplyForce(b2Vec2(0.0f, 150.f), Mario->rigidBody->GetWorldCenter(), true);
	}

	if (keyCode == VK_ESCAPE) {
		Mario->Destroy();
	}

	if (keyCode == VK_D) {
		coreRef.physics->isDebug = !coreRef.physics->isDebug;
	}
}

void InitialScene::Start()
{
	newDel = CREATE_MULTICAST_DELEGATE(coreRef.inputManager->OnMouseDown, InitialScene, &InitialScene::OnKeyDown, this);
	coreRef.inputManager->OnKeyDown += newDel;
	CachedImage* image = CacheManager::GetInstance()->AddImage(TEXT("Resources/Mario-Idle-Walk.png"));
	Mario = new Sprite(Vector2(50, 200.f), coreRef, *image);
	Mario->SetSpriteSheet(17, 33);

	//SET MARIO ANIM
	int idle[1] = { 0 };
	int walk[4] = { 1, 2, 3, 4 };
	Mario->animationManager.AddAnim(TEXT("idle"), new Animation(idle, 150, 1, true));
	Mario->animationManager.AddAnim(TEXT("walk"), new Animation(walk, 150, 4, true));

	//SET MARIO PHYSICS
	Mario->SetPhysics(true, PhysicShape::Circle, PhysicBodyType::Kinematic, false, 0.0f, 8.f);
	Mario->anchor.y = 26.f;
	b2MassData massData;
	Mario->rigidBody->GetMassData(&massData);
	massData.center = Renderer::PixelsToWorldUnits(Mario->anchor);
	Mario->rigidBody->SetMassData(&massData);
	Mario->rigidBody->SetFixedRotation(true);
	coreRef.physics->AddBoxFixture(Mario->rigidBody, Vector2(0.f, Mario->anchor.y - (Mario->frameHeight / 2.f)), Vector2(Mario->frameWidth / 2.f, Mario->frameHeight / 2.f), 0.0f, 0.0f, true);

	tilledImage = new GameObject(Vector2(10.f, 10.f), coreRef);
	TilledImageRenderer& tilledRenderer = tilledImage->AddComponent<TilledImageRenderer>(false, true);

	tilledRenderer.SetImage(image);
	tilledRenderer.SetSpriteSheet(17, 33);
	tilledRenderer.SetTilleSize(Vector2(200.f, 200.f));
	//OTHER PHYSICS OBJECTS (no need to add this objects to update list or render list, there are only present in the physics engine)
	coreRef.physics->CreateBoxBody(Vector2(40.f, 720.f / 2.f), Vector2(30.f, 720.f), 0.0f, 1.0f, PhysicBodyType::Static, false);
	coreRef.physics->CreateBoxBody(Vector2(1230.f, 720.f / 2.f), Vector2(30.f, 720.f), 0.0f, 1.0f, PhysicBodyType::Static, false);

	Rect* rect = new Rect(Vector2(1280.f / 2.f, 50.f), coreRef, 1280, 100, D2D1::ColorF(0.5f, 0.f, 0.5f));
	rect->SetPhysics(true, PhysicBodyType::Kinematic);
	AddGameObject(Mario);
	for (int i = 0; i < 40; i++) {
		Circle* rectDyn = new Circle(Vector2(i * 25.f + 100.f, 400.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 110.f, 460.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 100.f, 490.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 110.f, 520.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 100.f, 550.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 100.f, 580.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);

		rectDyn = new Circle(Vector2(i * 25.f + 100.f, 610.f), coreRef, 15.f, 15.f, D2D1::ColorF(MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f), MathUtils::RandomInRange(0.f, 1.0f)));
		rectDyn->SetPhysics(true, PhysicBodyType::Dynamic);
		AddGameObject(rectDyn);
	}
	AddGameObject(rect);
	AddGameObject(tilledImage);
}

void InitialScene::OnDestroy() {
	coreRef.inputManager->OnKeyDown -= newDel;
}

void InitialScene::Update(float deltaTime)
{
	EngineScene::Update(deltaTime);
	b2Vec2 currentVel = Mario->rigidBody->GetLinearVelocity();
	if (coreRef.inputManager->IsDown(VK_RIGHT)) {
		if (!Mario->animationManager.IsPlaying(TEXT("walk"))) {
			Mario->animationManager.PlayAnim(TEXT("walk"));
		}

		Mario->rigidBody->SetLinearVelocity(b2Vec2(5.f, currentVel.y));

		Mario->scale.width = 1;
		tilledImage->GetTransform().position.x += 60.f *deltaTime;
	}else if (coreRef.inputManager->IsDown(VK_LEFT)) {
		if (!Mario->animationManager.IsPlaying(TEXT("walk"))) {
			Mario->animationManager.PlayAnim(TEXT("walk"));
		}
		Mario->rigidBody->SetLinearVelocity(b2Vec2(-5.f, currentVel.y));

		Mario->scale.width = -1;
		tilledImage->GetTransform().position.x -= 60.f *deltaTime;
	}
	else {
		if (!Mario->animationManager.IsPlaying(TEXT("idle"))) {
			Mario->animationManager.PlayAnim(TEXT("idle"));
		}
		Mario->rigidBody->SetLinearVelocity(b2Vec2(0.f, currentVel.y));
	}

	currentVel = Mario->rigidBody->GetLinearVelocity();

	if (coreRef.inputManager->IsDown(VK_UP)) {
		Mario->rigidBody->SetLinearVelocity(b2Vec2(currentVel.x, 5.f));
		b2Vec2 vel = Mario->rigidBody->GetLinearVelocity();
		if (vel.x > 5.f) {
			vel.x = 5.f;
			Mario->rigidBody->SetLinearVelocity(vel);
		}
		tilledImage->GetTransform().position.y += 60.f *deltaTime;
	}
	else if (coreRef.inputManager->IsDown(VK_DOWN)) {
		Mario->rigidBody->SetLinearVelocity(b2Vec2(currentVel.x, -5.f));
		b2Vec2 vel = Mario->rigidBody->GetLinearVelocity();
		if (vel.x < -5.f) {
			vel.x = -5.f;
			Mario->rigidBody->SetLinearVelocity(vel);
		}
		tilledImage->GetTransform().position.y -= 60.f *deltaTime;

	}
	else {
		Mario->rigidBody->SetLinearVelocity(b2Vec2(currentVel.x, 0.f));
	}

	if (coreRef.inputManager->IsDown(VK_L)) {
		coreRef.camera->position.y += 20.f * deltaTime;
	}

}
<|endoftext|>