<commit_before>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);
	// Read galaxies
	Gals G;
    if(F.Ascii){
        G=read_galaxies_ascii(F);}
    else{
        G = read_galaxies(F);
    }
	F.Ngal = G.size();
	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
    std::vector<int> count;
    count=count_galaxies(G);
    for(int i=0;i<8;i++){printf ("   %d  \n",count[i]);}
    // make MTL
    MTL M=make_MTL(G,F);
    for(int i=0;i<M.priority_list.size();++i){
        printf(" priority   %d",M.priority_list[i]);
    }
    printf(" \n");
    assign_priority_class(M);
    //find available SS and SF galaxies on each petal

    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        count_class[M[i].priority_class]+=1;
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }

    printf(" number of MTL galaxies  %d\n",M.size());
    printf("Read fiber center positions and compute related things\n");
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
    printf("spectrometer has to be identified from 0 to F.Npetal-1\n");
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F); pp.compute_fibsofsp(F);
    printf("get neighbors of each fiber;\n");
                                                //for each spectrometer, get list of fibers

    printf("Read plates in order they are to be observed\n ");

	Plates P_original = read_plate_centers(F);
    F.Nplate=P_original.size();
    printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n");
    Plates P;
    P.resize(F.Nplate);//don't permute plates
/*    List permut = random_permut(F.Nplate);
    for (int jj=0; jj<F.Nplate; jj++){
        P[jj]=P_original[permut[jj]];
    }
 */
    P=P_original;
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
    //diagnostic
    for (int j=0;j<F.Nplate;++j){
        printf("\n j= %d ",j);
        for (int p=0;p<10;++p){
            printf(" %d ",P[j].SS_av_gal[p].size());
        }

    }
	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct target> T(M,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(M,T,P,pp,F);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(M,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf("before assignment\n");
	Assignment A(M,F);
	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
	//new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars
                                   // assumes maximum number of observations needed for QSOs, LRGs
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);

    simple_assign(M,P,pp,F,A);
    diagnostic(M,G,F,A);
    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
                                    // Want to have even distribution of unused fibers
                                    // so we can put in sky fibers and standard stars

	// Smooth out distribution of free fibers, and increase the number of assignments

	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
	for (int i=0; i<1; i++) {                           // more iterations will improve performance slightly
		improve(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
	}
	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);

	// Still not updated, so all QSO targets have multiple observations etc
	// Apply and update the plan --------------------------------------
	init_time_at(time,"# Begin real time assignment",t);
	for (int jj=0; jj<F.Nplate; jj++) {
		int j = A.next_plate;
        printf(" j = %d is next plate\n",j);

		assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation
		//assign_unused(j,M,P,pp,F,A);
		//if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies

		//printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl();
		// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
        printf("done with assign_sf_ss for plate %d\n", j);
		if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n");

		A.next_plate++;
		// Redistribute and improve on various occasions  add more times if desired
/*
		if ( j==1000 || j==4000) {
			redistribute_tf(M,P,pp,F,A);
			redistribute_tf(M,P,pp,F,A);
			improve(M,P,pp,F,A);
			redistribute_tf(M,P,pp,F,A);
            //diagnostic(M,G,F,A);
		}
*/
    }
	print_time(time,"# ... took :");

	// Results -------------------------------------------------------
	if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output
	display_results("doc/figs/",G,M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane

	print_time(t,"# Finished !... in");

	return(0);

}
<commit_msg>new diagnostics<commit_after>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"
//reduce redistributes, updates  07/02/15 rnc
int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t, time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file //
	F.readInputFile(argv[1]);
	printFile(argv[1]);
	// Read galaxies
	Gals G;
    if(F.Ascii){
        G=read_galaxies_ascii(F);}
    else{
        G = read_galaxies(F);
    }
	F.Ngal = G.size();
	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());
    std::vector<int> count;
    count=count_galaxies(G);
    for(int i=0;i<8;i++){printf ("   %d  \n",count[i]);}
    // make MTL
    MTL M=make_MTL(G,F);
    for(int i=0;i<M.priority_list.size();++i){
        printf(" priority   %d",M.priority_list[i]);
    }
    printf(" \n");
    assign_priority_class(M);
    //find available SS and SF galaxies on each petal

    std::vector <int> count_class(M.priority_list.size(),0);
    for(int i;i<M.size();++i){
        count_class[M[i].priority_class]+=1;
    }
    for(int i;i<M.priority_list.size();++i){
        printf("  class  %d  number  %d\n",i,count_class[i]);
    }

    printf(" number of MTL galaxies  %d\n",M.size());
    printf("Read fiber center positions and compute related things\n");
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1;
    printf("spectrometer has to be identified from 0 to F.Npetal-1\n");
	F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
	pp.get_neighbors(F); pp.compute_fibsofsp(F);
    printf("get neighbors of each fiber;\n");
                                                //for each spectrometer, get list of fibers

    printf("Read plates in order they are to be observed\n ");

	Plates P_original = read_plate_centers(F);
    F.Nplate=P_original.size();
    printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n");
    Plates P;
    P.resize(F.Nplate);//don't permute plates
/*    List permut = random_permut(F.Nplate);
    for (int jj=0; jj<F.Nplate; jj++){
        P[jj]=P_original[permut[jj]];
    }
 */
    P=P_original;
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
    //diagnostic
    for (int j=0;j<F.Nplate;++j){
        printf("\n j= %d ",j);
        for (int p=0;p<10;++p){
            printf(" %d ",P[j].av_gals[p].size());
        }

    }
	// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
	F.cb = create_cb(); // cb=central body
	F.fh = create_fh(); // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01;
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct target> T(M,MinTreeSize);
	print_time(time,"# ... took :");//T.stats();

	// For plates/fibers, collect available galaxies; done in parallel  P[plate j].av_gal[k]=[g1,g2,..]
	collect_galaxies_for_all(M,T,P,pp,F);

	// For each galaxy, computes available tilefibers  G[i].av_tfs = [(j1,k1),(j2,k2),..]
	collect_available_tilefibers(M,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
    printf("before assignment\n");
	Assignment A(M,F);
	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
	//new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars
                                   // assumes maximum number of observations needed for QSOs, LRGs
    printf(" Nplate %d  Ngal %d   Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);

    simple_assign(M,P,pp,F,A);
    diagnostic(M,G,F,A);
    print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
                                    // Want to have even distribution of unused fibers
                                    // so we can put in sky fibers and standard stars

	// Smooth out distribution of free fibers, and increase the number of assignments

	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
	for (int i=0; i<1; i++) {                           // more iterations will improve performance slightly
		improve(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
		redistribute_tf(M,P,pp,F,A);
	}
	for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);

	print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);

	// Still not updated, so all QSO targets have multiple observations etc
	// Apply and update the plan --------------------------------------
	init_time_at(time,"# Begin real time assignment",t);
	for (int jj=0; jj<F.Nplate; jj++) {
		int j = A.next_plate;
        printf(" j = %d is next plate\n",j);

		assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation
		//assign_unused(j,M,P,pp,F,A);
		//if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies

		//printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl();
		// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
        printf("done with assign_sf_ss for plate %d\n", j);
		if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n");

		A.next_plate++;
		// Redistribute and improve on various occasions  add more times if desired
/*
		if ( j==1000 || j==4000) {
			redistribute_tf(M,P,pp,F,A);
			redistribute_tf(M,P,pp,F,A);
			improve(M,P,pp,F,A);
			redistribute_tf(M,P,pp,F,A);
            //diagnostic(M,G,F,A);
		}
*/
    }
	print_time(time,"# ... took :");

	// Results -------------------------------------------------------
	if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output
	display_results("doc/figs/",G,M,P,pp,F,A,true);
	if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane

	print_time(t,"# Finished !... in");

	return(0);

}
<|endoftext|>


<commit_before>#include <Arduino.h>
#include "DiscoStrips.h"
#include "FastLED.h"
#include <SPI.h>
#include <WiFi101.h>
#include "Answer.h"
#include "DuinoREST.h"
#include "Modes.h"

using namespace std;

DiscoStrips* disco = NULL;
DuinoREST* rest = NULL;

#define NUM_STRIPS 1
#define NUM_LEDS 10

SimpleVector<CRGB>* ledArray;
int currentMode = 0;
int brightness = 25;
int colour = 4;

char ssid[] = "Resistance Is Futile 2"; // created AP name
char pass[] = "liss#dfe1AWdfew";      // AP password (needed only for WEP, must be exactly 10 or 26 characters in length)
int keyIndex = 0;                // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
WiFiServer server(80);

// We loop to add the line for each strip
template< unsigned N > struct AddLeds{
  static void generate() __attribute__((always_inline)){
    FastLED.addLeds<NEOPIXEL, N-1>(ledArray->get(N-1), NUM_LEDS);
    AddLeds< N - 1 >::generate();
  }
};
template<> struct AddLeds<0>{ static inline void generate(){} };

void printWiFiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  // print where to go in a browser:
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);

}

void discoFunc(String line, Answer* answer)
{
  disco->rest_parsing(line, answer);
}

void brightnessFunc(String line, Answer* answer)
{
  if(line.startsWith("PUT /brightness/"))
  {
    brightness = line.substring(16).toInt();
  }
  answer->add("{\"brightness\":");
  answer->add(String(brightness));
  answer->add("}");
}

String colours[] = {"red", "green", "yellow", "blue", "white"};
CRGB crgbs[] = {CRGB::Red, CRGB::DarkGreen, CRGB::Yellow, CRGB::Blue, CRGB::White};

void colourFunc(String line, Answer* answer)
{
  if(line.startsWith("PUT /colour/"))
  {
    String colourReq = line.substring(12);
    for(int i=0; i < 5; i++)
    {
      if(colourReq.startsWith(colours[i]))
      {
        colour = i;
        break;
      }
    }
  }
  answer->add("{\"colour\":");
  answer->add(colours[colour]);
  answer->add(",\"options\":[");
  for(int i=0; i < 5; i++)
  {
    answer->add("\"");
    answer->add(colours[i]);
    answer->add("\"");
    if(i < 4)
    {
      answer->add(", ");
    }
  }
  answer->add("]}");
}

void modesFunc(String line, Answer* answer)
{
  if(line.startsWith("GET /mode"))
  {
    answer->add("{\"modes\":[\"off\", \"on\", \"night\", \"fisco\"]}");
  }
  else if(line.startsWith("PUT /mode/on"))
  {
    currentMode = 1;
    answer->add("{\"mode\":\"on\"}");
  }
  else if(line.startsWith("PUT /mode/night"))
  {
    currentMode = 2;
    answer->add("{\"mode\":\"Night\"}");
  }
  else if(line.startsWith("PUT /mode/disco"))
  {
    currentMode = 3;
    answer->add("{\"mode\":\"disco\"}");
  }
  else
  {
    currentMode = 0;
    answer->add("{\"mode\":\"off\"}");
  }
}

void setup()
{
  Serial.begin(115200);
  delay(1000);
  Serial.println("Setup");
  delay(1000);
  Serial.println("Setup");
  ledArray = new SimpleVector<CRGB>(NUM_STRIPS, NUM_LEDS);
  AddLeds<NUM_STRIPS>::generate();

  disco = new DiscoStrips(ledArray);
  rest = new DuinoREST;

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // by default the local IP address of will be 192.168.1.1
  // you can override it with the following:
  // WiFi.config(IPAddress(10, 0, 0, 1));

  // Create open network. Change this line if you want to create an WEP network:
  // status = WiFi.beginAP(ssid);
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);

    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    // wait 10 seconds for connection:
//    delay(1000);
  }

  // start the web server on port 80
  server.begin();

  // you're connected now, so print out the status
  printWiFiStatus();

  rest->addHandler("disco", discoFunc);
  rest->addHandler("mode", modesFunc);
  rest->addHandler("brightness", brightnessFunc);
  rest->addHandler("colour", colourFunc);
}

void allLedsOff()
{
  for(int i=0; i < ledArray->rows(); i++)
  {
    for(int j=0; j < ledArray->cols(); j++)
    {
      *ledArray->get(i, j) = CRGB::Black;
    }
  }

}

void allLedsOn()
{
  for(int i=0; i < ledArray->rows(); i++)
  {
    for(int j=0; j < ledArray->cols(); j++)
    {
      *ledArray->get(i, j) = crgbs[colour];
      *ledArray->get(i, j) %= brightness;
    }
  }
}

void loop()
{
  // compare the previous status to the current status
  if (status != WiFi.status()) {
    // it has changed update the variable
    status = WiFi.status();

    if (status == WL_AP_CONNECTED) {
      byte remoteMac[6];

      // a device has connected to the AP
      Serial.print("Device connected to AP, MAC address: ");
      WiFi.APClientMacAddress(remoteMac);
      Serial.print(remoteMac[5], HEX);
      Serial.print(":");
      Serial.print(remoteMac[4], HEX);
      Serial.print(":");
      Serial.print(remoteMac[3], HEX);
      Serial.print(":");
      Serial.print(remoteMac[2], HEX);
      Serial.print(":");
      Serial.print(remoteMac[1], HEX);
      Serial.print(":");
      Serial.println(remoteMac[0], HEX);
    } else {
      // a device has disconnected from the AP, and we are back in listening mode
      Serial.println("Device disconnected from AP");
    }
  }
  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    rest->handle(client);
    // close the connection:
    delay(1);
    client.stop();
  }

  switch(currentMode)
  {
    case 3:
      disco->enable();
      break;

    case 2:
      disco->disable();
      break;

    case 1:
      disco->disable();
      allLedsOn();
      break;

    case 0:
    default:
      disco->disable();
      allLedsOff();
          break;
  }

  disco->tick();
  FastLED.show();
}
<commit_msg>dev: Minor update<commit_after>#include <Arduino.h>
#include "DiscoStrips.h"
#include "FastLED.h"
#include <SPI.h>
#include <WiFi101.h>
#include "Answer.h"
#include "DuinoREST.h"
#include "Modes.h"

using namespace std;

DiscoStrips* disco = NULL;
DuinoREST* rest = NULL;

#define NUM_STRIPS 1
#define NUM_LEDS 10

SimpleVector<CRGB>* ledArray;
int currentMode = 0;
int brightness = 25;
int colour = 4;

char ssid[] = "<AP name>";
char pass[] = "<password>";
int keyIndex = 0;

int status = WL_IDLE_STATUS;
WiFiServer server(80);

// We loop to add the line for each strip
template< unsigned N > struct AddLeds{
  static void generate() __attribute__((always_inline)){
    FastLED.addLeds<NEOPIXEL, N-1>(ledArray->get(N-1), NUM_LEDS);
    AddLeds< N - 1 >::generate();
  }
};
template<> struct AddLeds<0>{ static inline void generate(){} };

void printWiFiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  // print where to go in a browser:
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);

}

void discoFunc(String line, Answer* answer)
{
  disco->rest_parsing(line, answer);
}

void brightnessFunc(String line, Answer* answer)
{
  if(line.startsWith("PUT /brightness/"))
  {
    brightness = line.substring(16).toInt();
  }
  answer->add("{\"brightness\":");
  answer->add(String(brightness));
  answer->add("}");
}

String colours[] = {"red", "green", "yellow", "blue", "white"};
CRGB crgbs[] = {CRGB::Red, CRGB::DarkGreen, CRGB::Yellow, CRGB::Blue, CRGB::White};

void colourFunc(String line, Answer* answer)
{
  if(line.startsWith("PUT /colour/"))
  {
    String colourReq = line.substring(12);
    for(int i=0; i < 5; i++)
    {
      if(colourReq.startsWith(colours[i]))
      {
        colour = i;
        break;
      }
    }
  }
  answer->add("{\"colour\":");
  answer->add(colours[colour]);
  answer->add(",\"options\":[");
  for(int i=0; i < 5; i++)
  {
    answer->add("\"");
    answer->add(colours[i]);
    answer->add("\"");
    if(i < 4)
    {
      answer->add(", ");
    }
  }
  answer->add("]}");
}

void modesFunc(String line, Answer* answer)
{
  if(line.startsWith("GET /mode"))
  {
    answer->add("{\"modes\":[\"off\", \"on\", \"night\", \"fisco\"]}");
  }
  else if(line.startsWith("PUT /mode/on"))
  {
    currentMode = 1;
    answer->add("{\"mode\":\"on\"}");
  }
  else if(line.startsWith("PUT /mode/night"))
  {
    currentMode = 2;
    answer->add("{\"mode\":\"Night\"}");
  }
  else if(line.startsWith("PUT /mode/disco"))
  {
    currentMode = 3;
    answer->add("{\"mode\":\"disco\"}");
  }
  else
  {
    currentMode = 0;
    answer->add("{\"mode\":\"off\"}");
  }
}

void setup()
{
  Serial.begin(115200);
  delay(1000);
  Serial.println("Setup");
  delay(1000);
  Serial.println("Setup");
  ledArray = new SimpleVector<CRGB>(NUM_STRIPS, NUM_LEDS);
  AddLeds<NUM_STRIPS>::generate();

  disco = new DiscoStrips(ledArray);
  rest = new DuinoREST;

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // by default the local IP address of will be 192.168.1.1
  // you can override it with the following:
  // WiFi.config(IPAddress(10, 0, 0, 1));

  // Create open network. Change this line if you want to create an WEP network:
  // status = WiFi.beginAP(ssid);
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to Network named: ");
    Serial.println(ssid);                   // print the network name (SSID);

    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    // wait 10 seconds for connection:
//    delay(1000);
  }

  // start the web server on port 80
  server.begin();

  // you're connected now, so print out the status
  printWiFiStatus();

  rest->addHandler("disco", discoFunc);
  rest->addHandler("mode", modesFunc);
  rest->addHandler("brightness", brightnessFunc);
  rest->addHandler("colour", colourFunc);
}

void allLedsOff()
{
  for(int i=0; i < ledArray->rows(); i++)
  {
    for(int j=0; j < ledArray->cols(); j++)
    {
      *ledArray->get(i, j) = CRGB::Black;
    }
  }

}

void allLedsOn()
{
  for(int i=0; i < ledArray->rows(); i++)
  {
    for(int j=0; j < ledArray->cols(); j++)
    {
      *ledArray->get(i, j) = crgbs[colour];
      *ledArray->get(i, j) %= brightness;
    }
  }
}

void loop()
{
  // compare the previous status to the current status
  if (status != WiFi.status()) {
    // it has changed update the variable
    status = WiFi.status();

    if (status == WL_AP_CONNECTED) {
      byte remoteMac[6];

      // a device has connected to the AP
      Serial.print("Device connected to AP, MAC address: ");
      WiFi.APClientMacAddress(remoteMac);
      Serial.print(remoteMac[5], HEX);
      Serial.print(":");
      Serial.print(remoteMac[4], HEX);
      Serial.print(":");
      Serial.print(remoteMac[3], HEX);
      Serial.print(":");
      Serial.print(remoteMac[2], HEX);
      Serial.print(":");
      Serial.print(remoteMac[1], HEX);
      Serial.print(":");
      Serial.println(remoteMac[0], HEX);
    } else {
      // a device has disconnected from the AP, and we are back in listening mode
      Serial.println("Device disconnected from AP");
    }
  }
  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    rest->handle(client);
    // close the connection:
    delay(1);
    client.stop();
  }

  switch(currentMode)
  {
    case 3:
      disco->enable();
      break;

    case 2:
      disco->disable();
      break;

    case 1:
      disco->disable();
      allLedsOn();
      break;

    case 0:
    default:
      disco->disable();
      allLedsOff();
          break;
  }

  disco->tick();
  FastLED.show();
}
<|endoftext|>


<commit_before>#include <avr/io.h>
#include <SD.h>
#include <Arduino.h>

#include "bits.h"
#include "session.h"
#include "frame.h"

#define SD_CHIPSELECT 4
#define SAMPLE_RATE 256

uint8_t frame_buf[FRAME_SIZE];
uint8_t frame_counter;

int init_sd()
{
	if (!SD.begin(SD_CHIPSELECT)) {
		return -1;
	}
	return 0;
}

int init_ecg()
{
	frame_counter = 0;
	memset(frame_buf, 0, FRAME_SIZE);
	if (init_sd() < 0) {
		return -1;
	}
	uint64_t init_time = 1423297511ULL; // XXX: actually get time
	session *s = session_init(init_time, FRAME_CHANNELS);
	if (s == NULL) {
		return -2;
	}
	return 0;
}

int main(void)
{
	if (init_ecg() != 0) {
		return -1;
	}
	for (;;) {
		frame_buf[0] = frame_counter;
		// Counter will overflow at 256.
		frame_counter++;
	}
}
<commit_msg>Add error state and debugging output<commit_after>#include <avr/io.h>
#include <SD.h>
#include <Arduino.h>

#include "bits.h"
#include "session.h"
#include "frame.h"

#define SD_CHIPSELECT 4
#define SAMPLE_RATE 256

#define PIN_ERROR_LED 13

#define DEBUG 1

uint8_t frame_buf[FRAME_SIZE];
uint8_t frame_counter;

void state_error()
{
	#ifdef DEBUG
	Serial.println("Entering error state.");
	#endif
	pinMode(PIN_ERROR_LED, OUTPUT);
	for (;;) {
		digitalWrite(PIN_ERROR_LED, HIGH);
		delay(500);
		digitalWrite(PIN_ERROR_LED, LOW);
		delay(500);
	}
}

void state_run()
{
	for (;;) {
		// do stuff
	}
}

int init_sd()
{
	if (!SD.begin(SD_CHIPSELECT)) {
		return -1;
	}
	return 0;
}

int init_ecg()
{
	frame_counter = 0;
	memset(frame_buf, 0, FRAME_SIZE);
	if (init_sd() < 0) {
		#ifdef DEBUG
		Serial.println("Could not initialize SD card.");
		#endif
		return -1;
	}
	uint64_t init_time = 1423297511ULL; // XXX: actually get time
	session *s = session_init(init_time, FRAME_CHANNELS);
	if (s == NULL) {
		#ifdef DEBUG
		Serial.println("Could not initialize session.");
		#endif
		return -2;
	}
	return 0;
}

int main(void)
{
	#ifdef DEBUG
	Serial.begin(9600);
	Serial.println("ecg-datalogger initializing.");
	#endif
	if (init_ecg() != 0) {
		state_error();
	} else {
		state_run();
	}
}
<|endoftext|>


<commit_before>#include <tclap/CmdLine.h>
#include <llvm/IR/Module.h>
#include <fstream>
#include <sstream>
#include <chrono>

#include "utils/util.hpp"
#include "utils/error.hpp"
#include "lexer.hpp"
#include "parser/tokenParser.hpp"
#include "parser/xmlParser.hpp"
#include "llvm/compiler.hpp"
#include "llvm/runner.hpp"

enum ExitCodes: int {
  NORMAL_EXIT = 0, ///< Everything is OK
  TCLAP_ERROR = 11, ///< TCLAP did something bad, should not happen
  CLI_ERROR = 1, ///< The user used a wrong combination of options
  USER_PROGRAM_ERROR = 2, ///< The thing we had to lex/parse/run has an issue
  INTERNAL_ERROR = 3 ///< Unrecoverable error in this program, almost always a bug
};

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-declarations"

std::unique_ptr<AST> parseXML(fs::path filePath, std::string cliEval) {
  if (!filePath.empty()) {
    // Read from file
    auto file = rapidxml::file<>(filePath.c_str());
    return std::make_unique<AST>(XMLParser().parse(file).getTree());
  } else {
    // Read from CLI
    char* mutableCode = new char[cliEval.size() + 1];
    std::move(ALL(cliEval), mutableCode);
    mutableCode[cliEval.size()] = '\0';
    return std::make_unique<AST>(XMLParser().parse(mutableCode).getTree());
  }
}

std::vector<Token> tokenize(fs::path filePath, std::string cliEval) {
  std::string input;
  if (!filePath.empty()) {
    std::ifstream file(filePath);
    std::stringstream buffer;
    buffer << file.rdbuf();
    input = buffer.str();
  } else {
    input = cliEval;
  }
  auto lx = Lexer();
  return lx.tokenize(input, filePath.empty() ? "<cli-eval>" : filePath).getTokens();
}

void assertCliIntegrity(TCLAP::CmdLine& cmd, bool value, std::string message) {
  if (!value) return;
  TCLAP::ArgException arg(message);
  cmd.getOutput()->failure(cmd, arg);
}

int notReallyMain(int argc, const char* argv[]) {
  try {
    TCLAP::CmdLine cmd("Xylene", ' ', "pre-release");

    TCLAP::SwitchArg asXML("", "xml", "Read file using the XML parser", cmd);

    TCLAP::SwitchArg printTokens("", "tokens", "Print token list (if applicable)", cmd);
    TCLAP::SwitchArg printAST("", "ast", "Print AST (if applicable)", cmd);
    TCLAP::SwitchArg printIR("", "ir", "Print LLVM IR (if applicable)", cmd);

    TCLAP::SwitchArg doNotParse("", "no-parse", "Don't parse the token list", cmd);
    TCLAP::SwitchArg doNotRun("", "no-run", "Don't execute the AST", cmd);

    std::vector<std::string> runnerValues {"interpret", "compile"};
    TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues);
    TCLAP::ValueArg<std::string> runner("r", "runner", "How to run this code", false,
      "interpret", &runnerConstraint, cmd, nullptr);

    TCLAP::ValueArg<std::string> code("e", "eval", "Code to evaluate", false,
      std::string(), "string", cmd, nullptr);
    TCLAP::ValueArg<std::string> filePath("f", "file", "Load code from this file",
      false, std::string(), "path", cmd, nullptr);
    TCLAP::ValueArg<std::string> outPath("o", "output", "Write exe to this file",
      false, std::string(), "path", cmd, nullptr);
    cmd.parse(argc, argv);

    // There must be at least one input
    assertCliIntegrity(cmd, code.getValue().empty() && filePath.getValue().empty(),
      "Must specify either option -e or -f");

    // There is not much you can do to the XML without parsing it
    assertCliIntegrity(cmd, asXML.getValue() && doNotParse.getValue(),
      "--no-parse and --xml are incompatible");

    // The XML parser does not use tokens
    assertCliIntegrity(cmd, asXML.getValue() && printTokens.getValue(),
      "--tokens and --xml are incompatible");

    // Can't print AST without creating it first
    assertCliIntegrity(cmd, printAST.getValue() && doNotParse.getValue(),
      "--no-parse and --ast are incompatible");

    // Can't print IR without parsing the AST
    assertCliIntegrity(cmd, printIR.getValue() && doNotParse.getValue(),
      "--no-parse and --ir are incompatible");

    std::unique_ptr<AST> ast;

    if (asXML.getValue()) {
      ast = parseXML(filePath.getValue(), code.getValue());
    } else {
      auto tokens = tokenize(filePath.getValue(), code.getValue());
      if (printTokens.getValue()) for (auto tok : tokens) println(tok);

      if (doNotParse.getValue()) return NORMAL_EXIT;
      ast = std::make_unique<AST>(TokenParser().parse(tokens).getTree());
    }

    if (printAST.getValue()) ast->print();
    if (doNotRun.getValue()) return NORMAL_EXIT;

    ModuleCompiler::Link mc = ModuleCompiler::create("Command Line Module", *ast);
    mc->visit();
    if (printIR.getValue()) mc->getModule()->dump();

    if (runner.getValue() == "interpret") {
      return Runner(mc).run();
    } else if (runner.getValue() == "compile") {
      Compiler(std::unique_ptr<llvm::Module>(mc->getModule()),
        filePath.getValue(), outPath.getValue()).compile();
      return NORMAL_EXIT;
    }
  } catch (const TCLAP::ExitException& arg) {
    return CLI_ERROR;
  } catch (const TCLAP::ArgException& arg) {
    println("TCLAP error", arg.error(), "for", arg.argId());
    return TCLAP_ERROR;
  } catch (const Error& err) {
    println(err.what());
    return USER_PROGRAM_ERROR;
  }
  // If we're debugging, crash the program on InternalError
  #ifndef CRASH_ON_INTERNAL_ERROR
  catch (const InternalError& err) {
    println(err.what());
    return INTERNAL_ERROR;
  }
  #endif
  return 0;
}

#pragma GCC diagnostic pop

int main(int argc, const char* argv[]) {
  #ifdef XYLENE_MEASURE_TIME
  auto begin = std::chrono::steady_clock::now();
  #endif

  int exitCode = notReallyMain(argc, argv);

  #ifdef XYLENE_MEASURE_TIME
  auto end = std::chrono::steady_clock::now();
  println(
    "Time diff:",
    std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(),
    "μs"
  );
  #endif

  return exitCode;
}
<commit_msg>Add documentation<commit_after>#include <tclap/CmdLine.h>
#include <llvm/IR/Module.h>
#include <fstream>
#include <sstream>
#include <chrono>

#include "utils/util.hpp"
#include "utils/error.hpp"
#include "lexer.hpp"
#include "parser/tokenParser.hpp"
#include "parser/xmlParser.hpp"
#include "llvm/compiler.hpp"
#include "llvm/runner.hpp"

enum ExitCodes: int {
  NORMAL_EXIT = 0, ///< Everything is OK
  TCLAP_ERROR = 11, ///< TCLAP did something bad, should not happen
  CLI_ERROR = 1, ///< The user used a wrong combination of options
  USER_PROGRAM_ERROR = 2, ///< The thing we had to lex/parse/run has an issue
  INTERNAL_ERROR = 3 ///< Unrecoverable error in this program, almost always a bug
};

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-declarations"

std::unique_ptr<AST> parseXML(fs::path filePath, std::string cliEval) {
  if (!filePath.empty()) {
    // Read from file
    auto file = rapidxml::file<>(filePath.c_str());
    return std::make_unique<AST>(XMLParser().parse(file).getTree());
  } else {
    // Read from CLI
    char* mutableCode = new char[cliEval.size() + 1];
    std::move(ALL(cliEval), mutableCode);
    mutableCode[cliEval.size()] = '\0';
    return std::make_unique<AST>(XMLParser().parse(mutableCode).getTree());
  }
}

std::vector<Token> tokenize(fs::path filePath, std::string cliEval) {
  std::string input;
  if (!filePath.empty()) {
    std::ifstream file(filePath);
    std::stringstream buffer;
    buffer << file.rdbuf();
    input = buffer.str();
  } else {
    input = cliEval;
  }
  auto lx = Lexer();
  return lx.tokenize(input, filePath.empty() ? "<cli-eval>" : filePath).getTokens();
}

/// Throw if the assertion is false
void assertCliIntegrity(TCLAP::CmdLine& cmd, bool assertion, std::string message) {
  if (!assertion) return;
  TCLAP::ArgException arg(message);
  cmd.getOutput()->failure(cmd, arg);
}

/// Pseudo-main used to allow early returns while measuring execution time
int notReallyMain(int argc, const char* argv[]) {
  try {
    TCLAP::CmdLine cmd("Xylene", ' ', "pre-release");

    TCLAP::SwitchArg asXML("", "xml", "Read file using the XML parser", cmd);

    TCLAP::SwitchArg printTokens("", "tokens", "Print token list (if applicable)", cmd);
    TCLAP::SwitchArg printAST("", "ast", "Print AST (if applicable)", cmd);
    TCLAP::SwitchArg printIR("", "ir", "Print LLVM IR (if applicable)", cmd);

    TCLAP::SwitchArg doNotParse("", "no-parse", "Don't parse the token list", cmd);
    TCLAP::SwitchArg doNotRun("", "no-run", "Don't execute the AST", cmd);

    std::vector<std::string> runnerValues {"interpret", "compile"};
    TCLAP::ValuesConstraint<std::string> runnerConstraint(runnerValues);
    TCLAP::ValueArg<std::string> runner("r", "runner", "How to run this code", false,
      "interpret", &runnerConstraint, cmd, nullptr);

    TCLAP::ValueArg<std::string> code("e", "eval", "Code to evaluate", false,
      std::string(), "string", cmd, nullptr);
    TCLAP::ValueArg<std::string> filePath("f", "file", "Load code from this file",
      false, std::string(), "path", cmd, nullptr);
    TCLAP::ValueArg<std::string> outPath("o", "output", "Write exe to this file",
      false, std::string(), "path", cmd, nullptr);
    cmd.parse(argc, argv);

    // There must be at least one input
    assertCliIntegrity(cmd, code.getValue().empty() && filePath.getValue().empty(),
      "Must specify either option -e or -f");

    // There is not much you can do to the XML without parsing it
    assertCliIntegrity(cmd, asXML.getValue() && doNotParse.getValue(),
      "--no-parse and --xml are incompatible");

    // The XML parser does not use tokens
    assertCliIntegrity(cmd, asXML.getValue() && printTokens.getValue(),
      "--tokens and --xml are incompatible");

    // Can't print AST without creating it first
    assertCliIntegrity(cmd, printAST.getValue() && doNotParse.getValue(),
      "--no-parse and --ast are incompatible");

    // Can't print IR without parsing the AST
    assertCliIntegrity(cmd, printIR.getValue() && doNotParse.getValue(),
      "--no-parse and --ir are incompatible");

    std::unique_ptr<AST> ast;

    if (asXML.getValue()) {
      ast = parseXML(filePath.getValue(), code.getValue());
    } else {
      auto tokens = tokenize(filePath.getValue(), code.getValue());
      if (printTokens.getValue()) for (auto tok : tokens) println(tok);

      if (doNotParse.getValue()) return NORMAL_EXIT;
      ast = std::make_unique<AST>(TokenParser().parse(tokens).getTree());
    }

    if (printAST.getValue()) ast->print();
    if (doNotRun.getValue()) return NORMAL_EXIT;

    ModuleCompiler::Link mc = ModuleCompiler::create("Command Line Module", *ast);
    mc->visit();
    if (printIR.getValue()) mc->getModule()->dump();

    if (runner.getValue() == "interpret") {
      return Runner(mc).run();
    } else if (runner.getValue() == "compile") {
      Compiler(std::unique_ptr<llvm::Module>(mc->getModule()),
        filePath.getValue(), outPath.getValue()).compile();
      return NORMAL_EXIT;
    }
  } catch (const TCLAP::ExitException& arg) {
    return CLI_ERROR;
  } catch (const TCLAP::ArgException& arg) {
    println("TCLAP error", arg.error(), "for", arg.argId());
    return TCLAP_ERROR;
  } catch (const Error& err) {
    println(err.what());
    return USER_PROGRAM_ERROR;
  }
  // If we're debugging, crash the program on InternalError
  #ifndef CRASH_ON_INTERNAL_ERROR
  catch (const InternalError& err) {
    println(err.what());
    return INTERNAL_ERROR;
  }
  #endif
  return 0;
}

#pragma GCC diagnostic pop

/// Measures execution time if XYLENE_MEASURE_TIME is defined \see notReallyMain
int main(int argc, const char* argv[]) {
  #ifdef XYLENE_MEASURE_TIME
  auto begin = std::chrono::steady_clock::now();
  #endif

  int exitCode = notReallyMain(argc, argv);

  #ifdef XYLENE_MEASURE_TIME
  auto end = std::chrono::steady_clock::now();
  println(
    "Time diff:",
    std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(),
    "μs"
  );
  #endif

  return exitCode;
}
<|endoftext|>


<commit_before>/* * * * * * * * * * * * *\
|*             ╔═╗ v0.3  *|
|* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *|
|* ║ ╔═╣ '╔╬═╗╚╣ ║ ║  '║ *|
|* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *|
|* * * * * * * * * ╚═╝ * *|
|* Manipulation tool for *|
|*    ESRI Shapefiles    *|
|* * * * * * * * * * * * *|
|* http://www.npolar.no/ *|
\* * * * * * * * * * * * */

#include "handler.hpp"

int main(int argc, char* argv[])
{
    reshp::handler reshp(argc, argv, "0.3.4");
    return reshp.run();
}
<commit_msg>Updated version number<commit_after>/* * * * * * * * * * * * *\
|*             ╔═╗ v0.3  *|
|* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *|
|* ║ ╔═╣ '╔╬═╗╚╣ ║ ║  '║ *|
|* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *|
|* * * * * * * * * ╚═╝ * *|
|* Manipulation tool for *|
|*    ESRI Shapefiles    *|
|* * * * * * * * * * * * *|
|* http://www.npolar.no/ *|
\* * * * * * * * * * * * */

#include "handler.hpp"

int main(int argc, char* argv[])
{
    // TODO: Update version number
    reshp::handler reshp(argc, argv, "0.3.5");
    return reshp.run();
}
<|endoftext|>


<commit_before>/*
 * Adventures in OpenCL tutorial series
 * Part 2
 *
 * author: Ian Johnson
 * htt://enja.org
 * code based on advisor Gordon Erlebacher's work
 * NVIDIA's examples
 * as well as various blogs and resources on the internet
 *
 * Ported to GL4 and GFLW by Lubosz Sarnecki <lubosz@gmail.com>
 *
 */

#pragma GCC diagnostic ignored "-Wunused-parameter"

#include "Renderer.h"
#include "Simulator.h"
#include "util.h"
#include <math.h>

#define NUM_PARTICLES 200

Simulator* simulator;
Renderer* renderer;

//GL related variables
int window_width = 1280;
int window_height = 720;
// mouse controls
int mouse_old_x, mouse_old_y;
int mouse_buttons = 0;

static void windowFrameBufferCallback(GLFWwindow * 	window, int width, int height) {
    renderer->updateProjection(width, height);
}

static void errorCallback(int error, const char* description)
{
    fputs(description, stderr);
}
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}

void scrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
    renderer->translate(yoffset);
}

void buttonCallback(GLFWwindow* window, int button, int action, int mods)
{
    //handle mouse interaction for rotating/zooming the view
    if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
        mouse_buttons |= 1<<button;
    } else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {
        mouse_buttons = 0;
    }

    double x, y;
    glfwGetCursorPos(window, &x, &y);

    mouse_old_x = x;
    mouse_old_y = y;
}

static void cursorCallback(GLFWwindow* window, double x, double y)
{
    //hanlde the mouse motion for zooming and rotating the view
    float dx, dy;
    dx = x - mouse_old_x;
    dy = y - mouse_old_y;

    if (mouse_buttons & 1) {
        renderer->rotate(dx, dy);
    }

    mouse_old_x = x;
    mouse_old_y = y;
}

GLFWwindow* initGLFW() {
    GLFWwindow* window;
    glfwSetErrorCallback(errorCallback);
    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(window_width, window_height, "Universe Simulator", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);
    glfwSetKeyCallback(window, keyCallback);
    glfwSetMouseButtonCallback(window, buttonCallback);
    glfwSetScrollCallback(window, scrollCallback);
    glfwSetCursorPosCallback(window, cursorCallback);
    glfwSetFramebufferSizeCallback(window, windowFrameBufferCallback);

    return window;
}

void initParticles() {
    //initialize our particle system with positions, velocities and color
    int num = NUM_PARTICLES;
    //int num = 1;
    std::vector<Vec4> pos(num);
    std::vector<Vec4> vel(num);
    std::vector<Vec4> color(num);

    //fill our vectors with initial data
    for(int i = 0; i < num; i++)
    {
        //distribute the particles in a random circle around z axis
        float rad = randomFloat(.2, .5);
        //float rad = 1.0;
        float x = rad * sin(2 * M_PI * i/num);
        float z = 0.0f;// -.1 + .2f * i/num;
        float y = rad * cos(2 * M_PI * i/num);
        pos[i] = Vec4(x, y, z, 1.0f);

        //give some initial velocity
        //float xr = rand_float(-.1, .1);
        //float yr = rand_float(1.f, 3.f);
        //the life is the lifetime of the particle: 1 = alive 0 = dead
        //as you will see in part2.cl we reset the particle when it dies
        //float life_r = randomFloat(0.f, 1.f);
        //vel[i] = Vec4(0.0, 0.0, 3.0f, life_r);
        vel[i] =
                Vec4(
                    randomFloat(-1.f, 1.f),
                    randomFloat(-1.f, 1.f),
                    randomFloat(-1.f, 1.f),
                    1.0);

        //just make them red and full alpha
        color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f);
    }

    //our load data function sends our initial values to the GPU
    simulator->loadData(pos, vel, color);
}

int main(int argc, char** argv)
{
    GLFWwindow* window = initGLFW();
    renderer = new Renderer(window_width, window_height);

    std::string kernel_source = readFile("gpu/vortex.cl");
    simulator = new Simulator();
    simulator->loadProgram(kernel_source);

    initParticles();
    //initialize the kernel
    simulator->initKernel();

    while (!glfwWindowShouldClose(window))
    {
        //this updates the particle system by calling the kernel
        simulator->runKernel();
        renderer->draw(simulator->positionVBO,
                       simulator->colorVBO,
                       simulator->particleCount);
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<commit_msg>do not use vsync<commit_after>/*
 * Adventures in OpenCL tutorial series
 * Part 2
 *
 * author: Ian Johnson
 * htt://enja.org
 * code based on advisor Gordon Erlebacher's work
 * NVIDIA's examples
 * as well as various blogs and resources on the internet
 *
 * Ported to GL4 and GFLW by Lubosz Sarnecki <lubosz@gmail.com>
 *
 */

#pragma GCC diagnostic ignored "-Wunused-parameter"

#include "Renderer.h"
#include "Simulator.h"
#include "util.h"
#include <math.h>

#define NUM_PARTICLES 200

Simulator* simulator;
Renderer* renderer;

//GL related variables
int window_width = 1280;
int window_height = 720;
// mouse controls
int mouse_old_x, mouse_old_y;
int mouse_buttons = 0;

static void windowFrameBufferCallback(GLFWwindow * 	window, int width, int height) {
    renderer->updateProjection(width, height);
}

static void errorCallback(int error, const char* description)
{
    fputs(description, stderr);
}
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
}

void scrollCallback(GLFWwindow* window, double xoffset, double yoffset)
{
    renderer->translate(yoffset);
}

void buttonCallback(GLFWwindow* window, int button, int action, int mods)
{
    //handle mouse interaction for rotating/zooming the view
    if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
        mouse_buttons |= 1<<button;
    } else if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_RELEASE) {
        mouse_buttons = 0;
    }

    double x, y;
    glfwGetCursorPos(window, &x, &y);

    mouse_old_x = x;
    mouse_old_y = y;
}

static void cursorCallback(GLFWwindow* window, double x, double y)
{
    //hanlde the mouse motion for zooming and rotating the view
    float dx, dy;
    dx = x - mouse_old_x;
    dy = y - mouse_old_y;

    if (mouse_buttons & 1) {
        renderer->rotate(dx, dy);
    }

    mouse_old_x = x;
    mouse_old_y = y;
}

GLFWwindow* initGLFW() {
    GLFWwindow* window;
    glfwSetErrorCallback(errorCallback);
    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(window_width, window_height, "Universe Simulator", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    //glfwSwapInterval(1);
    glfwSetKeyCallback(window, keyCallback);
    glfwSetMouseButtonCallback(window, buttonCallback);
    glfwSetScrollCallback(window, scrollCallback);
    glfwSetCursorPosCallback(window, cursorCallback);
    glfwSetFramebufferSizeCallback(window, windowFrameBufferCallback);

    return window;
}

void initParticles() {
    //initialize our particle system with positions, velocities and color
    int num = NUM_PARTICLES;
    //int num = 1;
    std::vector<Vec4> pos(num);
    std::vector<Vec4> vel(num);
    std::vector<Vec4> color(num);

    //fill our vectors with initial data
    for(int i = 0; i < num; i++)
    {
        //distribute the particles in a random circle around z axis
        float rad = randomFloat(.2, .5);
        //float rad = 1.0;
        float x = rad * sin(2 * M_PI * i/num);
        float z = 0.0f;// -.1 + .2f * i/num;
        float y = rad * cos(2 * M_PI * i/num);
        pos[i] = Vec4(x, y, z, 1.0f);

        //give some initial velocity
        //float xr = rand_float(-.1, .1);
        //float yr = rand_float(1.f, 3.f);
        //the life is the lifetime of the particle: 1 = alive 0 = dead
        //as you will see in part2.cl we reset the particle when it dies
        //float life_r = randomFloat(0.f, 1.f);
        //vel[i] = Vec4(0.0, 0.0, 3.0f, life_r);
        vel[i] =
                Vec4(
                    randomFloat(-1.f, 1.f),
                    randomFloat(-1.f, 1.f),
                    randomFloat(-1.f, 1.f),
                    1.0);

        //just make them red and full alpha
        color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f);
    }

    //our load data function sends our initial values to the GPU
    simulator->loadData(pos, vel, color);
}

int main(int argc, char** argv)
{
    GLFWwindow* window = initGLFW();
    renderer = new Renderer(window_width, window_height);

    std::string kernel_source = readFile("gpu/vortex.cl");
    simulator = new Simulator();
    simulator->loadProgram(kernel_source);

    initParticles();
    //initialize the kernel
    simulator->initKernel();

    while (!glfwWindowShouldClose(window))
    {
        //this updates the particle system by calling the kernel
        simulator->runKernel();
        renderer->draw(simulator->positionVBO,
                       simulator->colorVBO,
                       simulator->particleCount);
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>//////////////
// Includes //
#include <SDL_image.h>
#include <SDL.h>

#include "window.hpp"

//////////
// Code //

// Loading an image from the disk.
SDL_Texture* loadImage(Window& w, std::string path) {
    SDL_Surface* img = IMG_Load(path.c_str());
    if (img == nullptr)
        return nullptr;

    SDL_Texture* tex = SDL_CreateTextureFromSurface(
        w.getRenderer(),
        img
    );

    SDL_FreeSurface(img);
    return tex;
}

// Entry point!
int main() {
    Window w("Hello World!", 640, 480, false);

    SDL_Texture* tex = loadImage(w, "res/test.png");
    if (tex == nullptr) {
        return 1;
    }

    SDL_RenderCopy(w.getRenderer(),
                   tex,
                   nullptr,
                   nullptr);
    SDL_RenderPresent(w.getRenderer());

    SDL_Event e;
    while (SDL_WaitEvent(&e)) {
        if (e.type == SDL_QUIT)
            break;
    }

    return 0;
}
<commit_msg>Made the background not horrid.<commit_after>//////////////
// Includes //
#include <SDL_image.h>
#include <SDL.h>

#include "window.hpp"

//////////
// Code //

// Loading an image from the disk.
SDL_Texture* loadImage(Window& w, std::string path) {
    SDL_Surface* img = IMG_Load(path.c_str());
    if (img == nullptr)
        return nullptr;

    SDL_Texture* tex = SDL_CreateTextureFromSurface(
        w.getRenderer(),
        img
    );

    SDL_FreeSurface(img);
    return tex;
}

// Entry point!
int main() {
    Window w("Hello World!", 640, 480, false);

    SDL_Texture* tex = loadImage(w, "res/test.png");
    if (tex == nullptr) {
        return 1;
    }

    SDL_RenderClear(w.getRenderer());
    SDL_RenderCopy(w.getRenderer(),
                   tex,
                   nullptr,
                   nullptr);

    SDL_RenderPresent(w.getRenderer());

    SDL_Event e;
    while (SDL_WaitEvent(&e)) {
        if (e.type == SDL_QUIT)
            break;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: May 25, 2015
 *      Author: Vance Zuo
 */

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>

#include <fstream>
#include <iostream>
#include <vector>
#include <chrono>

#include <src/grid.h>
#include <src/solver.h>

using std::string;
using std::vector;
using std::istream;
using std::ifstream;
using std::locale;
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
using sudoku::Grid;
using sudoku::Solver;

void printGrid(const Grid& grid) {
  int numberSpacing = floor(log10(grid.getMaxValue())) + 1;
  for (int i = 0; i < grid.getNumRows(); ++i) {
    for (int j = 0; j < grid.getNumCols(); ++j) {
      if (grid.getValues(i, j).size() == 1) {
        printf("%*d ", numberSpacing, *grid.getValues(i, j).begin());
      } else {
        printf("%*s ", numberSpacing, ".");
      }
    }
    printf("\n");
  }
  fflush(stdout);
}

int readGrid(istream& input, Grid& grid) {
  int value;
  for (int i = 0; i < grid.size(); ) {
    if (input.peek() == EOF)
      return i;
    if (!(input >> value)) {
      input.clear();
      input.ignore(1);
      continue;
    }
    grid.assign(i++, value);
  }
  return grid.size();
}

void printUsage() {
  printf("Usage: sudoku-solver.exe [-d SUBROWS SUBCOLS] [FILE]\n");
}

// Main method
// Args: [-d SUBROWS SUBCOLS] [FILE]
int main(int argc, char **argv) {
  int subrows = 3;
  int subcols = 3;
  istream *input;
  ifstream ifs;

  int i = 1;
  if (i < argc && !strcmp(argv[i], "-d")) {
    i = 4;
    if (*argv[2] == '\0' || *argv[3] == '\0') {
      printf("Error: Not enough arguments after -d.\n");
      printUsage();
      exit(1);
    }
    subrows = atoi(argv[2]);
    subcols = atoi(argv[3]);
    if (subrows == 0 || subcols == 0) {
      printf("Error: Illegal subrow/col arguments (should be integers >0).\n");
      printUsage();
      exit(1);
    }
  }

  if (i < argc && *argv[i] != '\0') {
    ifs.open(argv[i]);
    if (!ifs.is_open()) {
      printf("Error: Could not open file.\n");
      printUsage();
      exit(1);
    }
    input = &ifs;
  } else {
    input = &std::cin;
    printf("Enter the grid as a list of values (0 for blank):\n");
  }

  int completedGrids = 0;
  long totalNs = 0;
  while (true) {
    Grid grid(subrows, subcols);
    int numValues = readGrid(*input, grid);
    if (numValues < grid.size()) {
      if (numValues > 0 || completedGrids == 0)
        printf("Warning: Incomplete definition (%d values).\n", numValues);
      break;
    }
    if (input != &std::cin)
      printGrid(grid);

    auto begin = high_resolution_clock::now();

    Solver solver(grid);
    Grid solution;
    int steps;
    bool solved = solver.solve(solution, steps);

    auto end = high_resolution_clock::now();
    auto ns = duration_cast<nanoseconds>(end - begin).count();
    totalNs += ns;

    printf(" ||\n");
    printf(" || (%d steps, %.3fs)\n", steps, ns / 1000000000.0);
    printf(" \\/\n");
    if (solved) {
      printGrid(solution);
    } else {
      printf("[NO SOLUTION]\n");
    }
    printf("----\n");

    completedGrids++;
  }
  printf("Solved %d grids (%.3fs)", completedGrids, totalNs / 1000000000.0);

  if (ifs.is_open())
    ifs.close();

  exit(0);
}

<commit_msg>Change totalNs variable to double type<commit_after>/*
 * main.cpp
 *
 *  Created on: May 25, 2015
 *      Author: Vance Zuo
 */

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>

#include <fstream>
#include <iostream>
#include <vector>
#include <chrono>

#include <src/grid.h>
#include <src/solver.h>

using std::string;
using std::vector;
using std::istream;
using std::ifstream;
using std::locale;
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::nanoseconds;
using sudoku::Grid;
using sudoku::Solver;

void printGrid(const Grid& grid) {
  int numberSpacing = floor(log10(grid.getMaxValue())) + 1;
  for (int i = 0; i < grid.getNumRows(); ++i) {
    for (int j = 0; j < grid.getNumCols(); ++j) {
      if (grid.getValues(i, j).size() == 1) {
        printf("%*d ", numberSpacing, *grid.getValues(i, j).begin());
      } else {
        printf("%*s ", numberSpacing, ".");
      }
    }
    printf("\n");
  }
  fflush(stdout);
}

int readGrid(istream& input, Grid& grid) {
  int value;
  for (int i = 0; i < grid.size(); ) {
    if (input.peek() == EOF)
      return i;
    if (!(input >> value)) {
      input.clear();
      input.ignore(1);
      continue;
    }
    grid.assign(i++, value);
  }
  return grid.size();
}

void printUsage() {
  printf("Usage: sudoku-solver.exe [-d SUBROWS SUBCOLS] [FILE]\n");
}

// Main method
// Args: [-d SUBROWS SUBCOLS] [FILE]
int main(int argc, char **argv) {
  int subrows = 3;
  int subcols = 3;
  istream *input;
  ifstream ifs;

  int i = 1;
  if (i < argc && !strcmp(argv[i], "-d")) {
    i = 4;
    if (*argv[2] == '\0' || *argv[3] == '\0') {
      printf("Error: Not enough arguments after -d.\n");
      printUsage();
      exit(1);
    }
    subrows = atoi(argv[2]);
    subcols = atoi(argv[3]);
    if (subrows == 0 || subcols == 0) {
      printf("Error: Illegal subrow/col arguments (should be integers >0).\n");
      printUsage();
      exit(1);
    }
  }

  if (i < argc && *argv[i] != '\0') {
    ifs.open(argv[i]);
    if (!ifs.is_open()) {
      printf("Error: Could not open file.\n");
      printUsage();
      exit(1);
    }
    input = &ifs;
  } else {
    input = &std::cin;
    printf("Enter the grid as a list of values (0 for blank):\n");
  }

  int completedGrids = 0;
  double totalNs = 0;
  while (true) {
    Grid grid(subrows, subcols);
    int numValues = readGrid(*input, grid);
    if (numValues < grid.size()) {
      if (numValues > 0 || completedGrids == 0)
        printf("Warning: Incomplete definition (%d values).\n", numValues);
      break;
    }
    if (input != &std::cin)
      printGrid(grid);

    auto begin = high_resolution_clock::now();

    Solver solver(grid);
    Grid solution;
    int steps;
    bool solved = solver.solve(solution, steps);

    auto end = high_resolution_clock::now();
    auto ns = duration_cast<nanoseconds>(end - begin).count();
    totalNs += ns;

    printf(" ||\n");
    printf(" || (%d steps, %.3fs)\n", steps, ns / 1000000000.0);
    printf(" \\/\n");
    if (solved) {
      printGrid(solution);
    } else {
      printf("[NO SOLUTION]\n");
    }
    printf("----\n");

    completedGrids++;
  }
  printf("Solved %d grids (%.3fs)", completedGrids, totalNs / 1000000000.0);

  if (ifs.is_open())
    ifs.close();

  exit(0);
}

<|endoftext|>


<commit_before>#include "SimpleClient.h"
#include "Job/Remote.h"
#include "Job/StdInput.h"

#include <string>
#include <list>
#include <iostream>

void printSizes()
{
    cefpdf::PageSizesMap::const_iterator it;

    for (it = cefpdf::pageSizesMap.begin(); it != cefpdf::pageSizesMap.end(); ++it) {
        std::cout << it->name <<  " " << it->width << "x" << it->height << std::endl;
    }
}

void printHelp(std::string name)
{
    std::cout << name << " v" << cefpdf::constants::version << std::endl;
    std::cout << "  Creates PDF files from HTML pages" << std::endl;
    std::cout << std::endl;
    std::cout << "Usage:" << std::endl;
    std::cout << "  cef-pdf [options] [--url=<input>] [output]" << std::endl;
    std::cout << std::endl;
    std::cout << "Options:" << std::endl;
    std::cout << "  --help -h          This help screen." << std::endl;
    std::cout << "  --url=<input>      URL to load, may be http, file, data, anything supported by Chromium." << std::endl;
    std::cout << "                     If omitted standard input is read." << std::endl;
    std::cout << "  --size=<size>      Size (format) of the paper: A3, B2.. or custom <width>x<height> in mm." << std::endl;
    std::cout << "                     A4 is the default." << std::endl;
    std::cout << "  --list-sizes       Show all defined page sizes." << std::endl;
    std::cout << "  --landscape        Wheather to print with a landscape page orientation." << std::endl;
    std::cout << "                     Default is portrait" << std::endl;
    std::cout << "  --margin=<margin>  Paper margins in mm (much like CSS margin but without units)" << std::endl;
    std::cout << "                     If omitted default margin is applied." << std::endl;
    std::cout << std::endl;
    std::cout << "Output:" << std::endl;
    std::cout << "  PDF file name to create. Default is output.pdf" << std::endl;
    std::cout << std::endl;
}

std::string getExecutableName(CefString path)
{
    std::string program = path.ToString();

    // Remove directory if present.
    // Do this before extension removal in case directory has a period character.
    const std::size_t s = program.find_last_of("\\/");
    if (std::string::npos != s) {
        program.erase(0, s + 1);
    }

    // Remove extension if present.
    const std::size_t e = program.rfind('.');
    if (std::string::npos != e) {
        program.erase(e);
    }

    return program;
}

int main(int argc, char* argv[])
{
    CefRefPtr<cefpdf::SimpleClient> app = new cefpdf::SimpleClient();

    // Execute the sub-process logic, if any. This will either return immediately for the browser
    // process or block until the sub-process should exit.
    CefMainArgs mainArgs;
    int exitCode = CefExecuteProcess(mainArgs, app, NULL);
    if (exitCode >= 0) {
        // The sub-process terminated, exit now.
        return exitCode;
    }

    CefRefPtr<CefCommandLine> commandLine = CefCommandLine::CreateCommandLine();

#if defined(OS_WIN)
    commandLine->InitFromString(::GetCommandLineW());
#else
    commandLine->InitFromArgv(argc, argv);
#endif

    if (commandLine->HasSwitch("help") || commandLine->HasSwitch("h")) {
        printHelp(::getExecutableName(commandLine->GetProgram()));
        return 0;
    }

    if (commandLine->HasSwitch("list-sizes")) {
        printSizes();
        return 0;
    }

    cefpdf::job::Job* job;

    if (commandLine->HasSwitch("url")) {
        job = new cefpdf::job::Remote(commandLine->GetSwitchValue("url"));
    } else {
        job = new cefpdf::job::StdInput;
    }

    // Set output file
    CefCommandLine::ArgumentList args;
    commandLine->GetArguments(args);
    if (!args.empty()) {
        job->SetOutputPath(args[0]);
    } else {
        job->SetOutputPath("output.pdf");
    }

    try {
        if (commandLine->HasSwitch("size")) {
            job->SetPageSize(commandLine->GetSwitchValue("size"));
        }

        if (commandLine->HasSwitch("margin")) {
            job->SetPageMargin(commandLine->GetSwitchValue("margin"));
        }

        if (commandLine->HasSwitch("landscape")) {
            job->SetLandscape();
        }
    } catch (std::string error) {
        std::cerr << "ERROR: " << error << std::endl;
        return 1;
    }

    app->QueueJob(job);
    app->Run();

    return 0;
}
<commit_msg>Small changes in main function<commit_after>#include "SimpleClient.h"
#include "Job/Remote.h"
#include "Job/StdInput.h"

#include <string>
#include <list>
#include <iostream>

void printSizes()
{
    cefpdf::PageSizesMap::const_iterator it;

    for (it = cefpdf::pageSizesMap.begin(); it != cefpdf::pageSizesMap.end(); ++it) {
        std::cout << it->name <<  " " << it->width << "x" << it->height << std::endl;
    }
}

void printHelp(std::string name)
{
    std::cout << name << " v" << cefpdf::constants::version << std::endl;
    std::cout << "  Creates PDF files from HTML pages" << std::endl;
    std::cout << std::endl;
    std::cout << "Usage:" << std::endl;
    std::cout << "  cef-pdf [options] [--url=<input>] [output]" << std::endl;
    std::cout << std::endl;
    std::cout << "Options:" << std::endl;
    std::cout << "  --help -h          This help screen." << std::endl;
    std::cout << "  --url=<input>      URL to load, may be http, file, data, anything supported by Chromium." << std::endl;
    std::cout << "                     If omitted standard input is read." << std::endl;
    std::cout << "  --size=<size>      Size (format) of the paper: A3, B2.. or custom <width>x<height> in mm." << std::endl;
    std::cout << "                     A4 is the default." << std::endl;
    std::cout << "  --list-sizes       Show all defined page sizes." << std::endl;
    std::cout << "  --landscape        Wheather to print with a landscape page orientation." << std::endl;
    std::cout << "                     Default is portrait" << std::endl;
    std::cout << "  --margin=<margin>  Paper margins in mm (much like CSS margin but without units)" << std::endl;
    std::cout << "                     If omitted default margin is applied." << std::endl;
    std::cout << std::endl;
    std::cout << "Output:" << std::endl;
    std::cout << "  PDF file name to create. Default is output.pdf" << std::endl;
    std::cout << std::endl;
}

std::string getExecutableName(CefString path)
{
    std::string program = path.ToString();

    // Remove directory if present.
    // Do this before extension removal in case directory has a period character.
    const std::size_t s = program.find_last_of("\\/");
    if (std::string::npos != s) {
        program.erase(0, s + 1);
    }

    // Remove extension if present.
    const std::size_t e = program.rfind('.');
    if (std::string::npos != e) {
        program.erase(e);
    }

    return program;
}

int runJob(CefRefPtr<CefCommandLine> commandLine)
{
    cefpdf::job::Job* job;

    if (commandLine->HasSwitch("url")) {
        job = new cefpdf::job::Remote(commandLine->GetSwitchValue("url"));
    } else {
        job = new cefpdf::job::StdInput;
    }

    // Set output file
    CefCommandLine::ArgumentList args;
    commandLine->GetArguments(args);
    if (!args.empty()) {
        job->SetOutputPath(args[0]);
    } else {
        job->SetOutputPath("output.pdf");
    }

    try {
        if (commandLine->HasSwitch("size")) {
            job->SetPageSize(commandLine->GetSwitchValue("size"));
        }

        if (commandLine->HasSwitch("margin")) {
            job->SetPageMargin(commandLine->GetSwitchValue("margin"));
        }

        if (commandLine->HasSwitch("landscape")) {
            job->SetLandscape();
        }
    } catch (std::string error) {
        std::cerr << "ERROR: " << error << std::endl;
        return 1;
    }

    auto app = new cefpdf::SimpleClient();
    app->QueueJob(job);
    app->Run();

    return 0;
}

int main(int argc, char* argv[])
{

#if !defined(OS_MACOSX)
#if defined(OS_WIN)
    CefMainArgs mainArgs(::GetModuleHandle(NULL));
#else
    CefMainArgs mainArgs(argc, argv);
#endif // OS_WIN
    // Execute the sub-process logic, if any. This will either return immediately for the browser
    // process or block until the sub-process should exit.
    int exitCode = CefExecuteProcess(mainArgs, NULL, NULL);
    if (exitCode >= 0) {
        // The sub-process terminated, exit now.
        return exitCode;
    }
#endif // !OS_MACOSX

    CefRefPtr<CefCommandLine> commandLine = CefCommandLine::CreateCommandLine();

#if defined(OS_WIN)
    commandLine->InitFromString(::GetCommandLine());
#else
    commandLine->InitFromArgv(argc, argv);
#endif // OS_WIN

    if (commandLine->HasSwitch("help") || commandLine->HasSwitch("h")) {
        printHelp(getExecutableName(commandLine->GetProgram()));
        return 0;
    }

    if (commandLine->HasSwitch("list-sizes")) {
        printSizes();
        return 0;
    }

    return runJob(commandLine);
}
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int int main(void) {
  cout << "Hello World!" << endl;
  cout << "This program was written in C++" << endl;
  cout << "Bye now!" << endl;

  return 0;
}
<commit_msg>Even an Hello World can have bugs :sweat_smile:<commit_after>#include <iostream>

using namespace std;

int main(void) {
  cout << "Hello World!" << endl;
  cout << "This program was written in C++" << endl;
  cout << "Bye now!" << endl;

  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>
#include <unistd.h> //used for fork(), execvp()
#include <sys/types.h> //used for wait
#include <sys/wait.h> //used for wait
#include <sys/stat.h>
#include <string.h>
#include <cstdlib>
#include <vector>
#include <stack>
#include "command.h"
using namespace std;

int main(){
    string user_input = "";
    // bool execStatus = true;
    bool allSpace = true;
    // vector<string> argsList;

    while (user_input != "exit") {
        Parse p;
        p.print();
        getline(cin, user_input);
        //test for exit
        if(user_input == "exit") {
            exit(0);
        }
        //test for empty string
        else if(user_input.size() == 0) {
            break;
        }
        //test for only white spaces
        else {
            // argsList.clear();
            for(unsigned i = 0; i < user_input.size(); i++) {
                if(user_input.at(i) != ' ') {
                    allSpace = false;
                    break;
                }
            }
            //the actual shell
            if(!allSpace) {
                p.sepParenthesis(user_input);
                // e.exec(argsList, execStatus);
            }
            else{
                break;
            }
        }
    }
    return 0;
}<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include <gtest/gtest.h>

#include <sstream>
#include <pficommon/text/json.h>
#include <pficommon/lang/cast.h>

#include "jsonconfig.hpp"

using namespace std;
using namespace pfi::lang;
using namespace pfi::text::json;

namespace jubatus {
namespace jsonconfig {

TEST(jsonconfig, bool) {
  json j = json(new json_bool(false));
  EXPECT_EQ(false, config_root(j).As<bool>());
}

TEST(jsonconfig, bool_type_error) {
  try {
    json j = json(new json_bool(false));
    config_root(j).As<int>();
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(json::Bool, e.actual());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, int) {
  json j = json(new json_integer(10));
  EXPECT_EQ(10, config_root(j).As<int>());
}

TEST(jsonconfig, int_type_error) {
  try {
    json j = json(new json_integer(10));
    config_root(j).As<std::string>();
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(json::Integer, e.actual());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, float) {
  json j = json(new json_float(0.1));
  EXPECT_FLOAT_EQ(0.1, config_root(j).As<float>());
}

TEST(jsonconfig, float_type_error) {
  try {
    json j = json(new json_float(0.1));
    config_root(j).As<std::string>();
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(json::Float, e.actual());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, array) {
  json j = json(new json_array());
  j.add(json(new json_integer(10)));
  EXPECT_EQ(10, config_root(j)[0].As<int>());
}

TEST(jsonconfig, array_out_of_range) {
  json j = json(new json_array());
  try {
    config_root(j)[1].As<int>();
    FAIL();
  } catch (const out_of_range& e) {
    EXPECT_EQ(0u, e.size());
    EXPECT_EQ(1u, e.position());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, array_type_error) {
  json j = json(new json_integer(10));
  config_root c(j);
  try {
    c[1];
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(json::Array, e.expect());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, object) {
  json j = json(new json_object());
  j["age"] = json(new json_integer(10));
  EXPECT_EQ(10, config_root(j)["age"].As<int>());
}

TEST(jsonconfig, object_not_found) {
  json j = json(new json_object());
  j["age"] = json(new json_integer(10));
  config_root c(j);
  try {
    c["name"];
    FAIL();
  } catch (not_found& e) {
    EXPECT_EQ("name", e.key());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, object_type_error) {
  json j = json(new json_integer(10));
  config_root c(j);
  try {
    c["age"];
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(json::Object, e.expect());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, error_path) {
  json j = json(new json_array());
  j.add(json(new json_object()));
  j[0]["user"] = json(new json_object());
  j[0]["user"]["age"] = json(new json_integer(10));
  config_root c(j);
  try {
    c[0]["user"]["age"].As<std::string>();
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ("[0].user.age", e.path());
  }
}

TEST(jsonconfig_cast, int) {
  json j(new json_integer(1));
  config_root conf(j);
  EXPECT_EQ(1, config_cast<int>(conf));
}

TEST(jsonconfig_cast, string) {
  json j(new json_string("test"));
  config_root conf(j);
  EXPECT_EQ("test", config_cast<string>(conf));
}

TEST(jsonconfig_cast, vector_int) {
  config_root conf(lexical_cast<json>("[1,2,3]"));
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);

  EXPECT_EQ(v, config_cast<vector<int> >(conf));
}

TEST(jsonconfig_cast, map) {
  config_root conf(lexical_cast<json>("{\"height\": 160, \"weight\": 60}"));
  map<string, int> m;
  m["height"] = 160;
  m["weight"] = 60;

  EXPECT_EQ(m, (config_cast<map<string, int> >(conf)));
}

TEST(jsonconfig_cast, unordered_map) {
  config_root conf(lexical_cast<json>("{\"height\": 160, \"weight\": 60}"));
  pfi::data::unordered_map<string, int> m;
  m["height"] = 160;
  m["weight"] = 60;

  pfi::data::unordered_map<string, int> v = config_cast<pfi::data::unordered_map<string, int> >(conf);
  EXPECT_EQ(m["height"], v["height"]);
  EXPECT_EQ(m["weight"], v["weight"]);
}

TEST(jsonconfig_cast, error_path) {
  config_root conf(lexical_cast<json>("{\"value\": [1,2,\"test\"]}"));
  try {
    config_cast<map<string, vector<int> > >(conf);
    FAIL();
  } catch (type_error& e) {
    EXPECT_EQ(".value[2]", e.path());
    EXPECT_EQ(json::String, e.actual());
    EXPECT_EQ(json::Integer, e.expect());
  }
}

// epxect object[map<K, V>] but [array]
TEST(jsonconfig_cast, error_convert_map) {
  config_root conf(lexical_cast<json>("{\"value\": []}"));
  try {
    config_cast<map<string, map<string, string> > >(conf);
    FAIL();
  } catch (type_error& e) {
    EXPECT_EQ(".value", e.path());
    EXPECT_EQ(json::Array, e.actual());
    EXPECT_EQ(json::Object, e.expect());
  }
}

// epxect object[unordered_map<K, V>] but [array]
TEST(jsonconfig_cast, error_convert_unordered_map) {
  config_root conf(lexical_cast<json>("{\"value\": []}"));
  try {
    config_cast<map<string, pfi::data::unordered_map<string, string> > >(conf);
    FAIL();
  } catch (type_error& e) {
    EXPECT_EQ(".value", e.path());
    EXPECT_EQ(json::Array, e.actual());
    EXPECT_EQ(json::Object, e.expect());
  }
}

struct opt1 {
  int abc;
  pfi::data::optional<int> def;

  template <typename Ar>
  void serialize(Ar& ar) {
    ar & MEMBER(abc) & MEMBER(def);
  }
};

TEST(jsonconfig_cast, named_not_found) {
  config_root conf(lexical_cast<json>("{\"def\": 456}"));

  try {
    opt1 a = config_cast<opt1>(conf);
    FAIL();
  } catch (not_found& e) {
    EXPECT_EQ("", e.path());
    EXPECT_EQ("abc", e.key());
  }
}

TEST(jsonconfig_cast, named_type_null) {
  config_root conf(lexical_cast<json>("{\"abc\" : null }"));

  try {
    config_cast<opt1>(conf);
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(".abc", e.path());
    EXPECT_EQ(json::Null, e.actual());
    EXPECT_EQ(json::Integer, e.expect());
  }
}

TEST(jsonconfig_cast, named_optional_nullable) {
  config_root conf(lexical_cast<json>("{\"abc\": 123, \"def\": null}"));
  ASSERT_NO_THROW(config_cast<opt1>(conf));
}

struct opt2 {
  int abc;
  pfi::data::optional<int> def;

  struct test {
    int a;
    int b;

    template <typename Ar>
    void serialize(Ar& ar) {
      ar & MEMBER(a) & MEMBER(b);
    }
  } test;

  template <typename Ar>
  void serialize(Ar& ar) {
    ar & MEMBER(abc) & MEMBER(def) & MEMBER(test);
  }
};

TEST(jsonconfig_cast, named_nest_not_found) {
  config_root conf(lexical_cast<json>("{\"abc\" : 124 }"));

  try {
    config_cast<opt2>(conf);
    FAIL();
  } catch (not_found& e) {
    EXPECT_EQ("", e.path());
    EXPECT_EQ("test", e.key());
  }
}

#if 0
// FIXME: this depends pficommon's issue #122
TEST(jsonconfig_cast, named_bad_type) {
  config_root conf(lexical_cast<json>("{\"abc\" : 124, \"test\": [] }"));

  try {
    config_cast<opt2>(conf);
    FAIL();
  } catch (type_error& e) {
    cout << e.what() << endl;
    EXPECT_EQ("", e.path());
  } catch (std::exception& e) {
    cout << "what?: " << e.what() << endl;
  }
}
#endif

struct Person {
  string name;
  double height;
  int age;
  map<string, string> attributes;
  pfi::data::optional<string> sport;
  pfi::data::optional<string> hobby;

  bool operator ==(const Person& p) const {
    return name == p.name && height == p.height && age == p.age && attributes == p.attributes && sport == p.sport && hobby == p.hobby;
  }

  template <class Ar>
  void serialize(Ar& ar) {
    ar & MEMBER(name) & MEMBER(height) & MEMBER(age) & MEMBER(attributes) & MEMBER(sport) & MEMBER(hobby);
  }
};

TEST(jsonconfig_cast, struct) {
  config_root conf(lexical_cast<json>("{\"name\": \"Taro\", \"height\": 160.0, \"age\": 20, \"attributes\": {\"address\": \"Tokyo\"}, \"sport\": \"tennis\"}"));
  Person p;
  p.name = "Taro";
  p.height = 160.0;
  p.age = 20;
  p.attributes["address"] = "Tokyo";
  p.sport = "tennis";

  EXPECT_EQ(p, config_cast<Person>(conf));
}

struct server_conf {
  struct web_conf {
    std::string host;
    int port;

    template <typename Ar>
    void serialize(Ar& ar) {
      ar & MEMBER(host) & MEMBER(port);
    }
  } web_server;

  std::vector<std::string> users;

  template <typename Ar>
  void serialize(Ar& ar) {
    ar & MEMBER(web_server) & MEMBER(users);
  }
};

TEST(jsonconfig_cast, error) {
  config_root conf(lexical_cast<json>("{\"web_server\": { \"host\" : 123}, \"users\": [\"abc\", 1] }"));

  config_error_list errors;
  server_conf c = config_cast<server_conf>(conf, errors);

  for (size_t i = 0; i < errors.size(); i++) {
    cout << errors[i]->what() << endl;
  }

  EXPECT_EQ(3, errors.size());

  type_error* e1 = dynamic_cast<type_error*>(errors[0].get());
  ASSERT_TRUE(e1);
  EXPECT_EQ(".web_server.host", e1->path());
  EXPECT_EQ(json::Integer, e1->actual());

  not_found* e2 = dynamic_cast<not_found*>(errors[1].get());
  ASSERT_TRUE(e2);
  EXPECT_EQ(".web_server", e2->path());
  EXPECT_EQ("port", e2->key());

  type_error* e3 = dynamic_cast<type_error*>(errors[2].get());
  ASSERT_TRUE(e3);
  EXPECT_EQ(".users[1]", e3->path());
  EXPECT_EQ(json::Integer, e3->actual());
}

} // jsonconfig
} // jubatus
<commit_msg>Reformat jsonconfig test<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include <gtest/gtest.h>

#include <sstream>
#include <pficommon/text/json.h>
#include <pficommon/lang/cast.h>

#include "jsonconfig.hpp"

using namespace std;
using namespace pfi::lang;
using namespace pfi::text::json;

namespace jubatus {
namespace jsonconfig {

TEST(jsonconfig, bool) {
  json j(new json_bool(false));
  EXPECT_EQ(false, config_root(j).As<bool>());
}

TEST(jsonconfig, bool_type_error) {
  try {
    json j(new json_bool(false));
    config_root(j).As<int>();
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(json::Bool, e.actual());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, int) {
  json j(new json_integer(10));
  EXPECT_EQ(10, config_root(j).As<int>());
}

TEST(jsonconfig, int_type_error) {
  try {
    json j(new json_integer(10));
    config_root(j).As<std::string>();
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(json::Integer, e.actual());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, float) {
  json j(new json_float(0.1));
  EXPECT_FLOAT_EQ(0.1, config_root(j).As<float>());
}

TEST(jsonconfig, float_type_error) {
  try {
    json j(new json_float(0.1));
    config_root(j).As<std::string>();
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(json::Float, e.actual());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, array) {
  json j(new json_array());
  j.add(json(new json_integer(10)));
  EXPECT_EQ(10, config_root(j)[0].As<int>());
}

TEST(jsonconfig, array_out_of_range) {
  json j(new json_array());
  try {
    config_root(j)[1].As<int>();
    FAIL();
  } catch (const out_of_range& e) {
    EXPECT_EQ(0u, e.size());
    EXPECT_EQ(1u, e.position());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, array_type_error) {
  json j(new json_integer(10));
  config_root c(j);
  try {
    c[1];
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(json::Array, e.expect());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, object) {
  json j(new json_object());
  j["age"] = json(new json_integer(10));
  EXPECT_EQ(10, config_root(j)["age"].As<int>());
}

TEST(jsonconfig, object_not_found) {
  json j(new json_object());
  j["age"] = json(new json_integer(10));
  config_root c(j);
  try {
    c["name"];
    FAIL();
  } catch (const not_found& e) {
    EXPECT_EQ("name", e.key());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, object_type_error) {
  json j(new json_integer(10));
  config_root c(j);
  try {
    c["age"];
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(json::Object, e.expect());
    EXPECT_EQ("", e.path());
  }
}

TEST(jsonconfig, error_path) {
  json j(new json_array());
  j.add(json(new json_object()));
  j[0]["user"] = json(new json_object());
  j[0]["user"]["age"] = json(new json_integer(10));
  config_root c(j);
  try {
    c[0]["user"]["age"].As<std::string>();
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ("[0].user.age", e.path());
  }
}

TEST(jsonconfig_cast, int) {
  json j(new json_integer(1));
  config_root conf(j);
  EXPECT_EQ(1, config_cast<int>(conf));
}

TEST(jsonconfig_cast, string) {
  json j(new json_string("test"));
  config_root conf(j);
  EXPECT_EQ("test", config_cast<string>(conf));
}

TEST(jsonconfig_cast, vector_int) {
  config_root conf(lexical_cast<json>("[1,2,3]"));
  vector<int> v;
  v.push_back(1);
  v.push_back(2);
  v.push_back(3);

  EXPECT_EQ(v, config_cast<vector<int> >(conf));
}

TEST(jsonconfig_cast, map) {
  config_root conf(lexical_cast<json>("{\"height\": 160, \"weight\": 60}"));
  map<string, int> m;
  m["height"] = 160;
  m["weight"] = 60;

  EXPECT_EQ(m, (config_cast<map<string, int> >(conf)));
}

TEST(jsonconfig_cast, unordered_map) {
  config_root conf(lexical_cast<json>("{\"height\": 160, \"weight\": 60}"));
  pfi::data::unordered_map<string, int> m;
  m["height"] = 160;
  m["weight"] = 60;

  pfi::data::unordered_map<string, int> v = config_cast<pfi::data::unordered_map<string, int> >(conf);
  EXPECT_EQ(m["height"], v["height"]);
  EXPECT_EQ(m["weight"], v["weight"]);
}

TEST(jsonconfig_cast, error_path) {
  config_root conf(lexical_cast<json>("{\"value\": [1,2,\"test\"]}"));
  try {
    config_cast<map<string, vector<int> > >(conf);
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(".value[2]", e.path());
    EXPECT_EQ(json::String, e.actual());
    EXPECT_EQ(json::Integer, e.expect());
  }
}

// epxect object[map<K, V>] but [array]
TEST(jsonconfig_cast, error_convert_map) {
  config_root conf(lexical_cast<json>("{\"value\": []}"));
  try {
    config_cast<map<string, map<string, string> > >(conf);
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(".value", e.path());
    EXPECT_EQ(json::Array, e.actual());
    EXPECT_EQ(json::Object, e.expect());
  }
}

// epxect object[unordered_map<K, V>] but [array]
TEST(jsonconfig_cast, error_convert_unordered_map) {
  config_root conf(lexical_cast<json>("{\"value\": []}"));
  try {
    config_cast<map<string, pfi::data::unordered_map<string, string> > >(conf);
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(".value", e.path());
    EXPECT_EQ(json::Array, e.actual());
    EXPECT_EQ(json::Object, e.expect());
  }
}

struct opt1 {
  int abc;
  pfi::data::optional<int> def;

  template <typename Ar>
  void serialize(Ar& ar) {
    ar & MEMBER(abc) & MEMBER(def);
  }
};

TEST(jsonconfig_cast, named_not_found) {
  config_root conf(lexical_cast<json>("{\"def\": 456}"));

  try {
    opt1 a = config_cast<opt1>(conf);
    FAIL();
  } catch (const not_found& e) {
    EXPECT_EQ("", e.path());
    EXPECT_EQ("abc", e.key());
  }
}

TEST(jsonconfig_cast, named_type_null) {
  config_root conf(lexical_cast<json>("{\"abc\" : null }"));

  try {
    config_cast<opt1>(conf);
    FAIL();
  } catch (const type_error& e) {
    EXPECT_EQ(".abc", e.path());
    EXPECT_EQ(json::Null, e.actual());
    EXPECT_EQ(json::Integer, e.expect());
  }
}

TEST(jsonconfig_cast, named_optional_nullable) {
  config_root conf(lexical_cast<json>("{\"abc\": 123, \"def\": null}"));
  ASSERT_NO_THROW(config_cast<opt1>(conf));
}

struct opt2 {
  int abc;
  pfi::data::optional<int> def;

  struct test {
    int a;
    int b;

    template <typename Ar>
    void serialize(Ar& ar) {
      ar & MEMBER(a) & MEMBER(b);
    }
  } test;

  template <typename Ar>
  void serialize(Ar& ar) {
    ar & MEMBER(abc) & MEMBER(def) & MEMBER(test);
  }
};

TEST(jsonconfig_cast, named_nest_not_found) {
  config_root conf(lexical_cast<json>("{\"abc\" : 124 }"));

  try {
    config_cast<opt2>(conf);
    FAIL();
  } catch (const not_found& e) {
    EXPECT_EQ("", e.path());
    EXPECT_EQ("test", e.key());
  }
}

#if 0
// FIXME: this depends pficommon's issue #122
TEST(jsonconfig_cast, named_bad_type) {
  config_root conf(lexical_cast<json>("{\"abc\" : 124, \"test\": [] }"));

  try {
    config_cast<opt2>(conf);
    FAIL();
  } catch (type_error& e) {
    cout << e.what() << endl;
    EXPECT_EQ("", e.path());
  } catch (std::exception& e) {
    cout << "what?: " << e.what() << endl;
  }
}
#endif

struct Person {
  string name;
  double height;
  int age;
  map<string, string> attributes;
  pfi::data::optional<string> sport;
  pfi::data::optional<string> hobby;

  bool operator ==(const Person& p) const {
    return name == p.name && height == p.height && age == p.age && attributes == p.attributes && sport == p.sport && hobby == p.hobby;
  }

  template <class Ar>
  void serialize(Ar& ar) {
    ar & MEMBER(name) & MEMBER(height) & MEMBER(age) & MEMBER(attributes) & MEMBER(sport) & MEMBER(hobby);
  }
};

TEST(jsonconfig_cast, struct) {
  config_root conf(lexical_cast<json>("{\"name\": \"Taro\", \"height\": 160.0, \"age\": 20, \"attributes\": {\"address\": \"Tokyo\"}, \"sport\": \"tennis\"}"));
  Person p;
  p.name = "Taro";
  p.height = 160.0;
  p.age = 20;
  p.attributes["address"] = "Tokyo";
  p.sport = "tennis";

  EXPECT_EQ(p, config_cast<Person>(conf));
}

struct server_conf {
  struct web_conf {
    std::string host;
    int port;

    template <typename Ar>
    void serialize(Ar& ar) {
      ar & MEMBER(host) & MEMBER(port);
    }
  } web_server;

  std::vector<std::string> users;

  template <typename Ar>
  void serialize(Ar& ar) {
    ar & MEMBER(web_server) & MEMBER(users);
  }
};

TEST(jsonconfig_cast, error) {
  config_root conf(lexical_cast<json>("{\"web_server\": { \"host\" : 123}, \"users\": [\"abc\", 1] }"));

  config_error_list errors;
  server_conf c = config_cast<server_conf>(conf, errors);

  for (size_t i = 0; i < errors.size(); i++) {
    cout << errors[i]->what() << endl;
  }

  EXPECT_EQ(3, errors.size());

  type_error* e1 = dynamic_cast<type_error*>(errors[0].get());
  ASSERT_TRUE(e1);
  EXPECT_EQ(".web_server.host", e1->path());
  EXPECT_EQ(json::Integer, e1->actual());

  not_found* e2 = dynamic_cast<not_found*>(errors[1].get());
  ASSERT_TRUE(e2);
  EXPECT_EQ(".web_server", e2->path());
  EXPECT_EQ("port", e2->key());

  type_error* e3 = dynamic_cast<type_error*>(errors[2].get());
  ASSERT_TRUE(e3);
  EXPECT_EQ(".users[1]", e3->path());
  EXPECT_EQ(json::Integer, e3->actual());
}

} // jsonconfig
} // jubatus
<|endoftext|>