<commit_before>/*
 * DesktopWebView.cpp
 *
 * Copyright (C) 2009-18 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "DesktopWebView.hpp"

#include <QApplication>
#include <QClipboard>
#include <QMenu>
#include <QNetworkReply>
#include <QStyleFactory>

#include <QWebEngineContextMenuData>
#include <QWebEngineSettings>
#include <QWebEngineHistory>

#include <core/system/Environment.hpp>

#ifdef _WIN32
#include <windows.h>
#include <wingdi.h>
#endif

namespace rstudio {
namespace desktop {

WebView::WebView(QUrl baseUrl, QWidget *parent, bool allowExternalNavigate) :
    QWebEngineView(parent),
    baseUrl_(baseUrl)
{
#ifdef Q_OS_LINUX
   if (!core::system::getenv("KDE_FULL_SESSION").empty())
   {
      QString fusion = QString::fromUtf8("fusion");
      if (QStyleFactory::keys().contains(fusion))
         setStyle(QStyleFactory::create(fusion));
   }
#endif
   pWebPage_ = new WebPage(baseUrl, this, allowExternalNavigate);
   setPage(pWebPage_);
}

void WebView::setBaseUrl(const QUrl& baseUrl)
{
   baseUrl_ = baseUrl;
   pWebPage_->setBaseUrl(baseUrl_);
}

QUrl WebView::baseUrl()
{
   return baseUrl_;
}

void WebView::activateSatelliteWindow(QString name)
{
   pWebPage_->activateWindow(name);
}

void WebView::prepareForWindow(const PendingWindow& pendingWnd)
{
   pWebPage_->prepareForWindow(pendingWnd);
}

QString WebView::promptForFilename(const QNetworkRequest& request,
                                   QNetworkReply* pReply = nullptr)
{
   QString defaultFileName = QFileInfo(request.url().path()).fileName();

   // Content-Disposition's filename parameter should be used as the
   // default, if present.
   if (pReply && pReply->hasRawHeader("content-disposition"))
   {
      QString headerValue = QString::fromUtf8(pReply->rawHeader("content-disposition"));
      QRegExp regexp(QString::fromUtf8("filename=\"?([^\"]+)\"?"), Qt::CaseInsensitive);
      if (regexp.indexIn(headerValue) >= 0)
      {
         defaultFileName = regexp.cap(1);
      }
   }

   QString fileName = QFileDialog::getSaveFileName(this,
                                                   tr("Download File"),
                                                   defaultFileName,
                                                   QString(),
                                                   nullptr,
                                                   standardFileDialogOptions());
   return fileName;
}

void WebView::keyPressEvent(QKeyEvent* pEvent)
{
#ifdef Q_OS_MAC
   if (pEvent->key() == Qt::Key_W &&
       pEvent->modifiers() == Qt::CTRL)
   {
      // on macOS, intercept Cmd+W and emit the window close signal
      onCloseWindowShortcut();
   }
   else
   {
      // pass other key events through to WebEngine
      QWebEngineView::keyPressEvent(pEvent);
   }
#else

   QWebEngineView::keyPressEvent(pEvent);

#endif
}

void WebView::openFile(QString fileName)
{
   // force use of Preview for PDFs on the Mac (Adobe Reader 10.01 crashes)
#ifdef Q_OS_MAC
   if (fileName.toLower().endsWith(QString::fromUtf8(".pdf")))
   {
      QStringList args;
      args.append(QString::fromUtf8("-a"));
      args.append(QString::fromUtf8("Preview"));
      args.append(fileName);
      QProcess::startDetached(QString::fromUtf8("open"), args);
      return;
   }
#endif

   QDesktopServices::openUrl(QUrl::fromLocalFile(fileName));
}

bool WebView::event(QEvent* event)
{
   if (event->type() == QEvent::ShortcutOverride)
   {
      // take a first crack at shortcuts
      keyPressEvent(static_cast<QKeyEvent*>(event));
      return true;
   }
   return this->QWebEngineView::event(event);
}

void WebView::closeEvent(QCloseEvent*)
{
}

void WebView::contextMenuEvent(QContextMenuEvent* event)
{
   QMenu* menu = new QMenu(this);
   const auto& data = webPage()->contextMenuData();

   bool canNavigateHistory =
         webPage()->history()->canGoBack() ||
         webPage()->history()->canGoForward();

   if (data.selectedText().isEmpty() && canNavigateHistory)
   {
      auto* back = menu->addAction(tr("&Back"), [&]() {
         webPage()->history()->back();
      });
      back->setEnabled(webPage()->history()->canGoBack());

      auto* forward = menu->addAction(tr("&Forward"), [&]() {
         webPage()->history()->forward();
      });
      forward->setEnabled(webPage()->history()->canGoForward());

      menu->addSeparator();
   }

   if (data.mediaUrl().isValid())
   {
      switch (data.mediaType())
      {
      case QWebEngineContextMenuData::MediaTypeImage:
         menu->addAction(webPage()->action(QWebEnginePage::DownloadImageToDisk));
         menu->addAction(webPage()->action(QWebEnginePage::CopyImageUrlToClipboard));
         menu->addAction(webPage()->action(QWebEnginePage::CopyImageToClipboard));
         break;
      case QWebEngineContextMenuData::MediaTypeAudio:
      case QWebEngineContextMenuData::MediaTypeVideo:
         menu->addAction(webPage()->action(QWebEnginePage::DownloadMediaToDisk));
         menu->addAction(webPage()->action(QWebEnginePage::CopyMediaUrlToClipboard));
         menu->addAction(webPage()->action(QWebEnginePage::ToggleMediaPlayPause));
         menu->addAction(webPage()->action(QWebEnginePage::ToggleMediaLoop));
         break;
      case QWebEngineContextMenuData::MediaTypeFile:
         menu->addAction(webPage()->action(QWebEnginePage::DownloadLinkToDisk));
         menu->addAction(webPage()->action(QWebEnginePage::CopyMediaUrlToClipboard));
         break;
      default:
         break;
      }
   }
   else if (data.linkUrl().isValid())
   {
      menu->addAction(webPage()->action(QWebEnginePage::OpenLinkInNewWindow));
      menu->addAction(webPage()->action(QWebEnginePage::CopyLinkToClipboard));
      menu->addAction(webPage()->action(QWebEnginePage::DownloadLinkToDisk));
   }
   else
   {
      // always show cut / copy / paste, but only enable cut / copy if there
      // is some selected text, and only enable paste if there is something
      // on the clipboard. note that this isn't perfect -- the highlighted
      // text may not correspond to the context menu click target -- but
      // in general users who want to copy text will right-click on the
      // selection, rather than elsewhere on the screen.
      auto* cut   = webPage()->action(QWebEnginePage::Cut);
      auto* copy  = webPage()->action(QWebEnginePage::Copy);
      auto* paste = webPage()->action(QWebEnginePage::Paste);

      cut->setEnabled(data.isContentEditable() && !data.selectedText().isEmpty());
      copy->setEnabled(!data.selectedText().isEmpty());
      paste->setEnabled(QApplication::clipboard()->mimeData()->hasText());

      menu->addAction(cut);
      menu->addAction(copy);
      menu->addAction(paste);
      menu->addSeparator();
      menu->addAction(webPage()->action(QWebEnginePage::SelectAll));
   }

#ifndef NDEBUG
   menu->addSeparator();
   menu->addAction(tr("&Reload"), [&]() { triggerPageAction(QWebEnginePage::Reload); });
   menu->addAction(webPage()->action(QWebEnginePage::InspectElement));
#endif

   menu->setAttribute(Qt::WA_DeleteOnClose, true);

   menu->exec(event->globalPos());
}

} // namespace desktop
} // namespace rstudio
<commit_msg>avoid opening blank window in Right Click -> Open Window (closes #2767)<commit_after>/*
 * DesktopWebView.cpp
 *
 * Copyright (C) 2009-18 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "DesktopWebView.hpp"

#include <QApplication>
#include <QClipboard>
#include <QMenu>
#include <QNetworkReply>
#include <QStyleFactory>

#include <QWebEngineContextMenuData>
#include <QWebEngineSettings>
#include <QWebEngineHistory>

#include <core/system/Environment.hpp>

#ifdef _WIN32
#include <windows.h>
#include <wingdi.h>
#endif

namespace rstudio {
namespace desktop {

WebView::WebView(QUrl baseUrl, QWidget *parent, bool allowExternalNavigate) :
    QWebEngineView(parent),
    baseUrl_(baseUrl)
{
#ifdef Q_OS_LINUX
   if (!core::system::getenv("KDE_FULL_SESSION").empty())
   {
      QString fusion = QString::fromUtf8("fusion");
      if (QStyleFactory::keys().contains(fusion))
         setStyle(QStyleFactory::create(fusion));
   }
#endif
   pWebPage_ = new WebPage(baseUrl, this, allowExternalNavigate);
   setPage(pWebPage_);
}

void WebView::setBaseUrl(const QUrl& baseUrl)
{
   baseUrl_ = baseUrl;
   pWebPage_->setBaseUrl(baseUrl_);
}

QUrl WebView::baseUrl()
{
   return baseUrl_;
}

void WebView::activateSatelliteWindow(QString name)
{
   pWebPage_->activateWindow(name);
}

void WebView::prepareForWindow(const PendingWindow& pendingWnd)
{
   pWebPage_->prepareForWindow(pendingWnd);
}

QString WebView::promptForFilename(const QNetworkRequest& request,
                                   QNetworkReply* pReply = nullptr)
{
   QString defaultFileName = QFileInfo(request.url().path()).fileName();

   // Content-Disposition's filename parameter should be used as the
   // default, if present.
   if (pReply && pReply->hasRawHeader("content-disposition"))
   {
      QString headerValue = QString::fromUtf8(pReply->rawHeader("content-disposition"));
      QRegExp regexp(QString::fromUtf8("filename=\"?([^\"]+)\"?"), Qt::CaseInsensitive);
      if (regexp.indexIn(headerValue) >= 0)
      {
         defaultFileName = regexp.cap(1);
      }
   }

   QString fileName = QFileDialog::getSaveFileName(this,
                                                   tr("Download File"),
                                                   defaultFileName,
                                                   QString(),
                                                   nullptr,
                                                   standardFileDialogOptions());
   return fileName;
}

void WebView::keyPressEvent(QKeyEvent* pEvent)
{
#ifdef Q_OS_MAC
   if (pEvent->key() == Qt::Key_W &&
       pEvent->modifiers() == Qt::CTRL)
   {
      // on macOS, intercept Cmd+W and emit the window close signal
      onCloseWindowShortcut();
   }
   else
   {
      // pass other key events through to WebEngine
      QWebEngineView::keyPressEvent(pEvent);
   }
#else

   QWebEngineView::keyPressEvent(pEvent);

#endif
}

void WebView::openFile(QString fileName)
{
   // force use of Preview for PDFs on the Mac (Adobe Reader 10.01 crashes)
#ifdef Q_OS_MAC
   if (fileName.toLower().endsWith(QString::fromUtf8(".pdf")))
   {
      QStringList args;
      args.append(QString::fromUtf8("-a"));
      args.append(QString::fromUtf8("Preview"));
      args.append(fileName);
      QProcess::startDetached(QString::fromUtf8("open"), args);
      return;
   }
#endif

   QDesktopServices::openUrl(QUrl::fromLocalFile(fileName));
}

bool WebView::event(QEvent* event)
{
   if (event->type() == QEvent::ShortcutOverride)
   {
      // take a first crack at shortcuts
      keyPressEvent(static_cast<QKeyEvent*>(event));
      return true;
   }
   return this->QWebEngineView::event(event);
}

void WebView::closeEvent(QCloseEvent*)
{
}

void WebView::contextMenuEvent(QContextMenuEvent* event)
{
   QMenu* menu = new QMenu(this);
   const auto& data = webPage()->contextMenuData();

   bool canNavigateHistory =
         webPage()->history()->canGoBack() ||
         webPage()->history()->canGoForward();

   if (data.selectedText().isEmpty() && canNavigateHistory)
   {
      auto* back = menu->addAction(tr("&Back"), [&]() {
         webPage()->history()->back();
      });
      back->setEnabled(webPage()->history()->canGoBack());

      auto* forward = menu->addAction(tr("&Forward"), [&]() {
         webPage()->history()->forward();
      });
      forward->setEnabled(webPage()->history()->canGoForward());

      menu->addSeparator();
   }

   if (data.mediaUrl().isValid())
   {
      switch (data.mediaType())
      {
      case QWebEngineContextMenuData::MediaTypeImage:
         menu->addAction(webPage()->action(QWebEnginePage::DownloadImageToDisk));
         menu->addAction(webPage()->action(QWebEnginePage::CopyImageUrlToClipboard));
         menu->addAction(webPage()->action(QWebEnginePage::CopyImageToClipboard));
         break;
      case QWebEngineContextMenuData::MediaTypeAudio:
      case QWebEngineContextMenuData::MediaTypeVideo:
         menu->addAction(webPage()->action(QWebEnginePage::DownloadMediaToDisk));
         menu->addAction(webPage()->action(QWebEnginePage::CopyMediaUrlToClipboard));
         menu->addAction(webPage()->action(QWebEnginePage::ToggleMediaPlayPause));
         menu->addAction(webPage()->action(QWebEnginePage::ToggleMediaLoop));
         break;
      case QWebEngineContextMenuData::MediaTypeFile:
         menu->addAction(webPage()->action(QWebEnginePage::DownloadLinkToDisk));
         menu->addAction(webPage()->action(QWebEnginePage::CopyMediaUrlToClipboard));
         break;
      default:
         break;
      }
   }
   else if (data.linkUrl().isValid())
   {
      menu->addAction(tr("Open Link in &Browser"), [=]() { desktop::openUrl(data.linkUrl()); });
      menu->addAction(webPage()->action(QWebEnginePage::CopyLinkToClipboard));
      menu->addAction(tr("&Save Link As..."), [=]() { triggerPageAction(QWebEnginePage::DownloadLinkToDisk); });
   }
   else
   {
      // always show cut / copy / paste, but only enable cut / copy if there
      // is some selected text, and only enable paste if there is something
      // on the clipboard. note that this isn't perfect -- the highlighted
      // text may not correspond to the context menu click target -- but
      // in general users who want to copy text will right-click on the
      // selection, rather than elsewhere on the screen.
      auto* cut   = webPage()->action(QWebEnginePage::Cut);
      auto* copy  = webPage()->action(QWebEnginePage::Copy);
      auto* paste = webPage()->action(QWebEnginePage::Paste);

      cut->setEnabled(data.isContentEditable() && !data.selectedText().isEmpty());
      copy->setEnabled(!data.selectedText().isEmpty());
      paste->setEnabled(QApplication::clipboard()->mimeData()->hasText());

      menu->addAction(cut);
      menu->addAction(copy);
      menu->addAction(paste);
      menu->addSeparator();
      menu->addAction(webPage()->action(QWebEnginePage::SelectAll));
   }

#ifndef NDEBUG
   menu->addSeparator();
   menu->addAction(tr("&Reload"), [&]() { triggerPageAction(QWebEnginePage::Reload); });
   menu->addAction(webPage()->action(QWebEnginePage::InspectElement));
#endif

   menu->setAttribute(Qt::WA_DeleteOnClose, true);

   menu->exec(event->globalPos());
}

} // namespace desktop
} // namespace rstudio
<|endoftext|>


<commit_before><commit_msg>Unit Tests<commit_after><|endoftext|>


<commit_before>// Given a matrix of m x n elements (m rows, n columns), return all elements of
// the matrix in spiral order.
// For example,
// Given the following matrix:
// [
//  [ 1, 2, 3 ],
//  [ 4, 5, 6 ],
//  [ 7, 8, 9 ]
// ]
// You should return [1,2,3,6,9,8,7,4,5].

class Solution {
  public:
    vector<int> spiralOrder(vector<vector<int>> &matrix) {
        vector<int> res;
        if (matrix.empty())
            return res;
        int m = matrix.size(), n = matrix[0].size();
        int i = 0, j = 0;
        while (m > 0 && n > 0) {
            if (m == 1 && n == 1) {
                res.push_back(matrix[i][j]);
                break;
            }

            // left to right
            for (int i1 = 0; i1 < n - 1; ++i1)
                res.push_back(matrix[i][j++]);

            if (m == 1) {
                res.push_back(matrix[i][j]);
                break;
            }

            // up to down
            for (int i2 = 0; i2 < m - 1; ++i2)
                res.push_back(matrix[i++][j]);

            if (n == 1) {
                res.push_back(matrix[i][j]);
                break;
            }

            // right to left
            for (int i3 = 0; i3 < n - 1; ++i3)
                res.push_back(matrix[i][j--]);

            // down to up
            for (int i4 = 0; i4 < m - 1; ++i4)
                res.push_back(matrix[i--][j]);

            ++i;
            ++j;

            m -= 2;
            n -= 2;
        }

        return res;
    }
};<commit_msg>update 054 ver 2<commit_after>// Given a matrix of m x n elements (m rows, n columns), return all elements of
// the matrix in spiral order.
// For example,
// Given the following matrix:
// [
//  [ 1, 2, 3 ],
//  [ 4, 5, 6 ],
//  [ 7, 8, 9 ]
// ]
// You should return [1,2,3,6,9,8,7,4,5].

class Solution {
  public:
    vector<int> spiralOrder(vector<vector<int>> &matrix) {
        vector<int> res;
        if (matrix.empty())
            return res;
        int m = matrix.size(), n = matrix[0].size();
        int i = 0, j = 0;
        while (m > 0 && n > 0) {
            if (m == 1 && n == 1) {
                res.push_back(matrix[i][j]);
                break;
            }

            // left to right
            for (int i1 = 0; i1 < n - 1; ++i1)
                res.push_back(matrix[i][j++]);

            if (m == 1) {
                res.push_back(matrix[i][j]);
                break;
            }

            // up to down
            for (int i2 = 0; i2 < m - 1; ++i2)
                res.push_back(matrix[i++][j]);

            if (n == 1) {
                res.push_back(matrix[i][j]);
                break;
            }

            // right to left
            for (int i3 = 0; i3 < n - 1; ++i3)
                res.push_back(matrix[i][j--]);

            // down to up
            for (int i4 = 0; i4 < m - 1; ++i4)
                res.push_back(matrix[i--][j]);

            ++i;
            ++j;

            m -= 2;
            n -= 2;
        }

        return res;
    }
};

class Solution {
  public:
    vector<int> spiralOrder(vector<vector<int>> &matrix) {
        vector<int> res;
        if (matrix.empty())
            return res;
        int m = matrix.size(), n = matrix[0].size();
        int i = 0, j = 0;
        while (m > 0 && n > 0) {
            // left to right
            for (int i1 = 0; i1 < n; ++i1)
                res.push_back(matrix[i][j++]);
            ++i;
            --j;
            if (m > 1) {
                // up to down
                for (int i2 = 0; i2 < m - 1; ++i2)
                    res.push_back(matrix[i++][j]);
                --i;
                --j;
                if (n > 1) {
                    // right to left
                    for (int i3 = 0; i3 < n - 1; ++i3)
                        res.push_back(matrix[i][j--]);
                    --i;
                    ++j;
                    if (m > 2) {
                        // down to up
                        for (int i4 = 0; i4 < m - 2; ++i4)
                            res.push_back(matrix[i--][j]);
                        ++i;
                        ++j;
                    }
                }
            }

            m -= 2;
            n -= 2;
        }

        return res;
    }
};<|endoftext|>


<commit_before>// Dak Washbrook - M10A

/*

// Input
The first three integers are in the range 0..100000.  They represent seconds taken to solve the first, second, and third problems, respectively.
Zero seconds indicates that a problem has not been solved.  The last three integers are in the range 0..100, representing the attempts taken to
solve the first, second, and third problems, respectively.

// Output
Each output line should begin with the line number (right justified in a 3 character field), followed by a colon and a space, the teams name
(left justified in a 40 character field), followed by a single space, the number of solved problems (right justified in a 2 character field),
a single space, and the total number of seconds including penalties it took for the solved problems (right justified in a 7 character field).

*/

// Includes
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>

// Namespace used.
using namespace std;

const int ZERO = 0, SOLVED = 1, NOT_SOLVED = 0, COLUMN1 = 3, COLUMN2 = 40, COLUMN3 = 2, COLUMN4 = 7; // Declaring Constants for zero, if solved, and the column lengths.
const string READ_FILE = "RawScore.dat", WRITE_FILE = "ComputedScore.dat"; // Declaring Constants for the filenames.

// Prototypes
int Solved(int score);
bool ReadInputRecord(ifstream &, int &, int &, int &, int &, int &, int &, string &);
bool WriteInputRecord(ofstream &, int, string, int, int);
int CountLines(string);

int main() {

	// Declaring all integer values.
	int numLines = ZERO, numOfTeams = ZERO, iteration = ZERO, score1, score2, score3, attempt1, attempt2, attempt3, numSolved, totalTime;

	// Declaring the fstreams for the read and writted files.
	ifstream filename;
	ofstream newFilename;

	string teamName; // Declaring the string for the team name column.

	numLines = CountLines(READ_FILE); // Counts the number of lines in a file.

	if (numLines > 0) {

		cout << "Opening " << READ_FILE << endl;

		filename.open(READ_FILE); // Open the READ_FILE and stream contents.

		if (filename) {

			cout << READ_FILE << " successfuly opened." << endl << endl;

			cout << "Opening " << WRITE_FILE << endl;

			// Open the WRITE_FILE and stream contents.
			newFilename.open(WRITE_FILE);

			if (newFilename) {

				cout << WRITE_FILE << " successfully opened." << endl << endl;

				// For each line, read contents, then convert to desired output and write.
				for (int i = ZERO; i < numLines; i++) {
					cout << "Reading line." << endl;
					// Read the contents of 'filename' and store it into the reference variables.
					if (ReadInputRecord(filename, score1, score2, score3, attempt1, attempt2, attempt3, teamName)) {
						cout << "Line successfully read" << endl; // Say the line is read if it didn't fail.
						cout << "Team: " << teamName << " found." << endl; // Say the name of the team it found on the current line.
						cout << "Calculating number of successfully solved problems by " << teamName << "." << endl;
						numSolved = Solved(score1) + Solved(score2) + Solved(score3); // Find out how many were solved by the team.
						cout << teamName << " solved " << numSolved << " problems." << endl; // Output number of solved problems by the team on the current line.
						cout << "Calculating total time it took " << teamName << " to solve " << numSolved << " problems." << endl;
						totalTime = score1 + score2 + score3; // Fine the total time that it took for them to solve all problems.
						cout << teamName << " took " << totalTime << " seconds to solve " << numSolved << " problems." << endl; // Output the total time it took the team on the current line.
						iteration++; // Iterate for the first column's number.
						cout << "Writing data to " << WRITE_FILE << endl;
						if (WriteInputRecord(newFilename, iteration, teamName, numSolved, totalTime)) { // Write the new output to 'newFilename'.
							cout << "Data written to " << WRITE_FILE << endl << endl; // Output that the data was successfully written.
						}
						else {
							cout << "Error writing data to file." << endl << endl; // If failed to write, output an error.
							break; // Break the loop due to error.
						}
					}
					else {
						cout << "Error reading line." << endl << endl; // If failed to write, output an error.
						break; // Break the loop due to error.
					}
				}

				cout << "Closing " << WRITE_FILE << endl;
				newFilename.close(); // Close the WRITE_FILE;
				if (newFilename.is_open()) {
					cout << "Error closing file." << endl << endl; // If failed to close, output an error.
					return 0; // If failed to close, end program.
				}
				else {
					cout << WRITE_FILE << " closed." << endl << endl;
				}
			}
			else {
				// If 'newFilename' failed to open, display an error message.
				cout << "Error Opening " << WRITE_FILE << endl << endl;
			}

			cout << "Closing " << READ_FILE << endl;
			filename.close(); // Close the READ_FILE.
			if (filename.is_open()) {
				cout << "Error closing file." << endl << endl; // If failed to close, output an error.
				return 0; // If failed to close, end program.
			}
			else {
				cout << READ_FILE << " closed." << endl << endl;
			}
		}
		else {
			// If 'filename' failed to open, display an error message.
			cout << "Error Opening " << READ_FILE << endl << endl;
		}
	}

	return 0;

}

bool ReadInputRecord(ifstream &filename, int &score1, int &score2, int &score3, int &attempt1, int &attempt2, int &attempt3, string &teamName) {
	// Change the values of the reference variables to be the contents of the current line.
	if (filename >> score1 >> score2 >> score3 >> attempt1 >> attempt2 >> attempt3 >> teamName) {
		return true;
	}
	else {
		return false;
	}
}

bool WriteInputRecord(ofstream &newFilename, int iteration, string teamName, int numSolved, int totalTime) {
	// Write a new line to the 'newFilename' with the desired values and formatting. Also, sets the correct column widths for each column.
	if (newFilename << setw(COLUMN1) << iteration << ": " << setw(COLUMN2) << left << teamName << right << " " << setw(COLUMN3) << numSolved << " " << setw(COLUMN4) << totalTime << endl) {
		return true;
	}
	else {
		return false;
	}
}

int Solved(int score) {

	/* This function calculates if the problem was solved or not.
		Outputs SOLVED if it was, ZERO if it was not. Allowing
		the outputs to be added together to produce the total
		number of solved problems.
	*/

	if (score > ZERO) { // Find if the problem was solved by seeing if their seconds were greater than 0.
		return SOLVED; // Return SOLVED if solved.
	}
	else {
		return NOT_SOLVED; // Return NOT_SOLVED if not solved.
	}
}

int CountLines(string file) {

	/* This function finds the number of lines that exist in a file and outputs that number. */

	int numLines = ZERO; // Initiate numLines.
	ifstream filename;
	string line;

	filename.open(file); // Open the filename that was passed into the function via a string.

	if (filename) {

		cout << "Counting number of lines in " << file << endl;

		while (getline(filename, line)) {
			// For each line, iterate numLines.
			numLines++;
		}

		cout << numLines << " line(s) counted." << endl << endl;

		filename.close(); // Close the file after done.

	}
	else {
		cout << file << " could not be opened." << endl << endl;
	}

	return numLines; // Return the number of lines that exist.
}
<commit_msg>Update Assignment-3.cpp<commit_after>// Dak Washbrook - M10A

/*
 // Input
 The first three integers are in the range 0..100000.  They represent seconds taken to solve the first, second, and third problems, respectively.
 Zero seconds indicates that a problem has not been solved.  The last three integers are in the range 0..100, representing the attempts taken to
 solve the first, second, and third problems, respectively.

 // Output
 Each output line should begin with the line number (right justified in a 3 character field), followed by a colon and a space, the teams name
 (left justified in a 40 character field), followed by a single space, the number of solved problems (right justified in a 2 character field),
 a single space, and the total number of seconds including penalties it took for the solved problems (right justified in a 7 character field).
 */

// Includes
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>

// Namespace used.
using namespace std;

const int ZERO = 0, SOLVED = 1, NOT_SOLVED = 0, COLUMN1 = 3, COLUMN2 = 40, COLUMN3 = 2, COLUMN4 = 7; // Declaring Constants for zero, if solved, and the column lengths.
const string READ_FILE = "RawScore.dat", WRITE_FILE = "ComputedScore.dat"; // Declaring Constants for the filenames.

// Prototypes
int Solved(int score);
bool ReadInputRecord(ifstream &, int &, int &, int &, int &, int &, int &, string &);
bool WriteInputRecord(ofstream &, int, string, int, int);
int CountLines(string);

int main() {

    // Declaring all integer values.
    int numLines = ZERO, iteration = ZERO, score1, score2, score3, attempt1, attempt2, attempt3, numSolved, totalTime;

    // Declaring the fstreams for the read and writted files.
    ifstream filename;
    ofstream newFilename;

    string teamName; // Declaring the string for the team name column.

    numLines = CountLines(READ_FILE); // Counts the number of lines in a file.

    if (numLines > 0) {

        cout << "Opening " << READ_FILE << endl;

        filename.open(READ_FILE); // Open the READ_FILE and stream contents.

        if (filename) {

            cout << READ_FILE << " successfuly opened." << endl << endl;

            cout << "Opening " << WRITE_FILE << endl;

            // Open the WRITE_FILE and stream contents.
            newFilename.open(WRITE_FILE);

            if (newFilename) {

                cout << WRITE_FILE << " successfully opened." << endl << endl;

                // For each line, read contents, then convert to desired output and write.
                for (int i = ZERO; i < numLines; i++) {
                    cout << "Reading line." << endl;
                    // Read the contents of 'filename' and store it into the reference variables.
                    if (ReadInputRecord(filename, score1, score2, score3, attempt1, attempt2, attempt3, teamName)) {
                        cout << "Line successfully read" << endl; // Say the line is read if it didn't fail.
                        cout << "Team: " << teamName << " found." << endl; // Say the name of the team it found on the current line.
                        cout << "Calculating number of successfully solved problems by " << teamName << "." << endl;
                        numSolved = Solved(score1) + Solved(score2) + Solved(score3); // Find out how many were solved by the team.
                        cout << teamName << " solved " << numSolved << " problems." << endl; // Output number of solved problems by the team on the current line.
                        cout << "Calculating total time it took " << teamName << " to solve " << numSolved << " problems." << endl;
                        totalTime = score1 + score2 + score3; // Fine the total time that it took for them to solve all problems.
                        cout << teamName << " took " << totalTime << " seconds to solve " << numSolved << " problems." << endl; // Output the total time it took the team on the current line.
                        iteration++; // Iterate for the first column's number.
                        cout << "Writing data to " << WRITE_FILE << endl;
                        if (WriteInputRecord(newFilename, iteration, teamName, numSolved, totalTime)) { // Write the new output to 'newFilename'.
                            cout << "Data written to " << WRITE_FILE << endl << endl; // Output that the data was successfully written.
                        }
                        else {
                            cout << "Error writing data to file." << endl << endl; // If failed to write, output an error.
                            break; // Break the loop due to error.
                        }
                    }
                    else {
                        cout << "Error reading line." << endl << endl; // If failed to write, output an error.
                        break; // Break the loop due to error.
                    }
                }

                cout << "Closing " << WRITE_FILE << endl;
                newFilename.close(); // Close the WRITE_FILE;
                if (newFilename.is_open()) {
                    cout << "Error closing file." << endl << endl; // If failed to close, output an error.
                    return 0; // If failed to close, end program.
                }
                else {
                    cout << WRITE_FILE << " closed." << endl << endl;
                }
            }
            else {
                // If 'newFilename' failed to open, display an error message.
                cout << "Error Opening " << WRITE_FILE << endl << endl;
            }

            cout << "Closing " << READ_FILE << endl;
            filename.close(); // Close the READ_FILE.
            if (filename.is_open()) {
                cout << "Error closing file." << endl << endl; // If failed to close, output an error.
                return 0; // If failed to close, end program.
            }
            else {
                cout << READ_FILE << " closed." << endl << endl;
            }
        }
        else {
            // If 'filename' failed to open, display an error message.
            cout << "Error Opening " << READ_FILE << endl << endl;
        }
    }
    else {
        // If the file is empty then alert user.
        cout << READ_FILE << " is empty." << endl << endl;
    }

    return 0;

}

bool ReadInputRecord(ifstream &filename, int &score1, int &score2, int &score3, int &attempt1, int &attempt2, int &attempt3, string &teamName) {
    // Change the values of the reference variables to be the contents of the current line.
    if (filename >> score1 >> score2 >> score3 >> attempt1 >> attempt2 >> attempt3 >> teamName) {
        return true;
    }
    else {
        return false;
    }
}

bool WriteInputRecord(ofstream &newFilename, int iteration, string teamName, int numSolved, int totalTime) {
    // Write a new line to the 'newFilename' with the desired values and formatting. Also, sets the correct column widths for each column.
    if (newFilename << setw(COLUMN1) << iteration << ": " << setw(COLUMN2) << left << teamName << right << " " << setw(COLUMN3) << numSolved << " " << setw(COLUMN4) << totalTime << endl) {
        return true;
    }
    else {
        return false;
    }
}

int Solved(int score) {

    /* This function calculates if the problem was solved or not.
     Outputs SOLVED if it was, ZERO if it was not. Allowing
     the outputs to be added together to produce the total
     number of solved problems.
     */

    if (score > ZERO) { // Find if the problem was solved by seeing if their seconds were greater than 0.
        return SOLVED; // Return SOLVED if solved.
    }
    else {
        return NOT_SOLVED; // Return NOT_SOLVED if not solved.
    }
}

int CountLines(string file) {

    /* This function finds the number of lines that exist in a file and outputs that number. */

    int numLines = ZERO; // Initiate numLines.
    ifstream filename;
    string line;

    filename.open(file); // Open the filename that was passed into the function via a string.

    if (filename) {

        cout << "Counting number of lines in " << file << endl;

        while (getline(filename, line)) {
            // For each line, iterate numLines.
            numLines++;
        }

        cout << numLines << " line(s) counted." << endl << endl;

        filename.close(); // Close the file after done.

    }
    else {
        cout << file << " could not be opened." << endl << endl;
    }

    return numLines; // Return the number of lines that exist.
}
<|endoftext|>


<commit_before>// ***************************************************************************
//
//   Generated automatically by genwrapper.
//   Please DO NOT EDIT this file!
//
// ***************************************************************************

#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>

#include <osg/CopyOp>
#include <osg/Object>
#include <osg/Stats>
#include <osgAnimation/Action>
#include <osgAnimation/ActionVisitor>
#include <osgAnimation/StatsVisitor>
#include <osgAnimation/Timeline>

// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif

BEGIN_ENUM_REFLECTOR(osgAnimation::Timeline::TimelineStatus)
	I_DeclaringFile("osgAnimation/Timeline");
	I_EnumLabel(osgAnimation::Timeline::Play);
	I_EnumLabel(osgAnimation::Timeline::Stop);
END_REFLECTOR

TYPE_NAME_ALIAS(std::vector< osgAnimation::FrameAction >, osgAnimation::Timeline::ActionList)

TYPE_NAME_ALIAS(std::map< int COMMA  osgAnimation::Timeline::ActionList >, osgAnimation::Timeline::ActionLayers)

BEGIN_OBJECT_REFLECTOR(osgAnimation::Timeline)
	I_DeclaringFile("osgAnimation/Timeline");
	I_BaseType(osgAnimation::Action);
	I_Constructor0(____Timeline,
	               "",
	               "");
	I_ConstructorWithDefaults2(IN, const osgAnimation::Timeline &, nc, , IN, const osg::CopyOp &, op, osg::CopyOp::SHALLOW_COPY,
	                           ____Timeline__C5_Timeline_R1__C5_osg_CopyOp_R1,
	                           "",
	                           "");
	I_Method0(osg::Object *, cloneType,
	          Properties::VIRTUAL,
	          __osg_Object_P1__cloneType,
	          "Clone the type of an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, x,
	          Properties::VIRTUAL,
	          __osg_Object_P1__clone__C5_osg_CopyOp_R1,
	          "Clone an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj,
	          Properties::VIRTUAL,
	          __bool__isSameKindAs__C5_osg_Object_P1,
	          "",
	          "");
	I_Method0(const char *, className,
	          Properties::VIRTUAL,
	          __C5_char_P1__className,
	          "return the name of the object's class type. ",
	          "Must be defined by derived classes. ");
	I_Method0(const char *, libraryName,
	          Properties::VIRTUAL,
	          __C5_char_P1__libraryName,
	          "return the name of the object's library. ",
	          "Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. ");
	I_Method1(void, accept, IN, osgAnimation::ActionVisitor &, nv,
	          Properties::VIRTUAL,
	          __void__accept__osgAnimation_ActionVisitor_R1,
	          "",
	          "");
	I_Method0(osgAnimation::Timeline::TimelineStatus, getStatus,
	          Properties::NON_VIRTUAL,
	          __TimelineStatus__getStatus,
	          "",
	          "");
	I_Method1(const osgAnimation::Timeline::ActionList &, getActionLayer, IN, int, i,
	          Properties::NON_VIRTUAL,
	          __C5_ActionList_R1__getActionLayer__int,
	          "",
	          "");
	I_Method0(unsigned int, getCurrentFrame,
	          Properties::NON_VIRTUAL,
	          __unsigned_int__getCurrentFrame,
	          "",
	          "");
	I_Method0(double, getCurrentTime,
	          Properties::NON_VIRTUAL,
	          __double__getCurrentTime,
	          "",
	          "");
	I_Method0(void, play,
	          Properties::NON_VIRTUAL,
	          __void__play,
	          "",
	          "");
	I_Method1(void, gotoFrame, IN, unsigned int, frame,
	          Properties::NON_VIRTUAL,
	          __void__gotoFrame__unsigned_int,
	          "",
	          "");
	I_Method0(void, stop,
	          Properties::NON_VIRTUAL,
	          __void__stop,
	          "",
	          "");
	I_Method0(bool, getEvaluating,
	          Properties::NON_VIRTUAL,
	          __bool__getEvaluating,
	          "",
	          "");
	I_Method1(bool, isActive, IN, osgAnimation::Action *, activeAction,
	          Properties::NON_VIRTUAL,
	          __bool__isActive__Action_P1,
	          "",
	          "");
	I_Method1(void, removeAction, IN, osgAnimation::Action *, action,
	          Properties::NON_VIRTUAL,
	          __void__removeAction__Action_P1,
	          "",
	          "");
	I_MethodWithDefaults3(void, addActionAt, IN, unsigned int, frame, , IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::VIRTUAL,
	                      __void__addActionAt__unsigned_int__Action_P1__int,
	                      "",
	                      "");
	I_MethodWithDefaults3(void, addActionAt, IN, double, t, , IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::VIRTUAL,
	                      __void__addActionAt__double__Action_P1__int,
	                      "",
	                      "");
	I_MethodWithDefaults2(void, addActionNow, IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::NON_VIRTUAL,
	                      __void__addActionNow__Action_P1__int,
	                      "",
	                      "");
	I_Method0(void, clearActions,
	          Properties::NON_VIRTUAL,
	          __void__clearActions,
	          "",
	          "");
	I_Method1(void, update, IN, double, simulationTime,
	          Properties::VIRTUAL,
	          __void__update__double,
	          "",
	          "");
	I_Method1(void, setLastFrameEvaluated, IN, unsigned int, frame,
	          Properties::NON_VIRTUAL,
	          __void__setLastFrameEvaluated__unsigned_int,
	          "",
	          "");
	I_Method1(void, setEvaluating, IN, bool, state,
	          Properties::NON_VIRTUAL,
	          __void__setEvaluating__bool,
	          "",
	          "");
	I_Method1(void, traverse, IN, osgAnimation::ActionVisitor &, visitor,
	          Properties::VIRTUAL,
	          __void__traverse__ActionVisitor_R1,
	          "",
	          "");
	I_Method1(void, setStats, IN, osg::Stats *, stats,
	          Properties::NON_VIRTUAL,
	          __void__setStats__osg_Stats_P1,
	          "",
	          "");
	I_Method0(osg::Stats *, getStats,
	          Properties::NON_VIRTUAL,
	          __osg_Stats_P1__getStats,
	          "",
	          "");
	I_Method1(void, collectStats, IN, bool, state,
	          Properties::NON_VIRTUAL,
	          __void__collectStats__bool,
	          "",
	          "");
	I_Method0(osgAnimation::StatsActionVisitor *, getStatsVisitor,
	          Properties::NON_VIRTUAL,
	          __osgAnimation_StatsActionVisitor_P1__getStatsVisitor,
	          "",
	          "");
	I_Method0(const osgAnimation::Timeline::ActionLayers &, getActionLayers,
	          Properties::NON_VIRTUAL,
	          __C5_ActionLayers_R1__getActionLayers,
	          "",
	          "");
	I_Method0(void, processPendingOperation,
	          Properties::NON_VIRTUAL,
	          __void__processPendingOperation,
	          "",
	          "");
	I_ProtectedMethod1(void, internalRemoveAction, IN, osgAnimation::Action *, action,
	                   Properties::NON_VIRTUAL,
	                   Properties::NON_CONST,
	                   __void__internalRemoveAction__Action_P1,
	                   "",
	                   "");
	I_ProtectedMethod2(void, internalAddAction, IN, int, priority, IN, const osgAnimation::FrameAction &, ftl,
	                   Properties::NON_VIRTUAL,
	                   Properties::NON_CONST,
	                   __void__internalAddAction__int__C5_FrameAction_R1,
	                   "",
	                   "");
	I_SimpleProperty(const osgAnimation::Timeline::ActionLayers &, ActionLayers,
	                 __C5_ActionLayers_R1__getActionLayers,
	                 0);
	I_SimpleProperty(unsigned int, CurrentFrame,
	                 __unsigned_int__getCurrentFrame,
	                 0);
	I_SimpleProperty(double, CurrentTime,
	                 __double__getCurrentTime,
	                 0);
	I_SimpleProperty(bool, Evaluating,
	                 __bool__getEvaluating,
	                 __void__setEvaluating__bool);
	I_SimpleProperty(unsigned int, LastFrameEvaluated,
	                 0,
	                 __void__setLastFrameEvaluated__unsigned_int);
	I_SimpleProperty(osg::Stats *, Stats,
	                 __osg_Stats_P1__getStats,
	                 __void__setStats__osg_Stats_P1);
	I_SimpleProperty(osgAnimation::StatsActionVisitor *, StatsVisitor,
	                 __osgAnimation_StatsActionVisitor_P1__getStatsVisitor,
	                 0);
	I_SimpleProperty(osgAnimation::Timeline::TimelineStatus, Status,
	                 __TimelineStatus__getStatus,
	                 0);
END_REFLECTOR

STD_MAP_REFLECTOR(std::map< int COMMA  osgAnimation::Timeline::ActionList >)

<commit_msg>Updated wrappers<commit_after>// ***************************************************************************
//
//   Generated automatically by genwrapper.
//   Please DO NOT EDIT this file!
//
// ***************************************************************************

#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>

#include <osg/CopyOp>
#include <osg/Object>
#include <osg/Stats>
#include <osgAnimation/Action>
#include <osgAnimation/ActionVisitor>
#include <osgAnimation/AnimationManagerBase>
#include <osgAnimation/StatsVisitor>
#include <osgAnimation/Timeline>

// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif

BEGIN_ENUM_REFLECTOR(osgAnimation::Timeline::TimelineStatus)
	I_DeclaringFile("osgAnimation/Timeline");
	I_EnumLabel(osgAnimation::Timeline::Play);
	I_EnumLabel(osgAnimation::Timeline::Stop);
END_REFLECTOR

TYPE_NAME_ALIAS(std::vector< osgAnimation::FrameAction >, osgAnimation::Timeline::ActionList)

TYPE_NAME_ALIAS(std::map< int COMMA  osgAnimation::Timeline::ActionList >, osgAnimation::Timeline::ActionLayers)

BEGIN_OBJECT_REFLECTOR(osgAnimation::Timeline)
	I_DeclaringFile("osgAnimation/Timeline");
	I_BaseType(osgAnimation::Action);
	I_Constructor0(____Timeline,
	               "",
	               "");
	I_ConstructorWithDefaults2(IN, const osgAnimation::Timeline &, nc, , IN, const osg::CopyOp &, op, osg::CopyOp::SHALLOW_COPY,
	                           ____Timeline__C5_Timeline_R1__C5_osg_CopyOp_R1,
	                           "",
	                           "");
	I_Method0(osg::Object *, cloneType,
	          Properties::VIRTUAL,
	          __osg_Object_P1__cloneType,
	          "Clone the type of an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, x,
	          Properties::VIRTUAL,
	          __osg_Object_P1__clone__C5_osg_CopyOp_R1,
	          "Clone an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj,
	          Properties::VIRTUAL,
	          __bool__isSameKindAs__C5_osg_Object_P1,
	          "",
	          "");
	I_Method0(const char *, className,
	          Properties::VIRTUAL,
	          __C5_char_P1__className,
	          "return the name of the object's class type. ",
	          "Must be defined by derived classes. ");
	I_Method0(const char *, libraryName,
	          Properties::VIRTUAL,
	          __C5_char_P1__libraryName,
	          "return the name of the object's library. ",
	          "Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. ");
	I_Method1(void, accept, IN, osgAnimation::ActionVisitor &, nv,
	          Properties::VIRTUAL,
	          __void__accept__osgAnimation_ActionVisitor_R1,
	          "",
	          "");
	I_Method0(osgAnimation::Timeline::TimelineStatus, getStatus,
	          Properties::NON_VIRTUAL,
	          __TimelineStatus__getStatus,
	          "",
	          "");
	I_Method1(const osgAnimation::Timeline::ActionList &, getActionLayer, IN, int, i,
	          Properties::NON_VIRTUAL,
	          __C5_ActionList_R1__getActionLayer__int,
	          "",
	          "");
	I_Method0(unsigned int, getCurrentFrame,
	          Properties::NON_VIRTUAL,
	          __unsigned_int__getCurrentFrame,
	          "",
	          "");
	I_Method0(double, getCurrentTime,
	          Properties::NON_VIRTUAL,
	          __double__getCurrentTime,
	          "",
	          "");
	I_Method0(void, play,
	          Properties::NON_VIRTUAL,
	          __void__play,
	          "",
	          "");
	I_Method1(void, gotoFrame, IN, unsigned int, frame,
	          Properties::NON_VIRTUAL,
	          __void__gotoFrame__unsigned_int,
	          "",
	          "");
	I_Method0(void, stop,
	          Properties::NON_VIRTUAL,
	          __void__stop,
	          "",
	          "");
	I_Method0(bool, getEvaluating,
	          Properties::NON_VIRTUAL,
	          __bool__getEvaluating,
	          "",
	          "");
	I_Method1(bool, isActive, IN, osgAnimation::Action *, activeAction,
	          Properties::NON_VIRTUAL,
	          __bool__isActive__Action_P1,
	          "",
	          "");
	I_Method1(void, removeAction, IN, osgAnimation::Action *, action,
	          Properties::NON_VIRTUAL,
	          __void__removeAction__Action_P1,
	          "",
	          "");
	I_MethodWithDefaults3(void, addActionAt, IN, unsigned int, frame, , IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::VIRTUAL,
	                      __void__addActionAt__unsigned_int__Action_P1__int,
	                      "",
	                      "");
	I_MethodWithDefaults3(void, addActionAt, IN, double, t, , IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::VIRTUAL,
	                      __void__addActionAt__double__Action_P1__int,
	                      "",
	                      "");
	I_MethodWithDefaults2(void, addActionNow, IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::NON_VIRTUAL,
	                      __void__addActionNow__Action_P1__int,
	                      "",
	                      "");
	I_Method0(void, clearActions,
	          Properties::NON_VIRTUAL,
	          __void__clearActions,
	          "",
	          "");
	I_Method1(void, update, IN, double, simulationTime,
	          Properties::VIRTUAL,
	          __void__update__double,
	          "",
	          "");
	I_Method1(void, setLastFrameEvaluated, IN, unsigned int, frame,
	          Properties::NON_VIRTUAL,
	          __void__setLastFrameEvaluated__unsigned_int,
	          "",
	          "");
	I_Method1(void, setEvaluating, IN, bool, state,
	          Properties::NON_VIRTUAL,
	          __void__setEvaluating__bool,
	          "",
	          "");
	I_Method1(void, traverse, IN, osgAnimation::ActionVisitor &, visitor,
	          Properties::VIRTUAL,
	          __void__traverse__ActionVisitor_R1,
	          "",
	          "");
	I_Method1(void, setStats, IN, osg::Stats *, stats,
	          Properties::NON_VIRTUAL,
	          __void__setStats__osg_Stats_P1,
	          "",
	          "");
	I_Method0(osg::Stats *, getStats,
	          Properties::NON_VIRTUAL,
	          __osg_Stats_P1__getStats,
	          "",
	          "");
	I_Method1(void, collectStats, IN, bool, state,
	          Properties::NON_VIRTUAL,
	          __void__collectStats__bool,
	          "",
	          "");
	I_Method0(osgAnimation::StatsActionVisitor *, getStatsVisitor,
	          Properties::NON_VIRTUAL,
	          __osgAnimation_StatsActionVisitor_P1__getStatsVisitor,
	          "",
	          "");
	I_Method0(const osgAnimation::Timeline::ActionLayers &, getActionLayers,
	          Properties::NON_VIRTUAL,
	          __C5_ActionLayers_R1__getActionLayers,
	          "",
	          "");
	I_Method0(void, processPendingOperation,
	          Properties::NON_VIRTUAL,
	          __void__processPendingOperation,
	          "",
	          "");
	I_Method1(void, setAnimationManager, IN, osgAnimation::AnimationManagerBase *, x,
	          Properties::NON_VIRTUAL,
	          __void__setAnimationManager__AnimationManagerBase_P1,
	          "",
	          "");
	I_ProtectedMethod1(void, internalRemoveAction, IN, osgAnimation::Action *, action,
	                   Properties::NON_VIRTUAL,
	                   Properties::NON_CONST,
	                   __void__internalRemoveAction__Action_P1,
	                   "",
	                   "");
	I_ProtectedMethod2(void, internalAddAction, IN, int, priority, IN, const osgAnimation::FrameAction &, ftl,
	                   Properties::NON_VIRTUAL,
	                   Properties::NON_CONST,
	                   __void__internalAddAction__int__C5_FrameAction_R1,
	                   "",
	                   "");
	I_SimpleProperty(const osgAnimation::Timeline::ActionLayers &, ActionLayers,
	                 __C5_ActionLayers_R1__getActionLayers,
	                 0);
	I_SimpleProperty(osgAnimation::AnimationManagerBase *, AnimationManager,
	                 0,
	                 __void__setAnimationManager__AnimationManagerBase_P1);
	I_SimpleProperty(unsigned int, CurrentFrame,
	                 __unsigned_int__getCurrentFrame,
	                 0);
	I_SimpleProperty(double, CurrentTime,
	                 __double__getCurrentTime,
	                 0);
	I_SimpleProperty(bool, Evaluating,
	                 __bool__getEvaluating,
	                 __void__setEvaluating__bool);
	I_SimpleProperty(unsigned int, LastFrameEvaluated,
	                 0,
	                 __void__setLastFrameEvaluated__unsigned_int);
	I_SimpleProperty(osg::Stats *, Stats,
	                 __osg_Stats_P1__getStats,
	                 __void__setStats__osg_Stats_P1);
	I_SimpleProperty(osgAnimation::StatsActionVisitor *, StatsVisitor,
	                 __osgAnimation_StatsActionVisitor_P1__getStatsVisitor,
	                 0);
	I_SimpleProperty(osgAnimation::Timeline::TimelineStatus, Status,
	                 __TimelineStatus__getStatus,
	                 0);
END_REFLECTOR

STD_MAP_REFLECTOR(std::map< int COMMA  osgAnimation::Timeline::ActionList >)

<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

#ifndef __WINDOWS__
#include <arpa/inet.h>
#include <netdb.h>
#endif // __WINDOWS__

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include <glog/logging.h>

#include <iostream>
#include <sstream>
#include <string>

#include <process/pid.hpp>
#include <process/process.hpp>

#include <stout/net.hpp>
#include <stout/os.hpp>

#include "config.hpp"

using std::ios_base;
using std::istream;
using std::istringstream;
using std::ostream;
using std::ostringstream;
using std::string;

namespace process {

UPID::UPID(const char* s)
{
  istringstream in(s);
  in >> *this;
}

UPID::UPID(const string& s)
{
  istringstream in(s);
  in >> *this;
}

// TODO(benh): Make this inline-able (cyclic dependency issues).
UPID::UPID(const ProcessBase& process)
{
  id = process.self().id;
  address = process.self().address;
}

UPID::operator string() const
{
  ostringstream out;
  out << *this;
  return out.str();
}

ostream& operator<<(ostream& stream, const UPID& pid)
{
  stream << pid.id << "@" << pid.address;
  return stream;
}

istream& operator>>(istream& stream, UPID& pid)
{
  pid.id = "";
  pid.address.ip = net::IP(INADDR_ANY);
  pid.address.port = 0;

  string str;
  if (!(stream >> str)) {
    stream.setstate(ios_base::badbit);
    return stream;
  }

  VLOG(2) << "Attempting to parse '" << str << "' into a PID";

  if (str.size() == 0) {
    stream.setstate(ios_base::badbit);
    return stream;
  }

  string id;
  string host;
  network::Address address;

  size_t index = str.find('@');

  if (index != string::npos) {
    id = str.substr(0, index);
  } else {
    stream.setstate(ios_base::badbit);
    return stream;
  }

  str = str.substr(index + 1);

  index = str.find(':');

  if (index != string::npos) {
    host = str.substr(0, index);
  } else {
    stream.setstate(ios_base::badbit);
    return stream;
  }

  // TODO(evelinad): Extend this to support IPv6.
  Try<net::IP> ip = net::getIP(host, AF_INET);

  if (ip.isError()) {
    VLOG(2) << ip.error();
    stream.setstate(ios_base::badbit);
    return stream;
  }

  address.ip = ip.get();

  str = str.substr(index + 1);

  if (sscanf(str.c_str(), "%hu", &address.port) != 1) {
    stream.setstate(ios_base::badbit);
    return stream;
  }

  pid.id = id;
  pid.address = address;

  return stream;
}

} // namespace process {
<commit_msg>Changed the severity level of a log line in UPID::operator>>.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

#ifndef __WINDOWS__
#include <arpa/inet.h>
#include <netdb.h>
#endif // __WINDOWS__

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include <glog/logging.h>

#include <iostream>
#include <sstream>
#include <string>

#include <process/pid.hpp>
#include <process/process.hpp>

#include <stout/net.hpp>
#include <stout/os.hpp>

#include "config.hpp"

using std::ios_base;
using std::istream;
using std::istringstream;
using std::ostream;
using std::ostringstream;
using std::string;

namespace process {

UPID::UPID(const char* s)
{
  istringstream in(s);
  in >> *this;
}

UPID::UPID(const string& s)
{
  istringstream in(s);
  in >> *this;
}

// TODO(benh): Make this inline-able (cyclic dependency issues).
UPID::UPID(const ProcessBase& process)
{
  id = process.self().id;
  address = process.self().address;
}

UPID::operator string() const
{
  ostringstream out;
  out << *this;
  return out.str();
}

ostream& operator<<(ostream& stream, const UPID& pid)
{
  stream << pid.id << "@" << pid.address;
  return stream;
}

istream& operator>>(istream& stream, UPID& pid)
{
  pid.id = "";
  pid.address.ip = net::IP(INADDR_ANY);
  pid.address.port = 0;

  string str;
  if (!(stream >> str)) {
    stream.setstate(ios_base::badbit);
    return stream;
  }

  VLOG(3) << "Attempting to parse '" << str << "' into a PID";

  if (str.size() == 0) {
    stream.setstate(ios_base::badbit);
    return stream;
  }

  string id;
  string host;
  network::Address address;

  size_t index = str.find('@');

  if (index != string::npos) {
    id = str.substr(0, index);
  } else {
    stream.setstate(ios_base::badbit);
    return stream;
  }

  str = str.substr(index + 1);

  index = str.find(':');

  if (index != string::npos) {
    host = str.substr(0, index);
  } else {
    stream.setstate(ios_base::badbit);
    return stream;
  }

  // TODO(evelinad): Extend this to support IPv6.
  Try<net::IP> ip = net::getIP(host, AF_INET);

  if (ip.isError()) {
    VLOG(2) << ip.error();
    stream.setstate(ios_base::badbit);
    return stream;
  }

  address.ip = ip.get();

  str = str.substr(index + 1);

  if (sscanf(str.c_str(), "%hu", &address.port) != 1) {
    stream.setstate(ios_base::badbit);
    return stream;
  }

  pid.id = id;
  pid.address = address;

  return stream;
}

} // namespace process {
<|endoftext|>


<commit_before>#include "mpdas.h"

#define RED "\x1b[31;01m"
#define RESET "\x1b[0m"
#define GREEN "\x1b[32;01m"
#define YELLOW "\x1b[33;01m"

std::string
md5sum(const char* fmt, ...)
{
	va_list ap;
	char* abuf;
	md5_state_t state;
	unsigned char md5buf[16];

	va_start(ap, fmt);
	vasprintf(&abuf, fmt, ap);
	va_end(ap);

	std::string buf(abuf);
	free(abuf);

	md5_init(&state);
	md5_append(&state, (const md5_byte_t*)buf.c_str(), buf.length());
	md5_finish(&state, md5buf);

	std::ostringstream ret;
	for(unsigned int i = 0; i < 16; i++)
		ret << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)md5buf[i];
	return ret.str();
}

std::string
timestr()
{
	std::stringstream buf;
	time_t rawtime = time(NULL);
	struct tm* t = localtime(&rawtime);

	buf << t->tm_hour << ":";
	if(t->tm_min < 10)
		buf << "0";
	buf << t->tm_min << ":";
	if(t->tm_sec < 10)
		buf << "0";
	buf << t->tm_sec;

	return buf.str();
}

void
eprintf(const char* fmt, ...)
{
	char* abuf;
	va_list ap;
	va_start(ap, fmt);
	vasprintf(&abuf, fmt, ap);
	va_end(ap);

	std::string buf(abuf);
	free(abuf);

	std::cerr << "(" << timestr() << ") [" << RED << "ERROR" << RESET << "] " << buf << std::endl;
}

void
iprintf(const char* fmt, ...)
{
	time_t rawtime = time(NULL);
	struct tm* t = localtime(&rawtime);
	char* abuf;
	va_list ap;
	va_start(ap, fmt);
	vasprintf(&abuf, fmt, ap);
	va_end(ap);

	std::string buf(abuf);
	free(abuf);

	std::cerr << "(" << timestr() << ") [" << YELLOW << "INFO" << RESET << "] " << buf << std::endl;
}

<commit_msg>pad hours with zero<commit_after>#include "mpdas.h"

#define RED "\x1b[31;01m"
#define RESET "\x1b[0m"
#define GREEN "\x1b[32;01m"
#define YELLOW "\x1b[33;01m"

std::string
md5sum(const char* fmt, ...)
{
	va_list ap;
	char* abuf;
	md5_state_t state;
	unsigned char md5buf[16];

	va_start(ap, fmt);
	vasprintf(&abuf, fmt, ap);
	va_end(ap);

	std::string buf(abuf);
	free(abuf);

	md5_init(&state);
	md5_append(&state, (const md5_byte_t*)buf.c_str(), buf.length());
	md5_finish(&state, md5buf);

	std::ostringstream ret;
	for(unsigned int i = 0; i < 16; i++)
		ret << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)md5buf[i];
	return ret.str();
}

std::string
timestr()
{
	std::stringstream buf;
	time_t rawtime = time(NULL);
	struct tm* t = localtime(&rawtime);

	if(t->tm_hour < 10)
		buf << 0;
	buf << t->tm_hour << ":";
	if(t->tm_min < 10)
		buf << "0";
	buf << t->tm_min << ":";
	if(t->tm_sec < 10)
		buf << "0";
	buf << t->tm_sec;

	return buf.str();
}

void
eprintf(const char* fmt, ...)
{
	char* abuf;
	va_list ap;
	va_start(ap, fmt);
	vasprintf(&abuf, fmt, ap);
	va_end(ap);

	std::string buf(abuf);
	free(abuf);

	std::cerr << "(" << timestr() << ") [" << RED << "ERROR" << RESET << "] " << buf << std::endl;
}

void
iprintf(const char* fmt, ...)
{
	time_t rawtime = time(NULL);
	struct tm* t = localtime(&rawtime);
	char* abuf;
	va_list ap;
	va_start(ap, fmt);
	vasprintf(&abuf, fmt, ap);
	va_end(ap);

	std::string buf(abuf);
	free(abuf);

	std::cerr << "(" << timestr() << ") [" << YELLOW << "INFO" << RESET << "] " << buf << std::endl;
}

<|endoftext|>


<commit_before>#include "utils.hpp"

#include <chrono>

std::mt19937& rand_gen()
{
    static std::mt19937 gen(std::chrono::system_clock::now().time_since_epoch().count());
    return gen;
}

int rand_pos()
{
    return static_cast<int>(rand_gen()() % grid_size);
}

direction rand_action()
{
    return static_cast<direction>(rand_gen()() % action_count);
}
<commit_msg>Fixes #1 by changing the rand_pos and rand_action functions to use uniform int distribution.<commit_after>#include "utils.hpp"

#include <chrono>

std::mt19937& rand_gen()
{
    static std::mt19937 gen(std::chrono::system_clock::now().time_since_epoch().count());
    return gen;
}

int rand_pos()
{
    static std::uniform_int_distribution<> dis(0, grid_size - 1);

    return dis(rand_gen());
}

direction rand_action()
{
    static std::uniform_int_distribution<> dis(0, action_count - 1);

    return static_cast<direction>(dis(rand_gen()));
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include <QDateTime>
#include <QProcess>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTemporaryDir>
#include <QTextStream>

#define Z do { if (::testing::Test::HasFatalFailure()) { std::cerr << "At: " << __FILE__ << ":" << __LINE__ << std::endl; return; } } while (0)

namespace {

template <typename Device>
class IO {
public:
	IO(Device* device, bool verbose = false) : m_device(device), m_verbose(verbose) {}
	virtual ~IO() {}
	void ReadUntil(QByteArray pattern) {
		auto deadline = QDateTime::currentDateTime().addSecs(30);
		while (true) {
			int search = m_readed.indexOf(pattern);
			if (search != -1) {
				m_readed.remove(0, search + pattern.length());
				return;
			}
			if (m_readed.length() > pattern.length()) {
				m_readed = m_readed.right(pattern.length());
			}
			const int timeout_ms = QDateTime::currentDateTime().msecsTo(deadline);
			ASSERT_GT(timeout_ms, 0) << "Wanted:" << pattern.toStdString();
			ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms)) << "Wanted: " << pattern.toStdString();
			QByteArray chunk = m_device->readAll();
			if (m_verbose) {
				std::cout << chunk.toStdString() << std::flush;
			}
			m_readed += chunk;
		}
	}
	void Write(QString s = "") {
		s += "\n";
		if (m_verbose) {
			std::cout << s.toStdString() << std::flush;
		}
		{
			QTextStream str(m_device);
			str << s;
		}
		FlushIfCan(m_device);
	}

private:
	// QTextStream doesn't flush QTcpSocket, and QIODevice doesn't have flush() at all...
	static void FlushIfCan(QIODevice*) {}
	static void FlushIfCan(QTcpSocket* sock) {
		sock->flush();
	}

	Device* m_device;
	bool m_verbose;
	QByteArray m_readed;
};

template <typename Device>
IO<Device> WrapIO(Device* d) {
	return IO<Device>(d);
}

class Process : public IO<QProcess> {
public:
	Process(QString cmd, QStringList args, bool interactive) : IO(&m_proc, true) {
		if (!interactive) {
			m_proc.setProcessChannelMode(QProcess::ForwardedChannels);
		}
		m_proc.start(cmd, args);
	}
	~Process() {
		Destroy();
	}
	void ShouldFinishItself() {
		m_kill = false;
	}

private:
	void Destroy() {
		if (m_kill) m_proc.terminate();
		ASSERT_TRUE(m_proc.waitForFinished());
	}

	bool m_kill = true;
	QProcess m_proc;
};

void WriteConfig(QString path) {
	Process p("./znc", QStringList() << "--debug" << "--datadir" << path << "--makeconf", true);
	p.ReadUntil("Listen on port");Z;          p.Write("12345");
	p.ReadUntil("Listen using SSL");Z;        p.Write();
	p.ReadUntil("IPv6");Z;                    p.Write();
	p.ReadUntil("Username");Z;                p.Write("user");
	p.ReadUntil("password");Z;                p.Write("hunter2");
	p.ReadUntil("Confirm");Z;                 p.Write("hunter2");
	p.ReadUntil("Nick [user]");Z;             p.Write();
	p.ReadUntil("Alternate nick [user_]");Z;  p.Write();
	p.ReadUntil("Ident [user]");Z;            p.Write();
	p.ReadUntil("Real name");Z;               p.Write();
	p.ReadUntil("Bind host");Z;               p.Write();
	p.ReadUntil("Set up a network?");Z;       p.Write();
	p.ReadUntil("Name [freenode]");Z;         p.Write("test");
	p.ReadUntil("Server host (host only)");Z; p.Write("127.0.0.1");
	p.ReadUntil("Server uses SSL?");Z;        p.Write();
	p.ReadUntil("6667");Z;                    p.Write();
	p.ReadUntil("password");Z;                p.Write();
	p.ReadUntil("channels");Z;                p.Write("#znc");
	p.ReadUntil("Launch ZNC now?");Z;         p.Write("no");
	p.ShouldFinishItself();
}

TEST(ZNC, ConfigAlreadyExists) {
	QTemporaryDir dir;
	WriteConfig(dir.path());Z;
	Process p("./znc", QStringList() << "--debug" << "--datadir" << dir.path() << "--makeconf", true);
	p.ReadUntil("already exists");Z;
}

TEST(ZNC, Connect) {
	QTemporaryDir dir;
	WriteConfig(dir.path());Z;

	QTcpServer ser;
	ASSERT_TRUE(ser.listen(QHostAddress::LocalHost, 6667)) << ser.errorString().toStdString();

	Process znc("./znc", QStringList() << "--debug" << "--datadir" << dir.path(), false);

	ASSERT_TRUE(ser.waitForNewConnection(30000 /* msec */));
	auto ircd = WrapIO(ser.nextPendingConnection());
	ircd.ReadUntil("CAP LS");Z;

	QTcpSocket cli;
	cli.connectToHost("127.0.0.1", 12345);
	ASSERT_TRUE(cli.waitForConnected()) << cli.errorString().toStdString();
	auto cl = WrapIO(&cli);
	cl.Write("PASS :hunter2");
	cl.Write("NICK nick");
	cl.Write("USER user/test x x :x");
	cl.ReadUntil("Welcome");Z;
}

}  // namespace
<commit_msg>Test: extract some building blocks to make future tests easier<commit_after>/*
 * Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include <QDateTime>
#include <QProcess>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTemporaryDir>
#include <QTextStream>

#include <memory>

#define Z do { if (::testing::Test::HasFatalFailure()) { std::cerr << "At: " << __FILE__ << ":" << __LINE__ << std::endl; return; } } while (0)

namespace {

template <typename Device>
class IO {
public:
	IO(Device* device, bool verbose = false) : m_device(device), m_verbose(verbose) {}
	virtual ~IO() {}
	void ReadUntil(QByteArray pattern) {
		auto deadline = QDateTime::currentDateTime().addSecs(30);
		while (true) {
			int search = m_readed.indexOf(pattern);
			if (search != -1) {
				m_readed.remove(0, search + pattern.length());
				return;
			}
			if (m_readed.length() > pattern.length()) {
				m_readed = m_readed.right(pattern.length());
			}
			const int timeout_ms = QDateTime::currentDateTime().msecsTo(deadline);
			ASSERT_GT(timeout_ms, 0) << "Wanted:" << pattern.toStdString();
			ASSERT_TRUE(m_device->waitForReadyRead(timeout_ms)) << "Wanted: " << pattern.toStdString();
			QByteArray chunk = m_device->readAll();
			if (m_verbose) {
				std::cout << chunk.toStdString() << std::flush;
			}
			m_readed += chunk;
		}
	}
	void Write(QString s = "") {
		s += "\n";
		if (m_verbose) {
			std::cout << s.toStdString() << std::flush;
		}
		{
			QTextStream str(m_device);
			str << s;
		}
		FlushIfCan(m_device);
	}

private:
	// QTextStream doesn't flush QTcpSocket, and QIODevice doesn't have flush() at all...
	static void FlushIfCan(QIODevice*) {}
	static void FlushIfCan(QTcpSocket* sock) {
		sock->flush();
	}

	Device* m_device;
	bool m_verbose;
	QByteArray m_readed;
};

template <typename Device>
IO<Device> WrapIO(Device* d) {
	return IO<Device>(d);
}

class Process : public IO<QProcess> {
public:
	Process(QString cmd, QStringList args, bool interactive) : IO(&m_proc, true) {
		if (!interactive) {
			m_proc.setProcessChannelMode(QProcess::ForwardedChannels);
		}
		m_proc.start(cmd, args);
	}
	~Process() {
		if (m_kill) m_proc.terminate();
		[this]() { ASSERT_TRUE(m_proc.waitForFinished()); }();
	}
	void ShouldFinishItself() {
		m_kill = false;
	}

private:
	bool m_kill = true;
	QProcess m_proc;
};

void WriteConfig(QString path) {
	Process p("./znc", QStringList() << "--debug" << "--datadir" << path << "--makeconf", true);
	p.ReadUntil("Listen on port");Z;          p.Write("12345");
	p.ReadUntil("Listen using SSL");Z;        p.Write();
	p.ReadUntil("IPv6");Z;                    p.Write();
	p.ReadUntil("Username");Z;                p.Write("user");
	p.ReadUntil("password");Z;                p.Write("hunter2");
	p.ReadUntil("Confirm");Z;                 p.Write("hunter2");
	p.ReadUntil("Nick [user]");Z;             p.Write();
	p.ReadUntil("Alternate nick [user_]");Z;  p.Write();
	p.ReadUntil("Ident [user]");Z;            p.Write();
	p.ReadUntil("Real name");Z;               p.Write();
	p.ReadUntil("Bind host");Z;               p.Write();
	p.ReadUntil("Set up a network?");Z;       p.Write();
	p.ReadUntil("Name [freenode]");Z;         p.Write("test");
	p.ReadUntil("Server host (host only)");Z; p.Write("127.0.0.1");
	p.ReadUntil("Server uses SSL?");Z;        p.Write();
	p.ReadUntil("6667");Z;                    p.Write();
	p.ReadUntil("password");Z;                p.Write();
	p.ReadUntil("channels");Z;                p.Write("#znc");
	p.ReadUntil("Launch ZNC now?");Z;         p.Write("no");
	p.ShouldFinishItself();
}

TEST(Config, AlreadyExists) {
	QTemporaryDir dir;
	WriteConfig(dir.path());Z;
	Process p("./znc", QStringList() << "--debug" << "--datadir" << dir.path() << "--makeconf", true);
	p.ReadUntil("already exists");Z;
}

class ZNCTest : public testing::Test {
protected:
	void SetUp() override {
		WriteConfig(m_dir.path());Z;
		ASSERT_TRUE(m_server.listen(QHostAddress::LocalHost, 6667)) << m_server.errorString().toStdString();Z;
	}

	IO<QTcpSocket> ConnectIRCd() {
		[this]{ ASSERT_TRUE(m_server.waitForNewConnection(30000 /* msec */)); }();
		return WrapIO(m_server.nextPendingConnection());
	}

	IO<QTcpSocket> ConnectClient() {
		m_clients.emplace_back();
		QTcpSocket& sock = m_clients.back();
		sock.connectToHost("127.0.0.1", 12345);
		[&]{ ASSERT_TRUE(sock.waitForConnected()) << sock.errorString().toStdString(); }();
		return WrapIO(&sock);
	}

	std::unique_ptr<Process> Run() {
		return std::unique_ptr<Process>(new Process("./znc", QStringList() << "--debug" << "--datadir" << m_dir.path(), false));
	}

	QTemporaryDir m_dir;
	QTcpServer m_server;
	std::list<QTcpSocket> m_clients;
};

TEST_F(ZNCTest, Connect) {
	auto znc = Run();Z;

	auto ircd = ConnectIRCd();Z;
	ircd.ReadUntil("CAP LS");Z;

	auto client = ConnectClient();Z;
	client.Write("PASS :hunter2");
	client.Write("NICK nick");
	client.Write("USER user/test x x :x");
	client.ReadUntil("Welcome");Z;
}

}  // namespace
<|endoftext|>


<commit_before>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}
void ClassUI::run()
{
    cout << "\t" << "Welcome to the Amazing Database! " << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "\t" << "   *** Quote of the day ***" << endl;
    cout << getQuotes() << endl;
    mainMenu();
}
void ClassUI::mainMenu()
{
    string choice;
    do
    {
        cout << "--------------------------------------------------------------" << endl;
        cout << " (1) - " << "\t" << "Add a person to the database." << endl;
        cout << " (2) - " << "\t" << "Remove a person from the database." << endl;
        cout << " (3) - " << "\t" << "View the entire database." << endl;
        cout << " (4) - " << "\t" << "Save the database." << endl;
        cout << " (5) - " << "\t" << "Search the database." << endl;
        cout << " (6) - " << "\t" << "Sort the database." << endl;
        cout << " (7) - " << "\t" << "Exit." << endl;
        cout << "Enter your command (1 - 7): ";
        cin >> choice;
        cout << endl;

        if (choice != "7")
        {
           select(choice);
        }
        else
        {
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}
void ClassUI::select(string ch)
{
    if(ch == "1")
    {
        addPerson();
    }
    else if(ch == "2")
    {
        remove();
    }
    else if(ch == "3")
    {
        viewAll();
    }
    else if(ch == "4")
    {
        save();
    }
    else if(ch == "5")
    {
        searching();
    }
        else if(ch == "6")
    {
        sorting();
    }
    else if(ch == "yo")
    {
        yo();
    }
    else
    {
        cout << "Invalid input. Please enter a number between 1 - 7." << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);

    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;
    cout << list.getName(i);

    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }

    cout  << "|" << list.getBirth(i);

    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}
void ClassUI::searching()
{

    cout << "-------------Select any of the following commands-------------" << endl;
    cout << "What do you want to search for? (1 - 4)" << endl;
    cout << " (1) - Searches for a name." << endl;
    cout << " (2) - Searches for a Gender." << endl;
    cout << " (3) - Searches for a year born." << endl;
    cout << " (4) - Return to main menu" << endl;

    search();
}
void ClassUI::addPerson()
{
    string name;
    string comment;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;

    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }

    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n) ";
       cin >> yesOrNo;

       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
       cout << "Input a comment about the individual: ";
       cin.ignore();
       std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }

    cout << "Are you sure that you want to add this person? (y/n) ";
    string validatePerson;
    cin >> validatePerson;

    if(validatePerson == "y")
    {
        cout << "New person added!" << endl;
        list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);
    }
    else
    {
        cout << "Person not added!" << endl;
    }
}
void ClassUI::search()
{
    string searchChoice;
    cout << "Enter your command (1 - 4): ";
    cin >> searchChoice;
    cout << endl;

    if (searchChoice == "1")
    {
        string namesearch;
        cout << "Enter a name you want to search for: ";
        cin.ignore();
        std::getline(std::cin,namesearch);

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            std::size_t found = list.getName(i).find(namesearch);
            if (found!=std::string::npos)
            {
                view(i);
            }
        }

        if(list.nameSearcher(namesearch) == false)
        {
            cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "2")
    {
        char gendersearch;

        cout << "Enter a gender you want to search for: (M/F)";
        cin >> gendersearch;

        if(gendersearch == 'm')
            {
                 gendersearch = 'M';
            }
        else if (gendersearch == 'f')
            {
                 gendersearch = 'F';
            }

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            if(gendersearch == list.getGender(i))
            {
                gendersearch = list.getGender(i);
                view(i);
            }
        }

        if(list.genderSearcher(gendersearch) == false)
        {
            cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "3")
    {
            int yearsearch;
            cout << "Enter a year you want to search for: ";
            cin >> yearsearch;

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(yearsearch == list.getBirth(i))
                {
                    yearsearch = list.getBirth(i);
                    view(i);
                }
            }

            if(list.yearSearcher(yearsearch) == false)
            {
                cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
    }
    else if (searchChoice == "4")
    {
        mainMenu();
    }
    else
    {
        cout << "Error reading input. Please enter a number between 1- 3." << endl;
        search();
    }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter the full name of the person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);

    if (list.removePersonFound(name) == true)
    {
        char validateRemove;
        cout << "Person found!" << endl;
        cout << "Are you sure you want to remove this person? (y/n): ";
        cin >> validateRemove;

        if(validateRemove == 'y' || validateRemove == 'Y')
        {
            if(list.removePerson(name) == true)
            {
                cout << "Person removed!" << endl;
            }
            else
            {
                cout << "Person not removed!" << endl;
            }
        }
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
    cout << "Database saved." << endl;
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}
string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
void ClassUI::sorting()
{
    string sortcho;
    cout << "Enter a sort command (1 - 4):" << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << " (1) - Sort by alphabetical order" << endl;
    cout << " (2) - Sort by chronological order" << endl;
    cout << " (3) - Sort by gender" << endl;
    cout << " (4) - Return to main menu" << endl;
    cout << "Enter your command (1 - 4): ";
    cin >> sortcho;
    cout << endl;

    if(sortcho == "1")
    {
        list.sortNames();
         viewAll();
    }
    else if(sortcho == "2")
    {
        list.sortBirth();
         viewAll();
    }
    else if(sortcho == "3")
    {
        list.sortGender();
        viewAll();
    }
    else if(sortcho == "4")
    {
        mainMenu();
    }
}
<commit_msg>litlarbreytingar<commit_after>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>

using namespace std;

ClassUI::ClassUI()
{

}
void ClassUI::run()
{
    cout << "\t" << "Welcome to the Amazing Database! " << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "\t" << "   *** Quote of the day ***" << endl;
    cout << getQuotes() << endl;
    mainMenu();
}
void ClassUI::mainMenu()
{
    string choice;
    do
    {
        cout << "--------------------------------------------------------------" << endl;
        cout << " (1) - "  << "Add a person to the database." << endl;
        cout << " (2) - "  << "Remove a person from the database." << endl;
        cout << " (3) - "  << "View the entire database." << endl;
        cout << " (4) - "  << "Save the database." << endl;
        cout << " (5) - "  << "Search the database." << endl;
        cout << " (6) - "  << "Sort the database." << endl;
        cout << " (7) - "  << "Exit." << endl;
        cout << "Enter your command (1 - 7): ";
        cin >> choice;
        cout << endl;

        if (choice != "7")
        {
           select(choice);
        }
        else
        {
            list.saveFile();
            runOn = false;
        }
    }while(runOn == true);
}
void ClassUI::select(string ch)
{
    if(ch == "1")
    {
        addPerson();
    }
    else if(ch == "2")
    {
        remove();
    }
    else if(ch == "3")
    {
        viewAll();
    }
    else if(ch == "4")
    {
        save();
    }
    else if(ch == "5")
    {
        searching();
    }
        else if(ch == "6")
    {
        sorting();
    }
    else if(ch == "yo")
    {
        yo();
    }
    else
    {
        cout << "Invalid input. Please enter a number between 1 - 7." << endl;
    }
}
void ClassUI::view(int i)
{
    int nameSize  = list.getNameSize(i);

    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl;
    cout << "--------------------------------|-------|-------|-------------" << endl;
    cout << list.getName(i);

    if(nameSize > 0 && nameSize <= 7)
    {
        cout << "\t" << "\t" << "\t" << "\t";
    }
    else if(nameSize > 7 && nameSize <= 15)
    {
        cout << "\t" << "\t" << "\t";
    }
    else if(nameSize > 15 && nameSize <= 23)
    {
        cout << "\t" << "\t";
    }
    else if(nameSize > 23 && nameSize <= 31)
    {
        cout << "\t";
    }

    if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
    {
        cout << "|Male" << "\t";
    }
    else
    {
        cout << "|Female" << "\t";
    }

    cout  << "|" << list.getBirth(i);

    if(list.getDeath(i) == 0)
    {
        cout << "\t" << "| n/a"  << endl;
    }
    else
    {
        cout << "\t" << "|" << list.getDeath(i)  << endl;
    }
    cout << list.getComment(i) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
}
void ClassUI::searching()
{

    cout << "-------------Select any of the following commands-------------" << endl;
    cout << "What do you want to search for? (1 - 4)" << endl;
    cout << " (1) - Searches for a name." << endl;
    cout << " (2) - Searches for a Gender." << endl;
    cout << " (3) - Searches for a year born." << endl;
    cout << " (4) - Return to main menu" << endl;

    search();
}
void ClassUI::addPerson()
{
    string name;
    string comment;
    char gender;
    char yesOrNo;
    int yearOfBirth = 0;
    int yearOfDeath = 0;

    cout << "Input Name: ";
    cin.ignore();
    std::getline(std::cin,name);
    cout << "Input gender (M/F): ";
    cin >> gender;

    if (gender == 'm')
    {
        gender = 'M';
    }
    else if (gender == 'f')
    {
        gender = 'F';
    }

    if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
    {
       cout << "Input year of birth: ";
       cin >> yearOfBirth;

       cout << "Is the individual deceased? (y/n) ";
       cin >> yesOrNo;

       if (yesOrNo == 'Y' || yesOrNo == 'y')
       {
            cout << "Input year of death: ";
            cin >> yearOfDeath;
       }
       cout << "Input a comment about the individual: ";
       cin.ignore();
       std::getline(std::cin,comment);
    }
    else
    {
        cout << "Invalid gender! Try again." << endl;
        addPerson();
    }

    cout << "Are you sure that you want to add this person? (y/n) ";
    string validatePerson;
    cin >> validatePerson;

    if(validatePerson == "y")
    {
        cout << "New person added!" << endl;
        list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);
    }
    else
    {
        cout << "Person not added!" << endl;
    }
}
void ClassUI::search()
{
    string searchChoice;
    cout << "Enter your command (1 - 4): ";
    cin >> searchChoice;
    cout << endl;

    if (searchChoice == "1")
    {
        string namesearch;
        cout << "Enter a name you want to search for: ";
        cin.ignore();
        std::getline(std::cin,namesearch);

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            std::size_t found = list.getName(i).find(namesearch);
            if (found!=std::string::npos)
            {
                view(i);
            }
        }

        if(list.nameSearcher(namesearch) == false)
        {
            cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "2")
    {
        char gendersearch;

        cout << "Enter a gender you want to search for: (M/F)";
        cin >> gendersearch;

        if(gendersearch == 'm')
            {
                 gendersearch = 'M';
            }
        else if (gendersearch == 'f')
            {
                 gendersearch = 'F';
            }

        for(int i = 0; i < list.getPersonsSize();++i)
        {
            if(gendersearch == list.getGender(i))
            {
                gendersearch = list.getGender(i);
                view(i);
            }
        }

        if(list.genderSearcher(gendersearch) == false)
        {
            cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
            searching();
        }
    }
    else if (searchChoice == "3")
    {
            int yearsearch;
            cout << "Enter a year you want to search for: ";
            cin >> yearsearch;

            for(int i = 0; i < list.getPersonsSize();++i)
            {
                if(yearsearch == list.getBirth(i))
                {
                    yearsearch = list.getBirth(i);
                    view(i);
                }
            }

            if(list.yearSearcher(yearsearch) == false)
            {
                cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu." << endl;
                searching();
            }
    }
    else if (searchChoice == "4")
    {
        mainMenu();
    }
    else
    {
        cout << "Error reading input. Please enter a number between 1- 3." << endl;
        search();
    }
}
void ClassUI::remove()
{
    string name;
    cout << "Enter the full name of the person that you want to remove: ";
    cin.ignore();
    std::getline(std::cin,name);

    if (list.removePersonFound(name) == true)
    {
        char validateRemove;
        cout << "Person found!" << endl;
        cout << "Are you sure you want to remove this person? (y/n): ";
        cin >> validateRemove;

        if(validateRemove == 'y' || validateRemove == 'Y')
        {
            if(list.removePerson(name) == true)
            {
                cout << "Person removed!" << endl;
            }
            else
            {
                cout << "Person not removed!" << endl;
            }
        }
    }
    else
    {
        cout << "Person not found!" << endl;
    }
}
void ClassUI::save()
{
    list.saveFile();
    cout << "Database saved." << endl;
}
void ClassUI::viewAll()
{
    for(int i = 0; i < list.getPersonsSize(); i++)
    {
        view(i);
    }
}
void ClassUI::yo()
{
    cout << endl;
    cout << "`8.`8888.      ,8'     ,o888888o.     " << endl;
    cout << " `8.`8888.    ,8'   . 8888     `88.   " << endl;
    cout << "  `8.`8888.  ,8'   ,8 8888       `8b  " << endl;
    cout << "   `8.`8888.,8'    88 8888        `8b " << endl;
    cout << "    `8.`88888'     88 8888         88 " << endl;
    cout << "     `8. 8888      88 8888         88 " << endl;
    cout << "      `8 8888      88 8888        ,8P " << endl;
    cout << "       8 8888      `8 8888       ,8P  " << endl;
    cout << "       8 8888       ` 8888     ,88'   " << endl;
    cout << "       8 8888          `8888888P'     " << endl;
    cout << endl;
}
string ClassUI::getQuotes()
{
    string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
                        "\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
                        "\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
                        "\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
                        "\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
                       };
    int v1 = 0;
    srand (time(NULL));
    v1 = rand() % 5;
    return quotes[v1];
}
void ClassUI::sorting()
{
    string sortcho;
    cout << "Enter a sort command (1 - 4):" << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << " (1) - Sort by alphabetical order" << endl;
    cout << " (2) - Sort by chronological order" << endl;
    cout << " (3) - Sort by gender" << endl;
    cout << " (4) - Return to main menu" << endl;
    cout << "Enter your command (1 - 4): ";
    cin >> sortcho;
    cout << endl;

    if(sortcho == "1")
    {
        list.sortNames();
         viewAll();
    }
    else if(sortcho == "2")
    {
        list.sortBirth();
         viewAll();
    }
    else if(sortcho == "3")
    {
        list.sortGender();
        viewAll();
    }
    else if(sortcho == "4")
    {
        mainMenu();
    }
}
<|endoftext|>