<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

#include "pch_rhoruntime.h"
#include "rhoruntime.h"

//#include "../../shared/sqlite/sqlite3.h"
//#include "logging/RhoLogConf.h"
#include "common/RhoStd.h"
#include "common/RhodesApp.h"
#include "common/RhoFilePath.h"
#include "rubyext/WebView.h"

using namespace rhoruntime;
using namespace Platform;

CRhoRuntime^ CRhoRuntime::m_instance = nullptr;

CRhoRuntime::CRhoRuntime(IMainPage^ mainPage):
	m_MainPage(mainPage)
{
}

CRhoRuntime^ CRhoRuntime::getInstance(IMainPage^ mainPage)
{
	if (m_instance == nullptr)
		m_instance = ref new CRhoRuntime(mainPage);
    return m_instance;
}

CRhoRuntime^ CRhoRuntime::getInstance()
{
    return m_instance;
}

IMainPage^ CRhoRuntime::getMainPage()
{
	return m_MainPage;
}

// rhodes executed in a separate thread
void CRhoRuntime::Execute()
{
	rho::String m_strRootPath = rho_native_rhopath(), m_logPort, m_strRuntimePath;
    rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str());

    rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRuntimePath);
    //RHODESAPP().setExtManager( &m_oExtManager );

	//Create Main window
	createCustomMenu();

	RHODESAPP().startApp();

	// wait for 5 seconds
	//m_MainPage->DoWait(10000);
	//m_MainPage->fullscreenCommand(1);
	//m_MainPage->exitCommand();
}

// *** CALLBACKS from MainPage object ***

void CRhoRuntime::updateSizeProperties(int width, int height)
{
	// TODO: implement
}

void CRhoRuntime::onActivate(int active)
{
	//rho_webview_navigate("system/uicreated", 0); //HOTFIX, should remove after threadqueue fix
	RHODESAPP().callUiCreatedCallback();
    //rho_rhodesapp_callAppActiveCallback(active);
    //if (!active)
    //    rho_geoimpl_turngpsoff();
}

void CRhoRuntime::logEvent(::Platform::String^ message)
{
	LOG(INFO) + rho::common::convertToStringW(message->Data());
}

void CRhoRuntime::createCustomMenu()
{
	IMainPage^ mainPage = CRhoRuntime::getInstance()->getMainPage();
	rho::Vector<rho::common::CAppMenuItem> m_arAppMenuItems;
    RHODESAPP().getAppMenu().copyMenuItems(m_arAppMenuItems);
#ifdef ENABLE_DYNAMIC_RHOBUNDLE
	rho::String index = "index"RHO_ERB_EXT;
    rho::String strIndexPage = rho::common::CFilePath::join(RHODESAPP().getStartUrl(), index);
    if ( RHODESAPP().getCurrentUrl().compare(RHODESAPP().getStartUrl()) == 0 ||
         RHODESAPP().getCurrentUrl().compare(strIndexPage) == 0 )
        m_arAppMenuItems.addElement(rho::common::CAppMenuItem("Reload RhoBundle","reload_rhobundle"));
#endif //ENABLE_DYNAMIC_RHOBUNDLE

    //update UI with custom menu items
	mainPage->menuClear();
    for ( unsigned int i = 0; i < m_arAppMenuItems.size(); i++)
    {
        rho::common::CAppMenuItem& oItem = m_arAppMenuItems.elementAt(i);
        if (oItem.m_eType == rho::common::CAppMenuItem::emtSeparator)
            mainPage->menuAddSeparator();
        else {
			rho::StringW labelW;
			rho::common::convertToStringW(oItem.m_strLabel.c_str(), labelW);
			mainPage->menuAddAction((oItem.m_eType == rho::common::CAppMenuItem::emtClose ? "Exit" : ref new Platform::String(labelW.c_str())), i);
        }
    }
}

void CRhoRuntime::onCustomMenuItemCommand(int nItemPos)
{
	rho::Vector<rho::common::CAppMenuItem> m_arAppMenuItems;
    RHODESAPP().getAppMenu().copyMenuItems(m_arAppMenuItems);

	if ( nItemPos < 0 || nItemPos >= (int)m_arAppMenuItems.size() )
        return;

    rho::common::CAppMenuItem& oMenuItem = m_arAppMenuItems.elementAt(nItemPos);
    if ( oMenuItem.m_eType == rho::common::CAppMenuItem::emtUrl )
    {
		// TODO: implement ReloadRhoBundle
        if ( oMenuItem.m_strLink == "reload_rhobundle" )
        {
			#ifdef ENABLE_DYNAMIC_RHOBUNDLE
            //if ( RHODESAPP().getRhobundleReloadUrl().length()>0 ) {
            //    CAppManager::ReloadRhoBundle(m_hWnd,RHODESAPP().getRhobundleReloadUrl().c_str(), NULL);
            //} else {
            //    MessageBox(_T("Path to the bundle is not defined."),_T("Information"), MB_OK | MB_ICONINFORMATION );
            //}
			#endif
			return;
        }
    }
    oMenuItem.processCommand();
}

void CRhoRuntime::onToolbarAction(::Platform::String^ action)
{
	if ( action->Equals("forward") )
		rho_webview_navigate_forward();
	else
		RHODESAPP().loadUrl(rho::common::convertToStringA(action->Data()));
}

void CRhoRuntime::onWindowClose(void)
{
	// TODO: implement
}

void CRhoRuntime::onWebViewUrlChanged(::Platform::String^ url)
{
	RHODESAPP().keepLastVisitedUrl(rho::common::convertToStringA(url->Data()));
}

bool CRhoRuntime::onBackKeyPress()
{
	// TODO: implement check for history size (return false if there's no history)
	RHODESAPP().navigateBack();
	return true;
}

// *** PUBLIC METHODS ***

bool CRhoRuntime::Initialize(::Platform::String^ title)
{
	return true;
}

void CRhoRuntime::DestroyUi(void)
{
	rho_rhodesapp_callUiDestroyedCallback();
}

extern "C" void rho_sys_app_exit()
{
	// exit application
	CRhoRuntime::getInstance()->getMainPage()->exitCommand();
}

#ifdef OS_WP8
extern "C" void rho_net_impl_network_indicator(int active)
{
	 //TODO: rho_net_ping_network
    RAWLOGC_INFO("rhoruntime.cpp", "rho_net_impl_network_indicator() has no implementation on WP8.");
}

extern "C" int rho_net_ping_network(const char* szHost)
{
    //TODO: rho_net_ping_network
    RAWLOGC_INFO("rhoruntime.cpp", "rho_net_ping_network() has no implementation on WP8.");
    return 1;
}
#endif<commit_msg>wp8: special handling for 'Back' menu item<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

#include "pch_rhoruntime.h"
#include "rhoruntime.h"

//#include "../../shared/sqlite/sqlite3.h"
//#include "logging/RhoLogConf.h"
#include "common/RhoStd.h"
#include "common/RhodesApp.h"
#include "common/RhoFilePath.h"
#include "rubyext/WebView.h"

using namespace rhoruntime;
using namespace Platform;

CRhoRuntime^ CRhoRuntime::m_instance = nullptr;

CRhoRuntime::CRhoRuntime(IMainPage^ mainPage):
	m_MainPage(mainPage)
{
}

CRhoRuntime^ CRhoRuntime::getInstance(IMainPage^ mainPage)
{
	if (m_instance == nullptr)
		m_instance = ref new CRhoRuntime(mainPage);
    return m_instance;
}

CRhoRuntime^ CRhoRuntime::getInstance()
{
    return m_instance;
}

IMainPage^ CRhoRuntime::getMainPage()
{
	return m_MainPage;
}

// rhodes executed in a separate thread
void CRhoRuntime::Execute()
{
	rho::String m_strRootPath = rho_native_rhopath(), m_logPort, m_strRuntimePath;
    rho_logconf_Init(m_strRootPath.c_str(), m_strRootPath.c_str(), m_logPort.c_str());

    rho::common::CRhodesApp::Create(m_strRootPath, m_strRootPath, m_strRuntimePath);
    //RHODESAPP().setExtManager( &m_oExtManager );

	//Create Main window
	createCustomMenu();

	RHODESAPP().startApp();

	// wait for 5 seconds
	//m_MainPage->DoWait(10000);
	//m_MainPage->fullscreenCommand(1);
	//m_MainPage->exitCommand();
}

// *** CALLBACKS from MainPage object ***

void CRhoRuntime::updateSizeProperties(int width, int height)
{
	// TODO: implement
}

void CRhoRuntime::onActivate(int active)
{
	//rho_webview_navigate("system/uicreated", 0); //HOTFIX, should remove after threadqueue fix
	RHODESAPP().callUiCreatedCallback();
    //rho_rhodesapp_callAppActiveCallback(active);
    //if (!active)
    //    rho_geoimpl_turngpsoff();
}

void CRhoRuntime::logEvent(::Platform::String^ message)
{
	LOG(INFO) + rho::common::convertToStringW(message->Data());
}

void CRhoRuntime::createCustomMenu()
{
	IMainPage^ mainPage = CRhoRuntime::getInstance()->getMainPage();
	rho::Vector<rho::common::CAppMenuItem> m_arAppMenuItems;
    RHODESAPP().getAppMenu().copyMenuItems(m_arAppMenuItems);
#ifdef ENABLE_DYNAMIC_RHOBUNDLE
	rho::String index = "index"RHO_ERB_EXT;
    rho::String strIndexPage = rho::common::CFilePath::join(RHODESAPP().getStartUrl(), index);
    if ( RHODESAPP().getCurrentUrl().compare(RHODESAPP().getStartUrl()) == 0 ||
         RHODESAPP().getCurrentUrl().compare(strIndexPage) == 0 )
        m_arAppMenuItems.addElement(rho::common::CAppMenuItem("Reload RhoBundle","reload_rhobundle"));
#endif //ENABLE_DYNAMIC_RHOBUNDLE

    //update UI with custom menu items
	mainPage->menuClear();
	RHODESAPP().setAppBackUrl("");
    for ( unsigned int i = 0; i < m_arAppMenuItems.size(); i++)
    {
        rho::common::CAppMenuItem& oItem = m_arAppMenuItems.elementAt(i);
        if (oItem.m_eType == rho::common::CAppMenuItem::emtSeparator)
            mainPage->menuAddSeparator();
        else {
 			rho::StringW labelW;
			rho::common::convertToStringW(oItem.m_strLabel.c_str(), labelW);
			if ((oItem.m_eType == rho::common::CAppMenuItem::emtBack) && (oItem.m_strLink.compare("back") != 0))
				RHODESAPP().setAppBackUrl(oItem.m_strLink);
			mainPage->menuAddAction((oItem.m_eType == rho::common::CAppMenuItem::emtClose ? "Exit" : ref new Platform::String(labelW.c_str())), i);
        }
    }
}

void CRhoRuntime::onCustomMenuItemCommand(int nItemPos)
{
	rho::Vector<rho::common::CAppMenuItem> m_arAppMenuItems;
    RHODESAPP().getAppMenu().copyMenuItems(m_arAppMenuItems);

	if ( nItemPos < 0 || nItemPos >= (int)m_arAppMenuItems.size() )
        return;

    rho::common::CAppMenuItem& oMenuItem = m_arAppMenuItems.elementAt(nItemPos);
    if ( oMenuItem.m_eType == rho::common::CAppMenuItem::emtUrl )
    {
		// TODO: implement ReloadRhoBundle
        if ( oMenuItem.m_strLink == "reload_rhobundle" )
        {
			#ifdef ENABLE_DYNAMIC_RHOBUNDLE
            //if ( RHODESAPP().getRhobundleReloadUrl().length()>0 ) {
            //    CAppManager::ReloadRhoBundle(m_hWnd,RHODESAPP().getRhobundleReloadUrl().c_str(), NULL);
            //} else {
            //    MessageBox(_T("Path to the bundle is not defined."),_T("Information"), MB_OK | MB_ICONINFORMATION );
            //}
			#endif
			return;
        }
    }
    oMenuItem.processCommand();
}

void CRhoRuntime::onToolbarAction(::Platform::String^ action)
{
	if ( action->Equals("forward") )
		rho_webview_navigate_forward();
	else
		RHODESAPP().loadUrl(rho::common::convertToStringA(action->Data()));
}

void CRhoRuntime::onWindowClose(void)
{
	// TODO: implement
}

void CRhoRuntime::onWebViewUrlChanged(::Platform::String^ url)
{
	RHODESAPP().keepLastVisitedUrl(rho::common::convertToStringA(url->Data()));
}

bool CRhoRuntime::onBackKeyPress()
{
	// TODO: implement check for history size (return false if there's no history)
	RHODESAPP().navigateBack();
	return true;
}

// *** PUBLIC METHODS ***

bool CRhoRuntime::Initialize(::Platform::String^ title)
{
	return true;
}

void CRhoRuntime::DestroyUi(void)
{
	rho_rhodesapp_callUiDestroyedCallback();
}

extern "C" void rho_sys_app_exit()
{
	// exit application
	CRhoRuntime::getInstance()->getMainPage()->exitCommand();
}

#ifdef OS_WP8
extern "C" void rho_net_impl_network_indicator(int active)
{
	 //TODO: rho_net_ping_network
    RAWLOGC_INFO("rhoruntime.cpp", "rho_net_impl_network_indicator() has no implementation on WP8.");
}

extern "C" int rho_net_ping_network(const char* szHost)
{
    //TODO: rho_net_ping_network
    RAWLOGC_INFO("rhoruntime.cpp", "rho_net_ping_network() has no implementation on WP8.");
    return 1;
}
#endif<|endoftext|>


<commit_before>#include <math.h>
#include <stdlib.h>
#include <fftw3.h>
#include <gsl/gsl_rng.h>

#include "allvars.h"
#include "proto.h"
#include "part_data.hpp"

#include <gadgetreader.hpp>
#include <gadgetwriter.hpp>

int main(int argc, char **argv)
{
  int type;
  std::valarray<int64_t> npart(N_TYPE);
  int64_t FirstId=0;

  if(argc < 2)
    {
	  fprintf(stdout, "\nParameters are missing.\n");
	  fprintf(stdout, "Call with <ParameterFile>\n\n");
      exit(0);
    }
  /*Make sure stdout is line buffered even when not
   * printing to a terminal but, eg, perl*/
  setlinebuf(stdout);
  read_parameterfile(argv[1]);
  set_units();

  printf("Nmesh = %d Nsample = %d\n",Nmesh,Nsample);
  initialize_ffts();
  printf("Initialising pre-IC file '%s'\n",GlassFile);
  GadgetReader::GSnap snap(GlassFile);
  /*Set particle numbers*/
  for(type = 0; type < N_TYPE; type++)
    npart[type] = snap.GetNpart(type) * GlassTileFac * GlassTileFac * GlassTileFac;
  if(npart.sum() == 0)
          exit(1);
  /*Set the global variable saying there is no gas in the glassfile,
   * so that the OmegaBaryon should be added to the DM.*/
  if (npart[BARYON_TYPE] == 0)
          no_gas = 1;
  else
          no_gas = 0;
  /*We need to initialise the power spectrum here so that no_gas is set*/
  initialize_powerspectrum();

#ifdef NEUTRINO_PAIRS
  npart[NEUTRINO_TYPE] *= 2;
#endif //NEUTRINO_PAIRS
  GadgetWriter::GWriteSnap osnap(std::string(OutputDir)+std::string("/")+std::string(FileBase), npart,NumFiles, sizeof(id_type));
  /*Write headers*/
  if(osnap.WriteHeaders(generate_header(npart)))
          FatalError(23);

  for(type=0; type<N_TYPE;type++){
      int64_t NumPart = 0;
      if(npart[type] == 0)
              continue;
      part_data P(snap, type, GlassTileFac);
      NumPart = P.GetNumPart();
      displacement_fields(type, NumPart, P, Nmesh);
      FirstId = write_particle_data(osnap, type,P, NumPart,FirstId);
#ifdef PRINT_SPEC
      print_spec(type);
#endif
  }

  fftwf_free(Disp);
  fftwf_destroy_plan(Inverse_plan);

  printf("Initial scale factor = %g\n", InitTime);

  return 0;
}

/**Little macro to work the storage order of the FFT.*/
#define KVAL(n) ((n)< Nmesh/2 ? (n) : ((n)-Nmesh))

void displacement_fields(const int type, const int64_t NumPart, part_data& P, const int Nmesh)
{
  const double fac = pow(2 * M_PI / Box, 1.5);
  const unsigned int *seedtable = initialize_rng(Seed);
  double mindisp=0, maxdisp=0;

/*I really think this is not right; Omega should be specified as total matter density, not cdm matter*/
/*  if(neutrinos_ks)
    Omega = Omega + OmegaDM_2ndSpecies;*/

  /* the final term converts to Gadget velocity */

      for(int axes = 0; axes < 3; axes++) {
	  printf("Starting axis %d.\n", axes);

          #pragma omp parallel
	  {
          gsl_rng * random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);
	  /* first, clean the array */
	  #pragma omp for
	  for(size_t i = 0; i < ((size_t) 2*Nmesh*Nmesh)*(Nmesh/2+1); i++)
		  Disp[i] = 0;

	  #pragma omp for
	  for(int i = 0; i < Nmesh; i++) {
		  for(int j = 0; j < Nmesh; j++) {
		      gsl_rng_set(random_generator, seedtable[i * Nmesh + j]);

		      for(int k = 0; k < Nmesh / 2; k++) {
                          double kvec[3], kmag, kmag2, p_of_k;
                          double delta, phase, ampl;
			  phase = gsl_rng_uniform(random_generator) * 2 * M_PI;
			  do
			    ampl = gsl_rng_uniform(random_generator);
			  while(ampl == 0);

			  if(i == Nmesh / 2 || j == Nmesh / 2 || k == Nmesh / 2)
			    continue;
			  if(i == 0 && j == 0 && k == 0)
			    continue;

			  kvec[0] = KVAL(i) * 2 * M_PI / Box;
			  kvec[1] = KVAL(j) * 2 * M_PI / Box;
			  kvec[2] = KVAL(k) * 2 * M_PI / Box;

			  kmag2 = kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2];
			  kmag = sqrt(kmag2);

                          /* select a sphere in k-space */
			  if(SphereMode == 1){
			      if(kmag * Box / (2 * M_PI) > Nsample / 2)
                                      continue;
                          }
                          /*Or a box*/
			  else {
			      if(fabs(kvec[0]) * Box / (2 * M_PI) > Nsample / 2)
				continue;
			      if(fabs(kvec[1]) * Box / (2 * M_PI) > Nsample / 2)
				continue;
			      if(fabs(kvec[2]) * Box / (2 * M_PI) > Nsample / 2)
				continue;
			  }

			  p_of_k = PowerSpec(kmag, type);

			  // printf(" k %d %g %g \n",Type,kmag,p_of_k);
			  // p_of_k *= -log(ampl);

			  delta = fac * sqrt(p_of_k) ;
                          /* scale back to starting redshift */
                          /*If we are using the CAMB P(k), Dplus=1.
                            * fac=(2π/Box)^1.5*/
#ifdef CORRECT_CIC
			  /* do deconvolution of CIC interpolation */
			  delta *= invwindow(i,j,k,Nmesh);
#endif
			  if(k > 0) {
                                  size_t index = (i * Nmesh + j) * (Nmesh / 2 + 1) + k;
				  (Cdata[index])[0] =
				    -kvec[axes] / kmag2 * delta * sin(phase);
				  (Cdata[index])[1] =
				    kvec[axes] / kmag2 * delta * cos(phase);
			    }
			  else	/* k=0 plane needs special treatment */
			    {
			      if(i == 0)
				{
				  if(j >= Nmesh / 2)
				    continue;
				  else
				    {
					  int jj = Nmesh - j;	/* note: i=k=0 => j!=0 */
                                          size_t index = j * (Nmesh / 2 + 1);
					  (Cdata[index])[0] =
					    -kvec[axes] / kmag2 * delta * sin(phase);
					  (Cdata[index])[1] =
					    kvec[axes] / kmag2 * delta * cos(phase);

                                          index = jj * (Nmesh / 2 + 1);
					  (Cdata[index])[0] =
					    -kvec[axes] / kmag2 * delta * sin(phase);
					  (Cdata[index])[1] =
					    -kvec[axes] / kmag2 * delta * cos(phase);
				    }
				}
			      else	/* here comes i!=0 */
				{
				  if(i >= Nmesh / 2)
				    continue;
				  else
				    {
				      int jj = (Nmesh - j) % Nmesh;
                                      size_t index = (i * Nmesh + j) * (Nmesh / 2 + 1);
					  (Cdata[index])[0] =
					    -kvec[axes] / kmag2 * delta * sin(phase);
					  (Cdata[index])[1] =
					    kvec[axes] / kmag2 * delta * cos(phase);
                                      index = (i * Nmesh + jj) * (Nmesh / 2 + 1);
					  (Cdata[index])[0] = -kvec[axes] / kmag2 * delta * sin(phase);
					  (Cdata[index])[1] = -kvec[axes] / kmag2 * delta * cos(phase);
				    }
				}
			    }
			}

		    }
	    }

          gsl_rng_free(random_generator);
          #pragma omp barrier
          } //omp_parallel
	  fftwf_execute(Inverse_plan);	/** FFT **/

	  /* read-out displacements */
        #pragma omp parallel
          {
	  #pragma omp for
	  for(int n = 0; n < NumPart; n++)
	    {
                  double dis;
                  double f1, f2, f3, f4, f5, f6, f7, f8;
                  double u[3];
                  int64_t i[3], ii[3];
                  for(int q=0;q<3;q++){
        		  u[q] = P.Pos(n,q) / Box * Nmesh;
                          i[q] = static_cast<int64_t>(u[q]);
                          if(i[q] == Nmesh)
                                  i[q]--;
                          u[q] -= i[q];
                          ii[q] = i[q]+1;
        		  if(ii[q] >= Nmesh)
	        	    ii[q] -= Nmesh;
                  }

		  f1 = (1 - u[0]) * (1 - u[1]) * (1 - u[2]);
		  f2 = (1 - u[0]) * (1 - u[1]) * (u[2]);
		  f3 = (1 - u[0]) * (u[1]) * (1 - u[2]);
		  f4 = (1 - u[0]) * (u[1]) * (u[2]);
		  f5 = (u[0]) * (1 - u[1]) * (1 - u[2]);
		  f6 = (u[0]) * (1 - u[1]) * (u[2]);
		  f7 = (u[0]) * (u[1]) * (1 - u[2]);
		  f8 = (u[0]) * (u[1]) * (u[2]);

		  dis = Disp[(i[0] * Nmesh + i[1]) * (2 * (Nmesh / 2 + 1)) + i[2]] * f1 +
		    Disp[(i[0] * Nmesh + i[1]) * (2 * (Nmesh / 2 + 1)) + ii[2]] * f2 +
		    Disp[(i[0] * Nmesh + ii[1]) * (2 * (Nmesh / 2 + 1)) + i[2]] * f3 +
		    Disp[(i[0] * Nmesh + ii[1]) * (2 * (Nmesh / 2 + 1)) + ii[2]] * f4 +
		    Disp[(ii[0] * Nmesh + i[1]) * (2 * (Nmesh / 2 + 1)) + i[2]] * f5 +
		    Disp[(ii[0] * Nmesh + i[1]) * (2 * (Nmesh / 2 + 1)) + ii[2]] * f6 +
		    Disp[(ii[0] * Nmesh + ii[1]) * (2 * (Nmesh / 2 + 1)) + i[2]] * f7 +
		    Disp[(ii[0] * Nmesh + ii[1]) * (2 * (Nmesh / 2 + 1)) + ii[2]] * f8;

		  P.SetVel(dis, n,axes);
		  if(dis > maxdisp)
		    maxdisp = dis;
                  if(dis <mindisp)
                    mindisp=dis;
	    }
        } //end omp_parallel
	}

  printf("\nMaximum displacement: %g kpc/h, in units of the part-spacing= %g\n",
         maxdisp, maxdisp / (Box / Nmesh));
  printf("Minimum displacement: %g kpc/h, in units of the part-spacing= %g\n",
         mindisp, mindisp / (Box / Nmesh));
  return;
}

int FatalError(int errnum)
{
  printf("FatalError called with number=%d\n", errnum);
  fflush(stdout);
  exit(0);
}

#ifdef CORRECT_CIC
/* do deconvolution of CIC interpolation */
double invwindow(int kx,int ky,int kz,int n)
{
	double iwx=1.0,iwy=1.0,iwz=1.0;
        if(!n)
                return 0;
	if(kx){
		iwx=M_PI*kx/static_cast<float>(n);
		iwx=iwx/sin(iwx);
        }
	if(ky){
		iwy=M_PI*ky/static_cast<float>(n);
		iwy=iwy/sin(iwy);
        }
	if(kz){
		iwz=M_PI*kz/static_cast<float>(n);
		iwz=iwz/sin(iwz);
        }
	return pow(iwx*iwy*iwz,2);
}
#endif

<commit_msg>Re-enable Rayleigh scatterign of modes<commit_after>#include <math.h>
#include <stdlib.h>
#include <fftw3.h>
#include <gsl/gsl_rng.h>

#include "allvars.h"
#include "proto.h"
#include "part_data.hpp"

#include <gadgetreader.hpp>
#include <gadgetwriter.hpp>

int main(int argc, char **argv)
{
  int type;
  std::valarray<int64_t> npart(N_TYPE);
  int64_t FirstId=0;

  if(argc < 2)
    {
	  fprintf(stdout, "\nParameters are missing.\n");
	  fprintf(stdout, "Call with <ParameterFile>\n\n");
      exit(0);
    }
  /*Make sure stdout is line buffered even when not
   * printing to a terminal but, eg, perl*/
  setlinebuf(stdout);
  read_parameterfile(argv[1]);
  set_units();

  printf("Nmesh = %d Nsample = %d\n",Nmesh,Nsample);
  initialize_ffts();
  printf("Initialising pre-IC file '%s'\n",GlassFile);
  GadgetReader::GSnap snap(GlassFile);
  /*Set particle numbers*/
  for(type = 0; type < N_TYPE; type++)
    npart[type] = snap.GetNpart(type) * GlassTileFac * GlassTileFac * GlassTileFac;
  if(npart.sum() == 0)
          exit(1);
  /*Set the global variable saying there is no gas in the glassfile,
   * so that the OmegaBaryon should be added to the DM.*/
  if (npart[BARYON_TYPE] == 0)
          no_gas = 1;
  else
          no_gas = 0;
  /*We need to initialise the power spectrum here so that no_gas is set*/
  initialize_powerspectrum();

#ifdef NEUTRINO_PAIRS
  npart[NEUTRINO_TYPE] *= 2;
#endif //NEUTRINO_PAIRS
  GadgetWriter::GWriteSnap osnap(std::string(OutputDir)+std::string("/")+std::string(FileBase), npart,NumFiles, sizeof(id_type));
  /*Write headers*/
  if(osnap.WriteHeaders(generate_header(npart)))
          FatalError(23);

  for(type=0; type<N_TYPE;type++){
      int64_t NumPart = 0;
      if(npart[type] == 0)
              continue;
      part_data P(snap, type, GlassTileFac);
      NumPart = P.GetNumPart();
      displacement_fields(type, NumPart, P, Nmesh);
      FirstId = write_particle_data(osnap, type,P, NumPart,FirstId);
#ifdef PRINT_SPEC
      print_spec(type);
#endif
  }

  fftwf_free(Disp);
  fftwf_destroy_plan(Inverse_plan);

  printf("Initial scale factor = %g\n", InitTime);

  return 0;
}

/**Little macro to work the storage order of the FFT.*/
#define KVAL(n) ((n)< Nmesh/2 ? (n) : ((n)-Nmesh))

void displacement_fields(const int type, const int64_t NumPart, part_data& P, const int Nmesh)
{
  const double fac = pow(2 * M_PI / Box, 1.5);
  const unsigned int *seedtable = initialize_rng(Seed);
  double mindisp=0, maxdisp=0;

/*I really think this is not right; Omega should be specified as total matter density, not cdm matter*/
/*  if(neutrinos_ks)
    Omega = Omega + OmegaDM_2ndSpecies;*/

  /* the final term converts to Gadget velocity */

      for(int axes = 0; axes < 3; axes++) {
	  printf("Starting axis %d.\n", axes);

          #pragma omp parallel
	  {
          gsl_rng * random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);
	  /* first, clean the array */
	  #pragma omp for
	  for(size_t i = 0; i < ((size_t) 2*Nmesh*Nmesh)*(Nmesh/2+1); i++)
		  Disp[i] = 0;

	  #pragma omp for
	  for(int i = 0; i < Nmesh; i++) {
		  for(int j = 0; j < Nmesh; j++) {
		      gsl_rng_set(random_generator, seedtable[i * Nmesh + j]);

		      for(int k = 0; k < Nmesh / 2; k++) {
                          double kvec[3], kmag, kmag2, p_of_k;
                          double delta, phase, ampl;
			  phase = gsl_rng_uniform(random_generator) * 2 * M_PI;
			  do
			    ampl = gsl_rng_uniform(random_generator);
			  while(ampl == 0);

			  if(i == Nmesh / 2 || j == Nmesh / 2 || k == Nmesh / 2)
			    continue;
			  if(i == 0 && j == 0 && k == 0)
			    continue;

			  kvec[0] = KVAL(i) * 2 * M_PI / Box;
			  kvec[1] = KVAL(j) * 2 * M_PI / Box;
			  kvec[2] = KVAL(k) * 2 * M_PI / Box;

			  kmag2 = kvec[0] * kvec[0] + kvec[1] * kvec[1] + kvec[2] * kvec[2];
			  kmag = sqrt(kmag2);

                          /* select a sphere in k-space */
			  if(SphereMode == 1){
			      if(kmag * Box / (2 * M_PI) > Nsample / 2)
                                      continue;
                          }
                          /*Or a box*/
			  else {
			      if(fabs(kvec[0]) * Box / (2 * M_PI) > Nsample / 2)
				continue;
			      if(fabs(kvec[1]) * Box / (2 * M_PI) > Nsample / 2)
				continue;
			      if(fabs(kvec[2]) * Box / (2 * M_PI) > Nsample / 2)
				continue;
			  }

			  p_of_k = PowerSpec(kmag, type);

			  // printf(" k %d %g %g \n",Type,kmag,p_of_k);
			  p_of_k *= -log(ampl);

			  delta = fac * sqrt(p_of_k) ;
                          /* scale back to starting redshift */
                          /*If we are using the CAMB P(k), Dplus=1.
                            * fac=(2π/Box)^1.5*/
#ifdef CORRECT_CIC
			  /* do deconvolution of CIC interpolation */
			  delta *= invwindow(i,j,k,Nmesh);
#endif
			  if(k > 0) {
                                  size_t index = (i * Nmesh + j) * (Nmesh / 2 + 1) + k;
				  (Cdata[index])[0] =
				    -kvec[axes] / kmag2 * delta * sin(phase);
				  (Cdata[index])[1] =
				    kvec[axes] / kmag2 * delta * cos(phase);
			    }
			  else	/* k=0 plane needs special treatment */
			    {
			      if(i == 0)
				{
				  if(j >= Nmesh / 2)
				    continue;
				  else
				    {
					  int jj = Nmesh - j;	/* note: i=k=0 => j!=0 */
                                          size_t index = j * (Nmesh / 2 + 1);
					  (Cdata[index])[0] =
					    -kvec[axes] / kmag2 * delta * sin(phase);
					  (Cdata[index])[1] =
					    kvec[axes] / kmag2 * delta * cos(phase);

                                          index = jj * (Nmesh / 2 + 1);
					  (Cdata[index])[0] =
					    -kvec[axes] / kmag2 * delta * sin(phase);
					  (Cdata[index])[1] =
					    -kvec[axes] / kmag2 * delta * cos(phase);
				    }
				}
			      else	/* here comes i!=0 */
				{
				  if(i >= Nmesh / 2)
				    continue;
				  else
				    {
				      int jj = (Nmesh - j) % Nmesh;
                                      size_t index = (i * Nmesh + j) * (Nmesh / 2 + 1);
					  (Cdata[index])[0] =
					    -kvec[axes] / kmag2 * delta * sin(phase);
					  (Cdata[index])[1] =
					    kvec[axes] / kmag2 * delta * cos(phase);
                                      index = (i * Nmesh + jj) * (Nmesh / 2 + 1);
					  (Cdata[index])[0] = -kvec[axes] / kmag2 * delta * sin(phase);
					  (Cdata[index])[1] = -kvec[axes] / kmag2 * delta * cos(phase);
				    }
				}
			    }
			}

		    }
	    }

          gsl_rng_free(random_generator);
          #pragma omp barrier
          } //omp_parallel
	  fftwf_execute(Inverse_plan);	/** FFT **/

	  /* read-out displacements */
        #pragma omp parallel
          {
	  #pragma omp for
	  for(int n = 0; n < NumPart; n++)
	    {
                  double dis;
                  double f1, f2, f3, f4, f5, f6, f7, f8;
                  double u[3];
                  int64_t i[3], ii[3];
                  for(int q=0;q<3;q++){
        		  u[q] = P.Pos(n,q) / Box * Nmesh;
                          i[q] = static_cast<int64_t>(u[q]);
                          if(i[q] == Nmesh)
                                  i[q]--;
                          u[q] -= i[q];
                          ii[q] = i[q]+1;
        		  if(ii[q] >= Nmesh)
	        	    ii[q] -= Nmesh;
                  }

		  f1 = (1 - u[0]) * (1 - u[1]) * (1 - u[2]);
		  f2 = (1 - u[0]) * (1 - u[1]) * (u[2]);
		  f3 = (1 - u[0]) * (u[1]) * (1 - u[2]);
		  f4 = (1 - u[0]) * (u[1]) * (u[2]);
		  f5 = (u[0]) * (1 - u[1]) * (1 - u[2]);
		  f6 = (u[0]) * (1 - u[1]) * (u[2]);
		  f7 = (u[0]) * (u[1]) * (1 - u[2]);
		  f8 = (u[0]) * (u[1]) * (u[2]);

		  dis = Disp[(i[0] * Nmesh + i[1]) * (2 * (Nmesh / 2 + 1)) + i[2]] * f1 +
		    Disp[(i[0] * Nmesh + i[1]) * (2 * (Nmesh / 2 + 1)) + ii[2]] * f2 +
		    Disp[(i[0] * Nmesh + ii[1]) * (2 * (Nmesh / 2 + 1)) + i[2]] * f3 +
		    Disp[(i[0] * Nmesh + ii[1]) * (2 * (Nmesh / 2 + 1)) + ii[2]] * f4 +
		    Disp[(ii[0] * Nmesh + i[1]) * (2 * (Nmesh / 2 + 1)) + i[2]] * f5 +
		    Disp[(ii[0] * Nmesh + i[1]) * (2 * (Nmesh / 2 + 1)) + ii[2]] * f6 +
		    Disp[(ii[0] * Nmesh + ii[1]) * (2 * (Nmesh / 2 + 1)) + i[2]] * f7 +
		    Disp[(ii[0] * Nmesh + ii[1]) * (2 * (Nmesh / 2 + 1)) + ii[2]] * f8;

		  P.SetVel(dis, n,axes);
		  if(dis > maxdisp)
		    maxdisp = dis;
                  if(dis <mindisp)
                    mindisp=dis;
	    }
        } //end omp_parallel
	}

  printf("\nMaximum displacement: %g kpc/h, in units of the part-spacing= %g\n",
         maxdisp, maxdisp / (Box / Nmesh));
  printf("Minimum displacement: %g kpc/h, in units of the part-spacing= %g\n",
         mindisp, mindisp / (Box / Nmesh));
  return;
}

int FatalError(int errnum)
{
  printf("FatalError called with number=%d\n", errnum);
  fflush(stdout);
  exit(0);
}

#ifdef CORRECT_CIC
/* do deconvolution of CIC interpolation */
double invwindow(int kx,int ky,int kz,int n)
{
	double iwx=1.0,iwy=1.0,iwz=1.0;
        if(!n)
                return 0;
	if(kx){
		iwx=M_PI*kx/static_cast<float>(n);
		iwx=iwx/sin(iwx);
        }
	if(ky){
		iwy=M_PI*ky/static_cast<float>(n);
		iwy=iwy/sin(iwy);
        }
	if(kz){
		iwz=M_PI*kz/static_cast<float>(n);
		iwz=iwz/sin(iwz);
        }
	return pow(iwx*iwy*iwz,2);
}
#endif

<|endoftext|>


<commit_before>#include <sys/mman.h>
#include "asmtest.h"
#include "x86_64/Operand.h"
#include "x86_64/Assembler.h"
#include "x86_64/Codegen.h"
#include "ASTNode.h"
#include "CompiledCode.h"
#include "Linker.h"
#include "lib/IncrementalAlloc.h"
#include "Util.h"
#include <iostream>
using namespace std;

#include "lib/Runtime.h"
#include "lib/Object.h"

#define __ masm.

using namespace snow;
//using namespace snow::x86_64;

void test_codegen() {/*
	SymbolTable table;
	table["snow_create_object"] = (void*)snow::create_object;
	table["snow_send"] = (void*)snow::send;
	table["snow_call"] = (void*)snow::call;
	table["snow_destroy"] = (void*)snow::destroy;

	x86_64::Codegen masm;

	__ function_entry(3);
	auto l1 = Scope::Local(0, "hejsa");
	__ get_argument(0, l1);
	auto l2 = Scope::Local(1);
	__ get_argument(1, l2);

	__ set_argument(0, l1);
	__ set_argument(1, "+");
	__ set_argument(2, 1);
	__ set_argument(3, l2);
	auto retval = Scope::Local(2);
	__ call("snow_send", retval);

	__ set_argument(0, l1);
	__ call("snow_destroy");
	__ set_argument(0, l2);
	__ call("snow_destroy");

//	__ debug_break();
	__ set_return(retval);
	__ function_return();

	RefPtr<CompiledCode> code = __ compile();
	code->export_symbols(table);
	code->link(table);

	code->make_executable();

	print_mem(code->code(), &code->code()[code->size()]);
	printf("code is at 0x%llx\n", (uint64_t)code->code());

	VALUE(*entry)(VALUE a, VALUE b) = (VALUE(*)(VALUE, VALUE))code->code();
	printf("add: %lld\n", integer(entry(value(-67LL), value(-45LL))));*/
}

static VALUE global_puts(VALUE self, uint64_t num_args, VALUE* args) {
	for (uint64_t i = 0; i < num_args; ++i) {
		printf("%s\n", value_to_string(args[i]));
	}
	return nil();
}

void test_ast() {
	using namespace snow::ast;

	SymbolTable table;
	table["snow_init_stack_frame"] = (void*)snow::init_stack_frame;
	table["snow_destroy"] = (void*)snow::destroy;
	table["snow_eval_truth"] = (void*)snow::eval_truth;
	table["snow_call"] = (void*)snow::call;
	table["snow_call_method"] = (void*)snow::call_method;
	table["snow_send"] = (void*)snow::send;

	RefPtr<FunctionDefinition> scope = new FunctionDefinition;
	scope->arguments.push_back(new Identifier("c"));
	scope->add(new MethodCall(new Identifier("self"), new Identifier("puts"), new Sequence(new Identifier("c"))));
	scope->add(new Assignment(new Identifier("a"), new Literal("123", Literal::INTEGER_TYPE)));
	scope->add(new Assignment(new Identifier("b"), new Literal("567", Literal::INTEGER_TYPE)));
	scope->add(new Assignment(
			new Identifier("d"),
			new MethodCall(
				new Identifier("a"),
				new Identifier("+"),
				new Sequence(new Identifier("b"))
			)
		)
	);
	scope->add(new Identifier("d"));

	RefPtr<Codegen> codegen = Codegen::create(*scope);
	RefPtr<CompiledCode> cc = codegen->compile();

	cc->export_symbols(table);
	cc->link(table);
	cc->make_executable();

	VALUE global_scope = create_object();
	object(global_scope)->set("puts", create_function(global_puts));

	printf("code is at: 0x%llx\n", (uint64_t)cc->code());
	VALUE ret = cc->function()(global_scope, 5, (VALUE[]){value(5LL), value(5LL),value(5LL), value(5LL), value(5LL)});
	printf("returned: %s\n", value_to_string(ret));
}

void test_sib() {
	using namespace snow::x86_64;
	x86_64::Assembler masm;

	__ enter(32);
	__ mov(3LL, rax);
	__ mov(SIB(rdi, rax, SIB::SCALE_8), rbx);
	__ mov(rbx, rax);
	__ debug_break();
	__ leave();
	__ ret();

	RefPtr<CompiledCode> cc = masm.compile();
	cc->make_executable();

	int64_t* array = new int64_t[10];
	for (int i = 0; i < 10; ++i) {
		array[i] = 123 + i;
	}

	debug("array is at 0x%llx", array);
	debug("code is at 0x%llx", cc->function());
	int64_t ret = (int64_t)cc->function()(array, 0, NULL);

	delete[] array;

	debug("returned: %lld", ret);
}

int main (int argc, char const *argv[])
{
	test_ast();
	//test_sib();
	TempAllocator<ast::Node>::flush();
	return 0;
}
<commit_msg>test driver: simple loop test<commit_after>#include <sys/mman.h>
#include "asmtest.h"
#include "x86_64/Operand.h"
#include "x86_64/Assembler.h"
#include "x86_64/Codegen.h"
#include "ASTNode.h"
#include "CompiledCode.h"
#include "Linker.h"
#include "lib/IncrementalAlloc.h"
#include "Util.h"
#include <iostream>
using namespace std;

#include "lib/Runtime.h"
#include "lib/Object.h"

#define __ masm.

using namespace snow;
//using namespace snow::x86_64;

void test_codegen() {/*
	SymbolTable table;
	table["snow_create_object"] = (void*)snow::create_object;
	table["snow_send"] = (void*)snow::send;
	table["snow_call"] = (void*)snow::call;
	table["snow_destroy"] = (void*)snow::destroy;

	x86_64::Codegen masm;

	__ function_entry(3);
	auto l1 = Scope::Local(0, "hejsa");
	__ get_argument(0, l1);
	auto l2 = Scope::Local(1);
	__ get_argument(1, l2);

	__ set_argument(0, l1);
	__ set_argument(1, "+");
	__ set_argument(2, 1);
	__ set_argument(3, l2);
	auto retval = Scope::Local(2);
	__ call("snow_send", retval);

	__ set_argument(0, l1);
	__ call("snow_destroy");
	__ set_argument(0, l2);
	__ call("snow_destroy");

//	__ debug_break();
	__ set_return(retval);
	__ function_return();

	RefPtr<CompiledCode> code = __ compile();
	code->export_symbols(table);
	code->link(table);

	code->make_executable();

	print_mem(code->code(), &code->code()[code->size()]);
	printf("code is at 0x%llx\n", (uint64_t)code->code());

	VALUE(*entry)(VALUE a, VALUE b) = (VALUE(*)(VALUE, VALUE))code->code();
	printf("add: %lld\n", integer(entry(value(-67LL), value(-45LL))));*/
}

static VALUE global_puts(VALUE self, uint64_t num_args, VALUE* args) {
	for (uint64_t i = 0; i < num_args; ++i) {
		printf("%s\n", value_to_string(args[i]));
	}
	return nil();
}

void test_ast() {
	using namespace snow::ast;

	SymbolTable table;
	table["snow_init_stack_frame"] = (void*)snow::init_stack_frame;
	table["snow_destroy"] = (void*)snow::destroy;
	table["snow_eval_truth"] = (void*)snow::eval_truth;
	table["snow_call"] = (void*)snow::call;
	table["snow_call_method"] = (void*)snow::call_method;
	table["snow_send"] = (void*)snow::send;

	RefPtr<FunctionDefinition> scope = new FunctionDefinition;
	scope->arguments.push_back(new Identifier("c"));
	scope->add(new MethodCall(new Identifier("self"), new Identifier("puts"), new Sequence(new Identifier("c"))));
	scope->add(new Assignment(new Identifier("a"), new Literal("123", Literal::INTEGER_TYPE)));
	scope->add(new Assignment(new Identifier("b"), new Literal("567", Literal::INTEGER_TYPE)));
	scope->add(new Assignment(
			new Identifier("d"),
			new MethodCall(
				new Identifier("a"),
				new Identifier("+"),
				new Sequence(new Identifier("b"))
			)
		)
	);
	scope->add(new Assignment(
			new Identifier("d"),
			new MethodCall(
				new Identifier("d"),
				new Identifier("+"),
				new Sequence(new Identifier("c"))
			)
		)
	);
	scope->add(new Assignment(
			new Identifier("e"),
			new Literal("0", Literal::INTEGER_TYPE)
		)
	);
	scope->add(new Loop(
			new MethodCall(
				new Identifier("e"),
				new Identifier("<"),
				new Sequence(new Identifier("d"))
			),
			new Sequence(
				new MethodCall(
					new Identifier("self"),
					new Identifier("puts"),
					new Sequence(new Identifier("e"))
				),
				new Assignment(new Identifier("e"),
					new MethodCall(
						new Identifier("e"),
						new Identifier("+"),
						new Sequence(new Literal("1", Literal::INTEGER_TYPE))
					)
				)
			)

		)
	);
	scope->add(new Identifier("d"));

	RefPtr<Codegen> codegen = Codegen::create(*scope);
	RefPtr<CompiledCode> cc = codegen->compile();

	cc->export_symbols(table);
	cc->link(table);
	cc->make_executable();

	VALUE global_scope = create_object();
	object(global_scope)->set("puts", create_function(global_puts));

	printf("code is at: 0x%llx\n", (uint64_t)cc->code());
	VALUE ret = cc->function()(global_scope, 5, (VALUE[]){value(5LL), value(5LL),value(5LL), value(5LL), value(5LL)});
	printf("returned: %s\n", value_to_string(ret));
}

void test_sib() {
	using namespace snow::x86_64;
	x86_64::Assembler masm;

	__ enter(32);
	__ mov(3LL, rax);
	__ mov(SIB(rdi, rax, SIB::SCALE_8), rbx);
	__ mov(rbx, rax);
	__ debug_break();
	__ leave();
	__ ret();

	RefPtr<CompiledCode> cc = masm.compile();
	cc->make_executable();

	int64_t* array = new int64_t[10];
	for (int i = 0; i < 10; ++i) {
		array[i] = 123 + i;
	}

	debug("array is at 0x%llx", array);
	debug("code is at 0x%llx", cc->function());
	int64_t ret = (int64_t)cc->function()(array, 0, NULL);

	delete[] array;

	debug("returned: %lld", ret);
}

int main (int argc, char const *argv[])
{
	test_ast();
	//test_sib();
	TempAllocator<ast::Node>::flush();
	return 0;
}
<|endoftext|>


<commit_before>#include <QtCore>
#include <iostream>

#include <pHash.h>

static const QString TMPNAME = "xraytmp";   // name of temporary dir (usually below /tmp)
static const int THRESHOLD = 5;             // find at least x dupe snapshots to consider video duped
static const int KEYFRAMES = 10;            // how many snapshots (keyframes) to compare

// create snapshots from video file
void
createSnaps( const QString& file, const QString& tmpPath )
{
    QStringList args;
    args << "-sstep" << "10"                            // only output keyframes in 10 second increments
         << "-nosound" << "-vo" << "jpeg"               // output as jpegs
         << "-ss" << "00:00:45"                         // start 45 seconds into the video
         << "-frames" << QString::number( KEYFRAMES )   // output x frames total
         << file;

    QProcess p;
    p.setWorkingDirectory( tmpPath );
    p.start( "mplayer", args );
    p.waitForFinished( 60000 );             // wait one minute at most
}

// create perceptual hash for snapshots
QHash<ulong64, int>
hashSnaps( const QString& path )
{
    QHash<ulong64, int> hashes;

    QDir dir( path );
    QFileInfoList list = dir.entryInfoList();
    for ( int i = 0; i < list.size(); ++i )
    {
        QFileInfo fileInfo = list.at( i );
        if ( !fileInfo.fileName().endsWith( ".jpg" ) )
            continue;

        ulong64 hash;
        int err = ph_dct_imagehash( fileInfo.absoluteFilePath().toLocal8Bit(), hash );
        if ( err )
            continue;

        hashes.insertMulti( hash, i );

        // delete snapshot
        QFile::remove( fileInfo.absoluteFilePath() );
    }

    return hashes;
}

// finds similar hashes by hamming distance
QList <QPair <int, QString> >
closestHashes( QHash<ulong64, QPair<int, QString> >& hashes, const ulong64& searchKey )
{
    QList <QPair <int, QString> > res;

    for ( int i = 0; i < hashes.keys().count(); i++ )
    {
        ulong64 key = hashes.keys().at( i );
        if ( ph_hamming_distance( searchKey, key ) < 4 )
        {
            QPair<int, QString> pair = hashes.values().at( i );
            res << pair;
        }
    }

    return res;
}

void
scanDir( QHash<ulong64, QPair<int, QString> >& hashes, const QString& path )
{
//    qDebug() << "Scanning dir:" << path;

    QDir dir( path );
    QFileInfoList list = dir.entryInfoList();
    for ( int i = 0; i < list.size(); ++i )
    {
        QFileInfo fileInfo = list.at( i );
        if ( fileInfo.isSymLink() )
            continue;
        if ( fileInfo.fileName().startsWith( "." ) )
            continue;

        if ( fileInfo.isDir() )
        {
            // scan recursively
            scanDir( hashes, fileInfo.absolutePath() + "/" + fileInfo.fileName() );
            continue;
        }

        if ( !fileInfo.fileName().endsWith(".wmv") && !fileInfo.fileName().endsWith(".avi") &&
             !fileInfo.fileName().endsWith(".mp4") && !fileInfo.fileName().endsWith(".mkv") &&
             !fileInfo.fileName().endsWith(".flv") && !fileInfo.fileName().endsWith(".mpg") &&
             !fileInfo.fileName().endsWith(".m4v") && !fileInfo.fileName().endsWith(".mov") &&
             !fileInfo.fileName().endsWith(".divx") && !fileInfo.fileName().endsWith(".mpeg") )
        {
            // only index videos
            continue;
        }

        std::cout << "Indexing \"" << qPrintable( fileInfo.absoluteFilePath() ) << "\" - size: " << fileInfo.size() << std::endl;

        // create snapshots
        const QString tmpPath = QDir::tempPath() + "/" + TMPNAME;
        createSnaps( fileInfo.absoluteFilePath(), tmpPath );
        // analyze and hash snapshots
        QHash<ulong64, int> hash = hashSnaps( tmpPath );

        QPair<int, QString> pair;       // snapshot #, filename
        QHash<QString, int> matches;    // filename, matches

        // go through all extracted snapshots and find dupes
        for ( int j = 0; j < hash.keys().count(); j++ )
        {
            ulong64 key = hash.keys().at( j );  // hash
            int value = hash.values().at( j );  // snapshot #

            {
                QList<QPair<int, QString> > res;    // snapshot #, filename

                // find closest snapshots by hamming distance
                res = closestHashes( hashes, key );
                for ( int x = 0; x < res.count(); x++ )
                {
                    pair = res.at( x );
                    if ( pair.second == fileInfo.absoluteFilePath() )
                    {
                        // ignore matches to self
                        continue;
                    }

                    // add/increment match count
                    if ( !matches.contains( pair.second ) )
                        matches[pair.second] = 1;
                    else
                        matches[pair.second] = matches[pair.second] + 1;
                }
            }

            // store hashes for future comparisons
            pair.first = value;
            pair.second = fileInfo.absoluteFilePath();
            hashes.insertMulti( key, pair );
        }

        for ( int y = 0; y < matches.keys().count(); y++ )
        {
            // threshold of matched snapshots to consider duped
            if ( matches.values().at( y ) >= THRESHOLD )
            {
                std::cout << "   --> Dupe of \"" << qPrintable( matches.keys().at( y ) ) << "\" - size: " << QFileInfo( matches.keys().at( y ) ).size()
                          << " (scores " << qMin( KEYFRAMES, matches.values().at( y ) ) << " out of " << KEYFRAMES << ")" << std::endl;
            }
        }
    }
}

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

    if ( app.arguments().count() < 2 )
    {
        std::cout << "Usage: xray /some/dir/full/of/videos" << std::endl;
        std::cout << "xray indexes video files by their perceptual hash and finds duplicates." << std::endl
                  << "This means files are not compared byte for byte, but by their visual content." << std::endl
                  << "It will/should find dupes of videos, even when they are encoded in different formats and resolutions." << std::endl;
        return 1;
    }

    QHash<ulong64, QPair<int, QString> > hashes;    // perceptual hash, pair<snapshot #, filename>

    QDir::temp().mkdir( TMPNAME );
    scanDir( hashes, app.arguments().at( 1 ) );
    QDir::temp().rmdir( TMPNAME );

    return 0;
}
<commit_msg>* Use unique temporary processing dir per process.<commit_after>#include <QtCore>
#include <iostream>

#include <pHash.h>

static QString TMPPATH;       // name of temporary dir (usually below /tmp)
static const int THRESHOLD = 4;     // find at least x dupe snapshots to consider video duped
static const int KEYFRAMES = 10;    // how many snapshots (keyframes) to compare

// create snapshots from video file
void
createSnaps( const QString& file, const QString& tmpPath )
{
    QStringList args;
    args << "-sstep" << "10"                            // only output keyframes in 10 second increments
         << "-nosound" << "-vo" << "jpeg"               // output as jpegs
         << "-ss" << "00:00:45"                         // start 45 seconds into the video
         << "-frames" << QString::number( KEYFRAMES )   // output x frames total
         << file;

    QProcess p;
    p.setWorkingDirectory( tmpPath );
    p.start( "mplayer", args );
    p.waitForFinished( 60000 );     // wait one minute at most
}

// create perceptual hash for snapshots
QHash<ulong64, int>
hashSnaps( const QString& path )
{
    QHash<ulong64, int> hashes;

    QDir dir( path );
    QFileInfoList list = dir.entryInfoList();
    for ( int i = 0; i < list.size(); ++i )
    {
        QFileInfo fileInfo = list.at( i );
        if ( !fileInfo.fileName().endsWith( ".jpg" ) )
            continue;

        ulong64 hash;
        int err = ph_dct_imagehash( fileInfo.absoluteFilePath().toLocal8Bit(), hash );
        if ( err )
            continue;

        hashes.insertMulti( hash, i );

        // delete snapshot
        QFile::remove( fileInfo.absoluteFilePath() );
    }

    return hashes;
}

// finds similar hashes by hamming distance
QList <QPair <int, QString> >
closestHashes( QHash<ulong64, QPair<int, QString> >& hashes, const ulong64& searchKey )
{
    QList <QPair <int, QString> > res;

    for ( int i = 0; i < hashes.keys().count(); i++ )
    {
        ulong64 key = hashes.keys().at( i );
        if ( ph_hamming_distance( searchKey, key ) < 4 )
        {
            QPair<int, QString> pair = hashes.values().at( i );
            res << pair;
        }
    }

    return res;
}

void
scanDir( QHash<ulong64, QPair<int, QString> >& hashes, const QString& path )
{
//    qDebug() << "Scanning dir:" << path;

    QDir dir( path );
    QFileInfoList list = dir.entryInfoList();
    for ( int i = 0; i < list.size(); ++i )
    {
        QFileInfo fileInfo = list.at( i );
        if ( fileInfo.isSymLink() )
            continue;
        if ( fileInfo.fileName().startsWith( "." ) )
            continue;

        if ( fileInfo.isDir() )
        {
            // scan recursively
            scanDir( hashes, fileInfo.absolutePath() + "/" + fileInfo.fileName() );
            continue;
        }

        if ( !fileInfo.fileName().endsWith(".wmv") && !fileInfo.fileName().endsWith(".avi") &&
             !fileInfo.fileName().endsWith(".mp4") && !fileInfo.fileName().endsWith(".mkv") &&
             !fileInfo.fileName().endsWith(".flv") && !fileInfo.fileName().endsWith(".mpg") &&
             !fileInfo.fileName().endsWith(".m4v") && !fileInfo.fileName().endsWith(".mov") &&
             !fileInfo.fileName().endsWith(".divx") && !fileInfo.fileName().endsWith(".mpeg") )
        {
            // only index videos
            continue;
        }

        std::cout << "Indexing \"" << qPrintable( fileInfo.absoluteFilePath() ) << "\" - size: " << fileInfo.size() << std::endl;

        // create snapshots
        createSnaps( fileInfo.absoluteFilePath(), TMPPATH );
        // analyze and hash snapshots
        QHash<ulong64, int> hash = hashSnaps( TMPPATH );

        QPair<int, QString> pair;       // snapshot #, filename
        QHash<QString, int> matches;    // filename, matches

        // go through all extracted snapshots and find dupes
        for ( int j = 0; j < hash.keys().count(); j++ )
        {
            ulong64 key = hash.keys().at( j );  // hash
            int value = hash.values().at( j );  // snapshot #

            {
                QList<QPair<int, QString> > res;    // snapshot #, filename

                // find closest snapshots by hamming distance
                res = closestHashes( hashes, key );
                for ( int x = 0; x < res.count(); x++ )
                {
                    pair = res.at( x );
                    if ( pair.second == fileInfo.absoluteFilePath() )
                    {
                        // ignore matches to self
                        continue;
                    }

                    // add/increment match count
                    if ( !matches.contains( pair.second ) )
                        matches[pair.second] = 1;
                    else
                        matches[pair.second] = matches[pair.second] + 1;
                }
            }

            // store hashes for future comparisons
            pair.first = value;
            pair.second = fileInfo.absoluteFilePath();
            hashes.insertMulti( key, pair );
        }

        for ( int y = 0; y < matches.keys().count(); y++ )
        {
            // threshold of matched snapshots to consider duped
            if ( matches.values().at( y ) >= THRESHOLD )
            {
                std::cout << "   --> Dupe of \"" << qPrintable( matches.keys().at( y ) ) << "\" - size: " << QFileInfo( matches.keys().at( y ) ).size()
                          << " (scores " << qMin( KEYFRAMES, matches.values().at( y ) ) << " out of " << KEYFRAMES << ")" << std::endl;
            }
        }
    }
}

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

    if ( app.arguments().count() < 2 )
    {
        std::cout << "Usage: xray /some/dir/full/of/videos" << std::endl;
        std::cout << "xray indexes video files by their perceptual hash and finds duplicates." << std::endl
                  << "This means files are not compared byte for byte, but by their visual content." << std::endl
                  << "It will/should find dupes of videos, even when they are encoded in different formats and resolutions." << std::endl;
        return 1;
    }

    QHash<ulong64, QPair<int, QString> > hashes;    // perceptual hash, pair<snapshot #, filename>

    QTemporaryDir tmpDir;
    TMPPATH = tmpDir.path();
    scanDir( hashes, app.arguments().at( 1 ) );

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <math.h>
#include <stdlib.h>
#include <array>

#include <SFML/Graphics.hpp>

#include "vector2.h"
#include "triangle.h"
#include "delaunay.h"

float RandomFloat(float a, float b) {
    const float random = ((float) rand()) / (float) RAND_MAX;
    const float diff = b - a;
    const float r = random * diff;
    return a + r;
}

int main(int argc, char * argv[])
{
	int numberPoints = 40;
	if (argc==1)
	{
		numberPoints = (int) roundf(RandomFloat(4, numberPoints));
	}
	else if (argc>1)
	{
		numberPoints = atoi(argv[1]);
	}
	srand (time(NULL));

	std::cout << "Generating " << numberPoints << " random points" << std::endl;

	std::vector<Vector2<float> > points;
	for(int i = 0; i < numberPoints; ++i) {
		points.push_back(Vector2<float>(RandomFloat(0, 800), RandomFloat(0, 600)));
	}

	Delaunay<float> triangulation;
	const std::vector<Triangle<float> > triangles = triangulation.triangulate(points);
	std::cout << triangles.size() << " triangles generated\n";
	const std::vector<Edge<float> > edges = triangulation.getEdges();

	std::cout << " ========= ";

	std::cout << "\nPoints : " << points.size() << std::endl;
	for(const auto &p : points)
		std::cout << p << std::endl;

	std::cout << "\nTriangles : " << triangles.size() << std::endl;
	for(const auto &t : triangles)
		std::cout << t << std::endl;

	std::cout << "\nEdges : " << edges.size() << std::endl;
	for(const auto &e : edges)
		std::cout << e << std::endl;

	// SFML window
	sf::RenderWindow window(sf::VideoMode(800, 600), "Delaunay triangulation");

	// Transform each points of each vector as a rectangle
	std::vector<sf::RectangleShape*> squares;

	for(const auto p : points) {
		sf::RectangleShape *c1 = new sf::RectangleShape(sf::Vector2f(4, 4));
		c1->setPosition(p.x, p.y);
		squares.push_back(c1);
	}

	// Make the lines
	std::vector<std::array<sf::Vertex, 2> > lines;
	for(const auto &e : edges) {
		lines.push_back({{
			sf::Vertex(sf::Vector2f(e.p1.x + 2, e.p1.y + 2)),
			sf::Vertex(sf::Vector2f(e.p2.x + 2, e.p2.y + 2))
		}});
	}

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
		}

		window.clear();

		// Draw the squares
		for(auto s = begin(squares); s != end(squares); s++) {
			window.draw(**s);
		}

		// Draw the lines
		for(auto l = begin(lines); l != end(lines); l++) {
			window.draw((*l).data(), 2, sf::Lines);
		}

		window.display();
	}

	return 0;
}
<commit_msg>Use const auto for loops<commit_after>#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <math.h>
#include <stdlib.h>
#include <array>

#include <SFML/Graphics.hpp>

#include "vector2.h"
#include "triangle.h"
#include "delaunay.h"

float RandomFloat(float a, float b) {
    const float random = ((float) rand()) / (float) RAND_MAX;
    const float diff = b - a;
    const float r = random * diff;
    return a + r;
}

int main(int argc, char * argv[])
{
	int numberPoints = 40;
	if (argc==1)
	{
		numberPoints = (int) roundf(RandomFloat(4, numberPoints));
	}
	else if (argc>1)
	{
		numberPoints = atoi(argv[1]);
	}
	srand (time(NULL));

	std::cout << "Generating " << numberPoints << " random points" << std::endl;

	std::vector<Vector2<float> > points;
	for(int i = 0; i < numberPoints; ++i) {
		points.push_back(Vector2<float>(RandomFloat(0, 800), RandomFloat(0, 600)));
	}

	Delaunay<float> triangulation;
	const std::vector<Triangle<float> > triangles = triangulation.triangulate(points);
	std::cout << triangles.size() << " triangles generated\n";
	const std::vector<Edge<float> > edges = triangulation.getEdges();

	std::cout << " ========= ";

	std::cout << "\nPoints : " << points.size() << std::endl;
	for(const auto &p : points)
		std::cout << p << std::endl;

	std::cout << "\nTriangles : " << triangles.size() << std::endl;
	for(const auto &t : triangles)
		std::cout << t << std::endl;

	std::cout << "\nEdges : " << edges.size() << std::endl;
	for(const auto &e : edges)
		std::cout << e << std::endl;

	// SFML window
	sf::RenderWindow window(sf::VideoMode(800, 600), "Delaunay triangulation");

	// Transform each points of each vector as a rectangle
	std::vector<sf::RectangleShape*> squares;

	for(const auto p : points) {
		sf::RectangleShape *c1 = new sf::RectangleShape(sf::Vector2f(4, 4));
		c1->setPosition(p.x, p.y);
		squares.push_back(c1);
	}

	// Make the lines
	std::vector<std::array<sf::Vertex, 2> > lines;
	for(const auto &e : edges) {
		lines.push_back({{
			sf::Vertex(sf::Vector2f(e.p1.x + 2, e.p1.y + 2)),
			sf::Vertex(sf::Vector2f(e.p2.x + 2, e.p2.y + 2))
		}});
	}

	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();
		}

		window.clear();

		// Draw the squares
		for(const auto &s : squares) {
			window.draw(*s);
		}

		// Draw the lines
		for(const auto &l : lines) {
			window.draw(l.data(), 2, sf::Lines);
		}

		window.display();
	}

	return 0;
}
<|endoftext|>


<commit_before>45226107-2748-11e6-9c37-e0f84713e7b8<commit_msg>This'll fix that<commit_after>452d35c5-2748-11e6-900d-e0f84713e7b8<|endoftext|>


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

Wababa: Simple Question Game

************/

#include <iostream>

int main () {

    // Wababa Welcome.
    std::cout << "Wababa!\n"

    // Returns 0
    return 0;
}
<commit_msg>Created Working Game with hard-coded variables.<commit_after>/*********************************
**********************************
**                              **
** Wababa: Simple Question Game **
**                              **
**********************************
*********************************/

// Preprocessor Commands
#include <iostream>
#include <string>
//Global Scope Namespace
using namespace std;

// Wababa Answer Variables
int a = 5;
int apples;
string b = "woof";
string c = "sally";
string bark;
string dollname;

void answerA (int answer, int thevar) {

if ( answer == thevar )
    cout << "Yes!\n";
else
    cout << "Wrong!\n";
}

void answerQ (string answer, string thevar) {

if ( answer == thevar )
    cout << "Yes!\n";
else
    cout << "Wrong!\n";
}

int main () {

    // Wababa Welcome.
    string wababa;
    wababa = "Wababa!\n\n";
    cout << wababa;

    // Question #1
    cout << "How many red items are there: ";
    cin >> apples;
    answerA(apples, a);

    // Question #2
    cout << "What did the dog say: ";
    cin >> bark;
    answerQ(bark,b);

    // Question #3
    cout << "What's her name: ";
    cin >> dollname;
    answerQ(dollname,c);

    // Returns 0
    return 0;

}
<|endoftext|>


<commit_before>0d106e19-2748-11e6-8de6-e0f84713e7b8<commit_msg>I'm done<commit_after>0d1cbe70-2748-11e6-96ab-e0f84713e7b8<|endoftext|>


<commit_before>16c91b30-2748-11e6-84e2-e0f84713e7b8<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>16d2a0a6-2748-11e6-8ed9-e0f84713e7b8<|endoftext|>


<commit_before>c60d70a3-ad58-11e7-96aa-ac87a332f658<commit_msg>Nope, didn't work, now it does<commit_after>c67350cc-ad58-11e7-9bba-ac87a332f658<|endoftext|>


<commit_before>/*
 * =====================================================================================
 *
 *       Filename:  main.cpp
 *
 *    Description:  gaussian random number generator
 *
 *        Version:  1.0
 *        Created:  11/28/2015 12:18:30 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Gabe Jespersen (), gzackwebs@tfwno.gf
 *
 * =====================================================================================
 */

#include <vector>
#include <iostream>
#include <cstdlib>
#include <cstring>

#include "parse.h"

using namespace std;

int main(int argc, char** argv)
{
    vector<int> parsed = parse(argc, argv);
    for(int i = 0; i < parsed.size(); i++)
    {
        cout << parsed.at(i) << endl;
    }
    return 0;
}
<commit_msg>I don't even know<commit_after>/*
 * =====================================================================================
 *
 *       Filename:  main.cpp
 *
 *    Description:  gaussian random number generator
 *
 *        Version:  1.0
 *        Created:  11/28/2015 12:18:30 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Gabe Jespersen (), gzackwebs@tfwno.gf
 *
 * =====================================================================================
 */

#include <vector>
#include <iostream>
#include <cstdlib>
#include <cstring>

#include "parse.h"
#include "random.h"

using namespace std;

int main(int argc, char** argv)
{
    vector<int> parsed = parse(argc, argv);
    for(int i = 0; i < parsed.size(); i++)
    {
        cout << parsed.at(i) << endl;
    }
    return 0;
}
<|endoftext|>


<commit_before>4e929942-ad5a-11e7-9064-ac87a332f658<commit_msg>GOD DAMNED IT!<commit_after>4f15413d-ad5a-11e7-9abc-ac87a332f658<|endoftext|>


<commit_before>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
#include <defer.h>
#include <chrono>
#include "utils/utils.h"

static const GLfloat globVertexBufferData[] = {
  -1.0f, -1.0f,  0.0f,
   1.0f, -1.0f,  0.0f,
   0.0f,  1.0f,  0.0f,
};

void windowSizeCallback(GLFWwindow *, int width, int height) {
  glViewport(0, 0, width, height);
}

// TODO: box instead of triangle
// TODO: mouse, keyboard

int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }
  defer(std::cout << "Calling glfwTerminate()" << std::endl; glfwTerminate());

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

  GLFWwindow* window = glfwCreateWindow(300, 300, "Triangle", nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    return -1;
  }
  defer(std::cout << "Calling glfwDestroyWindow()" << std::endl; glfwDestroyWindow(window));

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    return -1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, windowSizeCallback);

  glfwShowWindow(window);

  glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER);
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  bool errorFlag = false;
  std::vector<GLuint> shaders;

  GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl;
    return -1;
  }

  shaders.push_back(vertexShaderId);

  GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl;
    return -1;
  }
  shaders.push_back(fragmentShaderId);

  GLuint programId = prepareProgram(shaders, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to prepare program" << std::endl;
    return -1;
  }
  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);

  GLuint vao;
  glGenVertexArrays(1, &vao);

  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO
  glBindVertexArray(0); // unbind VAO

  // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
  glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 1.0f, 100.0f);
  // Camera matrix
  glm::mat4 View       = glm::lookAt(
      //glm::vec3(4,3,3), // Camera is at (4,3,3), in World Space
      glm::vec3(0, 0, 5),
      glm::vec3(0, 0, 0), // and looks at the origin
      glm::vec3(0, 1, 0)  // Head is up (set to 0,-1,0 to look upside-down)
  );

  GLint matrixId = glGetUniformLocation(programId, "MVP");

  auto startTime = std::chrono::high_resolution_clock::now();
  while(glfwWindowShouldClose(window) == GL_FALSE) {
    auto currentTime = std::chrono::high_resolution_clock::now();
    auto duration = currentTime - startTime;
    long ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
    float rotationTimeMs = 3000.0f;
    float currentRotation = ms / rotationTimeMs;
    float angle = 360.0f*(currentRotation - (long)currentRotation);

    glm::mat4 Model      = glm::rotate(angle, 0.0f, 1.0f, 0.0f);
    glm::mat4 MVP        = Projection * View * Model; // Remember, matrix multiplication is the other way around
    glUniformMatrix4fv(matrixId, 1, GL_FALSE, &MVP[0][0]);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programId);

    glBindVertexArray(vao);
    glEnableVertexAttribArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableVertexAttribArray(0);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &vbo);
  glDeleteProgram(programId);

  return 0;
}
<commit_msg>glEnable(GL_CULL_FACE)<commit_after>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/transform.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
#include <defer.h>
#include <chrono>
#include "utils/utils.h"

static const GLfloat globVertexBufferData[] = {
  -1.0f, -1.0f,  0.0f,
   1.0f, -1.0f,  0.0f,
   0.0f,  1.0f,  0.0f,
};

void windowSizeCallback(GLFWwindow *, int width, int height) {
  glViewport(0, 0, width, height);
}

// TODO: box instead of triangle
// TODO: mouse, keyboard (camera.cpp / hpp ? )

int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }
  defer(std::cout << "Calling glfwTerminate()" << std::endl; glfwTerminate());

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

  GLFWwindow* window = glfwCreateWindow(300, 300, "Triangle", nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    return -1;
  }
  defer(std::cout << "Calling glfwDestroyWindow()" << std::endl; glfwDestroyWindow(window));

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    return -1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, windowSizeCallback);

  glfwShowWindow(window);

  glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER | GL_CULL_FACE); // TODO: describe GL_CULL_FACE!
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  bool errorFlag = false;
  std::vector<GLuint> shaders;

  GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl;
    return -1;
  }

  shaders.push_back(vertexShaderId);

  GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl;
    return -1;
  }
  shaders.push_back(fragmentShaderId);

  GLuint programId = prepareProgram(shaders, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to prepare program" << std::endl;
    return -1;
  }
  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);

  GLuint vao;
  glGenVertexArrays(1, &vao);

  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO
  glBindVertexArray(0); // unbind VAO

  // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
  glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 1.0f, 100.0f);
  // Camera matrix
  glm::mat4 View       = glm::lookAt(
      //glm::vec3(4,3,3), // Camera is at (4,3,3), in World Space
      glm::vec3(0, 0, 5),
      glm::vec3(0, 0, 0), // and looks at the origin
      glm::vec3(0, 1, 0)  // Head is up (set to 0,-1,0 to look upside-down)
  );

  GLint matrixId = glGetUniformLocation(programId, "MVP");

  auto startTime = std::chrono::high_resolution_clock::now();
  while(glfwWindowShouldClose(window) == GL_FALSE) {
    auto currentTime = std::chrono::high_resolution_clock::now();
    auto duration = currentTime - startTime;
    long ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
    float rotationTimeMs = 3000.0f;
    float currentRotation = ms / rotationTimeMs;
    float angle = 360.0f*(currentRotation - (long)currentRotation);

    glm::mat4 Model      = glm::rotate(angle, 0.0f, 1.0f, 0.0f);
    glm::mat4 MVP        = Projection * View * Model; // Remember, matrix multiplication is the other way around
    glUniformMatrix4fv(matrixId, 1, GL_FALSE, &MVP[0][0]);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programId);

    glBindVertexArray(vao);
    glEnableVertexAttribArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableVertexAttribArray(0);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &vbo);
  glDeleteProgram(programId);

  return 0;
}
<|endoftext|>


<commit_before>6f9e93c0-4b02-11e5-bd32-28cfe9171a43<commit_msg>roselyn broke it<commit_after>6fac8980-4b02-11e5-be15-28cfe9171a43<|endoftext|>


<commit_before>a65ce34c-4b02-11e5-8d0f-28cfe9171a43<commit_msg>We apologise for the previous fix. Those responsible have been sacked<commit_after>a66a68d4-4b02-11e5-afe6-28cfe9171a43<|endoftext|>


<commit_before>//
// Created by Mauro on 07/04/16.
//

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello world" << endl;

    cout << "Opencv upgrade added." << endl;
    return 0;
}<commit_msg>- Message<commit_after>//
// Created by Mauro on 07/04/16.
//

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello world" << endl;

    return 0;
}<|endoftext|>


<commit_before>#include <ctime>
#include <QDebug>
#include <QCoreApplication>
#include <QTime>

#include "shuf-t.h"
#include "utils.h"

QString source_filename;
QString destination_filename;
bool use_input_range;
uint input_range_min = 0;
uint input_range_max = 0;

inline bool getRangeArgument(QString s, uint& i1, uint& i2)
{
    QStringList sl = s.split('-', QString::SkipEmptyParts);
    bool ok = sl.count() == 2 && !sl[1].isEmpty();
    if(ok)
    {
        i1 = sl[0].toUInt(&ok);
        if(ok)
            i2 = sl[1].toUInt(&ok);
    }
    return ok;
}

uint processCommandLineArguments(QCommandLineParser& parser)
{
    //get shuffle parameters
    if(parser.isSet("b"))
        _param_buffer_size = parser.value("b").toFloat()*1024*1024;

    if(parser.isSet("q"))
        _param_verbose = !parser.value("q").toInt();

    if(parser.isSet("t"))
        _param_header  = parser.value("t").toUInt();

    if(parser.isSet("n"))
        _param_output_limit  = parser.value("n").toUInt();

    if (parser.isSet("l") && !getRangeArgument(parser.value("l"), _param_start_line, _param_end_line))
        {
        qCritical() << "lines argument is incorrect. Please use --help for format details.";
        return -1;
        }

    swapIfNeeded(_param_start_line, _param_end_line);

    if(parser.isSet("o"))
        destination_filename  = parser.value("o");

    if(parser.isSet("s"))
    {
        uint seed  = parser.value("s").toUInt();
        srand(seed);
    } else
        srand(time(NULL));

    use_input_range = false;

    if ( (use_input_range = parser.isSet("i")) && !getRangeArgument(parser.value("i"), input_range_min, input_range_max))
        {
            qCritical() << "--input_range argument is incorrect. Please use --help for format details.";
            return -1;
        }

    swapIfNeeded(input_range_min, input_range_max);

    QStringList pos_args = parser.positionalArguments();
    if (pos_args.count() > 0)
      source_filename = pos_args[0];

    if (use_input_range && !source_filename.isEmpty())
    {
        qWarning() << "WARNING: Both output file and -i parameter are specified. Output file is ignored.";
    }

return 0;

}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName("Shuf-t");
    QCoreApplication::setApplicationVersion("1.0");

    QCommandLineParser parser;
    initCommandOptionsParser(parser);
    parser.process(app);

    uint result = processCommandLineArguments(parser);
    if (result != 0)
        return result;

    if (!use_input_range && source_filename.isEmpty())
    {
        print("reading data from stdin...\n");
        source_filename = readStdinToTmpFile();
    }

    QTime performance_timer;
    performance_timer.start();

    QForkedTextStream in;

    print("searching line offsets:  ");
    if (use_input_range)
    {
        result = openInputRangeSource(in, input_range_min, input_range_max);
    } else {
        if( !source_filename.isEmpty() )
        result = openFileSource(in, source_filename);
    }

    print("offsets found: "+ QString::number(metadata.count())+'\n');
    printTime(performance_timer.elapsed());
    performance_timer.restart();

    QTextStream out;

    if (!destination_filename.isEmpty())
    {
        result = openFileDestination(out, destination_filename);
    } else {
        result = openStdOutDestination(out);
    }

    print("shuffling line offsets:  ");

    shuffleMetadata();

    printTime(performance_timer.elapsed());
    performance_timer.restart();

    print("writing lines to output: ");

    writeData(in, out);

    printTime(performance_timer.elapsed());

    closeFileDestination();

    if (use_input_range)
    {
        closeInputRangeSource();
    } else {
        closeFileSource();
    }

    return 0;
}
<commit_msg>rand seed output<commit_after>#include <ctime>
#include <QDebug>
#include <QCoreApplication>
#include <QTime>

#include "shuf-t.h"
#include "utils.h"

QString source_filename;
QString destination_filename;
bool use_input_range;
uint input_range_min = 0;
uint input_range_max = 0;

inline bool getRangeArgument(QString s, uint& i1, uint& i2)
{
    QStringList sl = s.split('-', QString::SkipEmptyParts);
    bool ok = sl.count() == 2 && !sl[1].isEmpty();
    if(ok)
    {
        i1 = sl[0].toUInt(&ok);
        if(ok)
            i2 = sl[1].toUInt(&ok);
    }
    return ok;
}

uint processCommandLineArguments(QCommandLineParser& parser)
{
    //get shuffle parameters
    if(parser.isSet("b"))
        _param_buffer_size = parser.value("b").toFloat()*1024*1024;

    if(parser.isSet("q"))
        _param_verbose = !parser.value("q").toInt();

    if(parser.isSet("t"))
        _param_header  = parser.value("t").toUInt();

    if(parser.isSet("n"))
        _param_output_limit  = parser.value("n").toUInt();

    if (parser.isSet("l") && !getRangeArgument(parser.value("l"), _param_start_line, _param_end_line))
        {
        qCritical() << "lines argument is incorrect. Please use --help for format details.";
        return -1;
        }

    swapIfNeeded(_param_start_line, _param_end_line);

    if(parser.isSet("o"))
        destination_filename  = parser.value("o");

    uint seed  = 0;
    if(parser.isSet("s"))
    {
        seed  = parser.value("s").toUInt();
    } else
        seed = time(NULL);

    srand(seed);
    print("random seed: ");
    print(QString::number(seed)+"\n");

    use_input_range = false;

    if ( (use_input_range = parser.isSet("i")) && !getRangeArgument(parser.value("i"), input_range_min, input_range_max))
        {
            qCritical() << "--input_range argument is incorrect. Please use --help for format details.";
            return -1;
        }

    swapIfNeeded(input_range_min, input_range_max);

    QStringList pos_args = parser.positionalArguments();
    if (pos_args.count() > 0)
      source_filename = pos_args[0];

    if (use_input_range && !source_filename.isEmpty())
    {
        qWarning() << "WARNING: Both output file and -i parameter are specified. Output file is ignored.";
    }

return 0;

}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName("Shuf-t");
    QCoreApplication::setApplicationVersion("1.0");

    QCommandLineParser parser;
    initCommandOptionsParser(parser);
    parser.process(app);

    uint result = processCommandLineArguments(parser);
    if (result != 0)
        return result;

    if (!use_input_range && source_filename.isEmpty())
    {
        print("reading data from stdin...\n");
        source_filename = readStdinToTmpFile();
    }

    QTime performance_timer;
    performance_timer.start();

    QForkedTextStream in;

    print("searching line offsets:  ");
    if (use_input_range)
    {
        result = openInputRangeSource(in, input_range_min, input_range_max);
    } else {
        if( !source_filename.isEmpty() )
        result = openFileSource(in, source_filename);
    }

    print("offsets found: "+ QString::number(metadata.count())+'\n');
    printTime(performance_timer.elapsed());
    performance_timer.restart();

    QTextStream out;

    if (!destination_filename.isEmpty())
    {
        result = openFileDestination(out, destination_filename);
    } else {
        result = openStdOutDestination(out);
    }

    print("shuffling line offsets:  ");

    shuffleMetadata();

    printTime(performance_timer.elapsed());
    performance_timer.restart();

    print("writing lines to output: ");

    writeData(in, out);

    printTime(performance_timer.elapsed());

    closeFileDestination();

    if (use_input_range)
    {
        closeInputRangeSource();
    } else {
        closeFileSource();
    }

    return 0;
}
<|endoftext|>


<commit_before>#include<stdio.h>
#include<stdlib.h>
#include"userinterview.h"

int main()
{
    printtile();
    return 0;
}
<commit_msg>test to change  main.cpp<commit_after>#include<stdio.h>
#include<stdlib.h>
#include"userinterview.h"

int main()
{
    printtile();
    printf("\n\ntest line\n");
    return 0;
}
<|endoftext|>


<commit_before>#include <sys/mman.h>
#include "asmtest.h"
#include "x86_64/Operand.h"
#include "x86_64/Assembler.h"
#include "x86_64/Codegen.h"
#include "ASTNode.h"
#include "CompiledCode.h"
#include "Linker.h"
#include "lib/IncrementalAlloc.h"
#include "Util.h"
#include <iostream>
using namespace std;

#include "lib/Runtime.h"
#include "lib/Object.h"

#define __ masm.

using namespace snow;
//using namespace snow::x86_64;

void test_codegen() {/*
	SymbolTable table;
	table["snow_create_object"] = (void*)snow::create_object;
	table["snow_send"] = (void*)snow::send;
	table["snow_call"] = (void*)snow::call;
	table["snow_destroy"] = (void*)snow::destroy;

	x86_64::Codegen masm;

	__ function_entry(3);
	auto l1 = Scope::Local(0, "hejsa");
	__ get_argument(0, l1);
	auto l2 = Scope::Local(1);
	__ get_argument(1, l2);

	__ set_argument(0, l1);
	__ set_argument(1, "+");
	__ set_argument(2, 1);
	__ set_argument(3, l2);
	auto retval = Scope::Local(2);
	__ call("snow_send", retval);

	__ set_argument(0, l1);
	__ call("snow_destroy");
	__ set_argument(0, l2);
	__ call("snow_destroy");

//	__ debug_break();
	__ set_return(retval);
	__ function_return();

	RefPtr<CompiledCode> code = __ compile();
	code->export_symbols(table);
	code->link(table);

	code->make_executable();

	print_mem(code->code(), &code->code()[code->size()]);
	printf("code is at 0x%llx\n", (uint64_t)code->code());

	VALUE(*entry)(VALUE a, VALUE b) = (VALUE(*)(VALUE, VALUE))code->code();
	printf("add: %lld\n", integer(entry(value(-67LL), value(-45LL))));*/
}

void test_ast() {
	using namespace snow::ast;

	SymbolTable table;
	table["muh"] = (void*)create_object;
	table["snow_init_stack_frame"] = (void*)snow::init_stack_frame;
	table["snow_destroy"] = (void*)snow::destroy;
	table["snow_eval_truth"] = (void*)snow::eval_truth;
	table["snow_call"] = (void*)snow::call;
	table["snow_call_method"] = (void*)snow::call_method;
	table["snow_send"] = (void*)snow::send;
	table["snow_value_to_string"] = (void*)snow::value_to_string;

	RefPtr<FunctionDefinition> scope = new FunctionDefinition;
	scope->arguments.push_back(new Identifier("c"));
	scope->add(new Assignment(new Identifier("a"), new Literal("123", Literal::INTEGER_TYPE)));
	scope->add(new Assignment(new Identifier("b"), new Literal("567", Literal::INTEGER_TYPE)));
	scope->add(new Assignment(
			new Identifier("c"),
			new MethodCall(
				new Call(new Identifier("a")),
				new Identifier("+"),
				new Sequence(new Identifier("b"))
			)
		)
	);
	scope->add(new Identifier("c"));

	RefPtr<Codegen> codegen = Codegen::create(*scope);
	RefPtr<CompiledCode> cc = codegen->compile();

	cc->export_symbols(table);
	cc->link(table);
	cc->make_executable();

	VALUE global_scope = create_object();

	printf("code is at: 0x%llx\n", (uint64_t)cc->code());
	VALUE ret = cc->function()(global_scope, 5, (VALUE[]){value(5LL), value(5LL),value(5LL), value(5LL), value(5LL)});
	printf("returned: %s\n", value_to_string(ret));
}

void test_sib() {
	using namespace snow::x86_64;
	x86_64::Assembler masm;

	__ enter(32);
	__ mov(3LL, rax);
	__ mov(SIB(rdi, rax, SIB::SCALE_8), rbx);
	__ mov(rbx, rax);
	__ debug_break();
	__ leave();
	__ ret();

	RefPtr<CompiledCode> cc = masm.compile();
	cc->make_executable();

	int64_t* array = new int64_t[10];
	for (int i = 0; i < 10; ++i) {
		array[i] = 123 + i;
	}

	debug("array is at 0x%llx", array);
	debug("code is at 0x%llx", cc->function());
	int64_t ret = (int64_t)cc->function()(array, 0, NULL);

	delete[] array;

	debug("returned: %lld", ret);
}

int main (int argc, char const *argv[])
{
	test_ast();
	//test_sib();
	TempAllocator<ast::Node>::flush();
	return 0;
}
<commit_msg>test driver: removed unnecessary debug stuff from symbol table<commit_after>#include <sys/mman.h>
#include "asmtest.h"
#include "x86_64/Operand.h"
#include "x86_64/Assembler.h"
#include "x86_64/Codegen.h"
#include "ASTNode.h"
#include "CompiledCode.h"
#include "Linker.h"
#include "lib/IncrementalAlloc.h"
#include "Util.h"
#include <iostream>
using namespace std;

#include "lib/Runtime.h"
#include "lib/Object.h"

#define __ masm.

using namespace snow;
//using namespace snow::x86_64;

void test_codegen() {/*
	SymbolTable table;
	table["snow_create_object"] = (void*)snow::create_object;
	table["snow_send"] = (void*)snow::send;
	table["snow_call"] = (void*)snow::call;
	table["snow_destroy"] = (void*)snow::destroy;

	x86_64::Codegen masm;

	__ function_entry(3);
	auto l1 = Scope::Local(0, "hejsa");
	__ get_argument(0, l1);
	auto l2 = Scope::Local(1);
	__ get_argument(1, l2);

	__ set_argument(0, l1);
	__ set_argument(1, "+");
	__ set_argument(2, 1);
	__ set_argument(3, l2);
	auto retval = Scope::Local(2);
	__ call("snow_send", retval);

	__ set_argument(0, l1);
	__ call("snow_destroy");
	__ set_argument(0, l2);
	__ call("snow_destroy");

//	__ debug_break();
	__ set_return(retval);
	__ function_return();

	RefPtr<CompiledCode> code = __ compile();
	code->export_symbols(table);
	code->link(table);

	code->make_executable();

	print_mem(code->code(), &code->code()[code->size()]);
	printf("code is at 0x%llx\n", (uint64_t)code->code());

	VALUE(*entry)(VALUE a, VALUE b) = (VALUE(*)(VALUE, VALUE))code->code();
	printf("add: %lld\n", integer(entry(value(-67LL), value(-45LL))));*/
}

void test_ast() {
	using namespace snow::ast;

	SymbolTable table;
	table["snow_init_stack_frame"] = (void*)snow::init_stack_frame;
	table["snow_destroy"] = (void*)snow::destroy;
	table["snow_eval_truth"] = (void*)snow::eval_truth;
	table["snow_call"] = (void*)snow::call;
	table["snow_call_method"] = (void*)snow::call_method;
	table["snow_send"] = (void*)snow::send;

	RefPtr<FunctionDefinition> scope = new FunctionDefinition;
	scope->arguments.push_back(new Identifier("c"));
	scope->add(new Assignment(new Identifier("a"), new Literal("123", Literal::INTEGER_TYPE)));
	scope->add(new Assignment(new Identifier("b"), new Literal("567", Literal::INTEGER_TYPE)));
	scope->add(new Assignment(
			new Identifier("c"),
			new MethodCall(
				new Call(new Identifier("a")),
				new Identifier("+"),
				new Sequence(new Identifier("b"))
			)
		)
	);
	scope->add(new Identifier("c"));

	RefPtr<Codegen> codegen = Codegen::create(*scope);
	RefPtr<CompiledCode> cc = codegen->compile();

	cc->export_symbols(table);
	cc->link(table);
	cc->make_executable();

	VALUE global_scope = create_object();

	printf("code is at: 0x%llx\n", (uint64_t)cc->code());
	VALUE ret = cc->function()(global_scope, 5, (VALUE[]){value(5LL), value(5LL),value(5LL), value(5LL), value(5LL)});
	printf("returned: %s\n", value_to_string(ret));
}

void test_sib() {
	using namespace snow::x86_64;
	x86_64::Assembler masm;

	__ enter(32);
	__ mov(3LL, rax);
	__ mov(SIB(rdi, rax, SIB::SCALE_8), rbx);
	__ mov(rbx, rax);
	__ debug_break();
	__ leave();
	__ ret();

	RefPtr<CompiledCode> cc = masm.compile();
	cc->make_executable();

	int64_t* array = new int64_t[10];
	for (int i = 0; i < 10; ++i) {
		array[i] = 123 + i;
	}

	debug("array is at 0x%llx", array);
	debug("code is at 0x%llx", cc->function());
	int64_t ret = (int64_t)cc->function()(array, 0, NULL);

	delete[] array;

	debug("returned: %lld", ret);
}

int main (int argc, char const *argv[])
{
	test_ast();
	//test_sib();
	TempAllocator<ast::Node>::flush();
	return 0;
}
<|endoftext|>


<commit_before>1cf609f5-ad58-11e7-b8ba-ac87a332f658<commit_msg>GOD DAMNED IT!<commit_after>1d50f530-ad58-11e7-860d-ac87a332f658<|endoftext|>


<commit_before>a9513a68-2747-11e6-8174-e0f84713e7b8<commit_msg>I am finally done<commit_after>a96658bd-2747-11e6-b5fd-e0f84713e7b8<|endoftext|>