Пример #1
0
//! Verify a range of flash against buffer
//!
void verifyRange(FlashData_t *flashData) {
   FlashController *controller   = flashData->controller;
   uint32_t        address       = flashData->address;
   const uint32_t *data          = flashData->data;
   uint32_t        numLongwords  = flashData->size/4;
   
   if ((flashData->flags&DO_VERIFY_RANGE) == 0) {
      return;
   }
   if ((address & 0x03) != 0) {
      setErrorCode(FLASH_ERR_ILLEGAL_PARAMS);
   }
//   // Initialise CRC
//   CRC_CTRL  = CRC_CTRL_TCRC;
//   CRC_GPOLY = 0x13451234;
//   CRC_CTRL  = CRC_CTRL_TCRC|CRC_CTRL_WAS;
//   CRC_CRC   = 0xFFFFFFFF;
//   CRC_CTRL  = CRC_CTRL_TCRC;
   
   // Verify words
   while (numLongwords-- > 0) {
      int rc;
      controller->fccob0_3 = (F_PGMCHK << 24) | address;
      controller->fccob4_7 = (F_USER_MARGIN<<24) | 0;
      controller->fccob8_B = *data;
//      CRC_CRC       = *data;
      rc = executeCommand(controller);
      if (rc != FLASH_ERR_OK) {
         if (rc == FLASH_ERR_PROG_MGSTAT0) {
            rc = FLASH_ERR_VERIFY_FAILED;
         }
         setErrorCode(rc);         
      }
      address += 4;
      data++;
   }
//   flashCommandTable->crc   = CRC_CRC;
   flashData->flags &= ~DO_VERIFY_RANGE;
}
Пример #2
0
unsigned int CameraVC0706::readFrame(unsigned char *buf,
        unsigned int frameOffset, unsigned int bufferOffset,
        unsigned int len) {
    unsigned int bytesRead = 0;
    unsigned char args[] = { 0x00, 0x0a, 0x00, 0x00,
            (unsigned char) ((frameOffset >> 8) & 0xff),
            (unsigned char) (frameOffset & 0xff), 0x00, 0x00,
            (unsigned char) ((len >> 8) & 0xff), (unsigned char) (len
                    & 0xff), (VC0760_CAMERA_DELAY >> 8) & 0xff,
            VC0760_CAMERA_DELAY & 0xff };

    if (!executeCommand(READ_FBUF, args, sizeof(args), 5)) {
        return 0;
    }
    while (bytesRead < len) {
        delay(10);
        bytesRead += read(&buf[bufferOffset + bytesRead],
                len - bytesRead);
    }
    readResponse(5);
    return bytesRead;
}
Пример #3
0
void prompt(){

  //declare variables.
	int retValue,i, result;
	char *command, *input, *arg;
	PCB * thisPCB;
  MainShell->isRunning = 1; // set isRunning to true.
  MainShell->prompt = ":>";	
  
 
	write("WELCOME to MPX \n");
    write("Type HELP for a command list\n\n");
	while(MainShell->isRunning){ //loop while MainShell is running.

		write(MainShell->prompt); //prompt user for input.
		
		
		input = trim(read(100)); //read input and trim it.

		command = strtok(input, " ,-|");//grab command from input.

    result = executeCommand(EXEC, command); //execute command.

    if(strcmpi(command, "exit") == 0){
	write("Exiting..\n");
	MainShell->isRunning = 0; //catch exit command.
	cleanR2();
	
		dispatcher();
	}
    if(result == 0 && strlen(input) != 0) write("Command not found!\n"); //command not valid
	
	
	sys_free_mem(input);
	
	sys_req(IDLE, NO_DEV, NULL, 0);
	}

}
Пример #4
0
int main(int argc, char *argv[])
{
    char answ[MAX_ANSW_SIZE];
    char character[MAX_ANSW_SIZE];
    character[0] = '0';
    printWelcome();
    seedDb(50);

    while(tolower(character[0]) != 'x')
    {
        listOptions();

        ask_question(answ, "Command me, master:", "Invalid input master, try again:", CHARACTER);
        strcpy(character, answ);

        if(!executeCommand(character))
        {
            printf("Invalid input, try again\n");
        }
    }
    return 0;
}
Пример #5
0
void historyReplay(icmProcessorP processor, const char *arg1)
{
    FILE *fp;
    char *filename = arg1 ? arg1 : "debugger.his";
    
    fp= fopen(filename, "rb");
    if(fp) {        
        char *tmp, buffer[1024];
        
        while( fgets(buffer, 1024-1, fp)) {
            buffer[1024-1] = '\0';
            
            
            tmp = trimString(buffer);
            if(!tmp) continue; /* empty string */
            
            if(executeCommand(processor, tmp))
                break;
        }
        fclose(fp);    
    } else fprintf(stderr, "ERROR: unable to open history file '%s' for reading!\n", filename);
}    
	void * runServiceShellThread(void * arg){
		RuntimeErrorValidator * validator ;
		ClientConnection * conn = (ClientConnection*)arg;
		char * cmd = NULL;

		MpsRequest * request = NULL;

		do{
			validator = buildErrorSuccessValidator();
			request = receiveMpsRequest(conn->clientSocket , validator);
			cmd = request->operationName;

			if( !isCommandQuit(cmd))
				executeCommand(conn->clientSocket , request);

		}while(!isCommandQuit(cmd));

		close(conn->clientSocket);
		free(conn);

		return EXIT_SUCCESS;
	}
Пример #7
0
void loop() {
  if (lastbytein != 0xFF && dataIO == DOUT) {
    counter = 0;
    noInterrupts();
    Serial.println(lastbytein, HEX);
    delay(1);
    switch(messageStep) { // Starts at -1
      case S_INIT:
      case S_COMMAND_ECHO:
        send(lastbytein);
        if (messageStep == S_COMMAND_ECHO) {
          executeCommand(lastbytein);
        }
        messageStep++;
        break;
      case S_RESP_LEN:
        send(messageToSend[0]);
        messageIndex = 1;
        messageStep++;
        break;
      case S_BYTE_SEND:
        if (lastbyteout != ~lastbytein) {
          resetMessage();
          break;
        }
        send(messageToSend[messageIndex]);
        if (messageIndex == messageToSend[0]) { // Checks if at last bite, and resets
          resetMessage();
          messageStep = S_COMMAND_ECHO;
          break;
        }
        messageIndex++;
        messageStep++;
        break;
    }
    interrupts();
  }
}
Пример #8
0
static asynStatus readUInt32(void* ppvt,asynUser* pasynUser,epicsUInt32* value,epicsUInt32 mask)
{
    asynStatus sts;
    Port* pport = (Port*)ppvt;
    Inst* pinst = (Inst*)pasynUser->drvUser;

    asynPrint(pasynUser,ASYN_TRACE_FLOW,"drvLove::readUInt32\n");

    if( pinst->pcmd->read )
        sprintf(pport->outMsg,"%s",pinst->pcmd->read);
    else
    {
        epicsSnprintf(pasynUser->errorMessage,pasynUser->errorMessageSize,"%s error %s",pport->name,pport->pasynUser->errorMessage);
        return( asynError );
    }

    lockPort(pport,pasynUser);
    sts = executeCommand(pport,pasynUser);
    unlockPort(pport,pasynUser);

    if( ISNOTOK(sts) )
    {
        epicsSnprintf(pasynUser->errorMessage,pasynUser->errorMessageSize,"%s error %s",pport->name,pport->pasynUser->errorMessage);
        return( sts );
    }

    sts = pinst->read(pinst,(epicsInt32*)value);
    if( ISNOTOK(sts) )
    {
        epicsSnprintf(pasynUser->errorMessage,pasynUser->errorMessageSize,"%s error %s",pport->name,pport->pasynUser->errorMessage);
        return( sts );
    }

    if( ISOK(sts) )
        asynPrint(pasynUser,ASYN_TRACEIO_FILTER,"drvLove::readUInt32 readback from %s is 0x%X,mask=0x%X\n",pport->name,*value,mask);

    return( asynSuccess );
}
//    Public methods:
void NAO:: startInteraction()
{
    std::string command;
    // 1. Localize speaker;

//    std::vector<float> position =
//    head->getSpeech().localizeSoundSource();
    // move head to the position;

    // 2. Receive commands;

    //turn back the head;
    // 3. Perform the job.
    while (1)
    {
        command = receiveCommands();
        if (! command.compare("stop")) break;
        else
        {
            executeCommand(command);
        }
    }
}
Пример #10
0
/**
 * @brief connect all buttons of the ui
 * @return
 *      void
 */
void DLDConfigureOB::connectSignals ()
{
	// connect menu actions
	connect(mainWindow.actionQuit,		SIGNAL(triggered ()), this, SLOT(close ()));
	connect(mainWindow.actionRefresh,	SIGNAL(triggered ()), this, SLOT(refreshDevices ()));
	connect(mainWindow.actionPreferences,	SIGNAL(triggered ()), this, SLOT(showPreferences ()));
	connect(mainWindow.actionOpenBeaconConfiguratorHelp, SIGNAL(triggered ()), this, SLOT(showHelp()));
	connect(mainWindow.actionAboutQt,	SIGNAL(triggered ()), qApp, SLOT(aboutQt ()));
	connect(mainWindow.actionAboutOpenBeacon,SIGNAL(triggered ()), this, SLOT(aboutOpenBeacon ()));

	// connect main Window buttons with methods
	connect(mainWindow.selectFileButton,	SIGNAL(clicked ()), this, SLOT(selectFlashImage ()));
	connect(mainWindow.flashButton,		SIGNAL(clicked ()), this, SLOT(flashDevice ()));
	connect(mainWindow.refreshButton,	SIGNAL(clicked ()), this, SLOT(refreshDevices ()));
	connect(mainWindow.executeButton,	SIGNAL(clicked ()), this, SLOT(executeCommand ()));
	connect(mainWindow.clearButton,		SIGNAL(clicked ()), this, SLOT(clearConsole ()));

	// connect box signals
	connect(mainWindow.commandCombo,	SIGNAL(highlighted (int)), this, SLOT(commandHighlighted (int)));
	connect(mainWindow.commandCombo,	SIGNAL(currentIndexChanged (int)), this, SLOT(updateCommandBoxStatusTip (int)));
	connect(mainWindow.deviceCombo,		SIGNAL(currentIndexChanged (int)), this, SLOT(updateGroupBoxVisibility (int)));
	connect(mainWindow.deviceCombo,		SIGNAL(activated (int)), this, SLOT(openNewDevice (int)));

	// connect device
	connect(device,				SIGNAL(newData (QString)), this, SLOT(receivedNewData (QString)));
	connect(device,				SIGNAL(writeFailed ()), this, SLOT(writeFailed ()));

	// connect internal signals
	connect(this,		SIGNAL(deviceSelected (bool, bool)),	this, SLOT(endisableGroupBox (bool, bool)));
	connect(this,		SIGNAL(commandListChanged ()),		this, SLOT(refillCommandList ()));
	connect(this,		SIGNAL(devicepathsChanged ()),		this, SLOT(refreshDevices ()));
	connect(refreshTimer,	SIGNAL(timeout()),			this, SLOT(refreshDevices ()));
	connect(this,		SIGNAL(logFileChanged (QString)),	this, SLOT(changeLogFile (QString)));
	connect(batchProcess,	SIGNAL(readyReadStandardOutput ()),	this, SLOT(addCharToConsole ()));
	connect(batchProcess,	SIGNAL(error (QProcess::ProcessError)),	this, SLOT(printProcessError (QProcess::ProcessError)));
	connect(batchProcess,	SIGNAL(finished (int, QProcess::ExitStatus)),this, SLOT(processFinished (int, QProcess::ExitStatus)));
}
    void* run()
    {
        // Remove 1 item at a time and process it. Blocks if no items are
        // available to process.
        for (int i = 0;; i++)
        {
            //qDebug("thread %lu, loop %d - waiting for item...", (long unsigned int)self(), i);
            WorkItem* item = m_queue.remove();
            //qDebug("thread %lu, loop %d - got one item", (long unsigned int)self(), i);
            TCPStream* stream = item->getStream();

            // Echo messages back the client until the connection is
            // closed
            char input[256];
            for (int i = 0; i < 255; i++)
            {
                input[i] = '\0';
            }

            string output;
            int len;

            while ((len = stream->receive(input, sizeof(input)-1)) > 0 )
            {
                output = "OK";
                stream->send(output.c_str(), (sizeof(output.c_str())-1));
                //qDebug("thread %lu, echoed '%s' back to the client", (long unsigned int)self(), input);
                std::string cmd(input);
                executeCommand(cmd);
            }
            delete item;

        }

        // Should never get here
        return NULL;
    }
Пример #12
0
void Go()
{
    QString inFolder = "C:/Users/Matt/Desktop/Crown_3/script/mesh/others";
    QString outFolder = "C:/Users/Matt/Desktop/Crown_3/script/mesh/others/out";
    QString sOgreMeshTool = "C:/SDK/OgreSDK/Ogre/Build/sdk/bin/release/OgreMeshTool.exe";

    QDirIterator it(inFolder, QDir::Files);

    while(it.hasNext())
    {
        QString fileFullPath = it.next();
        qDebug() << "file: " << fileFullPath;

        QString fileName = QFileInfo(fileFullPath).fileName();
        QString outFile = QDir(outFolder).filePath(fileName);

        QString strCmd2 = QString("\"%1\"").arg(sOgreMeshTool);
        strCmd2 += " -v2 -e -t -ts 4 -O puqs";
        strCmd2 += QString(" \"%1\"").arg(fileFullPath);
        strCmd2 += QString(" \"%1\"").arg(outFile);

        executeCommand(strCmd2);
    }
}
Пример #13
0
int main( int argc, char** argv ) {
    if( argc > 1 ){
    	/* Tiempo inicial y tiempo final */
    	time_t start, end;
    	/* Tiempo usado por el proceso */
    	double time_used;
    	/* T�tulo en consola */
    	SetConsoleTitle( argv[1] );
    	/* Programa a ejecutar */
    	char * command = argv[1];
    	/* Inicio segundos */
    	start = clock();
    	/* Ejecuci�n del comando */
    	executeCommand( command );
    	/* Fin de ejecuci�n */
    	end = clock();
    	time_used = (( double) ( end - start)) / CLOCKS_PER_SEC;
    	/* Pausa */
    	pauser( EXIT_SUCCESS, time_used );
    	
	}

    return 0;
}
Пример #14
0
void CameraController::run()
{
    while (d->running)
    {
        CameraCommand* command = 0;

        {
            QMutexLocker lock(&d->mutex);

            if (!d->commands.isEmpty())
            {
                command = d->commands.takeFirst();
            }
            else
            {
                emit signalBusy(false);
                d->condVar.wait(&d->mutex);
                continue;
            }
        }

        if (command)
        {
            // Special case with thumbs handling. We don't need progress bar in gui.
            if (command->action != CameraCommand::cam_thumbsinfo)
            {
                emit signalBusy(true);
            }

            executeCommand(command);
            delete command;
        }
    }

    emit signalBusy(false);
}
Пример #15
0
int
shell_loop ()
{
  char cmd[CMDLINE_LEN];
  char *params[MAX_ARGS];

	init_cleanup(); //delete this

  while (1)
    {
      printf ("Server > ");
      if (fgets (cmd, sizeof (cmd), stdin) == NULL)
	break;

      if (cmd[strlen (cmd) - 1] == '\n')
	{
	  cmd[strlen (cmd) - 1] = '\0';
	}
      readCommand (cmd, params);
      if (executeCommand (params) == EXIT)
	break;
    }
  return EXIT;
}
void MatLabEngine::clearVar( const std::string &varName ) {
	executeCommand(  std::string( "clear " ) + varName  );
}
std::string MatLabEngine::getData( const std::string &fullFieldName, bool encodeString ) {
	ArraySize arraySize = getMxMatrixSize( fullFieldName, true );

	std::string retval;

	if (   getMxIntValue(  std::string( "iscell( " ) + fullFieldName + " )", true  )   ) {
		retval += "{";

		for( int ix = 1 ; ix <= arraySize[0] ; (void)++ix ) {
			if ( ix != 1 ) retval += ";";
			for( int jx = 1 ; jx <= arraySize[1] ; (void)++jx ) {
				if ( jx != 1 ) retval += ",";
				retval += getData(
				 fullFieldName + "{" + boost::lexical_cast< std::string >( ix ) + "," +
				  boost::lexical_cast< std::string >( jx ) + "}",
				 true
				);
			}
		}

		retval += "}";
		return retval;
	}
	
	bool isscalar = getMxIntValue(  std::string( "isscalar( " ) + fullFieldName + " )", true  ) == 0 ? false : true;
	bool ischar = getMxIntValue(  std::string( "ischar( " ) + fullFieldName + " )", true  ) == 0 ? false : true;
	bool isstruct = getMxIntValue(  std::string( "isstruct( " ) + fullFieldName + " )", true  ) == 0 ? false : true;

	bool isMatrix = !isscalar && !ischar && !isstruct;

	if ( arraySize.size() > 2 ) retval += "reshape( ";
	if ( isMatrix ) retval += "[";

	if ( ischar ) {

		std::string data = getMxStringValue( fullFieldName );
		if ( encodeString ) {
			static boost::regex scPattern( ";" );
			static boost::regex cmPattern( "," );

			data = boost::regex_replace( data, scPattern, "&#x3B;" );
			data = boost::regex_replace( data, cmPattern, "&#x2C;" );
		}
		retval += data;

	} else if ( isstruct ) {
		retval += "{";
		// FIXME: this doesn't work right yet. try testing on cesna_a_37
		executeCommand(std::string("mdl2mga_fieldnames_ = fieldnames(") + fullFieldName + ")");
		for (int i = 1; i <= getMxIntValue("length(mdl2mga_fieldnames_)"); i++) {
			executeCommand(std::string("mdl2mga_fieldnames_field_ = mdl2mga_fieldnames_(") + boost::lexical_cast< std::string >(i) + ")");
			retval += getData("mdl2mga_fieldnames_field_") + ":";
			retval += getData(std::string("getfield(") + fullFieldName + ", mdl2mga_fieldnames_field_)");
		}
		retval += "}";
	} else if ( arraySize.size() <= 2 ) {
		for( int ix = 1 ; ix <= arraySize[0] ; ++ix ) {
			if ( ix != 1 ) retval += ";";
			for( int jx = 1 ; jx <= arraySize[1] ; ++jx ) {
				if ( jx != 1 ) retval += " ";

				std::string value = boost::lexical_cast< std::string >( getMxDoubleValue(
					fullFieldName + "(" + boost::lexical_cast< std::string >( ix ) + "," + boost::lexical_cast< std::string >( jx ) + ")"
				) );
				if ( value == "1.#INF" )       value = "inf";
				else if ( value == "-1.#INF" ) value = "-inf";

				retval += value;
			}
		}
	} else {
		int noElements = 1;
		for( ArraySize::iterator arsItr = arraySize.begin() ; arsItr != arraySize.end() ; ++arsItr ) {
			noElements *= *arsItr;
		}
		ArraySize counter( arraySize.size(), 1 );
		for( int ix = 0 ; ix < noElements ; ++ix ) {

			if ( ix != 0 ) retval += " ";

			std::string indexingString = "";
			bool firstIndex = true;
			for( ArraySize::iterator arsItr = counter.begin() ; arsItr != counter.end() ; ++arsItr ) {
				if ( firstIndex ) firstIndex = false;
				else              indexingString += ",";
				indexingString += boost::lexical_cast< std::string >( *arsItr );
			}

			std::string value = boost::lexical_cast< std::string >(  getMxDoubleValue( fullFieldName + "(" + indexingString + ")" )  );
			if ( value == "1.#INF" )       value = "inf";
			else if ( value == "-1.#INF" ) value = "-inf";

			retval += value;

			for( unsigned int jx = 0 ; jx < (unsigned int) arraySize.size() ; ++jx ) {
				if ( counter[jx] == arraySize[jx] ) counter[jx] = 1;
				else                                { ++counter[jx]; break; }
			}

		}

	}

	if ( isMatrix ) retval += "]";
	if ( arraySize.size() > 2 ) {
		retval += ",[";
		bool firstSize = false;
		for( ArraySize::iterator arsItr = arraySize.begin() ; arsItr != arraySize.end() ; ++arsItr ) {
			if ( firstSize ) firstSize = false;
			else             retval += " ";
			retval += boost::lexical_cast< std::string >( *arsItr );
		}
		retval += "])";
	}


	return retval;
}
Пример #18
0
void readAndExecute() {
    int readStatus;                     /* An variable to hold the return value of the readStatus function. */
    char input[COMMAND_MAX_LENGTH+2];    /* Array to be used for reading, with 2 extra char for newline and the '\0' char. */
    
    /* Read a line of max COMMAND_MAX_LENGTH command chars from stdin. */
    readStatus = readLine(input, COMMAND_MAX_LENGTH+2, stdin);
    
    /* Check the read line status */
    if(readStatus == 0) {
        /* Read was successful. */
        
        char *args[ARGUMENTS_MAX_LENGTH+2]; /* Array to hold all the arguments. 2 extra chars for command name and '\0' char. */
        
        /* Parse the command line by exploding command string. Args will then contain all arguments of the command. */
        explode(args, ARGUMENTS_MAX_LENGTH+2, input);
        
        /* Check for built-in commands. */
        if(executeCommand(args) != 0) {
            /* The command is not a built in command. The command should be executed externally. */
            
            struct timeval preExecute;      /* Structure to hold time info from pre execution of the command. */
            struct timeval postExecute;     /* Structure to hold time info from post execution of the command. */
            unsigned int elapsed;           /* The number of milliseconds needed for executing the command. */
            
            if(isBackgroundRequested(args, ARGUMENTS_MAX_LENGTH+2, BACKGROUND_REMOVE_CHAR) == 0) {
                /* Command should be executed in foreground. */
                
                /* Get the current time for command execution statistics. */
                CHECK_SAFE(gettimeofday(&preExecute, NULL));
                
                /* Execute the program with the executeChild function with foreground mode. */
                executeChild(args, CHILD_FOREGROUND);
                
                /* Get the current time for command executions statistics. */
                CHECK_SAFE(gettimeofday(&postExecute, NULL));
                
                /* Calculate the elapsed time. */
                elapsed = postExecute.tv_usec - preExecute.tv_usec;
                
                /* Print the statistics. */
                printf("Command '%s' executed in %i milliseconds.\n", args[0], elapsed);
            } else {
                /* Command should be executed in background. */
            
                /* Execute the program with the executeChild function with background mode. */
                executeChild(args, CHILD_BACKGROUND);
            }
        }
    } else if(readStatus == 1) {
        /* Too many characters were read. */
        
        /* Tell user to enter less number of characters. */
        printLine("The character limit of a command is %i", COMMAND_MAX_LENGTH);
    } else if(readStatus == -1) {
        /* An error have occured. */
        
        /* Check the error. */
        if(errno == EINTR) {
            /* Interrupted system call. */
            
            /* Do not treat this like an error, just try again. */
        } else {
            /* Unhandled error. */
        
            /* Force an error. */
            CHECK_SAFE(-1);
        }
    }
}
Пример #19
0
int main(int argc, char **argv)
{
	int status;
	do
	{
		/*	Start implementantion.
		It should stop when status is 0 (failure).	
		*/

		/* Set prompt as the '$' character.	*/
		printf("$");

		int inputSize = INPUT_SIZE; /* Set the buffer size of input. */
		int index = 0; /* Set the index of the input buffer. Initialise it to 0.*/
		char *programName = malloc(sizeof(char) * inputSize); /* Allocate an array named programName of inputSize. This will contain the input from the user. */
		int character;

		/* 	Error checking.
			If the programName array is NULL then the program should terminate
			showing the appropriate message to the user.
		*/
		if (programName == NULL)
		{
			fprintf(stderr, "programName allocation error!!\n");
			status = 0;
		}
		
		while(1)
		{
			character = getchar(); /* Read characters from the user input. */

			/* 	Check character. */
			if (character == EOF || character == '\n')
			{
				programName[index] = '\0';
				break;
			}
			else
			{
				programName[index] = character;
			}

			/* Set index of the programName array to the next read position. */
			index += 1;
		}

		// Here the programName variable contains the name of the program 
		// that the user wants to execute.
		// char delim[2] = "|";
		if (programName[0] != '\0')
		{
			if (strstr(programName, "|") != NULL) 
			{
				status = execPipe(programName);
			}
			else 
			{
				status = executeCommand(programName);  
			}
		}
		printf("Status:%d\n", status);
	}while(status);

  // Perform any shutdown/cleanup.
  return EXIT_SUCCESS;
}
void KisStrokeStrategyUndoCommandBased::doStrokeCallback(KisStrokeJobData *data)
{
    Data *d = dynamic_cast<Data*>(data);
    executeCommand(d->command, d->undo);
    notifyCommandDone(d->command, d->sequentiality(), d->exclusivity());
}
Пример #21
0
void SqliteMerge::createABUPS(sqlite3 *db)
{
  std::stringstream cmd;
  cmd << "CREATE TABLE ABUPS (Rowindex INTEGER PRIMARY KEY, EndUseName TEXT, Electricity REAL, ";
  cmd << "NaturalGas REAL, OtherFuel REAL, DistrictCooling REAL, DistrictHeating REAL, Water REAL)";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Heating'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Cooling'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Interior Lighting'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Exterior Lighting'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Interior Equipment'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Exterior Equipment'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Fans'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Pumps'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Heat Rejection'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Humidification'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Heat Recovery'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Water Systems'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Refrigeration'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('Generators'); ";
  cmd << "INSERT INTO ABUPS (EndUseName) VALUES ('TotalEndUses'); ";
  cmd << "UPDATE ABUPS SET Electricity =  0; ";
  cmd << "UPDATE ABUPS SET NaturalGas =  0; ";
  cmd << "UPDATE ABUPS SET OtherFuel =  0; ";
  cmd << "UPDATE ABUPS SET DistrictCooling =  0; ";
  cmd << "UPDATE ABUPS SET DistrictHeating =  0; ";
  cmd << "UPDATE ABUPS SET Water =  0; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string
  //heating
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Heating:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Heating'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET NaturalGas = NaturalGas + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Heating:Gas' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Heating'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET DistrictHeating = DistrictHeating + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Heating:DistrictHeating' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Heating'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string
  //cooling

  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Cooling:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Cooling'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET NaturalGas = NaturalGas + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Cooling:Gas' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Cooling'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET DistrictCooling = DistrictCooling + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Cooling:DistrictCooling' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Cooling'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  //Interior Lighting
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'InteriorLights:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Interior Lighting'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  //Exterior Lighting
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'ExteriorLights:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Exterior Lighting'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string  

  //Interior Equipment
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'InteriorEquipment:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Interior Equipment'; ";

  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string     
  cmd << "UPDATE ABUPS SET NaturalGas = NaturalGas + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'InteriorEquipment:Gas' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Interior Equipment'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  // Exterior Equipment
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'ExteriorEquipment:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Exterior Equipment'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET NaturalGas = NaturalGas + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'ExteriorEquipment:Gas' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Exterior Equipment'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  // Fans
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Fans:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Fans'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  // Pumps
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Pumps:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Pumps'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  //Heat Rejection
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'HeatRejection:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Heat Rejection'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET OtherFuel = OtherFuel + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'HeatRejection:EnergyTransfer' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Heat Rejection'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET Water = Water + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'HeatRejection:Water' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Heat Rejection'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  //  Humidification
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Humidifier:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Humidification'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET Water = Water + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Humidifier:Water' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Humidification'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string 

  //  Heat Recovery 
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'HeatRecovery:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Heat Recovery'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  // Water Systems
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'WaterSystems:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Water Systems'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET NaturalGas = NaturalGas + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'WaterSystems:Gas' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Water Systems'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET Water = Water + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'WaterSystems:Water' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Water Systems'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  //  Refrigeration 
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'Refrigeration:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Refrigeration'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  //  Generators
  cmd << "UPDATE ABUPS SET Electricity = Electricity + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'CoGeneration:Electricity' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Generators'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "UPDATE ABUPS SET NaturalGas = NaturalGas + (SELECT CASE WHEN sum(reportmeterdata.variablevalue) is not NULL THEN  sum(reportmeterdata.variablevalue) ELSE 0 END FROM ";
  cmd << "time,reportmeterdata,reportmeterdatadictionary where ";
  cmd << "time.daytype != 'WinterDesignDay' and time.daytype != 'SummerDesignDay' and time.daytype != 'customday1' and time.daytype != 'customday2' and time.timeindex = reportmeterdata.timeindex and ";
  cmd << "reportmeterdata.reportmeterdatadictionaryindex = reportmeterdatadictionary.reportmeterdatadictionaryindex and reportmeterdatadictionary.variablename = 'CoGeneration:Gas' and reportmeterdatadictionary.reportingfrequency = 'Hourly') where EndUseName = 'Generators'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  //TotalEndUses
  cmd << "UPDATE ABUPS SET Electricity = (select Sum(Electricity) from ABUPS) where EndUseName = 'TotalEndUses'; ";
  cmd << "UPDATE ABUPS SET NaturalGas = (select Sum(NaturalGas) from ABUPS) where EndUseName = 'TotalEndUses'; ";
  cmd << "UPDATE ABUPS SET OtherFuel = (select Sum(OtherFuel) from ABUPS) where EndUseName = 'TotalEndUses'; ";
  cmd << "UPDATE ABUPS SET DistrictCooling = (select Sum(DistrictCooling) from ABUPS) where EndUseName = 'TotalEndUses'; ";
  cmd << "UPDATE ABUPS SET DistrictHeating = (select Sum(DistrictHeating) from ABUPS) where EndUseName = 'TotalEndUses'; ";
  cmd << "UPDATE ABUPS SET Water = (select Sum(Water) from ABUPS) where EndUseName = 'TotalEndUses'; ";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string
}
Пример #22
0
void SqliteMerge::dropTabularData(sqlite3 *db)
{
  std::stringstream cmd;
  cmd << "delete from tabulardata";
  executeCommand(db, cmd.str().c_str());
}
Пример #23
0
void SqliteMerge::detachDatabases(sqlite3 *destination)
{
  //std::cout << "Detaching database" << std::endl;
  std::string tmpCmd = "detach database merger";
  executeCommand(destination, tmpCmd);
}
Пример #24
0
bool SqliteMerge::begin(sqlite3 *dest)
{
  std::string tmp = "begin";
  executeCommand(dest, tmp);
  return true;
}
Пример #25
0
/*
 * vacuum_one_database
 *
 * Process tables in the given database.  If the 'tables' list is empty,
 * process all tables in the database.
 *
 * Note that this function is only concerned with running exactly one stage
 * when in analyze-in-stages mode; caller must iterate on us if necessary.
 *
 * If concurrentCons is > 1, multiple connections are used to vacuum tables
 * in parallel.  In this case and if the table list is empty, we first obtain
 * a list of tables from the database.
 */
static void
vacuum_one_database(const char *dbname, vacuumingOptions *vacopts,
					int stage,
					SimpleStringList *tables,
					const char *host, const char *port,
					const char *username, enum trivalue prompt_password,
					int concurrentCons,
					const char *progname, bool echo, bool quiet)
{
	PQExpBufferData sql;
	PGconn	   *conn;
	SimpleStringListCell *cell;
	ParallelSlot *slots = NULL;
	SimpleStringList dbtables = {NULL, NULL};
	int			i;
	bool		result = 0;
	bool		parallel = concurrentCons > 1;
	const char *stage_commands[] = {
		"SET default_statistics_target=1; SET vacuum_cost_delay=0;",
		"SET default_statistics_target=10; RESET vacuum_cost_delay;",
		"RESET default_statistics_target;"
	};
	const char *stage_messages[] = {
		gettext_noop("Generating minimal optimizer statistics (1 target)"),
		gettext_noop("Generating medium optimizer statistics (10 targets)"),
		gettext_noop("Generating default (full) optimizer statistics")
	};

	Assert(stage == ANALYZE_NO_STAGE ||
		   (stage >= 0 && stage < ANALYZE_NUM_STAGES));

	if (!quiet)
	{
		if (stage != ANALYZE_NO_STAGE)
			printf(_("%s: processing database \"%s\": %s\n"), progname, dbname,
				   stage_messages[stage]);
		else
			printf(_("%s: vacuuming database \"%s\"\n"), progname, dbname);
		fflush(stdout);
	}

	conn = connectDatabase(dbname, host, port, username, prompt_password,
						   progname, false);

	initPQExpBuffer(&sql);

	/*
	 * If a table list is not provided and we're using multiple connections,
	 * prepare the list of tables by querying the catalogs.
	 */
	if (parallel && (!tables || !tables->head))
	{
		PQExpBufferData buf;
		PGresult   *res;
		int			ntups;
		int			i;

		initPQExpBuffer(&buf);

		res = executeQuery(conn,
			"SELECT c.relname, ns.nspname FROM pg_class c, pg_namespace ns\n"
			 " WHERE relkind IN (\'r\', \'m\') AND c.relnamespace = ns.oid\n"
						   " ORDER BY c.relpages DESC;",
						   progname, echo);

		ntups = PQntuples(res);
		for (i = 0; i < ntups; i++)
		{
			appendPQExpBuffer(&buf, "%s",
							  fmtQualifiedId(PQserverVersion(conn),
											 PQgetvalue(res, i, 1),
											 PQgetvalue(res, i, 0)));

			simple_string_list_append(&dbtables, buf.data);
			resetPQExpBuffer(&buf);
		}

		termPQExpBuffer(&buf);
		tables = &dbtables;

		/*
		 * If there are more connections than vacuumable relations, we don't
		 * need to use them all.
		 */
		if (concurrentCons > ntups)
			concurrentCons = ntups;
		if (concurrentCons <= 1)
			parallel = false;
	}

	/*
	 * Setup the database connections. We reuse the connection we already have
	 * for the first slot.  If not in parallel mode, the first slot in the
	 * array contains the connection.
	 */
	slots = (ParallelSlot *) pg_malloc(sizeof(ParallelSlot) * concurrentCons);
	init_slot(slots, conn);
	if (parallel)
	{
		for (i = 1; i < concurrentCons; i++)
		{
			conn = connectDatabase(dbname, host, port, username, prompt_password,
								   progname, false);
			init_slot(slots + i, conn);
		}
	}

	/*
	 * Prepare all the connections to run the appropriate analyze stage, if
	 * caller requested that mode.
	 */
	if (stage != ANALYZE_NO_STAGE)
	{
		int			j;

		/* We already emitted the message above */

		for (j = 0; j < concurrentCons; j++)
			executeCommand((slots + j)->connection,
						   stage_commands[stage], progname, echo);
	}

	cell = tables ? tables->head : NULL;
	do
	{
		ParallelSlot *free_slot;
		const char *tabname = cell ? cell->val : NULL;

		prepare_vacuum_command(&sql, conn, vacopts, tabname);

		if (CancelRequested)
		{
			result = -1;
			goto finish;
		}

		/*
		 * Get the connection slot to use.  If in parallel mode, here we wait
		 * for one connection to become available if none already is.  In
		 * non-parallel mode we simply use the only slot we have, which we
		 * know to be free.
		 */
		if (parallel)
		{
			/*
			 * Get a free slot, waiting until one becomes free if none
			 * currently is.
			 */
			free_slot = GetIdleSlot(slots, concurrentCons, dbname, progname);
			if (!free_slot)
			{
				result = -1;
				goto finish;
			}

			free_slot->isFree = false;
		}
		else
			free_slot = slots;

		run_vacuum_command(free_slot->connection, sql.data,
						   echo, dbname, tabname, progname, parallel);

		if (cell)
			cell = cell->next;
	} while (cell != NULL);

	if (parallel)
	{
		int			j;

		for (j = 0; j < concurrentCons; j++)
		{
			/* wait for all connection to return the results */
			if (!GetQueryResult((slots + j)->connection, dbname, progname))
				goto finish;

			(slots + j)->isFree = true;
		}
	}

finish:
	for (i = 0; i < concurrentCons; i++)
		DisconnectDatabase(slots + i);
	pfree(slots);

	termPQExpBuffer(&sql);

	if (result == -1)
		exit(1);
}
Пример #26
0
int
main(int argc, char *argv[])
{
	static struct option long_options[] = {
		{"list", no_argument, NULL, 'l'},
		{"host", required_argument, NULL, 'h'},
		{"port", required_argument, NULL, 'p'},
		{"username", required_argument, NULL, 'U'},
		{"no-password", no_argument, NULL, 'w'},
		{"password", no_argument, NULL, 'W'},
		{"dbname", required_argument, NULL, 'd'},
		{"echo", no_argument, NULL, 'e'},
		{NULL, 0, NULL, 0}
	};

	const char *progname;
	int			optindex;
	int			c;
	bool		listlangs = false;
	const char *dbname = NULL;
	char	   *host = NULL;
	char	   *port = NULL;
	char	   *username = NULL;
	enum trivalue prompt_password = TRI_DEFAULT;
	bool		echo = false;
	char	   *langname = NULL;
	char	   *p;
	Oid			lanplcallfoid;
	Oid			laninline;
	Oid			lanvalidator;
	char	   *handler;
	char	   *inline_handler;
	char	   *validator;
	char	   *handler_ns;
	char	   *inline_ns;
	char	   *validator_ns;
	bool		keephandler;
	bool		keepinline;
	bool		keepvalidator;
	PQExpBufferData sql;
	PGconn	   *conn;
	PGresult   *result;

	progname = get_progname(argv[0]);
	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pgscripts"));

	handle_help_version_opts(argc, argv, "droplang", help);

	while ((c = getopt_long(argc, argv, "lh:p:U:wWd:e", long_options, &optindex)) != -1)
	{
		switch (c)
		{
			case 'l':
				listlangs = true;
				break;
			case 'h':
				host = optarg;
				break;
			case 'p':
				port = optarg;
				break;
			case 'U':
				username = optarg;
				break;
			case 'w':
				prompt_password = TRI_NO;
				break;
			case 'W':
				prompt_password = TRI_YES;
				break;
			case 'd':
				dbname = optarg;
				break;
			case 'e':
				echo = true;
				break;
			default:
				fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
				exit(1);
		}
	}

	if (argc - optind > 0)
	{
		if (listlangs)
			dbname = argv[optind++];
		else
		{
			langname = argv[optind++];
			if (argc - optind > 0)
				dbname = argv[optind++];
		}
	}

	if (argc - optind > 0)
	{
		fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
				progname, argv[optind]);
		fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
		exit(1);
	}

	if (dbname == NULL)
	{
		if (getenv("PGDATABASE"))
			dbname = getenv("PGDATABASE");
		else if (getenv("PGUSER"))
			dbname = getenv("PGUSER");
		else
			dbname = get_user_name(progname);
	}

	initPQExpBuffer(&sql);

	/*
	 * List option
	 */
	if (listlangs)
	{
		printQueryOpt popt;
		static const bool translate_columns[] = {false, true};

		conn = connectDatabase(dbname, host, port, username, prompt_password,
							   progname);

		printfPQExpBuffer(&sql, "SELECT lanname as \"%s\", "
				"(CASE WHEN lanpltrusted THEN '%s' ELSE '%s' END) as \"%s\" "
						  "FROM pg_catalog.pg_language WHERE lanispl;",
						  gettext_noop("Name"),
						  gettext_noop("yes"), gettext_noop("no"),
						  gettext_noop("Trusted?"));
		result = executeQuery(conn, sql.data, progname, echo);

		memset(&popt, 0, sizeof(popt));
		popt.topt.format = PRINT_ALIGNED;
		popt.topt.border = 1;
		popt.topt.start_table = true;
		popt.topt.stop_table = true;
		popt.topt.encoding = PQclientEncoding(conn);
		popt.title = _("Procedural Languages");
		popt.translate_header = true;
		popt.translate_columns = translate_columns;
		printQuery(result, &popt, stdout, NULL);

		PQfinish(conn);
		exit(0);
	}

	if (langname == NULL)
	{
		fprintf(stderr, _("%s: missing required argument language name\n"),
				progname);
		fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
				progname);
		exit(1);
	}

	for (p = langname; *p; p++)
		if (*p >= 'A' && *p <= 'Z')
			*p += ('a' - 'A');

	conn = connectDatabase(dbname, host, port, username, prompt_password, progname);

	/*
	 * Force schema search path to be just pg_catalog, so that we don't have
	 * to be paranoid about search paths below.
	 */
	executeCommand(conn, "SET search_path = pg_catalog;", progname, echo);

	/*
	 * Make sure the language is installed and find the OIDs of the language
	 * support functions
	 */
	printfPQExpBuffer(&sql, "SELECT lanplcallfoid, laninline, lanvalidator "
					  "FROM pg_language WHERE lanname = '%s' AND lanispl;",
					  langname);
	result = executeQuery(conn, sql.data, progname, echo);
	if (PQntuples(result) == 0)
	{
		PQfinish(conn);
		fprintf(stderr, _("%s: language \"%s\" is not installed in "
						  "database \"%s\"\n"),
				progname, langname, dbname);
		exit(1);
	}
	lanplcallfoid = atooid(PQgetvalue(result, 0, 0));
	laninline = atooid(PQgetvalue(result, 0, 1));
	lanvalidator = atooid(PQgetvalue(result, 0, 2));
	PQclear(result);

	/*
	 * Check that there are no functions left defined in that language
	 */
	printfPQExpBuffer(&sql, "SELECT count(proname) FROM pg_proc P, "
					  "pg_language L WHERE P.prolang = L.oid "
					  "AND L.lanname = '%s';", langname);
	result = executeQuery(conn, sql.data, progname, echo);
	if (strcmp(PQgetvalue(result, 0, 0), "0") != 0)
	{
		PQfinish(conn);
		fprintf(stderr,
				_("%s: still %s functions declared in language \"%s\"; "
				  "language not removed\n"),
				progname, PQgetvalue(result, 0, 0), langname);
		exit(1);
	}
	PQclear(result);

	/*
	 * Check that the handler function isn't used by some other language
	 */
	printfPQExpBuffer(&sql, "SELECT count(*) FROM pg_language "
					  "WHERE lanplcallfoid = %u AND lanname <> '%s';",
					  lanplcallfoid, langname);
	result = executeQuery(conn, sql.data, progname, echo);
	if (strcmp(PQgetvalue(result, 0, 0), "0") == 0)
		keephandler = false;
	else
		keephandler = true;
	PQclear(result);

	/*
	 * Find the handler name
	 */
	if (!keephandler)
	{
		printfPQExpBuffer(&sql, "SELECT proname, (SELECT nspname "
						  "FROM pg_namespace ns WHERE ns.oid = pronamespace) "
						  "AS prons FROM pg_proc WHERE oid = %u;",
						  lanplcallfoid);
		result = executeQuery(conn, sql.data, progname, echo);
		handler = strdup(PQgetvalue(result, 0, 0));
		handler_ns = strdup(PQgetvalue(result, 0, 1));
		PQclear(result);
	}
	else
	{
		handler = NULL;
		handler_ns = NULL;
	}

	/*
	 * Check that the inline function isn't used by some other language
	 */
	if (OidIsValid(laninline))
	{
		printfPQExpBuffer(&sql, "SELECT count(*) FROM pg_language "
						  "WHERE laninline = %u AND lanname <> '%s';",
						  laninline, langname);
		result = executeQuery(conn, sql.data, progname, echo);
		if (strcmp(PQgetvalue(result, 0, 0), "0") == 0)
			keepinline = false;
		else
			keepinline = true;
		PQclear(result);
	}
	else
		keepinline = true;		/* don't try to delete it */

	/*
	 * Find the inline handler name
	 */
	if (!keepinline)
	{
		printfPQExpBuffer(&sql, "SELECT proname, (SELECT nspname "
						  "FROM pg_namespace ns WHERE ns.oid = pronamespace) "
						  "AS prons FROM pg_proc WHERE oid = %u;",
						  laninline);
		result = executeQuery(conn, sql.data, progname, echo);
		inline_handler = strdup(PQgetvalue(result, 0, 0));
		inline_ns = strdup(PQgetvalue(result, 0, 1));
		PQclear(result);
	}
	else
	{
		inline_handler = NULL;
		inline_ns = NULL;
	}

	/*
	 * Check that the validator function isn't used by some other language
	 */
	if (OidIsValid(lanvalidator))
	{
		printfPQExpBuffer(&sql, "SELECT count(*) FROM pg_language "
						  "WHERE lanvalidator = %u AND lanname <> '%s';",
						  lanvalidator, langname);
		result = executeQuery(conn, sql.data, progname, echo);
		if (strcmp(PQgetvalue(result, 0, 0), "0") == 0)
			keepvalidator = false;
		else
			keepvalidator = true;
		PQclear(result);
	}
	else
		keepvalidator = true;	/* don't try to delete it */

	/*
	 * Find the validator name
	 */
	if (!keepvalidator)
	{
		printfPQExpBuffer(&sql, "SELECT proname, (SELECT nspname "
						  "FROM pg_namespace ns WHERE ns.oid = pronamespace) "
						  "AS prons FROM pg_proc WHERE oid = %u;",
						  lanvalidator);
		result = executeQuery(conn, sql.data, progname, echo);
		validator = strdup(PQgetvalue(result, 0, 0));
		validator_ns = strdup(PQgetvalue(result, 0, 1));
		PQclear(result);
	}
	else
	{
		validator = NULL;
		validator_ns = NULL;
	}

	/*
	 * Drop the language and the functions
	 */
	printfPQExpBuffer(&sql, "DROP LANGUAGE \"%s\";\n", langname);
	if (!keephandler)
		appendPQExpBuffer(&sql, "DROP FUNCTION \"%s\".\"%s\" ();\n",
						  handler_ns, handler);
	if (!keepinline)
		appendPQExpBuffer(&sql, "DROP FUNCTION \"%s\".\"%s\" (internal);\n",
						  inline_ns, inline_handler);
	if (!keepvalidator)
		appendPQExpBuffer(&sql, "DROP FUNCTION \"%s\".\"%s\" (oid);\n",
						  validator_ns, validator);
	if (echo)
		printf("%s", sql.data);
	result = PQexec(conn, sql.data);
	if (PQresultStatus(result) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, _("%s: language removal failed: %s"),
				progname, PQerrorMessage(conn));
		PQfinish(conn);
		exit(1);
	}

	PQclear(result);
	PQfinish(conn);
	exit(0);
}
Пример #27
0
/*
 * Make a database connection with the given parameters.  An
 * interactive password prompt is automatically issued if required.
 *
 * If fail_on_error is false, we return NULL without printing any message
 * on failure, but preserve any prompted password for the next try.
 */
static PGconn *
connectDatabase(const char *dbname, const char *pghost, const char *pgport,
				const char *pguser, bool require_password, bool fail_on_error)
{
	PGconn	   *conn;
	bool		need_pass = false;
	const char *remoteversion_str;
	int			my_version;
	static char *password = NULL;

	if (require_password && !password)
		password = simple_prompt("Password: "******"%s: could not connect to database \"%s\"\n"),
					progname, dbname);
			exit(1);
		}

		if (PQstatus(conn) == CONNECTION_BAD &&
			strcmp(PQerrorMessage(conn), PQnoPasswordSupplied) == 0 &&
			!feof(stdin))
		{
			PQfinish(conn);
			need_pass = true;
			if (password)
				free(password);
			password = NULL;
			password = simple_prompt("Password: "******"%s: could not connect to database \"%s\": %s\n"),
					progname, dbname, PQerrorMessage(conn));
			exit(1);
		}
		else
		{
			PQfinish(conn);
			return NULL;
		}
	}

	remoteversion_str = PQparameterStatus(conn, "server_version");
	if (!remoteversion_str)
	{
		fprintf(stderr, _("%s: could not get server version\n"), progname);
		exit(1);
	}
	server_version = parse_version(remoteversion_str);
	if (server_version < 0)
	{
		fprintf(stderr, _("%s: could not parse server version \"%s\"\n"),
				progname, remoteversion_str);
		exit(1);
	}

	my_version = parse_version(PG_VERSION);
	if (my_version < 0)
	{
		fprintf(stderr, _("%s: could not parse version \"%s\"\n"),
				progname, PG_VERSION);
		exit(1);
	}

	if (my_version != server_version
		&& (server_version < 70000		/* we can handle back to 7.0 */
			|| server_version > my_version))
	{
		fprintf(stderr, _("server version: %s; %s version: %s\n"),
				remoteversion_str, progname, PG_VERSION);
		if (ignoreVersion)
			fprintf(stderr, _("proceeding despite version mismatch\n"));
		else
		{
			fprintf(stderr, _("aborting because of version mismatch  (Use the -i option to proceed anyway.)\n"));
			exit(1);
		}
	}

	/*
	 * On 7.3 and later, make sure we are not fooled by non-system schemas in
	 * the search path.
	 */
	if (server_version >= 70300)
		executeCommand(conn, "SET search_path = pg_catalog");

	return conn;
}
Пример #28
0
void SqliteMerge::createView(sqlite3 *db)
{
  std::stringstream cmd;

  cmd << "CREATE VIEW 'Electricity:Facility:Monthly' AS ";
  cmd << "SELECT Time.Month, Time.Day, Time.hour, Time.TimeIndex, ReportMeterData.VariableValue from Time, ReportMeterData, ";
  cmd << "ReportMeterDataDictionary where (time.TimeIndex = ReportMeterData.TimeIndex) and (ReportMeterData.ReportMeterDataDictionaryIndex = ";
  cmd << "ReportMeterDataDictionary.ReportMeterDataDictionaryIndex) and (ReportMeterDataDictionary.VariableName = 'Electricity:Facility' and ";
  cmd << "ReportMeterDataDictionary.ReportingFrequency = 'Monthly')";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "CREATE VIEW 'Electricity:Facility:Hourly' AS ";
  cmd << "SELECT Time.Month, Time.Day, Time.hour, Time.TimeIndex, ReportMeterData.VariableValue from Time, ReportMeterData, ";
  cmd << "ReportMeterDataDictionary where (time.TimeIndex = ReportMeterData.TimeIndex) and (ReportMeterData.ReportMeterDataDictionaryIndex = ";
  cmd << "ReportMeterDataDictionary.ReportMeterDataDictionaryIndex) and (ReportMeterDataDictionary.VariableName = 'Electricity:Facility' and ";
  cmd << "ReportMeterDataDictionary.ReportingFrequency = 'Hourly')";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "CREATE VIEW 'Gas:Facility:Monthly' AS ";
  cmd << "SELECT Time.Month, Time.Day, Time.hour, Time.TimeIndex, ReportMeterData.VariableValue from Time, ReportMeterData, ";
  cmd << "ReportMeterDataDictionary where (time.TimeIndex = ReportMeterData.TimeIndex) and (ReportMeterData.ReportMeterDataDictionaryIndex = ";
  cmd << "ReportMeterDataDictionary.ReportMeterDataDictionaryIndex) and (ReportMeterDataDictionary.VariableName = 'Gas:Facility' and ";
  cmd << "ReportMeterDataDictionary.ReportingFrequency = 'Monthly')";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "CREATE VIEW 'Gas:Facility:Hourly' AS ";
  cmd << "SELECT Time.Month, Time.Day, Time.hour, Time.TimeIndex, ReportMeterData.VariableValue from Time, ReportMeterData, ";
  cmd << "ReportMeterDataDictionary where (time.TimeIndex = ReportMeterData.TimeIndex) and (ReportMeterData.ReportMeterDataDictionaryIndex = ";
  cmd << "ReportMeterDataDictionary.ReportMeterDataDictionaryIndex) and (ReportMeterDataDictionary.VariableName = 'Gas:Facility' and ";
  cmd << "ReportMeterDataDictionary.ReportingFrequency = 'Hourly')";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "CREATE VIEW 'Fans:Electricity:Hourly' AS ";
  cmd << "SELECT Time.Month, Time.Day, Time.hour, Time.TimeIndex, ReportMeterData.VariableValue from Time, ReportMeterData, ";
  cmd << "ReportMeterDataDictionary where (time.TimeIndex = ReportMeterData.TimeIndex) and (ReportMeterData.ReportMeterDataDictionaryIndex = ";
  cmd << "ReportMeterDataDictionary.ReportMeterDataDictionaryIndex) and (ReportMeterDataDictionary.VariableName = 'Fans:Electricity' and ";
  cmd << "ReportMeterDataDictionary.ReportingFrequency = 'Hourly')";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "CREATE VIEW 'Cooling:Electricity:Hourly' AS ";
  cmd << "SELECT Time.Month, Time.Day, Time.hour, Time.TimeIndex, ReportMeterData.VariableValue from Time, ReportMeterData, ";
  cmd << "ReportMeterDataDictionary where (time.TimeIndex = ReportMeterData.TimeIndex) and (ReportMeterData.ReportMeterDataDictionaryIndex = ";
  cmd << "ReportMeterDataDictionary.ReportMeterDataDictionaryIndex) and (ReportMeterDataDictionary.VariableName = 'Cooling:Electricity' and ";
  cmd << "ReportMeterDataDictionary.ReportingFrequency = 'Hourly')";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "CREATE VIEW 'Heating:Gas:Hourly' AS ";
  cmd << "SELECT Time.Month, Time.Day, Time.hour, Time.TimeIndex, ReportMeterData.VariableValue from Time, ReportMeterData, ";
  cmd << "ReportMeterDataDictionary where (time.TimeIndex = ReportMeterData.TimeIndex) and (ReportMeterData.ReportMeterDataDictionaryIndex = ";
  cmd << "ReportMeterDataDictionary.ReportMeterDataDictionaryIndex) and (ReportMeterDataDictionary.VariableName = 'Heating:Gas' and ";
  cmd << "ReportMeterDataDictionary.ReportingFrequency = 'Hourly')";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string

  cmd << "CREATE VIEW 'InteriorLights:Electricity:Hourly' AS ";
  cmd << "SELECT Time.Month, Time.Day, Time.hour, Time.TimeIndex, ReportMeterData.VariableValue from Time, ReportMeterData, ";
  cmd << "ReportMeterDataDictionary where (time.TimeIndex = ReportMeterData.TimeIndex) and (ReportMeterData.ReportMeterDataDictionaryIndex = ";
  cmd << "ReportMeterDataDictionary.ReportMeterDataDictionaryIndex) and (ReportMeterDataDictionary.VariableName = 'InteriorLights:Electricity' and ";
  cmd << "ReportMeterDataDictionary.ReportingFrequency = 'Hourly')";
  executeCommand(db, cmd.str().c_str());
  cmd.str(std::string());  //clear out the string
}
Пример #29
0
void unpackJars(LauncherProperties * props, WCHAR * jvmDir, WCHAR * startDir, WCHAR * unpack200exe) {
    DWORD attrs;
    DWORD dwError;
    DWORD count = 0 ;
    
    if(!isOK(props)) return;
    attrs = GetFileAttributesW(startDir);
    if(attrs==INVALID_FILE_ATTRIBUTES) {
        writeErrorA(props, OUTPUT_LEVEL_DEBUG, 1, "Error! Can`t get attributes of the file : ", startDir, GetLastError());
        return;
    }
    if(attrs & FILE_ATTRIBUTE_DIRECTORY) { // is directory
        WIN32_FIND_DATAW FindFileData;
        HANDLE hFind = INVALID_HANDLE_VALUE;
        
        WCHAR * DirSpec = appendStringW(appendStringW(NULL, startDir), L"\\*" );
        
        // Find the first file in the directory.
        hFind = FindFirstFileW(DirSpec, &FindFileData);
        
        if (hFind == INVALID_HANDLE_VALUE) {
            writeErrorA(props, OUTPUT_LEVEL_DEBUG, 1, "Error! Can`t file with pattern ", DirSpec, GetLastError());
        }
        else {
            // List all the other files in the directory.
            writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, "... listing directory ", 0);
            writeMessageW(props, OUTPUT_LEVEL_DEBUG, 0, startDir, 1);
            
            while (FindNextFileW(hFind, &FindFileData) != 0 && isOK(props)) {
                if(lstrcmpW(FindFileData.cFileName, L".")!=0 &&
                        lstrcmpW(FindFileData.cFileName, L"..")!=0) {
                    WCHAR * child = NULL;
                    
                    child = appendStringW(appendStringW(appendStringW(NULL, startDir), FILE_SEP), FindFileData.cFileName);
                    if(isDirectory(child)) {
                        writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, "... directory : ", 0);
                        writeMessageW(props, OUTPUT_LEVEL_DEBUG, 0, child, 1);
                        unpackJars(props, jvmDir, child, unpack200exe);
                    } else  if(searchW(FindFileData.cFileName, JAR_PACK_GZ_SUFFIX)!=NULL) {
                        WCHAR * jarName = appendStringW(appendStringW(
                                appendStringW(NULL, startDir), FILE_SEP),
                                appendStringNW(NULL, 0, FindFileData.cFileName,
                                getLengthW(FindFileData.cFileName) - getLengthW(PACK_GZ_SUFFIX)));
                        WCHAR * unpackCommand = NULL;
                        writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, "... packed jar : ", 0);
                        writeMessageW(props, OUTPUT_LEVEL_DEBUG, 0, child, 1);
                        writeMessageA(props, OUTPUT_LEVEL_DEBUG, 0, "... jar name : ", 0);
                        writeMessageW(props, OUTPUT_LEVEL_DEBUG, 0, jarName, 1);
                        
                        
                        appendCommandLineArgument(&unpackCommand, unpack200exe);
                        appendCommandLineArgument(&unpackCommand, child);
                        appendCommandLineArgument(&unpackCommand, jarName);
                        
                        executeCommand(props, unpackCommand, NULL, UNPACK200_EXTRACTION_TIMEOUT, props->stdoutHandle, props->stderrHandle, NORMAL_PRIORITY_CLASS);
                        FREE(unpackCommand);
                        if(!isOK(props)) {
                            if(props->status==ERROR_PROCESS_TIMEOUT) {
                                writeMessageA(props, OUTPUT_LEVEL_DEBUG, 1, "... could not unpack file : timeout", 1);
                            } else {
                                writeMessageA(props, OUTPUT_LEVEL_DEBUG, 1, "... an error occured unpacking the file", 1);
                            }
                            props->exitCode = props->status;
                        }
                        FREE(jarName);
                    }
                    FREE(child);
                }
            }
            
            dwError = GetLastError();
            FindClose(hFind);
            if (dwError != ERROR_NO_MORE_FILES) {
                writeErrorA(props, OUTPUT_LEVEL_DEBUG, 1, "Error! Can`t find file with pattern : ", DirSpec, dwError);
            }
        }
        FREE(DirSpec);
    }
    
}
Пример #30
0
bool SqliteMerge::commit(sqlite3 *dest)
{
  std::string tmp = "commit";
  executeCommand(dest, tmp);
  return true;
}