<commit_before>/***********************************************************************
 load_jpeg.cpp - Example showing how to insert BLOB data into the
	database from a file.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and
 (c) 2004-2009 by Educational Technology Resources, Inc.  Others may
 also hold copyrights on code in this file.  See the CREDITS.txt file
 in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ is free software; you can redistribute it and/or modify it
 under the terms of the GNU Lesser General Public License as published
 by the Free Software Foundation; either version 2.1 of the License, or
 (at your option) any later version.

 MySQL++ is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "cmdline.h"
#include "images.h"
#include "printdata.h"

#include <fstream>

using namespace std;
using namespace mysqlpp;

// This is just an implementation detail for the example.  Skip down to
// main() for the concept this example is trying to demonstrate.
static bool
is_jpeg(const char* img_data)
{
	const unsigned char* idp =
			reinterpret_cast<const unsigned char*>(img_data);
	return (idp[0] == 0xFF) && (idp[1] == 0xD8) &&
			((memcmp(idp + 6, "JFIF", 4) == 0) ||
			 (memcmp(idp + 6, "Exif", 4) == 0));
}

// Another implementation detail.  Skip to main().
static bool
load_jpeg_file(const mysqlpp::examples::CommandLine& cmdline,
		images& img, string& img_name)
{
	if (cmdline.extra_args().size() == 0) {
		// Nothing for us to do here.  Caller will insert NULL BLOB.
		return true;
	}

	// Got a file's name on the command line, so open it.
	img_name = cmdline.extra_args()[0];
	ifstream img_file(img_name.c_str(), ios::ate | ios::binary);
	if (img_file) {
		// File opened, so try to slurp its contents into RAM.  The key
		// thing to get from this function is that we're storing the
		// binary data in a mysqlpp::sql_blob value, which we assign from
		// a C++ string (stringstream::str()), thus not truncating the
		// string at the first embedded null character.
		stringstream sstr;
		sstr << img_file.rdbuf();
		img.data.data = sstr.str();

		// Check JPEG data for sanity
		if (img.data.data.size() > 10) {
			// The following triple 'data' sure does look foolish,
			// doesn't it?  Sorry, we're not trying to be obscure here,
			// it's just a coincidence of naming.  Right-to-left, what
			// we have here is:
			//
			// 1. A call to mysqlpp::sql_blob::data() (mirroring C++'s
			//    std::string:data() interface) to get the raw C data
			//    pointer without null-terminating it first.
			// 2. Access to the mysqlpp::sql_blob object through its
			//    mysqlpp::Null<> wrapper, which lets us have a "NULL
			//    JPEG" in the DB when the file doesn't exist.
			// 3. Access to the JPEG BLOB column, images.data.
			if (is_jpeg(img.data.data.data())) {
				return true;
			}
			else {
				cerr << '"' << img_file <<
						"\" isn't a JPEG!" << endl;
			}
		}
		else {
			cerr << "File is too short to be a JPEG!" << endl;
		}
	}

	cmdline.print_usage("[jpeg_file]");
	return false;
}

int
main(int argc, char *argv[])
{
	// Get database access parameters from command line
	mysqlpp::examples::CommandLine cmdline(argc, argv);
	if (!cmdline) {
		return 1;
	}

	try {
		// Establish the connection to the database server.
		mysqlpp::Connection con(mysqlpp::examples::db_name,
				cmdline.server(), cmdline.user(), cmdline.pass());

		// Load the file named on the command line
		images img(mysqlpp::null, mysqlpp::null);
		string img_name("NULL");
		if (load_jpeg_file(cmdline, img, img_name)) {
			// Insert image data or SQL NULL into the images.data BLOB
			// column.  The key here is that we're holding the raw
			// binary data in a mysqlpp::sql_blob, which avoids data
			// conversion problems that can lead to treating BLOB data
			// as C strings, thus causing null-truncation.  The fact
			// that we're using SSQLS here is a side issue, simply
			// demonstrating that mysqlpp::Null<mysqlpp::sql_blob> is
			// now legal in SSQLS, as of MySQL++ 3.0.7.
			Query query = con.query();
			query.insert(img);
			SimpleResult res = query.execute();

			// Report successful insertion
			cout << "Inserted \"" << img_name <<
					"\" into images table, " << img.data.data.size() <<
					" bytes, ID " << res.insert_id() << endl;
		}
	}
	catch (const BadQuery& er) {
		// Handle any query errors
		cerr << "Query error: " << er.what() << endl;
		return -1;
	}
	catch (const BadConversion& er) {
		// Handle bad conversions
		cerr << "Conversion error: " << er.what() << endl <<
				"\tretrieved data size: " << er.retrieved <<
				", actual size: " << er.actual_size << endl;
		return -1;
	}
	catch (const Exception& er) {
		// Catch-all for any other MySQL++ exceptions
		cerr << "Error: " << er.what() << endl;
		return -1;
	}

	return 0;
}
<commit_msg>WS fix<commit_after>/***********************************************************************
 load_jpeg.cpp - Example showing how to insert BLOB data into the
	database from a file.

 Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and
 (c) 2004-2009 by Educational Technology Resources, Inc.  Others may
 also hold copyrights on code in this file.  See the CREDITS.txt file
 in the top directory of the distribution for details.

 This file is part of MySQL++.

 MySQL++ is free software; you can redistribute it and/or modify it
 under the terms of the GNU Lesser General Public License as published
 by the Free Software Foundation; either version 2.1 of the License, or
 (at your option) any later version.

 MySQL++ is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with MySQL++; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
 USA
***********************************************************************/

#include "cmdline.h"
#include "images.h"
#include "printdata.h"

#include <fstream>

using namespace std;
using namespace mysqlpp;

// This is just an implementation detail for the example.  Skip down to
// main() for the concept this example is trying to demonstrate.
static bool
is_jpeg(const char* img_data)
{
	const unsigned char* idp =
			reinterpret_cast<const unsigned char*>(img_data);
	return (idp[0] == 0xFF) && (idp[1] == 0xD8) &&
			((memcmp(idp + 6, "JFIF", 4) == 0) ||
			 (memcmp(idp + 6, "Exif", 4) == 0));
}

// Another implementation detail.  Skip to main().
static bool
load_jpeg_file(const mysqlpp::examples::CommandLine& cmdline,
		images& img, string& img_name)
{
	if (cmdline.extra_args().size() == 0) {
		// Nothing for us to do here.  Caller will insert NULL BLOB.
		return true;
	}

	// Got a file's name on the command line, so open it.
	img_name = cmdline.extra_args()[0];
	ifstream img_file(img_name.c_str(), ios::ate | ios::binary);
	if (img_file) {
		// File opened, so try to slurp its contents into RAM.  The key
		// thing to get from this function is that we're storing the
		// binary data in a mysqlpp::sql_blob value, which we assign from
		// a C++ string (stringstream::str()), thus not truncating the
		// string at the first embedded null character.
		stringstream sstr;
		sstr << img_file.rdbuf();
		img.data.data = sstr.str();

		// Check JPEG data for sanity
		if (img.data.data.size() > 10) {
			// The following triple 'data' sure does look foolish,
			// doesn't it?  Sorry, we're not trying to be obscure here,
			// it's just a coincidence of naming.  Right-to-left, what
			// we have here is:
			//
			// 1. A call to mysqlpp::sql_blob::data() (mirroring C++'s
			//    std::string:data() interface) to get the raw C data
			//    pointer without null-terminating it first.
			// 2. Access to the mysqlpp::sql_blob object through its
			//    mysqlpp::Null<> wrapper, which lets us have a "NULL
			//    JPEG" in the DB when the file doesn't exist.
			// 3. Access to the JPEG BLOB column, images.data.
			if (is_jpeg(img.data.data.data())) {
				return true;
			}
			else {
				cerr << '"' << img_file << "\" isn't a JPEG!" << endl;
			}
		}
		else {
			cerr << "File is too short to be a JPEG!" << endl;
		}
	}

	cmdline.print_usage("[jpeg_file]");
	return false;
}

int
main(int argc, char *argv[])
{
	// Get database access parameters from command line
	mysqlpp::examples::CommandLine cmdline(argc, argv);
	if (!cmdline) {
		return 1;
	}

	try {
		// Establish the connection to the database server.
		mysqlpp::Connection con(mysqlpp::examples::db_name,
				cmdline.server(), cmdline.user(), cmdline.pass());

		// Load the file named on the command line
		images img(mysqlpp::null, mysqlpp::null);
		string img_name("NULL");
		if (load_jpeg_file(cmdline, img, img_name)) {
			// Insert image data or SQL NULL into the images.data BLOB
			// column.  The key here is that we're holding the raw
			// binary data in a mysqlpp::sql_blob, which avoids data
			// conversion problems that can lead to treating BLOB data
			// as C strings, thus causing null-truncation.  The fact
			// that we're using SSQLS here is a side issue, simply
			// demonstrating that mysqlpp::Null<mysqlpp::sql_blob> is
			// now legal in SSQLS, as of MySQL++ 3.0.7.
			Query query = con.query();
			query.insert(img);
			SimpleResult res = query.execute();

			// Report successful insertion
			cout << "Inserted \"" << img_name <<
					"\" into images table, " << img.data.data.size() <<
					" bytes, ID " << res.insert_id() << endl;
		}
	}
	catch (const BadQuery& er) {
		// Handle any query errors
		cerr << "Query error: " << er.what() << endl;
		return -1;
	}
	catch (const BadConversion& er) {
		// Handle bad conversions
		cerr << "Conversion error: " << er.what() << endl <<
				"\tretrieved data size: " << er.retrieved <<
				", actual size: " << er.actual_size << endl;
		return -1;
	}
	catch (const Exception& er) {
		// Catch-all for any other MySQL++ exceptions
		cerr << "Error: " << er.what() << endl;
		return -1;
	}

	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Alonzo Coeus
#include "crypto/lamport.h"

#include "crypto/ripemd160.h"
#include "crypto/common.h"
#include "uint256.h"

using namespace std;
typedef vector<unsigned char> valtype;

bool LAMPORT::checksig(valtype *pointerdata, valtype *pointerasig, valtype *pointerrootkey, valtype *pointermerklewit)
{

valtype data = *pointerdata;
valtype asig = *pointerasig;
valtype rootkey = *pointerrootkey;
valtype merklewit = *pointermerklewit;

//STARTING to convert asig vector to sig[20][2][20]
unsigned char sig[20][2][20];
for(int i = 0; i < 20; i++)
{
  for(int o = 0; o < 2; o++)
  {
    for(int p = 0; p < 20; p++)
    {
      sig[i][o][p] = asig[p + (o * 20) + (p * 40)];
    }
  }
}
//END converting asig vector to sig[20][2][20]

  valtype exmerklewit[8]; /*this is the merkle wit minus the main public key max number of publickeys to rootkey is 256 due to 2^n where n is the first array index is 8*/
  char pubkey[20][2][20];
  valtype hashablepubkey;

  //START converting merkle wit to exmerklewit and public key
  char merklebuffer[800]; //size of publickey is the max size of the buffer
  unsigned int i;
  for(i = 0; i < sizeof(merklewit); i++)
  {
    if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) /*test for partition beetween merkle segments*/
      break;
    merklebuffer[i] = merklewit[i];
  }

  memcpy(&(pubkey[0][0][0]), &(merklebuffer[0]), sizeof(merklebuffer));
  memcpy(&(hashablepubkey[0]), &(merklebuffer[0]), sizeof(merklebuffer));

  int o = 0;
  int r = 0; //number of times we have reset o count
  for(; i < merklewit.size(); i++)
  {
    if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00)
    {
      if(r == 8)
        break; //lim of exmerklewit
      memcpy(&(exmerklewit[r][0]), &(merklebuffer[0]), sizeof(merklebuffer));
      r++;
      i++; //get i+1 index chunk so we can jump to next part of the merklewit at the end of cycle
      o = 0; //merklebuffer index
    }
    else
    {
      merklebuffer[o] = merklewit[i];
      o++;
    }
  }
  //END decoding merkle wit format

  //START checking if new publickey is a part of the root key
  valtype tempverifyhash;
  CRIPEMD160().Write(&(hashablepubkey[0]), hashablepubkey.size()).Finalize(&(tempverifyhash[0])); //first element is start of arrays address length pre-def
  for(int i = 0; true; i++) //to end if false we will use return to lower processing time
  {
    if(exmerklewit[i][0] == 0 && exmerklewit[i][1] == 0 && exmerklewit[i][2] == 0 && exmerklewit[i][3] == 0)
    {
      if(tempverifyhash == rootkey)
      {
        break;
      }
      else
      {
        return false;
      }
    }

    CRIPEMD160().Write(&(tempverifyhash[0]), tempverifyhash.size()).Write(&(exmerklewit[i][0]), exmerklewit[i].size()).Finalize(&(tempverifyhash[0]));
  }

  //END checking if new publickey is a part of the root key
  //START verifying sig

  //END verifying sig
      return true; // if compleats all tests return true
}
    char *LAMPORT::createsig(valtype *data, uint512_t *prikey, int sellectedpubkey)
    {
      valtype dat = *data;
      uint512_t privatekey = *prikey;

      /* the signing will happen under this */
      return &sig[0][0][0];
    }
<commit_msg>Update lamport.cpp<commit_after>// Copyright (c) 2016 Alonzo Coeus
#include "crypto/lamport.h"

#include "crypto/ripemd160.h"
#include "crypto/common.h"
#include "uint256.h"

using namespace std;
typedef vector<unsigned char> valtype;

bool LAMPORT::checksig(valtype *pointerdata, valtype *pointerasig, valtype *pointerrootkey, valtype *pointermerklewit)
{

valtype data = *pointerdata;
valtype asig = *pointerasig;
valtype rootkey = *pointerrootkey;
valtype merklewit = *pointermerklewit;

//STARTING to convert asig vector to sig[20][2][20]
unsigned char sig[160/(LAMPORT::chunksize*8)][2][20];
for(int i = 0; i < (LAMPORT::chunksize*8); i++)
{
  for(int o = 0; o < 2; o++)
  {
    for(int p = 0; p < 20; p++)
    {
      sig[i][o][p] = asig[p + (o * 20) + (p * 40)];
    }
  }
}
//END converting asig vector to sig[20][2][20]

  valtype exmerklewit[8]; /*this is the merkle wit minus the main public key max number of publickeys to rootkey is 256 due to 2^n where n is the first array index is 8*/
  char pubkey[160/(LAMPORT::chunksize*8)][2][20];
  valtype hashablepubkey;

  //START converting merkle wit to exmerklewit and public key
  char merklebuffer[800]; //size of publickey is the max size of the buffer
  unsigned int i;
  for(i = 0; i < sizeof(merklewit); i++)
  {
    if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00) /*test for partition beetween merkle segments*/
      break;
    merklebuffer[i] = merklewit[i];
  }

  memcpy(&(pubkey[0][0][0]), &(merklebuffer[0]), sizeof(merklebuffer));
  memcpy(&(hashablepubkey[0]), &(merklebuffer[0]), sizeof(merklebuffer));

  int o = 0;
  int r = 0; //number of times we have reset o count
  for(; i < merklewit.size(); i++)
  {
    if(merklewit[i] == 0x00 && merklewit[i+1] == 0x00)
    {
      if(r == 8)
        break; //lim of exmerklewit
      memcpy(&(exmerklewit[r][0]), &(merklebuffer[0]), sizeof(merklebuffer));
      r++;
      i++; //get i+1 index chunk so we can jump to next part of the merklewit at the end of cycle
      o = 0; //merklebuffer index
    }
    else
    {
      merklebuffer[o] = merklewit[i];
      o++;
    }
  }
  //END decoding merkle wit format

  //START checking if new publickey is a part of the root key
  valtype tempverifyhash;
  CRIPEMD160().Write(&(hashablepubkey[0]), hashablepubkey.size()).Finalize(&(tempverifyhash[0])); //first element is start of arrays address length pre-def
  for(int i = 0; true; i++) //to end if false we will use return to lower processing time
  {
    if(exmerklewit[i][0] == 0 && exmerklewit[i][1] == 0 && exmerklewit[i][2] == 0 && exmerklewit[i][3] == 0)
    {
      if(tempverifyhash == rootkey)
      {
        break;
      }
      else
      {
        return false;
      }
    }

    CRIPEMD160().Write(&(tempverifyhash[0]), tempverifyhash.size()).Write(&(exmerklewit[i][0]), exmerklewit[i].size()).Finalize(&(tempverifyhash[0]));
  }

  //END checking if new publickey is a part of the root key

  //START checking if sig is valid

  //create hash of data
  valtype hashdata;
  valtype sellectedhashseg; //to allow seamless scaling to larger segment sizes
  uint512_t sellectedinthashseg; //memcpy of valtype to uint512_t format
  CRIPEMD160().Write(&(data[0]), data.size()).Finalize(&(hashdata[0]));
  valtype keypair[2]; //the two public values at the ends of the ladder
  valtype sigpair[2]; //the two values from each side of hash ladder when signing

  for(int i = 0; i < 160/(LAMPORT::chunksize*8); i++) {
    //get sig, key pair and sellect hash segments
    memcpy(&(sellectedhashseg), &(hashdata[i*LAMPORT::chunksize]), LAMPORT::chunksize);
    sellectedinthashseg = (uint512_t)sellectedhashseg;
    for(int o = 0; o < 2; o++) {
      memcpy(&(keypair[o]), &(pubkey[i][o]), 20);
      memcpy(&(sigpair[i]), &(sig[i][o]), 20);
    }
    //
    int i_a = 0;
    valtype
    while (true) { //i-a sigpair[0]
      CRIPEMD160().Write(&(sigpair[0]), data.size()).Finalize(&(sigpair[0]));
      i_a++; //increment after data hased
      if(o = 256) {
        return false;
      }
      if(sigpair[0] == keypair[0]) {
        break;
      }
    }
    int i_b = 0;
    while (true) { //i-b sigpair[1]
      CRIPEMD160().Write(&(sigpair[1]), data.size()).Finalize(&(sigpair[1]));
      i_b++;
      if(o = 256) {
        return false;
      }
      if(sigpair[1] == keypair[1]) {
        break;
      }
    }
    if((256-i_a != i_b-1) || (256-i_a != V)) {
      return false;
    }
  }
  //END checking if sig is valid
  return true; // if compleats all tests return true
}
    char *LAMPORT::createsig(valtype *data, uint512_t *prikey, int sellectedpubkey)
    {
      /* the signing will happen under this */
      return &sig[0][0][0];
    }
<|endoftext|>


<commit_before>#include <iostream>
#include "custom_interpreter.hpp"

namespace custom
{

    nl::json custom_interpreter::execute_request_impl(int execution_counter, // Typically the cell number
                                                      const std::string& /*code*/, // Code to execute
                                                      bool /*silent*/,
                                                      bool /*store_history*/,
                                                      nl::json /*user_expressions*/,
                                                      bool /*allow_stdin*/)
    {
        // You can use the C-API of your target language for executing the code,
        // e.g. `PyRun_String` for the Python C-API
        //      `luaL_dostring` for the Lua C-API

        // Use this method for publishing the execution result to the client,
        // this method takes the ``execution_counter`` as first argument,
        // the data to publish (mime type data) as second argument and metadata
        // as third argument.
        // Replace "Hello World !!" by what you want to be displayed under the execution cell
        nl::json pub_data;
        pub_data["text/plain"] = "Hello World !!";
        publish_execution_result(execution_counter, std::move(pub_data), nl::json());

        // You can also use this method for publishing errors to the client, if the code
        // failed to execute
        // publish_execution_error(error_name, error_value, error_traceback);
        publish_execution_error("TypeError", "123", {"!@#$", "*(*"});

        nl::json result;
        result["status"] = "ok";
        return result;
    }

    void custom_interpreter::configure_impl()
    {
        // Perform some operations
    }

    nl::json custom_interpreter::complete_request_impl(const std::string& code,
                                                       int cursor_pos)
    {
        nl::json result;

        // Code starts with 'H', it could be the following completion
        if (code[0] == 'H')
        {
            result["status"] = "ok";
            result["matches"] = {"Hello", "Hey", "Howdy"};
            result["cursor_start"] = 5;
            result["cursor_end"] = cursor_pos;
        }
        // No completion result
        else
        {
            result["status"] = "ok";
            result["matches"] = {};
            result["cursor_start"] = cursor_pos;
            result["cursor_end"] = cursor_pos;
        }

        return result;
    }

    nl::json custom_interpreter::inspect_request_impl(const std::string& code,
                                                      int /*cursor_pos*/,
                                                      int /*detail_level*/)
    {
        nl::json result;

        if (code.compare("print") == 0)
        {
            result["found"] = true;
            result["text/plain"] = "Print objects to the text stream file, [...]";
        }
        else
        {
            result["found"] = false;
        }

        result["status"] = "ok";
        return result;
    }

    nl::json custom_interpreter::is_complete_request_impl(const std::string& /*code*/)
    {
        nl::json result;

        // if (is_complete(code))
        // {
            result["status"] = "complete";
        // }
        // else
        // {
        //    result["status"] = "incomplete";
        //    result["indent"] = 4;
        //}

        return result;
    }

    nl::json custom_interpreter::kernel_info_request_impl()
    {
        nl::json result;
        result["implementation"] = "my_kernel";
        result["implementation_version"] = "0.1.0";
        result["language_info"]["name"] = "python";
        result["language_info"]["version"] = "3.7";
        result["language_info"]["mimetype"] = "text/x-python";
        result["language_info"]["file_extension"] = ".py";
        return result;
    }

    void custom_interpreter::shutdown_request_impl() {
        std::cout << "Bye!!" << std::endl;
    }

}
<commit_msg>Several fixes and improvements for the sample kernel (#192)<commit_after>#include <iostream>
#include "custom_interpreter.hpp"

namespace custom
{

    nl::json custom_interpreter::execute_request_impl(int execution_counter, // Typically the cell number
                                                      const std::string& /*code*/, // Code to execute
                                                      bool /*silent*/,
                                                      bool /*store_history*/,
                                                      nl::json /*user_expressions*/,
                                                      bool /*allow_stdin*/)
    {
        // You can use the C-API of your target language for executing the code,
        // e.g. `PyRun_String` for the Python C-API
        //      `luaL_dostring` for the Lua C-API

        // Use this method for publishing the execution result to the client,
        // this method takes the ``execution_counter`` as first argument,
        // the data to publish (mime type data) as second argument and metadata
        // as third argument.
        // Replace "Hello World !!" by what you want to be displayed under the execution cell
        nl::json pub_data;
        pub_data["text/plain"] = "Hello World !!";
        publish_execution_result(execution_counter, std::move(pub_data), nl::json::object());

        // You can also use this method for publishing errors to the client, if the code
        // failed to execute
        // publish_execution_error(error_name, error_value, error_traceback);
        publish_execution_error("TypeError", "123", {"!@#$", "*(*"});

        nl::json result;
        result["status"] = "ok";
        return result;
    }

    void custom_interpreter::configure_impl()
    {
        // Perform some operations
    }

    nl::json custom_interpreter::complete_request_impl(const std::string& code,
                                                       int cursor_pos)
    {
        nl::json result;

        // Code starts with 'H', it could be the following completion
        if (code[0] == 'H')
        {
            result["status"] = "ok";
            result["matches"] = {"Hello", "Hey", "Howdy"};
            result["cursor_start"] = 5;
            result["cursor_end"] = cursor_pos;
        }
        // No completion result
        else
        {
            result["status"] = "ok";
            result["matches"] = nl::json::array();
            result["cursor_start"] = cursor_pos;
            result["cursor_end"] = cursor_pos;
        }

        return result;
    }

    nl::json custom_interpreter::inspect_request_impl(const std::string& code,
                                                      int /*cursor_pos*/,
                                                      int /*detail_level*/)
    {
        nl::json result;

        if (code.compare("print") == 0)
        {
            result["found"] = true;
            result["text/plain"] = "Print objects to the text stream file, [...]";
        }
        else
        {
            result["found"] = false;
        }

        result["status"] = "ok";
        return result;
    }

    nl::json custom_interpreter::is_complete_request_impl(const std::string& /*code*/)
    {
        nl::json result;

        // if (is_complete(code))
        // {
            result["status"] = "complete";
        // }
        // else
        // {
        //    result["status"] = "incomplete";
        //    result["indent"] = 4;
        //}

        return result;
    }

    nl::json custom_interpreter::kernel_info_request_impl()
    {
        nl::json result;
        result["implementation"] = "my_kernel";
        result["implementation_version"] = "0.1.0";
        result["language_info"]["name"] = "python";
        result["language_info"]["version"] = "3.7";
        result["language_info"]["mimetype"] = "text/x-python";
        result["language_info"]["file_extension"] = ".py";
        return result;
    }

    void custom_interpreter::shutdown_request_impl() {
        std::cout << "Bye!!" << std::endl;
    }

}
<|endoftext|>


<commit_before>class Solution {
    public:
        int maxArea(vector<int> &height) {
            int max = 0;
            for(int i = 0; i != height.size(); ++i){
                for(int j = i + 1; j < height.size(); ++j){
                    int s = (j-i)*std::abs(height[j]-height[i]);
                    if(s > max) max = s;
                }
            }
            return max;
        }
};
<commit_msg>add a O(n) time and constant space solution<commit_after>class Solution {
    public:
        int maxArea(vector<int> &height) {
            int left = 0, right = height.size() - 1;
            int max = 0;
            while(left < right){
                int area = (right - left) * min(height[left], height[right]);
                if(area > max) max = area;
                if(height[left] > height[right]){
                    right --;
                }else{
                    left ++;
                }
            }
            return max;
        }

        inline int min(int a, int b){
            return a < b ? a : b;
        }
};
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperParameter.h"
#include "itksys/SystemTools.hxx"

int main(int argc, char* argv[])
{
  if (argc < 3)
    {
    std::cerr << "Usage : " << argv[0] << " module_path  output_script" << std::endl;
    return EXIT_FAILURE;
    }
  std::string module_path(argv[1]);
  std::string output_path(argv[2]);

  otb::Wrapper::ApplicationRegistry::SetApplicationPath(module_path);

  std::vector<std::string> appList = otb::Wrapper::ApplicationRegistry::GetAvailableApplications(false);

  otb::Wrapper::Application::Pointer appPtr;

  std::ofstream ofs;
  ofs.open(output_path.c_str());

  for (unsigned int i=0 ; i < appList.size() ; ++i)
    {
    appPtr = otb::Wrapper::ApplicationRegistry::CreateApplication(appList[i],false);
    if (appPtr.IsNull())
      {
      std::cout << "Error loading application "<< appList[i] << std::endl;
      return EXIT_FAILURE;
      }
    std::vector<std::string> keys = appPtr->GetParametersKeys();

    ofs << "# completion for application "<< appList[i] << std::endl;
    ofs << "_otbcli_"<<appList[i]<<"()" << std::endl;
    ofs << "{" << std::endl;

    ofs << "  local cur prev" << std::endl;
    ofs << "  COMPREPLY=()" << std::endl;
    ofs << "  _get_comp_words_by_ref cur prev" << std::endl;
    ofs << "  case \"$cur\" in" << std::endl;
    ofs << "    -*)" << std::endl;
    ofs << "      key_list=\"";
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      ofs << "-" << keys[k] << " ";
      }
    ofs << "\"" << std::endl;
    ofs << "      COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
    ofs << "      return 0" << std::endl;
    ofs << "      ;;" << std::endl;
    ofs << "  esac" << std::endl;

  //case "$prev" in
    //-type)
    //key_list="none linear log2"
    //COMPREPLY=( $( compgen -W '$key_list' -- $cur) )
    //;;
  //esac

    ofs << "  return 0" << std::endl;
    ofs << "}" << std::endl;
    ofs << "complete -o default -F _otbcli_" << appList[i] << " otbcli_"<< appList[i] << std::endl;
    }
  ofs.close();

  return EXIT_SUCCESS;
}
<commit_msg>ENH: specific completion for choices<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperParameter.h"
#include "otbWrapperChoiceParameter.h"
#include "itksys/SystemTools.hxx"

int main(int argc, char* argv[])
{
  if (argc < 3)
    {
    std::cerr << "Usage : " << argv[0] << " module_path  output_script" << std::endl;
    return EXIT_FAILURE;
    }
  std::string module_path(argv[1]);
  std::string output_path(argv[2]);

  otb::Wrapper::ApplicationRegistry::SetApplicationPath(module_path);

  std::vector<std::string> appList = otb::Wrapper::ApplicationRegistry::GetAvailableApplications(false);

  otb::Wrapper::Application::Pointer appPtr;

  std::ofstream ofs;
  ofs.open(output_path.c_str());

  for (unsigned int i=0 ; i < appList.size() ; ++i)
    {
    appPtr = otb::Wrapper::ApplicationRegistry::CreateApplication(appList[i],false);
    if (appPtr.IsNull())
      {
      std::cout << "Error loading application "<< appList[i] << std::endl;
      return EXIT_FAILURE;
      }
    std::vector<std::string> keys = appPtr->GetParametersKeys();

    ofs << "# completion for application "<< appList[i] << std::endl;
    ofs << "_otbcli_"<<appList[i]<<"()" << std::endl;
    ofs << "{" << std::endl;

    ofs << "  local cur prev" << std::endl;
    ofs << "  COMPREPLY=()" << std::endl;
    ofs << "  _get_comp_words_by_ref cur prev" << std::endl;
    ofs << "  case \"$cur\" in" << std::endl;
    ofs << "    -*)" << std::endl;
    ofs << "      key_list=\"";
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      ofs << "-" << keys[k] << " ";
      }
    ofs << "\"" << std::endl;
    ofs << "      COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
    ofs << "      return 0" << std::endl;
    ofs << "      ;;" << std::endl;
    ofs << "  esac" << std::endl;

    // detect choice parameters
    std::vector<std::string> choiceKeys;
    for (unsigned int k=0 ; k < keys.size() ; k++ )
      {
      if ( appPtr->GetParameterType(keys[k]) == otb::Wrapper::ParameterType_Choice)
        {
        choiceKeys.push_back(keys[k]);
        }
      }
    if (choiceKeys.size())
      {
      ofs << "  case \"$prev\" in" << std::endl;
      for (unsigned int k=0 ; k < choiceKeys.size() ; k++)
        {
        ofs << "    -" << choiceKeys[k] << ")" << std::endl;
        ofs << "      key_list=\"";
        std::vector<std::string> choices = dynamic_cast<otb::Wrapper::ChoiceParameter*>(appPtr->GetParameterByKey(choiceKeys[k]))->GetChoiceKeys();
        for (unsigned int j=0 ; j < choices.size() ; j++)
          {
          ofs << choices[j];
          if (j+1 < choices.size() )
            {
            ofs << " ";
            }
          }
        ofs << "\"" << std::endl;
        ofs << "      COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
        ofs << "      ;;" << std::endl;
        }
      ofs << "  esac" << std::endl;
      }

    ofs << "  return 0" << std::endl;
    ofs << "}" << std::endl;
    ofs << "complete -o default -F _otbcli_" << appList[i] << " otbcli_"<< appList[i] << std::endl;
    }
  ofs.close();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright (c) 2017 offa
// Copyright 2011 Ciaran McHale.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions.
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include "danek/internal/LexToken.h"
#include "danek/internal/LexBase.h"
#include <assert.h>

namespace danek
{
    LexToken::LexToken() : LexToken(LexBase::LEX_UNKNOWN_SYM, -1, "")
    {
    }

    LexToken::LexToken(short type, int lineNum, const char* spelling)
        : m_type(type), m_spelling(spelling), m_lineNum(lineNum), m_funcType(FunctionType::None)
    {
    }

    void LexToken::reset(short type, int lineNum, const char* spelling)
    {
        m_type = type;
        m_lineNum = lineNum;
        m_spelling = spelling;
        m_funcType = FunctionType::None;
    }

    void LexToken::reset(short type, int lineNum, const char* spelling, FunctionType funcType)
    {
        m_type = type;
        m_lineNum = lineNum;
        m_spelling = spelling;
        m_funcType = funcType;
    }

    void LexToken::resetWithOwnership(short type, int lineNum, StringBuffer& str)
    {
        m_type = type;
        m_lineNum = lineNum;
        m_funcType = FunctionType::None;
        m_spelling = str;
    }

    const char* LexToken::spelling()
    {
        return m_spelling.str().c_str();
    }

    int LexToken::lineNum()
    {
        return m_lineNum;
    }

    short LexToken::type()
    {
        return m_type;
    }

    bool LexToken::isStringFunc()
    {
        return m_funcType == FunctionType::String;
    }

    bool LexToken::isListFunc()
    {
        return m_funcType == FunctionType::List;
    }

    bool LexToken::isBoolFunc()
    {
        return m_funcType == FunctionType::Bool;
    }
}
<commit_msg>Refactoring.<commit_after>// Copyright (c) 2017 offa
// Copyright 2011 Ciaran McHale.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions.
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include "danek/internal/LexToken.h"
#include "danek/internal/LexBase.h"
#include <assert.h>

namespace danek
{
    LexToken::LexToken() : LexToken(LexBase::LEX_UNKNOWN_SYM, -1, "")
    {
    }

    LexToken::LexToken(short type, int lineNum, const char* spelling) : m_type(type),
                                                                    m_spelling(spelling),
                                                                    m_lineNum(lineNum),
                                                                    m_funcType(FunctionType::None)
    {
    }

    void LexToken::reset(short type, int lineNum, const char* spelling)
    {
        reset(type, lineNum, spelling, FunctionType::None);
    }

    void LexToken::reset(short type, int lineNum, const char* spelling, FunctionType funcType)
    {
        m_type = type;
        m_lineNum = lineNum;
        m_spelling = spelling;
        m_funcType = funcType;
    }

    void LexToken::resetWithOwnership(short type, int lineNum, StringBuffer& str)
    {
        reset(type, lineNum, str.str().c_str(), FunctionType::None);
    }

    const char* LexToken::spelling()
    {
        return m_spelling.str().c_str();
    }

    int LexToken::lineNum()
    {
        return m_lineNum;
    }

    short LexToken::type()
    {
        return m_type;
    }

    bool LexToken::isStringFunc()
    {
        return m_funcType == FunctionType::String;
    }

    bool LexToken::isListFunc()
    {
        return m_funcType == FunctionType::List;
    }

    bool LexToken::isBoolFunc()
    {
        return m_funcType == FunctionType::Bool;
    }
}
<|endoftext|>


<commit_before>// Copyright © 2012, Université catholique de Louvain
// 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.
//
// 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 <mozart.hh>
#include <boostenv.hh>

#include <iostream>
#include <fstream>

using namespace mozart;

void createThreadFromOZB(VM vm, const char* functorName,
                         RichNode baseEnv, RichNode bootMM) {
  std::string fileName = std::string(functorName) + ".ozb";
  std::ifstream input(fileName);
  UnstableNode codeArea = bootUnpickle(vm, input);

  UnstableNode abstraction = Abstraction::build(vm, 2, codeArea);
  auto globalsArray =
    RichNode(abstraction).as<Abstraction>().getElementsArray();

  globalsArray[0].init(vm, baseEnv);
  globalsArray[1].init(vm, bootMM);

  new (vm) Thread(vm, vm->getTopLevelSpace(), abstraction);
}

int main(int argc, char** argv) {
  boostenv::BoostBasedVM boostBasedVM;
  VM vm = boostBasedVM.vm;

  if (argc >= 2) {
    boostBasedVM.setApplicationURL(argv[1]);
    boostBasedVM.setApplicationArgs(argc-2, argv+2);
  } else {
    boostBasedVM.setApplicationURL(u8"x-oz://system/OPI.ozf");
    boostBasedVM.setApplicationArgs(0, nullptr);
  }

  UnstableNode baseEnv = OptVar::build(vm);
  UnstableNode bootMM = OptVar::build(vm);

  vm->getPropertyRegistry().registerConstantProp(
    vm, MOZART_STR("internal.bootmm"), bootMM);

  createThreadFromOZB(vm, "Base", baseEnv, bootMM);
  createThreadFromOZB(vm, "OPI", baseEnv, bootMM);
  createThreadFromOZB(vm, "Emacs", baseEnv, bootMM);
  createThreadFromOZB(vm, "OPIServer", baseEnv, bootMM);
  createThreadFromOZB(vm, "OPIEnv", baseEnv, bootMM);
  createThreadFromOZB(vm, "Space", baseEnv, bootMM);
  createThreadFromOZB(vm, "System", baseEnv, bootMM);
  createThreadFromOZB(vm, "Property", baseEnv, bootMM);
  createThreadFromOZB(vm, "Listener", baseEnv, bootMM);
  createThreadFromOZB(vm, "Type", baseEnv, bootMM);
  createThreadFromOZB(vm, "ErrorListener", baseEnv, bootMM);
  createThreadFromOZB(vm, "ObjectSupport", baseEnv, bootMM);
  createThreadFromOZB(vm, "CompilerSupport", baseEnv, bootMM);
  createThreadFromOZB(vm, "Narrator", baseEnv, bootMM);
  createThreadFromOZB(vm, "DefaultURL", baseEnv, bootMM);
  createThreadFromOZB(vm, "Init", baseEnv, bootMM);
  createThreadFromOZB(vm, "Error", baseEnv, bootMM);
  createThreadFromOZB(vm, "ErrorFormatters", baseEnv, bootMM);
  createThreadFromOZB(vm, "Open", baseEnv, bootMM);
  createThreadFromOZB(vm, "Combinator", baseEnv, bootMM);
  createThreadFromOZB(vm, "RecordC", baseEnv, bootMM);
  createThreadFromOZB(vm, "URL", baseEnv, bootMM);
  createThreadFromOZB(vm, "Application", baseEnv, bootMM);
  createThreadFromOZB(vm, "OS", baseEnv, bootMM);
  createThreadFromOZB(vm, "Annotate", baseEnv, bootMM);
  createThreadFromOZB(vm, "Assembler", baseEnv, bootMM);
  createThreadFromOZB(vm, "BackquoteMacro", baseEnv, bootMM);
  createThreadFromOZB(vm, "Builtins", baseEnv, bootMM);
  createThreadFromOZB(vm, "CodeEmitter", baseEnv, bootMM);
  createThreadFromOZB(vm, "CodeGen", baseEnv, bootMM);
  createThreadFromOZB(vm, "CodeStore", baseEnv, bootMM);
  createThreadFromOZB(vm, "Compiler", baseEnv, bootMM);
  createThreadFromOZB(vm, "Core", baseEnv, bootMM);
  createThreadFromOZB(vm, "ForLoop", baseEnv, bootMM);
  createThreadFromOZB(vm, "GroundZip", baseEnv, bootMM);
  createThreadFromOZB(vm, "Macro", baseEnv, bootMM);
  createThreadFromOZB(vm, "PrintName", baseEnv, bootMM);
  createThreadFromOZB(vm, "RunTime", baseEnv, bootMM);
  createThreadFromOZB(vm, "StaticAnalysis", baseEnv, bootMM);
  createThreadFromOZB(vm, "Unnester", baseEnv, bootMM);
  createThreadFromOZB(vm, "WhileLoop", baseEnv, bootMM);
  createThreadFromOZB(vm, "NewAssembler", baseEnv, bootMM);
  createThreadFromOZB(vm, "Parser", baseEnv, bootMM);
  createThreadFromOZB(vm, "PEG", baseEnv, bootMM);

  boostBasedVM.run();

  {
    auto runAtom = build(vm, MOZART_STR("run"));
    auto runProc = Dottable(bootMM).dot(vm, runAtom);
    new (vm) Thread(vm, vm->getTopLevelSpace(), runProc);
  }

  boostBasedVM.run();
}
<commit_msg>Reviewed the way that <Base> and the boot MM are accessed.<commit_after>// Copyright © 2012, Université catholique de Louvain
// 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.
//
// 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 <mozart.hh>
#include <boostenv.hh>

#include <iostream>
#include <fstream>

using namespace mozart;

void createThreadFromOZB(VM vm, const char* functorName) {
  std::string fileName = std::string(functorName) + ".ozb";
  std::ifstream input(fileName);
  UnstableNode codeArea = bootUnpickle(vm, input);

  UnstableNode abstraction = Abstraction::build(vm, 0, codeArea);

  new (vm) Thread(vm, vm->getTopLevelSpace(), abstraction);
}

int main(int argc, char** argv) {
  boostenv::BoostBasedVM boostBasedVM;
  VM vm = boostBasedVM.vm;

  if (argc >= 2) {
    boostBasedVM.setApplicationURL(argv[1]);
    boostBasedVM.setApplicationArgs(argc-2, argv+2);
  } else {
    boostBasedVM.setApplicationURL(u8"x-oz://system/OPI.ozf");
    boostBasedVM.setApplicationArgs(0, nullptr);
  }

  UnstableNode bootVirtualFS = OptVar::build(vm);
  UnstableNode runProc = OptVar::build(vm);
  UnstableNode baseEnv = OptVar::build(vm);

  vm->getPropertyRegistry().registerConstantProp(
    vm, MOZART_STR("internal.boot.virtualfs"), bootVirtualFS);
  vm->getPropertyRegistry().registerConstantProp(
    vm, MOZART_STR("internal.boot.run"), runProc);
  vm->getPropertyRegistry().registerConstantProp(
    vm, MOZART_STR("internal.boot.base"), baseEnv);

  createThreadFromOZB(vm, "Base");

  boostBasedVM.run();

  createThreadFromOZB(vm, "OPI");
  createThreadFromOZB(vm, "Emacs");
  createThreadFromOZB(vm, "OPIServer");
  createThreadFromOZB(vm, "OPIEnv");
  createThreadFromOZB(vm, "Space");
  createThreadFromOZB(vm, "System");
  createThreadFromOZB(vm, "Property");
  createThreadFromOZB(vm, "Listener");
  createThreadFromOZB(vm, "Type");
  createThreadFromOZB(vm, "ErrorListener");
  createThreadFromOZB(vm, "ObjectSupport");
  createThreadFromOZB(vm, "CompilerSupport");
  createThreadFromOZB(vm, "Narrator");
  createThreadFromOZB(vm, "DefaultURL");
  createThreadFromOZB(vm, "Init");
  createThreadFromOZB(vm, "Error");
  createThreadFromOZB(vm, "ErrorFormatters");
  createThreadFromOZB(vm, "Open");
  createThreadFromOZB(vm, "Combinator");
  createThreadFromOZB(vm, "RecordC");
  createThreadFromOZB(vm, "URL");
  createThreadFromOZB(vm, "Application");
  createThreadFromOZB(vm, "OS");
  createThreadFromOZB(vm, "Annotate");
  createThreadFromOZB(vm, "Assembler");
  createThreadFromOZB(vm, "BackquoteMacro");
  createThreadFromOZB(vm, "Builtins");
  createThreadFromOZB(vm, "CodeEmitter");
  createThreadFromOZB(vm, "CodeGen");
  createThreadFromOZB(vm, "CodeStore");
  createThreadFromOZB(vm, "Compiler");
  createThreadFromOZB(vm, "Core");
  createThreadFromOZB(vm, "ForLoop");
  createThreadFromOZB(vm, "GroundZip");
  createThreadFromOZB(vm, "Macro");
  createThreadFromOZB(vm, "PrintName");
  createThreadFromOZB(vm, "RunTime");
  createThreadFromOZB(vm, "StaticAnalysis");
  createThreadFromOZB(vm, "Unnester");
  createThreadFromOZB(vm, "WhileLoop");
  createThreadFromOZB(vm, "NewAssembler");
  createThreadFromOZB(vm, "Parser");
  createThreadFromOZB(vm, "PEG");

  boostBasedVM.run();

  new (vm) Thread(vm, vm->getTopLevelSpace(), runProc);

  boostBasedVM.run();
}
<|endoftext|>


<commit_before>/**
 * @file
 * @brief
 * This example is an adaptation of the example that can be found in the
 * gengetopt documentation:
 * https://www.gnu.org/software/gengetopt/gengetopt.html. It does not reach
 * feature parity because argagg does not implement dependent options, option
 * sections, word wrapping, and a few other features.
 */
#include <argagg/argagg.hpp>

#include <iostream>
#include <cstdlib>

int main(int argc, char **argv)
{
  using argagg::parser_results;
  using argagg::parser;
  using std::cerr;
  using std::cout;
  using std::endl;
  using std::ofstream;
  using std::ostream;
  using std::ostringstream;
  using std::string;

  parser argparser {{
      {
        "help", {"-h", "--help"},
        "Print help and exit", 0},
      {
        "version", {"-V", "--version"},
        "Print version and exit", 0},
      {
        "str-opt", {"-s", "--str-opt"},
        "A string option, for a filename", 1},
      {
        "my-opt", {"-m", "--my-opt"},
        "Another integer option", 1},
      {
        "int-opt", {"-i", "--int-opt"},
        "A int option", 1},
      {
        "flag-opt", {"--flag-opt"},
        "A flag option (default: off)", 0},
      {
        "funct-opt", {"-F", "--funct-opt"},
        "A function option", 0},
      {
        "long-opt", {"--long-opt"},
        "A long option", 1},
      {
        "def-opt", {"--def-opt"},
        "A string option with default (default: 'Hello')", 1},
      {
        "enum-opt", {"--enum-opt"},
        "A string option with list of values (possible values=\"foo\", "
        "\"bar\", \"hello\", \"bye\"; default=\"hello\")", 1},
      {
        "dependant", {"--dependant"},
        "option that depends on str-opt", 1},
    }};

  cout << "This one is from a C++ program" << endl ;
  cout << "Try to launch me with some options" << endl ;
  cout << "(type " << argv[0] << " --help for the complete list)" << endl ;
  cout << "For example: " << argv[0] << " *.* --funct-opt" << endl ;

  // Define our usage text.
  ostringstream usage;
  usage
    << argv[0] << " 2.0" << endl
    << endl
    << "Usage: " << argv[0] << " [OPTIONS]... [FILES]..." << endl
    << endl;

  // Use our argument parser to... parse the command line arguments. If there
  // are any problems then just spit out the usage and help text and exit.
  argagg::parser_results args;
  try {
    args = argparser.parse(argc, argv);
  } catch (const std::exception& e) {
    cerr << usage.str() << argparser << endl
         << "Encountered exception while parsing arguments: " << e.what()
         << endl;
    return EXIT_FAILURE;
  }

  // If the help flag was specified then spit out the usage and help text and
  // exit.
  if (args["help"]) {
    cerr << usage.str() << argparser;
    return EXIT_SUCCESS;
  }

  if (args["version"]) {
    cerr << "2.0" << endl;
    return EXIT_SUCCESS;
  }

  if (!args["int-opt"]) {
    cerr << args.program << ": '--int-opt' ('-i') option required" << endl;
    return EXIT_FAILURE;
  }

  cout << "Here are the options you passed..." << endl;

  for (const auto& file : args.pos) {
    cout << "file: " << file << endl;
  }

  if (args["funct-opt"]) {
    cout << "You chose --funct-opt or -F." << endl;
  }

  if (args["str-opt"]) {
    cout << "You inserted " << args["str-opt"].as<std::string>() << " for " <<
      "--str-opt option." << endl;
  }

  if (args["int-opt"]) {
    cout << "This is the integer you input: " << args["int-opt"].as<int>()
      << "." << endl;
  }

  string flag_opt_arg = "off";
  if (args["flag-opt"]) {
    cout << "The flag option was given!" << endl;
    flag_opt_arg = "on";
  }
  cout << "The flag is " << flag_opt_arg << "." << endl;

  if (args["enum-opt"]) {
    cout << "enum-opt value: " << args["enum-opt"].as<string>() << endl;
    cout << "enum-opt (original specified) value: " << "hello" << endl;
  }

  cout << "def_opt: " << args["def-opt"].as<string>("Hello") << "! ";

  cout << "Have a nice day! :-)" << endl;

  return EXIT_SUCCESS;
}
<commit_msg>Use fmt_ostream for gengetopt_main1.cpp example<commit_after>/**
 * @file
 * @brief
 * This example is an adaptation of the example that can be found in the
 * gengetopt documentation:
 * https://www.gnu.org/software/gengetopt/gengetopt.html. It does not reach
 * feature parity because argagg does not implement dependent options, option
 * sections, word wrapping, and a few other features.
 */
#include <argagg/argagg.hpp>

#include <iostream>
#include <cstdlib>

int main(int argc, char **argv)
{
  using argagg::parser_results;
  using argagg::parser;
  using std::cerr;
  using std::cout;
  using std::endl;
  using std::ofstream;
  using std::ostream;
  using std::ostringstream;
  using std::string;

  parser argparser {{
      {
        "help", {"-h", "--help"},
        "Print help and exit", 0},
      {
        "version", {"-V", "--version"},
        "Print version and exit", 0},
      {
        "str-opt", {"-s", "--str-opt"},
        "A string option, for a filename", 1},
      {
        "my-opt", {"-m", "--my-opt"},
        "Another integer option", 1},
      {
        "int-opt", {"-i", "--int-opt"},
        "A int option", 1},
      {
        "flag-opt", {"--flag-opt"},
        "A flag option (default: off)", 0},
      {
        "funct-opt", {"-F", "--funct-opt"},
        "A function option", 0},
      {
        "long-opt", {"--long-opt"},
        "A long option", 1},
      {
        "def-opt", {"--def-opt"},
        "A string option with default (default: 'Hello')", 1},
      {
        "enum-opt", {"--enum-opt"},
        "A string option with list of values (possible values=\"foo\", "
        "\"bar\", \"hello\", \"bye\"; default=\"hello\")", 1},
      {
        "dependant", {"--dependant"},
        "option that depends on str-opt", 1},
    }};

  cout << "This one is from a C++ program" << endl ;
  cout << "Try to launch me with some options" << endl ;
  cout << "(type " << argv[0] << " --help for the complete list)" << endl ;
  cout << "For example: " << argv[0] << " *.* --funct-opt" << endl ;

  // Define our usage text.
  ostringstream usage;
  usage
    << argv[0] << " 2.0" << endl
    << endl
    << "Usage: " << argv[0] << " [OPTIONS]... [FILES]..." << endl
    << endl;

  // Use our argument parser to... parse the command line arguments. If there
  // are any problems then just spit out the usage and help text and exit.
  argagg::parser_results args;
  try {
    args = argparser.parse(argc, argv);
  } catch (const std::exception& e) {
    argagg::fmt_ostream fmt(cerr);
    fmt << usage.str() << argparser << endl
        << "Encountered exception while parsing arguments: " << e.what()
        << endl;
    return EXIT_FAILURE;
  }

  // If the help flag was specified then spit out the usage and help text and
  // exit.
  if (args["help"]) {
    argagg::fmt_ostream fmt(cerr);
    fmt << usage.str() << argparser;
    return EXIT_SUCCESS;
  }

  if (args["version"]) {
    cerr << "2.0" << endl;
    return EXIT_SUCCESS;
  }

  if (!args["int-opt"]) {
    cerr << args.program << ": '--int-opt' ('-i') option required" << endl;
    return EXIT_FAILURE;
  }

  cout << "Here are the options you passed..." << endl;

  for (const auto& file : args.pos) {
    cout << "file: " << file << endl;
  }

  if (args["funct-opt"]) {
    cout << "You chose --funct-opt or -F." << endl;
  }

  if (args["str-opt"]) {
    cout << "You inserted " << args["str-opt"].as<std::string>() << " for " <<
      "--str-opt option." << endl;
  }

  if (args["int-opt"]) {
    cout << "This is the integer you input: " << args["int-opt"].as<int>()
      << "." << endl;
  }

  string flag_opt_arg = "off";
  if (args["flag-opt"]) {
    cout << "The flag option was given!" << endl;
    flag_opt_arg = "on";
  }
  cout << "The flag is " << flag_opt_arg << "." << endl;

  if (args["enum-opt"]) {
    cout << "enum-opt value: " << args["enum-opt"].as<string>() << endl;
    cout << "enum-opt (original specified) value: " << "hello" << endl;
  }

  cout << "def_opt: " << args["def-opt"].as<string>("Hello") << "! ";

  cout << "Have a nice day! :-)" << endl;

  return EXIT_SUCCESS;
}
<|endoftext|>


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

#include "mergedcomponentdata.hxx"

#ifndef CONFIGMGR_TREE_NODEFACTORY_HXX
#include "treenodefactory.hxx"
#endif

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace backend
    {
// -----------------------------------------------------------------------------

MergedComponentData::MergedComponentData(  )
: m_pSchemaTree()
, m_pTemplatesTree()
{

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

MergedComponentData::~MergedComponentData(  )
{

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

void MergedComponentData::clear(  )
{
    m_pTemplatesTree.reset();
    m_pSchemaTree.reset();
}
// -----------------------------------------------------------------------------

bool MergedComponentData::hasSchema()const
{
    return m_pSchemaTree.get() != NULL;
}
// -----------------------------------------------------------------------------

bool MergedComponentData::hasTemplates() const
{
    return m_pTemplatesTree.get() != NULL;
}
// -----------------------------------------------------------------------------

OUString MergedComponentData::getTemplateAccessor (TemplateIdentifier const & _aTemplateName) const
{
    return _aTemplateName.Name;
}
// -----------------------------------------------------------------------------

bool MergedComponentData::hasTemplate(OUString const & _aTemplateName) const
{
    return m_pTemplatesTree.get() != NULL &&
            m_pTemplatesTree->getChild( _aTemplateName ) != NULL;
}
// -----------------------------------------------------------------------------

std::auto_ptr<ISubtree> MergedComponentData::extractSchemaTree()
{
    return m_pSchemaTree;
}
// -----------------------------------------------------------------------------

std::auto_ptr<ISubtree> MergedComponentData::extractTemplatesTree()
{
    return m_pTemplatesTree;
}
// -----------------------------------------------------------------------------

std::auto_ptr<INode> MergedComponentData::extractTemplateNode(OUString const & _aTemplateName)
{
    if (m_pTemplatesTree.get() == NULL)
        return std::auto_ptr<INode>();

    return m_pTemplatesTree->removeChild(_aTemplateName);
}
// -----------------------------------------------------------------------------

ISubtree const * MergedComponentData::findTemplate(OUString const & _aTemplateName) const
{
    INode const * pTemplateNode = m_pTemplatesTree->getChild(_aTemplateName);

    ISubtree const * pTemplateTree = pTemplateNode ? pTemplateNode->asISubtree() : NULL;

    OSL_ENSURE(pTemplateTree || !pTemplateNode, "ERROR: Template is not a subtree");

    return pTemplateTree;
}
// -----------------------------------------------------------------------------

std::auto_ptr<INode>    MergedComponentData::instantiateTemplate(OUString const & _aName, OUString const & _aTemplateName) const
{
    if (INode const * pTemplateNode = m_pTemplatesTree->getChild(_aTemplateName))
    {
        std::auto_ptr<INode> aResult = pTemplateNode->clone();
        aResult->setName(_aName);
        return aResult;
    }
    else
    {
        return std::auto_ptr<INode>();
    }
}
// -----------------------------------------------------------------------------

ISubtree  * MergedComponentData::setSchemaRoot(std::auto_ptr<ISubtree>  _aSchemaRoot)
{
    OSL_PRECOND(_aSchemaRoot.get(),"ERROR: Setting a NULL schema root.");
    OSL_PRECOND(!hasSchema(),"ERROR: Schema root already set");

    m_pSchemaTree = _aSchemaRoot;

    return m_pSchemaTree.get();
}
// -----------------------------------------------------------------------------
void  MergedComponentData::setTemplatesTree(std::auto_ptr<ISubtree>  _aTemplateTree)
{
    OSL_PRECOND(!hasTemplates(),"ERROR: Template Tree already set");
    m_pTemplatesTree = _aTemplateTree;
}
// -----------------------------------------------------------------------------
ISubtree  * MergedComponentData::addTemplate(std::auto_ptr<ISubtree>  _aNode, TemplateIdentifier const & aTemplate)
{
    OSL_PRECOND(_aNode.get(), "ERROR: Adding a NULL template");

    if (!m_pTemplatesTree.get())
    {
        m_pTemplatesTree = getDefaultTreeNodeFactory().createGroupNode( aTemplate.Component, node::Attributes() );
    }
    else
    {
        OSL_ENSURE(m_pTemplatesTree->getName().equals(aTemplate.Component),
                    "Template Component names do not match");
    }

    return m_pTemplatesTree->addChild( base_ptr(_aNode) )->asISubtree();
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
    } // namespace backend

// -------------------------------------------------------------------------
} // namespace configmgr
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.170); FILE MERGED 2005/09/05 17:04:03 rt 1.5.170.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mergedcomponentdata.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:32:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "mergedcomponentdata.hxx"

#ifndef CONFIGMGR_TREE_NODEFACTORY_HXX
#include "treenodefactory.hxx"
#endif

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace backend
    {
// -----------------------------------------------------------------------------

MergedComponentData::MergedComponentData(  )
: m_pSchemaTree()
, m_pTemplatesTree()
{

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

MergedComponentData::~MergedComponentData(  )
{

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

void MergedComponentData::clear(  )
{
    m_pTemplatesTree.reset();
    m_pSchemaTree.reset();
}
// -----------------------------------------------------------------------------

bool MergedComponentData::hasSchema()const
{
    return m_pSchemaTree.get() != NULL;
}
// -----------------------------------------------------------------------------

bool MergedComponentData::hasTemplates() const
{
    return m_pTemplatesTree.get() != NULL;
}
// -----------------------------------------------------------------------------

OUString MergedComponentData::getTemplateAccessor (TemplateIdentifier const & _aTemplateName) const
{
    return _aTemplateName.Name;
}
// -----------------------------------------------------------------------------

bool MergedComponentData::hasTemplate(OUString const & _aTemplateName) const
{
    return m_pTemplatesTree.get() != NULL &&
            m_pTemplatesTree->getChild( _aTemplateName ) != NULL;
}
// -----------------------------------------------------------------------------

std::auto_ptr<ISubtree> MergedComponentData::extractSchemaTree()
{
    return m_pSchemaTree;
}
// -----------------------------------------------------------------------------

std::auto_ptr<ISubtree> MergedComponentData::extractTemplatesTree()
{
    return m_pTemplatesTree;
}
// -----------------------------------------------------------------------------

std::auto_ptr<INode> MergedComponentData::extractTemplateNode(OUString const & _aTemplateName)
{
    if (m_pTemplatesTree.get() == NULL)
        return std::auto_ptr<INode>();

    return m_pTemplatesTree->removeChild(_aTemplateName);
}
// -----------------------------------------------------------------------------

ISubtree const * MergedComponentData::findTemplate(OUString const & _aTemplateName) const
{
    INode const * pTemplateNode = m_pTemplatesTree->getChild(_aTemplateName);

    ISubtree const * pTemplateTree = pTemplateNode ? pTemplateNode->asISubtree() : NULL;

    OSL_ENSURE(pTemplateTree || !pTemplateNode, "ERROR: Template is not a subtree");

    return pTemplateTree;
}
// -----------------------------------------------------------------------------

std::auto_ptr<INode>    MergedComponentData::instantiateTemplate(OUString const & _aName, OUString const & _aTemplateName) const
{
    if (INode const * pTemplateNode = m_pTemplatesTree->getChild(_aTemplateName))
    {
        std::auto_ptr<INode> aResult = pTemplateNode->clone();
        aResult->setName(_aName);
        return aResult;
    }
    else
    {
        return std::auto_ptr<INode>();
    }
}
// -----------------------------------------------------------------------------

ISubtree  * MergedComponentData::setSchemaRoot(std::auto_ptr<ISubtree>  _aSchemaRoot)
{
    OSL_PRECOND(_aSchemaRoot.get(),"ERROR: Setting a NULL schema root.");
    OSL_PRECOND(!hasSchema(),"ERROR: Schema root already set");

    m_pSchemaTree = _aSchemaRoot;

    return m_pSchemaTree.get();
}
// -----------------------------------------------------------------------------
void  MergedComponentData::setTemplatesTree(std::auto_ptr<ISubtree>  _aTemplateTree)
{
    OSL_PRECOND(!hasTemplates(),"ERROR: Template Tree already set");
    m_pTemplatesTree = _aTemplateTree;
}
// -----------------------------------------------------------------------------
ISubtree  * MergedComponentData::addTemplate(std::auto_ptr<ISubtree>  _aNode, TemplateIdentifier const & aTemplate)
{
    OSL_PRECOND(_aNode.get(), "ERROR: Adding a NULL template");

    if (!m_pTemplatesTree.get())
    {
        m_pTemplatesTree = getDefaultTreeNodeFactory().createGroupNode( aTemplate.Component, node::Attributes() );
    }
    else
    {
        OSL_ENSURE(m_pTemplatesTree->getName().equals(aTemplate.Component),
                    "Template Component names do not match");
    }

    return m_pTemplatesTree->addChild( base_ptr(_aNode) )->asISubtree();
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
    } // namespace backend

// -------------------------------------------------------------------------
} // namespace configmgr
<|endoftext|>


<commit_before>#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <functional>
#include <iostream>
#include <memory>
#include <numeric>
#include <random>
#include <string>

#include "chainerx/array.h"
#include "chainerx/array_index.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward.h"
#include "chainerx/device_id.h"
#include "chainerx/dtype.h"
#include "chainerx/routines/creation.h"
#include "chainerx/routines/linalg.h"
#include "chainerx/routines/loss.h"
#include "chainerx/routines/manipulation.h"
#include "chainerx/routines/misc.h"
#include "chainerx/routines/reduction.h"
#include "chainerx/shape.h"
#include "chainerx/slice.h"
#include "mnist.h"

namespace chx = chainerx;

chx::Array MakeRandomParam(const chx::Shape& shape, std::mt19937& gen, std::normal_distribution<float>& dist) {
    int64_t n = shape.GetTotalSize();
    std::shared_ptr<float> data{new float[n], std::default_delete<float[]>{}};
    std::generate_n(data.get(), n, [&dist, &gen]() { return dist(gen); });

    return chx::FromContiguousHostData(shape, chx::Dtype::kFloat32, static_cast<std::shared_ptr<void>>(data), chx::GetDefaultDevice());
}

chx::Array MakePermutationOfIndices(int64_t n, std::mt19937& gen) {
    std::shared_ptr<int64_t> data{new int64_t[n], std::default_delete<int64_t[]>{}};
    std::iota(data.get(), data.get() + n, 0);
    std::shuffle(data.get(), data.get() + n, gen);

    return chx::FromContiguousHostData({n}, chx::Dtype::kInt64, static_cast<std::shared_ptr<void>>(data), chx::GetDefaultDevice());
}

class Model {
public:
    Model(int64_t n_in, int64_t n_hidden, int64_t n_out, int64_t n_layers, std::mt19937& gen, std::normal_distribution<float>& dist)
        : n_in_{n_in}, n_hidden_{n_hidden}, n_out_{n_out}, n_layers_{n_layers} {
        params_.clear();

        for (int64_t i = 0; i < n_layers_; ++i) {
            int64_t n_in = i == 0 ? n_in_ : n_hidden_;
            int64_t n_out = i == n_layers_ - 1 ? n_out_ : n_hidden_;
            params_.emplace_back(MakeRandomParam({n_in, n_out}, gen, dist));
            params_.emplace_back(chx::Zeros({n_out}, chx::Dtype::kFloat32));
        }

        for (const chx::Array& param : params_) {
            param.RequireGrad();
        }
    }

    chx::Array operator()(const chx::Array& x) {
        chx::Array h = x;
        for (int64_t i = 0; i < n_layers_; ++i) {
            h = chx::Dot(h, params_[i * 2]) + params_[i * 2 + 1];
            if (i != n_layers_ - 1) {
                h = chx::Maximum(0, h);
            }
        }
        return h;
    }

    const std::vector<chx::Array>& params() { return params_; }

private:
    int64_t n_in_;
    int64_t n_hidden_;
    int64_t n_out_;
    int64_t n_layers_;
    std::vector<chx::Array> params_;
};

void Run(int64_t epochs, int64_t batch_size, int64_t n_hidden, int64_t n_layers, float lr, const std::string& mnist_root) {
    // Read the MNIST dataset.
    chx::Array train_x = ReadMnistImages(mnist_root + "train-images-idx3-ubyte");
    chx::Array train_t = ReadMnistLabels(mnist_root + "train-labels-idx1-ubyte");
    chx::Array test_x = ReadMnistImages(mnist_root + "t10k-images-idx3-ubyte");
    chx::Array test_t = ReadMnistLabels(mnist_root + "t10k-labels-idx1-ubyte");

    train_x = train_x.AsType(chx::Dtype::kFloat32) / 255.f;
    train_t = train_t.AsType(chx::Dtype::kInt32);
    test_x = test_x.AsType(chx::Dtype::kFloat32) / 255.f;
    test_t = test_t.AsType(chx::Dtype::kInt32);

    int64_t n_train = train_x.shape().front();
    int64_t n_test = test_x.shape().front();

    // Initialize the model with random parameters.
    std::random_device rd{};
    std::mt19937 gen{rd()};
    std::normal_distribution<float> dist{0.f, 0.05f};
    Model model{train_x.shape()[1], n_hidden, 10, n_layers, gen, dist};

    auto start = std::chrono::high_resolution_clock::now();

    for (int64_t epoch = 0; epoch < epochs; ++epoch) {
        chx::Array train_indices = MakePermutationOfIndices(n_train, gen);

        for (int64_t i = 0; i < n_train; i += batch_size) {
            chx::Array indices = train_indices.At({chx::Slice{i, i + batch_size}});
            chx::Array x = train_x.Take(indices, 0);
            chx::Array t = train_t.Take(indices, 0);

            chx::Backward(chx::SoftmaxCrossEntropy(model(x), t).Mean());

            // Vanilla SGD.
            for (const chx::Array& param : model.params()) {
                chx::Array p = param.AsGradStopped();
                p -= param.GetGrad()->AsGradStopped() * lr;
                param.ClearGrad();
            }
        }

        // Evaluate.
        {
            chx::NoBackpropModeScope scope{};

            chx::Array loss = chx::Zeros({}, chx::Dtype::kFloat32);
            chx::Array acc = chx::Zeros({}, chx::Dtype::kFloat32);

            for (int64_t i = 0; i < n_test; i += batch_size) {
                std::vector<chx::ArrayIndex> indices{chx::Slice{i, i + batch_size}};
                chx::Array x = test_x.At(indices);
                chx::Array t = test_t.At(indices);
                chx::Array y = model(x);
                loss += chx::SoftmaxCrossEntropy(y, t);
                acc += (y.ArgMax(1).AsType(t.dtype()) == t).Sum().AsType(acc.dtype());
            }

            std::cout << "epoch: " << epoch << " loss=" << chx::AsScalar(loss / n_test) << " accuracy=" << chx::AsScalar(acc / n_test)
                      << " elapsed_time=" << std::chrono::duration<double>{std::chrono::high_resolution_clock::now() - start}.count()
                      << std::endl;
        }
    }
}

int main(int argc, char** argv) {
    int64_t epochs{20};
    int64_t batch_size{100};
    int64_t n_hidden{1000};
    int64_t n_layers{3};
    float lr{0.01};
    std::string device_name{"native"};
    std::string mnist_root{"./"};

    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];

        auto read_next_string = [&]() {
            ++i;
            if (i >= argc) {
                throw std::runtime_error("The value of flag " + arg + " is omitted.");
            }
            return argv[i];
        };
        auto read_next_int = [&]() { return std::atoi(read_next_string()); };
        auto read_next_float = [&]() { return std::atof(read_next_string()); };

        if (arg == "--epoch") {
            epochs = read_next_int();
        } else if (arg == "--batchsize") {
            batch_size = read_next_int();
        } else if (arg == "--unit") {
            n_hidden = read_next_int();
        } else if (arg == "--layer") {
            n_layers = read_next_int();
        } else if (arg == "--lr") {
            lr = read_next_float();
        } else if (arg == "--device") {
            device_name = read_next_string();
        } else if (arg == "--data") {
            mnist_root = read_next_string();
        } else {
            throw std::runtime_error("Unknown argument: " + arg);
        }
    }

    if (mnist_root.empty()) {
        throw std::runtime_error("MNIST directory cannot be empty.");
    }
    if (mnist_root.back() != '/') {
        mnist_root += "/";
    }

    chx::Context ctx{};
    chx::SetDefaultContext(&ctx);
    chx::Device& device = ctx.GetDevice(device_name);
    chx::SetDefaultDevice(&device);

    std::cout << "Epochs: " << epochs << std::endl;
    std::cout << "Minibatch size: " << batch_size << std::endl;
    std::cout << "Hidden neurons: " << n_hidden << std::endl;
    std::cout << "Layers: " << n_layers << std::endl;
    std::cout << "Learning rate: " << lr << std::endl;
    std::cout << "Device: " << device.name() << std::endl;
    std::cout << "MNIST root: " << mnist_root << std::endl;

    Run(epochs, batch_size, n_hidden, n_layers, lr, mnist_root);
}
<commit_msg>Sum the result of SCE<commit_after>#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <functional>
#include <iostream>
#include <memory>
#include <numeric>
#include <random>
#include <string>

#include "chainerx/array.h"
#include "chainerx/array_index.h"
#include "chainerx/backprop_mode.h"
#include "chainerx/backward.h"
#include "chainerx/device_id.h"
#include "chainerx/dtype.h"
#include "chainerx/routines/creation.h"
#include "chainerx/routines/linalg.h"
#include "chainerx/routines/loss.h"
#include "chainerx/routines/manipulation.h"
#include "chainerx/routines/misc.h"
#include "chainerx/routines/reduction.h"
#include "chainerx/shape.h"
#include "chainerx/slice.h"
#include "mnist.h"

namespace chx = chainerx;

chx::Array MakeRandomParam(const chx::Shape& shape, std::mt19937& gen, std::normal_distribution<float>& dist) {
    int64_t n = shape.GetTotalSize();
    std::shared_ptr<float> data{new float[n], std::default_delete<float[]>{}};
    std::generate_n(data.get(), n, [&dist, &gen]() { return dist(gen); });

    return chx::FromContiguousHostData(shape, chx::Dtype::kFloat32, static_cast<std::shared_ptr<void>>(data), chx::GetDefaultDevice());
}

chx::Array MakePermutationOfIndices(int64_t n, std::mt19937& gen) {
    std::shared_ptr<int64_t> data{new int64_t[n], std::default_delete<int64_t[]>{}};
    std::iota(data.get(), data.get() + n, 0);
    std::shuffle(data.get(), data.get() + n, gen);

    return chx::FromContiguousHostData({n}, chx::Dtype::kInt64, static_cast<std::shared_ptr<void>>(data), chx::GetDefaultDevice());
}

class Model {
public:
    Model(int64_t n_in, int64_t n_hidden, int64_t n_out, int64_t n_layers, std::mt19937& gen, std::normal_distribution<float>& dist)
        : n_in_{n_in}, n_hidden_{n_hidden}, n_out_{n_out}, n_layers_{n_layers} {
        params_.clear();

        for (int64_t i = 0; i < n_layers_; ++i) {
            int64_t n_in = i == 0 ? n_in_ : n_hidden_;
            int64_t n_out = i == n_layers_ - 1 ? n_out_ : n_hidden_;
            params_.emplace_back(MakeRandomParam({n_in, n_out}, gen, dist));
            params_.emplace_back(chx::Zeros({n_out}, chx::Dtype::kFloat32));
        }

        for (const chx::Array& param : params_) {
            param.RequireGrad();
        }
    }

    chx::Array operator()(const chx::Array& x) {
        chx::Array h = x;
        for (int64_t i = 0; i < n_layers_; ++i) {
            h = chx::Dot(h, params_[i * 2]) + params_[i * 2 + 1];
            if (i != n_layers_ - 1) {
                h = chx::Maximum(0, h);
            }
        }
        return h;
    }

    const std::vector<chx::Array>& params() { return params_; }

private:
    int64_t n_in_;
    int64_t n_hidden_;
    int64_t n_out_;
    int64_t n_layers_;
    std::vector<chx::Array> params_;
};

void Run(int64_t epochs, int64_t batch_size, int64_t n_hidden, int64_t n_layers, float lr, const std::string& mnist_root) {
    // Read the MNIST dataset.
    chx::Array train_x = ReadMnistImages(mnist_root + "train-images-idx3-ubyte");
    chx::Array train_t = ReadMnistLabels(mnist_root + "train-labels-idx1-ubyte");
    chx::Array test_x = ReadMnistImages(mnist_root + "t10k-images-idx3-ubyte");
    chx::Array test_t = ReadMnistLabels(mnist_root + "t10k-labels-idx1-ubyte");

    train_x = train_x.AsType(chx::Dtype::kFloat32) / 255.f;
    train_t = train_t.AsType(chx::Dtype::kInt32);
    test_x = test_x.AsType(chx::Dtype::kFloat32) / 255.f;
    test_t = test_t.AsType(chx::Dtype::kInt32);

    int64_t n_train = train_x.shape().front();
    int64_t n_test = test_x.shape().front();

    // Initialize the model with random parameters.
    std::random_device rd{};
    std::mt19937 gen{rd()};
    std::normal_distribution<float> dist{0.f, 0.05f};
    Model model{train_x.shape()[1], n_hidden, 10, n_layers, gen, dist};

    auto start = std::chrono::high_resolution_clock::now();

    for (int64_t epoch = 0; epoch < epochs; ++epoch) {
        chx::Array train_indices = MakePermutationOfIndices(n_train, gen);

        for (int64_t i = 0; i < n_train; i += batch_size) {
            chx::Array indices = train_indices.At({chx::Slice{i, i + batch_size}});
            chx::Array x = train_x.Take(indices, 0);
            chx::Array t = train_t.Take(indices, 0);

            chx::Backward(chx::SoftmaxCrossEntropy(model(x), t).Mean());

            // Vanilla SGD.
            for (const chx::Array& param : model.params()) {
                chx::Array p = param.AsGradStopped();
                p -= param.GetGrad()->AsGradStopped() * lr;
                param.ClearGrad();
            }
        }

        // Evaluate.
        {
            chx::NoBackpropModeScope scope{};

            chx::Array loss = chx::Zeros({}, chx::Dtype::kFloat32);
            chx::Array acc = chx::Zeros({}, chx::Dtype::kFloat32);

            for (int64_t i = 0; i < n_test; i += batch_size) {
                std::vector<chx::ArrayIndex> indices{chx::Slice{i, i + batch_size}};
                chx::Array x = test_x.At(indices);
                chx::Array t = test_t.At(indices);
                chx::Array y = model(x);
                loss += chx::SoftmaxCrossEntropy(y, t).Sum();
                acc += (y.ArgMax(1).AsType(t.dtype()) == t).Sum().AsType(acc.dtype());
            }

            std::cout << "epoch: " << epoch << " loss=" << chx::AsScalar(loss / n_test) << " accuracy=" << chx::AsScalar(acc / n_test)
                      << " elapsed_time=" << std::chrono::duration<double>{std::chrono::high_resolution_clock::now() - start}.count()
                      << std::endl;
        }
    }
}

int main(int argc, char** argv) {
    int64_t epochs{20};
    int64_t batch_size{100};
    int64_t n_hidden{1000};
    int64_t n_layers{3};
    float lr{0.01};
    std::string device_name{"native"};
    std::string mnist_root{"./"};

    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];

        auto read_next_string = [&]() {
            ++i;
            if (i >= argc) {
                throw std::runtime_error("The value of flag " + arg + " is omitted.");
            }
            return argv[i];
        };
        auto read_next_int = [&]() { return std::atoi(read_next_string()); };
        auto read_next_float = [&]() { return std::atof(read_next_string()); };

        if (arg == "--epoch") {
            epochs = read_next_int();
        } else if (arg == "--batchsize") {
            batch_size = read_next_int();
        } else if (arg == "--unit") {
            n_hidden = read_next_int();
        } else if (arg == "--layer") {
            n_layers = read_next_int();
        } else if (arg == "--lr") {
            lr = read_next_float();
        } else if (arg == "--device") {
            device_name = read_next_string();
        } else if (arg == "--data") {
            mnist_root = read_next_string();
        } else {
            throw std::runtime_error("Unknown argument: " + arg);
        }
    }

    if (mnist_root.empty()) {
        throw std::runtime_error("MNIST directory cannot be empty.");
    }
    if (mnist_root.back() != '/') {
        mnist_root += "/";
    }

    chx::Context ctx{};
    chx::SetDefaultContext(&ctx);
    chx::Device& device = ctx.GetDevice(device_name);
    chx::SetDefaultDevice(&device);

    std::cout << "Epochs: " << epochs << std::endl;
    std::cout << "Minibatch size: " << batch_size << std::endl;
    std::cout << "Hidden neurons: " << n_hidden << std::endl;
    std::cout << "Layers: " << n_layers << std::endl;
    std::cout << "Learning rate: " << lr << std::endl;
    std::cout << "Device: " << device.name() << std::endl;
    std::cout << "MNIST root: " << mnist_root << std::endl;

    Run(epochs, batch_size, n_hidden, n_layers, lr, mnist_root);
}
<|endoftext|>


<commit_before>/***************************************************************************
 *  @file       main.cpp
 *  @author     Alan.W
 *  @date       22  Jan 2014
 *  @remark     This code is for the exercises from C++ Primer 5th Edition
 *  @note
 ***************************************************************************/
//
// Exercise 15.12:
// Is it ever useful to declare a member function as both override and final?
// Why or why not?
//  Sure. override means overriding the same name virtual function in base class.
//  final means preventing any overriding this virtual function by any derived classes
//  that are more lower at the hierachy .
//
// Exercise 15.13:
// Given the following classes, explain each print function:
// If there is a problem in this code, how would you fix it?
//
// Exercise 15.14:
// Given the classes from the previous exercise and the following objects,
// determine which function is called at run time:
//

#include <iostream>
#include <string>

#include "quote.h"
#include "bulk_quote.h"
#include "limit_quote.h"

class base
{
public:
   std::string name() { return basename; }
   virtual void print(std::ostream &os) { os << basename; }
   //     ~~~~~^^^^^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   //  The print here just output the basename of the base.
private:
   std::string basename = "base\n";
};

class derived : public base
{
public:
   void print(std::ostream &os) override { base::print(os); os << " derived\n " << i; }
   //   ^^^^^                   ^^^^^^^^   ^^^^^^    --  added to fix this problem
   //  this print wanted to call the print from the base class.
   //  however, the class scope base:: was omitted.As a result
   //  it will cause an infinit recursion.
   //  btw, we can add a keyword `override` to show this function
   //  overrides a virtual function from the base class, although
   //  it is not neccessary, but for security, the more, the better.

private:
   int i;
};

void print_debug(const Quote& q);
double print_total (std::ostream& os, const Quote& item, size_t n);
int main()
{
    // ex15.14
    base bobj;
    base *bp1 = &bobj;
    base &br1 = bobj;
    derived dobj;
    base *bp2 = &dobj;
    base &br2 = dobj;

    // a.  this is an object, so compile time.
    //bobj.print(std::cout);

    // b.  this is an object, so compile time.
    //dobj.print(std::cout);

    // c.  function name is not virtual , so no dynamic
    //     binding happens.so compile time
    //std::cout << bp1->name();

    // d.  function name is not virtual , so no dynamic
    //     binding happens.so compile time
    //std::cout << bp2->name();

    // e.  run time
    //br1.print(std::cout);

    // f.  run time
    br2.print(std::cout);

    return 0;
}

double print_total(std::ostream &os, const Quote &item, size_t n)
{
    double ret = item.net_price(n);

    os << "ISBN:" << item.isbn()
       << "# sold: " << n << " total due: " << ret << std::endl;

    return ret;
}

void print_debug(const Quote &q)
{
    q.debug();
}
<commit_msg>fixed a little typo in ex15.12.13.14/main.cpp<commit_after>/***************************************************************************
 *  @file       main.cpp
 *  @author     Alan.W
 *  @date       22  Jan 2014
 *  @remark     This code is for the exercises from C++ Primer 5th Edition
 *  @note
 ***************************************************************************/
//
// Exercise 15.12:
// Is it ever useful to declare a member function as both override and final?
// Why or why not?
//  Sure. override means overriding the same name virtual function in base class.
//  final means preventing any overriding this virtual function by any derived classes
//  that are more lower at the hierarchy .
//
// Exercise 15.13:
// Given the following classes, explain each print function:
// If there is a problem in this code, how would you fix it?
//
// Exercise 15.14:
// Given the classes from the previous exercise and the following objects,
// determine which function is called at run time:
//

#include <iostream>
#include <string>

#include "quote.h"
#include "bulk_quote.h"
#include "limit_quote.h"

class base
{
public:
   std::string name() { return basename; }
   virtual void print(std::ostream &os) { os << basename; }
   //     ~~~~~^^^^^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   //  The print here just output the basename of the base.
private:
   std::string basename = "base\n";
};

class derived : public base
{
public:
   void print(std::ostream &os) override { base::print(os); os << " derived\n " << i; }
   //   ^^^^^                   ^^^^^^^^   ^^^^^^    --  added to fix this problem
   //  this print wanted to call the print from the base class.
   //  however, the class scope base:: was omitted.As a result
   //  it will cause an infinit recursion.
   //  btw, we can add a keyword `override` to show this function
   //  overrides a virtual function from the base class, although
   //  it is not neccessary, but for security, the more, the better.

private:
   int i;
};

void print_debug(const Quote& q);
double print_total (std::ostream& os, const Quote& item, size_t n);
int main()
{
    // ex15.14
    base bobj;
    base *bp1 = &bobj;
    base &br1 = bobj;
    derived dobj;
    base *bp2 = &dobj;
    base &br2 = dobj;

    // a.  this is an object, so compile time.
    //bobj.print(std::cout);

    // b.  this is an object, so compile time.
    //dobj.print(std::cout);

    // c.  function name is not virtual , so no dynamic
    //     binding happens.so compile time
    //std::cout << bp1->name();

    // d.  function name is not virtual , so no dynamic
    //     binding happens.so compile time
    //std::cout << bp2->name();

    // e.  run time
    //br1.print(std::cout);

    // f.  run time
    br2.print(std::cout);

    return 0;
}

double print_total(std::ostream &os, const Quote &item, size_t n)
{
    double ret = item.net_price(n);

    os << "ISBN:" << item.isbn()
       << "# sold: " << n << " total due: " << ret << std::endl;

    return ret;
}

void print_debug(const Quote &q)
{
    q.debug();
}
<|endoftext|>


<commit_before>#include "aquila/global.h"
#include "aquila/transform/FftFactory.h"
#include "aquila/tools/TextPlot.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include <memory>

int main()
{
    // input signal parameters
    const std::size_t SIZE = 64;
    const Aquila::FrequencyType sampleFreq = 2000;
    const double dt = 1.0/sampleFreq;
    const Aquila::FrequencyType f1 = 96, f2 = 813;
    const Aquila::FrequencyType f_lp = 500;

    double x[SIZE];
    for (std::size_t i = 0; i < SIZE; ++i)
    {
        x[i] = 32*std::sin(2*M_PI*f1*i*dt) + 8*std::sin(2*M_PI*f2*i*dt + 0.75*M_PI);
    }
    Aquila::TextPlot plt("Signal waveform before filtration");
    plt.plot(x, SIZE);

    // calculate the FFT
    std::auto_ptr<Aquila::Fft> fft = Aquila::FftFactory::getFft(SIZE);
    Aquila::ComplexType spectrum[SIZE];
    fft->fft(x, spectrum);
    plt.setTitle("Signal spectrum before filtration");
    plt.plotSpectrum(spectrum, SIZE);

    // generate a low-pass filter spectrum
    Aquila::ComplexType filterSpectrum[SIZE];
    for (std::size_t i = 0; i < SIZE; ++i)
    {
        if (i < (SIZE * f_lp / sampleFreq))
        {
            // passband
            filterSpectrum[i] = 1.0;
        }
        else
        {
            // stopband
            filterSpectrum[i] = 0.0;
        }
    }
    plt.setTitle("Filter spectrum");
    plt.plotSpectrum(filterSpectrum, SIZE);

    // the following line does the multiplication of two spectra
    // (which is complementary to convolution in time domain)
    std::transform(spectrum, spectrum + SIZE, filterSpectrum, spectrum,
                   std::multiplies<Aquila::ComplexType>());
    plt.setTitle("Signal spectrum after filtration");
    plt.plotSpectrum(spectrum, SIZE);

    // Inverse FFT moves us back to time domain
    double x1[SIZE];
    fft->ifft(spectrum, x1);
    plt.setTitle("Signal waveform after filtration");
    plt.plot(x1, SIZE);

    return 0;
}
<commit_msg>Used C++11 lambda in fft_filter example.<commit_after>#include "aquila/global.h"
#include "aquila/transform/FftFactory.h"
#include "aquila/tools/TextPlot.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include <memory>

int main()
{
    // input signal parameters
    const std::size_t SIZE = 64;
    const Aquila::FrequencyType sampleFreq = 2000;
    const double dt = 1.0/sampleFreq;
    const Aquila::FrequencyType f1 = 96, f2 = 813;
    const Aquila::FrequencyType f_lp = 500;

    double x[SIZE];
    for (std::size_t i = 0; i < SIZE; ++i)
    {
        x[i] = 32*std::sin(2*M_PI*f1*i*dt) + 8*std::sin(2*M_PI*f2*i*dt + 0.75*M_PI);
    }
    Aquila::TextPlot plt("Signal waveform before filtration");
    plt.plot(x, SIZE);

    // calculate the FFT
    std::auto_ptr<Aquila::Fft> fft = Aquila::FftFactory::getFft(SIZE);
    Aquila::ComplexType spectrum[SIZE];
    fft->fft(x, spectrum);
    plt.setTitle("Signal spectrum before filtration");
    plt.plotSpectrum(spectrum, SIZE);

    // generate a low-pass filter spectrum
    Aquila::ComplexType filterSpectrum[SIZE];
    for (std::size_t i = 0; i < SIZE; ++i)
    {
        if (i < (SIZE * f_lp / sampleFreq))
        {
            // passband
            filterSpectrum[i] = 1.0;
        }
        else
        {
            // stopband
            filterSpectrum[i] = 0.0;
        }
    }
    plt.setTitle("Filter spectrum");
    plt.plotSpectrum(filterSpectrum, SIZE);

    // the following line does the multiplication of two spectra
    // (which is complementary to convolution in time domain)
    typedef Aquila::ComplexType cplx;
    std::transform(spectrum, spectrum + SIZE, filterSpectrum, spectrum,
                   [] (cplx x, cplx y) { return x * y; });
    plt.setTitle("Signal spectrum after filtration");
    plt.plotSpectrum(spectrum, SIZE);

    // Inverse FFT moves us back to time domain
    double x1[SIZE];
    fft->ifft(spectrum, x1);
    plt.setTitle("Signal waveform after filtration");
    plt.plot(x1, SIZE);

    return 0;
}
<|endoftext|>