<commit_before>void PlotPressure()
{
    FILE* file;
    file=fopen("gasPressure.dat","r");
    Float_t z1[20];
    Float_t g1[20], g2[20], g3[20], g4[20], g5[20];
    Float_t z2[21];
    Float_t h1[21], h2[21], h3[21], h4[21], h5[21];

    char c[45];
    Float_t z;

    for (Int_t i = 0; i < 20; i++)
    {
	fscanf(file, "%f %f %f %f %f %f", &z,
	       &g1[i], &g2[i], &g3[i], &g4[i], &g5[i]);
//	printf("%d %f %f %f %f %f %f \n", i, z1[i],
//		       g1[i][0], g1[i][1], g1[i][2], g1[i][3], g1[i][4]);
	if (i > 0) {
	    z1[i] = z1[i-1] + z;
	} else {
	    z1[i] = 20.;
	}
    }

    for (Int_t i = 0; i < 21; i++)
    {
	fscanf(file, "%f %f %f %f %f %f", &z,
	       &h1[i], &h2[i], &h3[i], &h4[i], &h5[i]);
	if (i > 0) {
	    z2[i] = z2[i-1] + z;
	} else {
	    z2[i] = 20.;
	}
    }

//
//
    TCanvas *c1 = new TCanvas("c1","Gas Pressure Beam 1", 200, 10, 700, 500);
    gPad->SetLogy();

    TGraph* gr1  = new TGraph(20, z1, g1);
    gr1->SetMaximum(1e17);
    gr1->SetMinimum(1e11);
    gr1->SetLineColor(1);
    gr1->SetTitle("Ring 1: Beginning of Run");

    TGraph* gr2  = new TGraph(20, z1, g3);
    gr2->SetLineColor(2);

    TGraph* gr3  = new TGraph(20, z1, g5);
    gr3->SetLineColor(4);

    gr1->Draw("AL");
    gr2->Draw("L");
//    gr3->Draw("L");
    text();

//
//
    TCanvas *c2 = new TCanvas("c2","Gas Pressure Beam 1", 200, 10, 700, 500);
    gPad->SetLogy();

    TGraph* gr4  = new TGraph(20, z1, g2);
    gr4->SetMaximum(1e17);
    gr4->SetMinimum(1e11);
    gr4->SetLineColor(1);
    gr4->SetTitle("Ring 1");

    TGraph* gr5  = new TGraph(20, z1, g4);
    gr5->SetLineColor(2);

    TGraph* gr6  = new TGraph(20, z1, g5);
    gr6->SetLineColor(4);

    gr4->Draw("AL");
    gr5->Draw("L");
    gr6->Draw("L");
    text();

//
//
    TCanvas *c3 = new TCanvas("c3","Gas Pressure Beam 2", 200, 10, 700, 500);
    gPad->SetLogy();

    TGraph* hr1  = new TGraph(21, z2, h1);
    hr1->SetMaximum(1e17);
    hr1->SetMinimum(1e11);
    hr1->SetLineColor(1);
    hr1->SetTitle("Ring 2: Beginning of Run");

    TGraph* hr2  = new TGraph(21, z2, h3);
    hr2->SetLineColor(2);

    TGraph* hr3  = new TGraph(21, z2, h5);
    hr3->SetLineColor(4);

    hr1->Draw("AL");
    hr2->Draw("L");
//    hr3->Draw("L");
    text();

//
//
    TCanvas *c4 = new TCanvas("c4","Gas Pressure Beam 2", 200, 10, 700, 500);
    gPad->SetLogy();

    TGraph* hr4  = new TGraph(21, z2, h2);
    hr4->SetMaximum(1e17);
    hr4->SetMinimum(1e11);
    hr4->SetLineColor(1);
    hr4->SetTitle("Ring 2");

    TGraph* hr5  = new TGraph(21, z2, h4);
    hr5->SetLineColor(2);

    TGraph* hr6  = new TGraph(21, z2, h5);
    hr6->SetLineColor(4);

    hr4->Draw("AL");
    hr5->Draw("L");
    hr6->Draw("L");
    text();

}

void text()
{

    TPave *pave = new TPave(194.619,11.0495,293.103,12.6485,4,"br");
    pave->SetFillColor(18);
    pave->Draw();
    TLine *line = new TLine(199.702,11.8109,232.106,11.8109);
    line->SetLineColor(2);
    line->Draw();
    line = new TLine(198.431,12.2868,232.106,12.2868);
    line->Draw();
    line = new TLine(199.066,11.3731,232.742,11.3731);
    line->SetLineColor(4);
    line->Draw();
    line = new TLine(215.586,13.3338,215.586,13.3147);
    line->Draw();
    tex = new TLatex(239.096,11.6777,"2nd year");
    tex->SetTextSize(0.05);
    tex->SetLineWidth(2);
    tex->Draw();
    tex = new TLatex(236.554,12.1536,"1st year");
    tex->SetTextSize(0.0507614);
    tex->SetLineWidth(2);
    tex->Draw();
    tex = new TLatex(239.096,11.2589,"3rd year");
    tex->SetTextSize(0.05);
    tex->SetLineWidth(2);
    tex->Draw();
    c1->Modified();
    c1->cd();
}
<commit_msg>Example for interaction rate calculation added.<commit_after>void PlotPressure()
{
    FILE* file;
    file=fopen("gasPressure.dat","r");
    Float_t z1[20];
    Float_t g1[20], g2[20], g3[20], g4[20], g5[20];
    Float_t z2[21];
    Float_t h1[21], h2[21], h3[21], h4[21], h5[21];

    char c[45];
    Float_t z;

    for (Int_t i = 0; i < 20; i++)
    {
	fscanf(file, "%f %f %f %f %f %f", &z,
	       &g1[i], &g2[i], &g3[i], &g4[i], &g5[i]);
//	printf("%d %f %f %f %f %f %f \n", i, z1[i],
//		       g1[i][0], g1[i][1], g1[i][2], g1[i][3], g1[i][4]);
	if (i > 0) {
	    z1[i] = z1[i-1] + z;
	} else {
	    z1[i] = 20.;
	}
    }

    for (Int_t i = 0; i < 21; i++)
    {
	fscanf(file, "%f %f %f %f %f %f", &z,
	       &h1[i], &h2[i], &h3[i], &h4[i], &h5[i]);
	if (i > 0) {
	    z2[i] = z2[i-1] + z;
	} else {
	    z2[i] = 20.;
	}
    }

//
//
    TCanvas *c1 = new TCanvas("c1","Gas Pressure Beam 1", 200, 10, 700, 500);
    gPad->SetLogy();

    TGraph* gr1  = new TGraph(20, z1, g1);
    gr1->SetMaximum(1e17);
    gr1->SetMinimum(1e11);
    gr1->SetLineColor(1);
    gr1->SetTitle("Ring 1: Beginning of Run");

    TGraph* gr2  = new TGraph(20, z1, g3);
    gr2->SetLineColor(2);

    TGraph* gr3  = new TGraph(20, z1, g5);
    gr3->SetLineColor(4);

    gr1->Draw("AL");
    gr2->Draw("L");
//    gr3->Draw("L");
    text();

//
//
    TCanvas *c2 = new TCanvas("c2","Gas Pressure Beam 1", 200, 10, 700, 500);
    gPad->SetLogy();

    TGraph* gr4  = new TGraph(20, z1, g2);
    gr4->SetMaximum(1e17);
    gr4->SetMinimum(1e11);
    gr4->SetLineColor(1);
    gr4->SetTitle("Ring 1");

    TGraph* gr5  = new TGraph(20, z1, g4);
    gr5->SetLineColor(2);

    TGraph* gr6  = new TGraph(20, z1, g5);
    gr6->SetLineColor(4);

    gr4->Draw("AL");
    gr5->Draw("L");
    gr6->Draw("L");
    text();

//
//
    TCanvas *c3 = new TCanvas("c3","Gas Pressure Beam 2", 200, 10, 700, 500);
    gPad->SetLogy();

    TGraph* hr1  = new TGraph(21, z2, h1);
    hr1->SetMaximum(1e17);
    hr1->SetMinimum(1e11);
    hr1->SetLineColor(1);
    hr1->SetTitle("Ring 2: Beginning of Run");

    TGraph* hr2  = new TGraph(21, z2, h3);
    hr2->SetLineColor(2);

    TGraph* hr3  = new TGraph(21, z2, h5);
    hr3->SetLineColor(4);

    hr1->Draw("AL");
    hr2->Draw("L");
//    hr3->Draw("L");
    text();

//
//
    TCanvas *c4 = new TCanvas("c4","Gas Pressure Beam 2", 200, 10, 700, 500);
    gPad->SetLogy();

    TGraph* hr4  = new TGraph(21, z2, h2);
    hr4->SetMaximum(1e17);
    hr4->SetMinimum(1e11);
    hr4->SetLineColor(1);
    hr4->SetTitle("Ring 2");

    TGraph* hr5  = new TGraph(21, z2, h4);
    hr5->SetLineColor(2);

    TGraph* hr6  = new TGraph(21, z2, h5);
    hr6->SetLineColor(4);

    hr4->Draw("AL");
    hr5->Draw("L");
    hr6->Draw("L");
    text();
//
// One example of interaction rate calculation
//
// 3rd year, full intensity
//
    Float_t r[20];
    const Float_t crossSection = 0.094e-28;   //  m^2
    const Float_t pFlux        = 1.e11/25.e-9; // 1/s

    for (Int_t i= 0; i < 20; i++)
    {
	r[i] =  g5[i] * crossSection * pFlux; // 1/m/s
    }

    TCanvas *c5 = new TCanvas("c5","Interaction Rate Beam 1, 3rd year", 200, 10, 700, 500);
    gPad->SetLogy();

    TGraph* rr1  = new TGraph(20, z1, r);
    rr1->SetMaximum(1e6);
    rr1->SetMinimum(1e1);
    rr1->SetLineColor(4);
    rr1->SetTitle("Ring 1");
    rr1->Draw("AL");
}

void text()
{

    TPave *pave = new TPave(194.619,11.0495,293.103,12.6485,4,"br");
    pave->SetFillColor(18);
    pave->Draw();
    TLine *line = new TLine(199.702,11.8109,232.106,11.8109);
    line->SetLineColor(2);
    line->Draw();
    line = new TLine(198.431,12.2868,232.106,12.2868);
    line->Draw();
    line = new TLine(199.066,11.3731,232.742,11.3731);
    line->SetLineColor(4);
    line->Draw();
    line = new TLine(215.586,13.3338,215.586,13.3147);
    line->Draw();
    tex = new TLatex(239.096,11.6777,"2nd year");
    tex->SetTextSize(0.05);
    tex->SetLineWidth(2);
    tex->Draw();
    tex = new TLatex(236.554,12.1536,"1st year");
    tex->SetTextSize(0.0507614);
    tex->SetLineWidth(2);
    tex->Draw();
    tex = new TLatex(239.096,11.2589,"3rd year");
    tex->SetTextSize(0.05);
    tex->SetLineWidth(2);
    tex->Draw();
    c1->Modified();
    c1->cd();
}
<|endoftext|>


<commit_before>/* Copyright 2014 CyberTech Labs Ltd.
 *
 * 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 "wiFiModeWidget.h"

#include <QtGui/QKeyEvent>

#include <trikKernel/paths.h>
#include <QsLog.h>

#include "wiFiClientWidget.h"
#include "wiFiAPWidget.h"
#include "wiFiInitWidget.h"

using namespace trikGui;

WiFiModeWidget::WiFiModeWidget(trikWiFi::TrikWiFi &wiFi, QWidget *parent)
	: TrikGuiDialog(parent)
	, mWiFi(wiFi)
	, mRcReader(trikKernel::Paths::trikRcName())
	, mTitle(tr("Choose mode:"))
{
	mModes.addItem(tr("Wi-Fi client"));
	mModes.addItem(tr("Wi-Fi access point"));

	mLayout.addWidget(&mTitle);
	mLayout.addWidget(&mModes);
	setLayout(&mLayout);

	mModes.selectionModel()->select(
			mModes.model()->index(0, 0)
			, QItemSelectionModel::ClearAndSelect
			);
}

QString WiFiModeWidget::menuEntry()
{
	return tr("Network Config");
}

void WiFiModeWidget::renewFocus()
{
	mModes.setFocus();
}

void WiFiModeWidget::keyPressEvent(QKeyEvent *event)
{
	switch (event->key()) {
		case Qt::Key_Return: {
			if (mModes.currentItem()->text() == tr("Wi-Fi client")) {
				setMode(client);
			} else {
				setMode(accessPoint);
			}
			break;
		}
		default: {
			TrikGuiDialog::keyPressEvent(event);
			break;
		}
	}
}

void WiFiModeWidget::setMode(Mode mode)
{
	mRcReader.read();

	const QString currentModeText = mRcReader.value("trik_wifi_mode");

	Mode currentMode = unknown;
	if (currentModeText == "client") {
		currentMode = client;
	} else if (currentModeText == "ap") {
		currentMode = accessPoint;
	}

	if (currentMode != mode) {
		WiFiInitWidget wiFiInitWidget;
		emit newWidget(wiFiInitWidget);
		if (wiFiInitWidget.init(mode) == WiFiInitWidget::fail) {
			QLOG_ERROR() << "Faile on init WiFi widget in mode" << currentModeText;
			return;
		}
	}

	int returnValue = 0;

	switch (mode) {
		case client: {
			if (currentMode != mode) {
				mWiFi.reinit();
			}
			WiFiClientWidget wiFiClientWidget(mWiFi);
			emit newWidget(wiFiClientWidget);
			returnValue = wiFiClientWidget.exec();
			break;
		}
		case accessPoint: {
			mWiFi.dispose();
			WiFiAPWidget wiFiAPWidget;
			emit newWidget(wiFiAPWidget);
			returnValue = wiFiAPWidget.exec();
			break;
		}
		case unknown: {
			QLOG_ERROR() << "Error: unknown WiFi mode in WiFiModeWidget::setMode()";
			break;
		}
	}

	if (returnValue == 1) {
		goHome();
	}
}
<commit_msg>Typo fix<commit_after>/* Copyright 2014 CyberTech Labs Ltd.
 *
 * 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 "wiFiModeWidget.h"

#include <QtGui/QKeyEvent>

#include <trikKernel/paths.h>
#include <QsLog.h>

#include "wiFiClientWidget.h"
#include "wiFiAPWidget.h"
#include "wiFiInitWidget.h"

using namespace trikGui;

WiFiModeWidget::WiFiModeWidget(trikWiFi::TrikWiFi &wiFi, QWidget *parent)
	: TrikGuiDialog(parent)
	, mWiFi(wiFi)
	, mRcReader(trikKernel::Paths::trikRcName())
	, mTitle(tr("Choose mode:"))
{
	mModes.addItem(tr("Wi-Fi client"));
	mModes.addItem(tr("Wi-Fi access point"));

	mLayout.addWidget(&mTitle);
	mLayout.addWidget(&mModes);
	setLayout(&mLayout);

	mModes.selectionModel()->select(
			mModes.model()->index(0, 0)
			, QItemSelectionModel::ClearAndSelect
			);
}

QString WiFiModeWidget::menuEntry()
{
	return tr("Network Config");
}

void WiFiModeWidget::renewFocus()
{
	mModes.setFocus();
}

void WiFiModeWidget::keyPressEvent(QKeyEvent *event)
{
	switch (event->key()) {
		case Qt::Key_Return: {
			if (mModes.currentItem()->text() == tr("Wi-Fi client")) {
				setMode(client);
			} else {
				setMode(accessPoint);
			}
			break;
		}
		default: {
			TrikGuiDialog::keyPressEvent(event);
			break;
		}
	}
}

void WiFiModeWidget::setMode(Mode mode)
{
	mRcReader.read();

	const QString currentModeText = mRcReader.value("trik_wifi_mode");

	Mode currentMode = unknown;
	if (currentModeText == "client") {
		currentMode = client;
	} else if (currentModeText == "ap") {
		currentMode = accessPoint;
	}

	if (currentMode != mode) {
		WiFiInitWidget wiFiInitWidget;
		emit newWidget(wiFiInitWidget);
		if (wiFiInitWidget.init(mode) == WiFiInitWidget::fail) {
			QLOG_ERROR() << "Failed to init WiFi widget in mode" << currentModeText;
			return;
		}
	}

	int returnValue = 0;

	switch (mode) {
		case client: {
			if (currentMode != mode) {
				mWiFi.reinit();
			}
			WiFiClientWidget wiFiClientWidget(mWiFi);
			emit newWidget(wiFiClientWidget);
			returnValue = wiFiClientWidget.exec();
			break;
		}
		case accessPoint: {
			mWiFi.dispose();
			WiFiAPWidget wiFiAPWidget;
			emit newWidget(wiFiAPWidget);
			returnValue = wiFiAPWidget.exec();
			break;
		}
		case unknown: {
			QLOG_ERROR() << "Error: unknown WiFi mode in WiFiModeWidget::setMode()";
			break;
		}
	}

	if (returnValue == 1) {
		goHome();
	}
}
<|endoftext|>


<commit_before>#ifdef HAVE_CXX11
#include <functional>
#define HAVE_CPP_FUNC_PTR
namespace funcptr = std;
#else
#ifdef HAVE_BOOST
#include <boost/function.hpp>
namespace funcptr = boost;
#define HAVE_CPP_FUNC_PTR
#endif
#endif

#include <fstream>
#include <cctype>

#ifndef WIN32
#include <cstdio>
#include <unistd.h>
#endif

#include <algorithm>

#ifndef YAHTTP_MAX_REQUEST_SIZE
#define YAHTTP_MAX_REQUEST_SIZE 2097152
#endif

#ifndef YAHTTP_MAX_RESPONSE_SIZE
#define YAHTTP_MAX_RESPONSE_SIZE 2097152
#endif

#define YAHTTP_TYPE_REQUEST 1
#define YAHTTP_TYPE_RESPONSE 2

namespace YaHTTP {
  typedef std::map<std::string,Cookie,ASCIICINullSafeComparator> strcookie_map_t; //<! String to Cookie map

  typedef enum {
    urlencoded,
    multipart
  } postformat_t; //<! Enumeration of possible post encodings, url encoding or multipart

  /*! Base class for request and response */
  class HTTPBase {
  public:
    /*! Default renderer for request/response, simply copies body to response */
    class SendBodyRender {
    public:
      SendBodyRender() {};

      size_t operator()(const HTTPBase *doc, std::ostream& os, bool chunked) const {
        if (chunked) {
          std::string::size_type i,cl;
          for(i=0;i<doc->body.length();i+=1024) {
            cl = std::min(static_cast<std::string::size_type>(1024), doc->body.length()-i); // for less than 1k blocks
            os << std::hex << cl << std::dec << "\r\n";
            os << doc->body.substr(i, cl) << "\r\n";
          }
          os << 0 << "\r\n\r\n"; // last chunk
        } else {
          os << doc->body;
        }
        return doc->body.length();
      }; //<! writes body to ostream and returns length
    };
    /* Simple sendfile renderer which streams file to ostream */
    class SendFileRender {
    public:
      SendFileRender(const std::string& path_) {
        this->path = path_;
      };

      size_t operator()(const HTTPBase *doc __attribute__((unused)), std::ostream& os, bool chunked) const {
        char buf[4096];
        size_t n,k;
#ifdef HAVE_CXX11
        std::ifstream ifs(path, std::ifstream::binary);
#else
        std::ifstream ifs(path.c_str(), std::ifstream::binary);
#endif
        n = 0;

        while(ifs.good()) {
          ifs.read(buf, sizeof buf);
          n += (k = ifs.gcount());
          if (k > 0) {
            if (chunked) os << std::hex << k << std::dec << "\r\n";
            os.write(buf, k);
            if (chunked) os << "\r\n";
          }
        }
        if (chunked) os << 0 << "\r\n\r\n";
        return n;
      }; //<! writes file to ostream and returns length

      std::string path; //<! File to send
    };

    HTTPBase() {
      initialize();
    };

    virtual void initialize() {
      kind = 0;
      status = 0;
#ifdef HAVE_CPP_FUNC_PTR
      renderer = SendBodyRender();
#endif
      max_request_size = YAHTTP_MAX_REQUEST_SIZE;
      max_response_size = YAHTTP_MAX_RESPONSE_SIZE;
      url = "";
      method = "";
      statusText = "";
      jar.clear();
      headers.clear();
      parameters.clear();
      getvars.clear();
      postvars.clear();
      body = "";
      routeName = "";
      version = 11; // default to version 1.1
      is_multipart = false;
    }
protected:
    HTTPBase(const HTTPBase& rhs) {
      this->url = rhs.url; this->kind = rhs.kind;
      this->status = rhs.status; this->statusText = rhs.statusText;
      this->method = rhs.method; this->headers = rhs.headers;
      this->jar = rhs.jar; this->postvars = rhs.postvars;
      this->parameters = rhs.parameters; this->getvars = rhs.getvars;
      this->body = rhs.body; this->max_request_size = rhs.max_request_size;
      this->max_response_size = rhs.max_response_size; this->version = rhs.version;
#ifdef HAVE_CPP_FUNC_PTR
      this->renderer = rhs.renderer;
#endif
      this->is_multipart = rhs.is_multipart;
    };
    virtual HTTPBase& operator=(const HTTPBase& rhs) {
      this->url = rhs.url; this->kind = rhs.kind;
      this->status = rhs.status; this->statusText = rhs.statusText;
      this->method = rhs.method; this->headers = rhs.headers;
      this->jar = rhs.jar; this->postvars = rhs.postvars;
      this->parameters = rhs.parameters; this->getvars = rhs.getvars;
      this->body = rhs.body; this->max_request_size = rhs.max_request_size;
      this->max_response_size = rhs.max_response_size; this->version = rhs.version;
#ifdef HAVE_CPP_FUNC_PTR
      this->renderer = rhs.renderer;
#endif
      this->is_multipart = rhs.is_multipart;
      return *this;
    };
public:
    URL url; //<! URL of this request/response
    int kind; //<! Type of object (1 = request, 2 = response)
    int status; //<! status code
    int version; //<! http version 9 = 0.9, 10 = 1.0, 11 = 1.1
    std::string statusText; //<! textual representation of status code
    std::string method; //<! http verb
    strstr_map_t headers; //<! map of header(s)
    CookieJar jar; //<! cookies
    strstr_map_t postvars; //<! map of POST variables (from POST body)
    strstr_map_t getvars; //<! map of GET variables (from URL)
// these two are for Router
    strstr_map_t parameters; //<! map of route parameters (only if you use YaHTTP::Router)
    std::string routeName; //<! name of the current route (only if you use YaHTTP::Router)

    std::string body; //<! the actual content

    ssize_t max_request_size; //<! maximum size of request
    ssize_t max_response_size;  //<! maximum size of response
    bool is_multipart; //<! if the request is multipart, prevents Content-Length header
#ifdef HAVE_CPP_FUNC_PTR
    funcptr::function<size_t(const HTTPBase*,std::ostream&,bool)> renderer; //<! rendering function
#endif
    void write(std::ostream& os) const; //<! writes request to the given output stream

    strstr_map_t& GET() { return getvars; }; //<! acccessor for getvars
    strstr_map_t& POST() { return postvars; }; //<! accessor for postvars
    strcookie_map_t& COOKIES() { return jar.cookies; }; //<! accessor for cookies

    std::string versionStr(int version_) const {
      switch(version_) {
      case  9: return "0.9";
      case 10: return "1.0";
      case 11: return "1.1";
      default: throw YaHTTP::Error("Unsupported version");
      }
    };

    std::string str() const {
       std::ostringstream oss;
       write(oss);
       return oss.str();
    }; //<! return string representation of this object
  };

  /*! Response class, represents a HTTP Response document */
  class Response: public HTTPBase {
  public:
    Response() { initialize(); };
    Response(const HTTPBase& rhs): HTTPBase(rhs) {
      this->kind = YAHTTP_TYPE_RESPONSE;
    };
    Response& operator=(const HTTPBase& rhs) {
      HTTPBase::operator=(rhs);
      this->kind = YAHTTP_TYPE_RESPONSE;
      return *this;
    };
    void initialize() {
      HTTPBase::initialize();
      this->kind = YAHTTP_TYPE_RESPONSE;
    }
    void initialize(const HTTPBase& rhs) {
      HTTPBase::initialize();
      this->kind = YAHTTP_TYPE_RESPONSE;
      // copy SOME attributes
      this->url = rhs.url;
      this->method = rhs.method;
      this->jar = rhs.jar;
      this->version = rhs.version;
    }
    friend std::ostream& operator<<(std::ostream& os, const Response &resp);
    friend std::istream& operator>>(std::istream& is, Response &resp);
  };

  /* Request class, represents a HTTP Request document */
  class Request: public HTTPBase {
  public:
    Request() { initialize(); };
    Request(const HTTPBase& rhs): HTTPBase(rhs) {
      this->kind = YAHTTP_TYPE_REQUEST;
    };
    Request& operator=(const HTTPBase& rhs) {
      HTTPBase::operator=(rhs);
      this->kind = YAHTTP_TYPE_REQUEST;
      return *this;
    };
    void initialize() {
      HTTPBase::initialize();
      this->kind = YAHTTP_TYPE_REQUEST;
    }
    void initialize(const HTTPBase& rhs) {
      HTTPBase::initialize();
      this->kind = YAHTTP_TYPE_REQUEST;
      // copy SOME attributes
      this->url = rhs.url;
      this->method = rhs.method;
      this->jar = rhs.jar;
      this->version = rhs.version;
    }
    void setup(const std::string& method_, const std::string& url_) {
      this->url.parse(url_);
      this->headers["host"] = this->url.host;
      this->method = method_;
      std::transform(this->method.begin(), this->method.end(), this->method.begin(), ::toupper);
      this->headers["user-agent"] = "YaHTTP v1.0";
    }; //<! Set some initial things for a request

    void preparePost(postformat_t format = urlencoded) {
      std::ostringstream postbuf;
      if (format == urlencoded) {
        for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {
          postbuf << Utility::encodeURL(i->first, false) << "=" << Utility::encodeURL(i->second, false) << "&";
        }
        // remove last bit
        if (postbuf.str().length()>0)
          body = postbuf.str().substr(0, postbuf.str().length()-1);
        else
          body = "";
        headers["content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
      } else if (format == multipart) {
        headers["content-type"] = "multipart/form-data; boundary=YaHTTP-12ca543";
        this->is_multipart = true;
        for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {
          postbuf << "--YaHTTP-12ca543\r\nContent-Disposition: form-data; name=\"" << Utility::encodeURL(i->first, false) << "\"; charset=UTF-8\r\nContent-Length: " << i->second.size() << "\r\n\r\n"
            << Utility::encodeURL(i->second, false) << "\r\n";
        }
        postbuf << "--";
        body = postbuf.str();
      }

      postbuf.str("");
      postbuf << body.length();
      // set method and change headers
      method = "POST";
      if (!this->is_multipart)
        headers["content-length"] = postbuf.str();
    }; //<! convert all postvars into string and stuff it into body

    friend std::ostream& operator<<(std::ostream& os, const Request &resp);
    friend std::istream& operator>>(std::istream& is, Request &resp);
  };

  /*! Asynchronous HTTP document loader */
  template <class T>
  class AsyncLoader {
  public:
    T* target; //<! target to populate
    int state; //<! reader state
    size_t pos; //<! reader position

    std::string buffer; //<! read buffer
    bool chunked; //<! whether we are parsing chunked data
    int chunk_size; //<! expected size of next chunk
    std::ostringstream bodybuf; //<! buffer for body
    size_t maxbody; //<! maximum size of body
    size_t minbody; //<! minimum size of body
    bool hasBody; //<! are we expecting body

    void keyValuePair(const std::string &keyvalue, std::string &key, std::string &value); //<! key value pair parser helper

    void initialize(T* target_) {
      chunked = false; chunk_size = 0;
      bodybuf.str(""); minbody = 0; maxbody = 0;
      pos = 0; state = 0; this->target = target_;
      hasBody = false;
      buffer = "";
      this->target->initialize();
    }; //<! Initialize the parser for target and clear state
    bool feed(const std::string& somedata); //<! Feed data to the parser
    bool ready() {
     return (chunked == true && state == 3) || // if it's chunked we get end of data indication
             (chunked == false && state > 1 &&
               (!hasBody ||
                 (bodybuf.str().size() <= maxbody &&
                  bodybuf.str().size() >= minbody)
               )
             );
    }; //<! whether we have received enough data
    void finalize() {
      bodybuf.flush();
      if (ready()) {
        strstr_map_t::iterator cpos = target->headers.find("content-type");
        if (cpos != target->headers.end() && Utility::iequals(cpos->second, "application/x-www-form-urlencoded", 32)) {
          target->postvars = Utility::parseUrlParameters(bodybuf.str());
        }
        target->body = bodybuf.str();
      }
      bodybuf.str("");
      this->target = NULL;
    }; //<! finalize and release target
  };

  /*! Asynchronous HTTP response loader */
  class AsyncResponseLoader: public AsyncLoader<Response> {
  };

  /*! Asynchronous HTTP request loader */
  class AsyncRequestLoader: public AsyncLoader<Request> {
  };

};
<commit_msg>reqresp.hpp: Use override keyword<commit_after>#ifdef HAVE_CXX11
#include <functional>
#define HAVE_CPP_FUNC_PTR
namespace funcptr = std;
#else
#ifdef HAVE_BOOST
#include <boost/function.hpp>
namespace funcptr = boost;
#define HAVE_CPP_FUNC_PTR
#endif
#endif

#include <fstream>
#include <cctype>

#ifndef WIN32
#include <cstdio>
#include <unistd.h>
#endif

#include <algorithm>

#ifndef YAHTTP_MAX_REQUEST_SIZE
#define YAHTTP_MAX_REQUEST_SIZE 2097152
#endif

#ifndef YAHTTP_MAX_RESPONSE_SIZE
#define YAHTTP_MAX_RESPONSE_SIZE 2097152
#endif

#define YAHTTP_TYPE_REQUEST 1
#define YAHTTP_TYPE_RESPONSE 2

namespace YaHTTP {
  typedef std::map<std::string,Cookie,ASCIICINullSafeComparator> strcookie_map_t; //<! String to Cookie map

  typedef enum {
    urlencoded,
    multipart
  } postformat_t; //<! Enumeration of possible post encodings, url encoding or multipart

  /*! Base class for request and response */
  class HTTPBase {
  public:
    /*! Default renderer for request/response, simply copies body to response */
    class SendBodyRender {
    public:
      SendBodyRender() {};

      size_t operator()(const HTTPBase *doc, std::ostream& os, bool chunked) const {
        if (chunked) {
          std::string::size_type i,cl;
          for(i=0;i<doc->body.length();i+=1024) {
            cl = std::min(static_cast<std::string::size_type>(1024), doc->body.length()-i); // for less than 1k blocks
            os << std::hex << cl << std::dec << "\r\n";
            os << doc->body.substr(i, cl) << "\r\n";
          }
          os << 0 << "\r\n\r\n"; // last chunk
        } else {
          os << doc->body;
        }
        return doc->body.length();
      }; //<! writes body to ostream and returns length
    };
    /* Simple sendfile renderer which streams file to ostream */
    class SendFileRender {
    public:
      SendFileRender(const std::string& path_) {
        this->path = path_;
      };

      size_t operator()(const HTTPBase *doc __attribute__((unused)), std::ostream& os, bool chunked) const {
        char buf[4096];
        size_t n,k;
#ifdef HAVE_CXX11
        std::ifstream ifs(path, std::ifstream::binary);
#else
        std::ifstream ifs(path.c_str(), std::ifstream::binary);
#endif
        n = 0;

        while(ifs.good()) {
          ifs.read(buf, sizeof buf);
          n += (k = ifs.gcount());
          if (k > 0) {
            if (chunked) os << std::hex << k << std::dec << "\r\n";
            os.write(buf, k);
            if (chunked) os << "\r\n";
          }
        }
        if (chunked) os << 0 << "\r\n\r\n";
        return n;
      }; //<! writes file to ostream and returns length

      std::string path; //<! File to send
    };

    HTTPBase() {
      initialize();
    };

    virtual void initialize() {
      kind = 0;
      status = 0;
#ifdef HAVE_CPP_FUNC_PTR
      renderer = SendBodyRender();
#endif
      max_request_size = YAHTTP_MAX_REQUEST_SIZE;
      max_response_size = YAHTTP_MAX_RESPONSE_SIZE;
      url = "";
      method = "";
      statusText = "";
      jar.clear();
      headers.clear();
      parameters.clear();
      getvars.clear();
      postvars.clear();
      body = "";
      routeName = "";
      version = 11; // default to version 1.1
      is_multipart = false;
    }
protected:
    HTTPBase(const HTTPBase& rhs) {
      this->url = rhs.url; this->kind = rhs.kind;
      this->status = rhs.status; this->statusText = rhs.statusText;
      this->method = rhs.method; this->headers = rhs.headers;
      this->jar = rhs.jar; this->postvars = rhs.postvars;
      this->parameters = rhs.parameters; this->getvars = rhs.getvars;
      this->body = rhs.body; this->max_request_size = rhs.max_request_size;
      this->max_response_size = rhs.max_response_size; this->version = rhs.version;
#ifdef HAVE_CPP_FUNC_PTR
      this->renderer = rhs.renderer;
#endif
      this->is_multipart = rhs.is_multipart;
    };
    virtual HTTPBase& operator=(const HTTPBase& rhs) {
      this->url = rhs.url; this->kind = rhs.kind;
      this->status = rhs.status; this->statusText = rhs.statusText;
      this->method = rhs.method; this->headers = rhs.headers;
      this->jar = rhs.jar; this->postvars = rhs.postvars;
      this->parameters = rhs.parameters; this->getvars = rhs.getvars;
      this->body = rhs.body; this->max_request_size = rhs.max_request_size;
      this->max_response_size = rhs.max_response_size; this->version = rhs.version;
#ifdef HAVE_CPP_FUNC_PTR
      this->renderer = rhs.renderer;
#endif
      this->is_multipart = rhs.is_multipart;
      return *this;
    };
public:
    URL url; //<! URL of this request/response
    int kind; //<! Type of object (1 = request, 2 = response)
    int status; //<! status code
    int version; //<! http version 9 = 0.9, 10 = 1.0, 11 = 1.1
    std::string statusText; //<! textual representation of status code
    std::string method; //<! http verb
    strstr_map_t headers; //<! map of header(s)
    CookieJar jar; //<! cookies
    strstr_map_t postvars; //<! map of POST variables (from POST body)
    strstr_map_t getvars; //<! map of GET variables (from URL)
// these two are for Router
    strstr_map_t parameters; //<! map of route parameters (only if you use YaHTTP::Router)
    std::string routeName; //<! name of the current route (only if you use YaHTTP::Router)

    std::string body; //<! the actual content

    ssize_t max_request_size; //<! maximum size of request
    ssize_t max_response_size;  //<! maximum size of response
    bool is_multipart; //<! if the request is multipart, prevents Content-Length header
#ifdef HAVE_CPP_FUNC_PTR
    funcptr::function<size_t(const HTTPBase*,std::ostream&,bool)> renderer; //<! rendering function
#endif
    void write(std::ostream& os) const; //<! writes request to the given output stream

    strstr_map_t& GET() { return getvars; }; //<! acccessor for getvars
    strstr_map_t& POST() { return postvars; }; //<! accessor for postvars
    strcookie_map_t& COOKIES() { return jar.cookies; }; //<! accessor for cookies

    std::string versionStr(int version_) const {
      switch(version_) {
      case  9: return "0.9";
      case 10: return "1.0";
      case 11: return "1.1";
      default: throw YaHTTP::Error("Unsupported version");
      }
    };

    std::string str() const {
       std::ostringstream oss;
       write(oss);
       return oss.str();
    }; //<! return string representation of this object
  };

  /*! Response class, represents a HTTP Response document */
  class Response: public HTTPBase {
  public:
    Response() { initialize(); };
    Response(const HTTPBase& rhs): HTTPBase(rhs) {
      this->kind = YAHTTP_TYPE_RESPONSE;
    };
    Response& operator=(const HTTPBase& rhs) override {
      HTTPBase::operator=(rhs);
      this->kind = YAHTTP_TYPE_RESPONSE;
      return *this;
    };
    void initialize() override {
      HTTPBase::initialize();
      this->kind = YAHTTP_TYPE_RESPONSE;
    }
    void initialize(const HTTPBase& rhs) {
      HTTPBase::initialize();
      this->kind = YAHTTP_TYPE_RESPONSE;
      // copy SOME attributes
      this->url = rhs.url;
      this->method = rhs.method;
      this->jar = rhs.jar;
      this->version = rhs.version;
    }
    friend std::ostream& operator<<(std::ostream& os, const Response &resp);
    friend std::istream& operator>>(std::istream& is, Response &resp);
  };

  /* Request class, represents a HTTP Request document */
  class Request: public HTTPBase {
  public:
    Request() { initialize(); };
    Request(const HTTPBase& rhs): HTTPBase(rhs) {
      this->kind = YAHTTP_TYPE_REQUEST;
    };
    Request& operator=(const HTTPBase& rhs) override {
      HTTPBase::operator=(rhs);
      this->kind = YAHTTP_TYPE_REQUEST;
      return *this;
    };
    void initialize() override {
      HTTPBase::initialize();
      this->kind = YAHTTP_TYPE_REQUEST;
    }
    void initialize(const HTTPBase& rhs) {
      HTTPBase::initialize();
      this->kind = YAHTTP_TYPE_REQUEST;
      // copy SOME attributes
      this->url = rhs.url;
      this->method = rhs.method;
      this->jar = rhs.jar;
      this->version = rhs.version;
    }
    void setup(const std::string& method_, const std::string& url_) {
      this->url.parse(url_);
      this->headers["host"] = this->url.host;
      this->method = method_;
      std::transform(this->method.begin(), this->method.end(), this->method.begin(), ::toupper);
      this->headers["user-agent"] = "YaHTTP v1.0";
    }; //<! Set some initial things for a request

    void preparePost(postformat_t format = urlencoded) {
      std::ostringstream postbuf;
      if (format == urlencoded) {
        for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {
          postbuf << Utility::encodeURL(i->first, false) << "=" << Utility::encodeURL(i->second, false) << "&";
        }
        // remove last bit
        if (postbuf.str().length()>0)
          body = postbuf.str().substr(0, postbuf.str().length()-1);
        else
          body = "";
        headers["content-type"] = "application/x-www-form-urlencoded; charset=utf-8";
      } else if (format == multipart) {
        headers["content-type"] = "multipart/form-data; boundary=YaHTTP-12ca543";
        this->is_multipart = true;
        for(strstr_map_t::const_iterator i = POST().begin(); i != POST().end(); i++) {
          postbuf << "--YaHTTP-12ca543\r\nContent-Disposition: form-data; name=\"" << Utility::encodeURL(i->first, false) << "\"; charset=UTF-8\r\nContent-Length: " << i->second.size() << "\r\n\r\n"
            << Utility::encodeURL(i->second, false) << "\r\n";
        }
        postbuf << "--";
        body = postbuf.str();
      }

      postbuf.str("");
      postbuf << body.length();
      // set method and change headers
      method = "POST";
      if (!this->is_multipart)
        headers["content-length"] = postbuf.str();
    }; //<! convert all postvars into string and stuff it into body

    friend std::ostream& operator<<(std::ostream& os, const Request &resp);
    friend std::istream& operator>>(std::istream& is, Request &resp);
  };

  /*! Asynchronous HTTP document loader */
  template <class T>
  class AsyncLoader {
  public:
    T* target; //<! target to populate
    int state; //<! reader state
    size_t pos; //<! reader position

    std::string buffer; //<! read buffer
    bool chunked; //<! whether we are parsing chunked data
    int chunk_size; //<! expected size of next chunk
    std::ostringstream bodybuf; //<! buffer for body
    size_t maxbody; //<! maximum size of body
    size_t minbody; //<! minimum size of body
    bool hasBody; //<! are we expecting body

    void keyValuePair(const std::string &keyvalue, std::string &key, std::string &value); //<! key value pair parser helper

    void initialize(T* target_) {
      chunked = false; chunk_size = 0;
      bodybuf.str(""); minbody = 0; maxbody = 0;
      pos = 0; state = 0; this->target = target_;
      hasBody = false;
      buffer = "";
      this->target->initialize();
    }; //<! Initialize the parser for target and clear state
    bool feed(const std::string& somedata); //<! Feed data to the parser
    bool ready() {
     return (chunked == true && state == 3) || // if it's chunked we get end of data indication
             (chunked == false && state > 1 &&
               (!hasBody ||
                 (bodybuf.str().size() <= maxbody &&
                  bodybuf.str().size() >= minbody)
               )
             );
    }; //<! whether we have received enough data
    void finalize() {
      bodybuf.flush();
      if (ready()) {
        strstr_map_t::iterator cpos = target->headers.find("content-type");
        if (cpos != target->headers.end() && Utility::iequals(cpos->second, "application/x-www-form-urlencoded", 32)) {
          target->postvars = Utility::parseUrlParameters(bodybuf.str());
        }
        target->body = bodybuf.str();
      }
      bodybuf.str("");
      this->target = NULL;
    }; //<! finalize and release target
  };

  /*! Asynchronous HTTP response loader */
  class AsyncResponseLoader: public AsyncLoader<Response> {
  };

  /*! Asynchronous HTTP request loader */
  class AsyncRequestLoader: public AsyncLoader<Request> {
  };

};
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
///
/// SoundTouch - main class for tempo/pitch/rate adjusting routines.
///
/// Notes:
/// - Initialize the SoundTouch object instance by setting up the sound stream
///   parameters with functions 'setSampleRate' and 'setChannels', then set
///   desired tempo/pitch/rate settings with the corresponding functions.
///
/// - The SoundTouch class behaves like a first-in-first-out pipeline: The
///   samples that are to be processed are fed into one of the pipe by calling
///   function 'putSamples', while the ready processed samples can be read
///   from the other end of the pipeline with function 'receiveSamples'.
///
/// - The SoundTouch processing classes require certain sized 'batches' of
///   samples in order to process the sound. For this reason the classes buffer
///   incoming samples until there are enough of samples available for
///   processing, then they carry out the processing step and consequently
///   make the processed samples available for outputting.
///
/// - For the above reason, the processing routines introduce a certain
///   'latency' between the input and output, so that the samples input to
///   SoundTouch may not be immediately available in the output, and neither
///   the amount of outputtable samples may not immediately be in direct
///   relationship with the amount of previously input samples.
///
/// - The tempo/pitch/rate control parameters can be altered during processing.
///   Please notice though that they aren't currently protected by semaphores,
///   so in multi-thread application external semaphore protection may be
///   required.
///
/// - This class utilizes classes 'TDStretch' for tempo change (without modifying
///   pitch) and 'RateTransposer' for changing the playback rate (that is, both
///   tempo and pitch in the same ratio) of the sound. The third available control
///   'pitch' (change pitch but maintain tempo) is produced by a combination of
///   combining the two other controls.
///
/// Author        : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed  : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
//  SoundTouch audio processing library
//  Copyright (c) Olli Parviainen
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
////////////////////////////////////////////////////////////////////////////////

#include <assert.h>
#include <stdlib.h>
#include <memory.h>
#include <math.h>
#include <stdexcept>
#include <stdio.h>

#include "SoundTouch.h"
#include "TDStretch.h"
#include "RateTransposer.h"
#include "cpu_detect.h"

using namespace soundtouch;

/// test if two floating point numbers are equal
#define TEST_FLOAT_EQUAL(a, b)  (fabs(a - b) < 1e-10)

/// Print library version string for autoconf
extern "C" void soundtouch_ac_test()
{
    printf("SoundTouch Version: %s\n",SOUNDTOUCH_VERSION);
}

SoundTouch::SoundTouch()
{
    // Initialize rate transposer and tempo changer instances

    pRateTransposer = RateTransposer::newInstance();
    pTDStretch = TDStretch::newInstance();

    setOutPipe(pTDStretch);

    rate = tempo = 0;

    virtualPitch =
    virtualRate =
    virtualTempo = 1.0;

    calcEffectiveRateAndTempo();

    channels = 0;
    bSrateSet = FALSE;
}

SoundTouch::~SoundTouch()
{
    delete pRateTransposer;
    delete pTDStretch;
}

/// Get SoundTouch library version string
const char *SoundTouch::getVersionString()
{
    static const char *_version = SOUNDTOUCH_VERSION;

    return _version;
}

/// Get SoundTouch library version Id
uint SoundTouch::getVersionId()
{
    return SOUNDTOUCH_VERSION_ID;
}

// Sets the number of channels, 1 = mono, 2 = stereo
void SoundTouch::setChannels(uint numChannels)
{
    if (numChannels != 1 && numChannels != 2)
    {
        throw std::runtime_error("Illegal number of channels");
    }
    channels = numChannels;
    pRateTransposer->setChannels((int)numChannels);
    pTDStretch->setChannels((int)numChannels);
}

// Sets new rate control value. Normal rate = 1.0, smaller values
// represent slower rate, larger faster rates.
void SoundTouch::setRate(float newRate)
{
    virtualRate = newRate;
    calcEffectiveRateAndTempo();
}

// Sets new rate control value as a difference in percents compared
// to the original rate (-50 .. +100 %)
void SoundTouch::setRateChange(float newRate)
{
    virtualRate = 1.0f + 0.01f * newRate;
    calcEffectiveRateAndTempo();
}

// Sets new tempo control value. Normal tempo = 1.0, smaller values
// represent slower tempo, larger faster tempo.
void SoundTouch::setTempo(float newTempo)
{
    virtualTempo = newTempo;
    calcEffectiveRateAndTempo();
}

// Sets new tempo control value as a difference in percents compared
// to the original tempo (-50 .. +100 %)
void SoundTouch::setTempoChange(float newTempo)
{
    virtualTempo = 1.0f + 0.01f * newTempo;
    calcEffectiveRateAndTempo();
}

// Sets new pitch control value. Original pitch = 1.0, smaller values
// represent lower pitches, larger values higher pitch.
void SoundTouch::setPitch(float newPitch)
{
    virtualPitch = newPitch;
    calcEffectiveRateAndTempo();
}

// Sets pitch change in octaves compared to the original pitch
// (-1.00 .. +1.00)
void SoundTouch::setPitchOctaves(float newPitch)
{
    virtualPitch = (float)exp(0.69314718056f * newPitch);
    calcEffectiveRateAndTempo();
}

// Sets pitch change in semi-tones compared to the original pitch
// (-12 .. +12)
void SoundTouch::setPitchSemiTones(int newPitch)
{
    setPitchOctaves((float)newPitch / 12.0f);
}

void SoundTouch::setPitchSemiTones(float newPitch)
{
    setPitchOctaves(newPitch / 12.0f);
}

// Calculates 'effective' rate and tempo values from the
// nominal control values.
void SoundTouch::calcEffectiveRateAndTempo()
{
    float oldTempo = tempo;
    float oldRate = rate;

    tempo = virtualTempo / virtualPitch;
    rate = virtualPitch * virtualRate;

    if (!TEST_FLOAT_EQUAL(rate,oldRate)) pRateTransposer->setRate(rate);
    if (!TEST_FLOAT_EQUAL(tempo, oldTempo)) pTDStretch->setTempo(tempo);

#ifndef PREVENT_CLICK_AT_RATE_CROSSOVER
    if (rate <= 1.0f)
    {
        if (output != pTDStretch)
        {
            FIFOSamplePipe *tempoOut;

            assert(output == pRateTransposer);
            // move samples in the current output buffer to the output of pTDStretch
            tempoOut = pTDStretch->getOutput();
            tempoOut->moveSamples(*output);
            // move samples in pitch transposer's store buffer to tempo changer's input
            pTDStretch->moveSamples(*pRateTransposer->getStore());

            output = pTDStretch;
        }
    }
    else
#endif
    {
        if (output != pRateTransposer)
        {
            FIFOSamplePipe *transOut;

            assert(output == pTDStretch);
            // move samples in the current output buffer to the output of pRateTransposer
            transOut = pRateTransposer->getOutput();
            transOut->moveSamples(*output);
            // move samples in tempo changer's input to pitch transposer's input
            pRateTransposer->moveSamples(*pTDStretch->getInput());

            output = pRateTransposer;
        }
    }
}

// Sets sample rate.
void SoundTouch::setSampleRate(uint srate)
{
    bSrateSet = TRUE;
    // set sample rate, leave other tempo changer parameters as they are.
    pTDStretch->setParameters((int)srate);
}

// Adds 'numSamples' pcs of samples from the 'samples' memory position into
// the input of the object.
void SoundTouch::putSamples(const SAMPLETYPE *samples, uint nSamples)
{
    if (bSrateSet == FALSE)
    {
        throw std::runtime_error("SoundTouch : Sample rate not defined");
    }
    else if (channels == 0)
    {
        throw std::runtime_error("SoundTouch : Number of channels not defined");
    }

    // Transpose the rate of the new samples if necessary
    /* Bypass the nominal setting - can introduce a click in sound when tempo/pitch control crosses the nominal value...
    if (rate == 1.0f)
    {
        // The rate value is same as the original, simply evaluate the tempo changer.
        assert(output == pTDStretch);
        if (pRateTransposer->isEmpty() == 0)
        {
            // yet flush the last samples in the pitch transposer buffer
            // (may happen if 'rate' changes from a non-zero value to zero)
            pTDStretch->moveSamples(*pRateTransposer);
        }
        pTDStretch->putSamples(samples, nSamples);
    }
    */
#ifndef _PREVENT_CLICK_AT_RATE_CROSSOVER
    else if (rate <= 1.0f)
    {
        // transpose the rate down, output the transposed sound to tempo changer buffer
        assert(output == pTDStretch);
        pRateTransposer->putSamples(samples, nSamples);
        pTDStretch->moveSamples(*pRateTransposer);
    }
    else
#endif
    {
        // evaluate the tempo changer, then transpose the rate up,
        assert(output == pRateTransposer);
        pTDStretch->putSamples(samples, nSamples);
        pRateTransposer->moveSamples(*pTDStretch);
    }
}

// Flushes the last samples from the processing pipeline to the output.
// Clears also the internal processing buffers.
//
// Note: This function is meant for extracting the last samples of a sound
// stream. This function may introduce additional blank samples in the end
// of the sound stream, and thus it's not recommended to call this function
// in the middle of a sound stream.
void SoundTouch::flush()
{
    int i;
    uint nOut;
    SAMPLETYPE buff[128];

    nOut = numSamples();

    memset(buff, 0, 128 * sizeof(SAMPLETYPE));
    // "Push" the last active samples out from the processing pipeline by
    // feeding blank samples into the processing pipeline until new,
    // processed samples appear in the output (not however, more than
    // 8ksamples in any case)
    for (i = 0; i < 128; i ++)
    {
        putSamples(buff, 64);
        if (numSamples() != nOut) break;  // new samples have appeared in the output!
    }

    // Clear working buffers
    pRateTransposer->clear();
    pTDStretch->clearInput();
    // yet leave the 'tempoChanger' output intouched as that's where the
    // flushed samples are!
}

// Changes a setting controlling the processing system behaviour. See the
// 'SETTING_...' defines for available setting ID's.
BOOL SoundTouch::setSetting(int settingId, int value)
{
    int sampleRate, sequenceMs, seekWindowMs, overlapMs;

    // read current tdstretch routine parameters
    pTDStretch->getParameters(&sampleRate, &sequenceMs, &seekWindowMs, &overlapMs);

    switch (settingId)
    {
        case SETTING_USE_AA_FILTER :
            // enables / disabless anti-alias filter
            pRateTransposer->enableAAFilter((value != 0) ? TRUE : FALSE);
            return TRUE;

        case SETTING_AA_FILTER_LENGTH :
            // sets anti-alias filter length
            pRateTransposer->getAAFilter()->setLength(value);
            return TRUE;

        case SETTING_USE_QUICKSEEK :
            // enables / disables tempo routine quick seeking algorithm
            pTDStretch->enableQuickSeek((value != 0) ? TRUE : FALSE);
            return TRUE;

        case SETTING_SEQUENCE_MS:
            // change time-stretch sequence duration parameter
            pTDStretch->setParameters(sampleRate, value, seekWindowMs, overlapMs);
            return TRUE;

        case SETTING_SEEKWINDOW_MS:
            // change time-stretch seek window length parameter
            pTDStretch->setParameters(sampleRate, sequenceMs, value, overlapMs);
            return TRUE;

        case SETTING_OVERLAP_MS:
            // change time-stretch overlap length parameter
            pTDStretch->setParameters(sampleRate, sequenceMs, seekWindowMs, value);
            return TRUE;

        default :
            return FALSE;
    }
}

// Reads a setting controlling the processing system behaviour. See the
// 'SETTING_...' defines for available setting ID's.
//
// Returns the setting value.
int SoundTouch::getSetting(int settingId) const
{
    int temp;

    switch (settingId)
    {
        case SETTING_USE_AA_FILTER :
            return (uint)pRateTransposer->isAAFilterEnabled();

        case SETTING_AA_FILTER_LENGTH :
            return pRateTransposer->getAAFilter()->getLength();

        case SETTING_USE_QUICKSEEK :
            return (uint)   pTDStretch->isQuickSeekEnabled();

        case SETTING_SEQUENCE_MS:
            pTDStretch->getParameters(NULL, &temp, NULL, NULL);
            return temp;

        case SETTING_SEEKWINDOW_MS:
            pTDStretch->getParameters(NULL, NULL, &temp, NULL);
            return temp;

        case SETTING_OVERLAP_MS:
            pTDStretch->getParameters(NULL, NULL, NULL, &temp);
            return temp;

        default :
            return 0;
    }
}

// Clears all the samples in the object's output and internal processing
// buffers.
void SoundTouch::clear()
{
    pRateTransposer->clear();
    pTDStretch->clear();
}

/// Returns number of samples currently unprocessed.
uint SoundTouch::numUnprocessedSamples() const
{
    FIFOSamplePipe * psp;
    if (pTDStretch)
    {
        psp = pTDStretch->getInput();
        if (psp)
        {
            return psp->numSamples();
        }
    }
    return 0;
}
<commit_msg>Fixed a typo bug<commit_after>//////////////////////////////////////////////////////////////////////////////
///
/// SoundTouch - main class for tempo/pitch/rate adjusting routines.
///
/// Notes:
/// - Initialize the SoundTouch object instance by setting up the sound stream
///   parameters with functions 'setSampleRate' and 'setChannels', then set
///   desired tempo/pitch/rate settings with the corresponding functions.
///
/// - The SoundTouch class behaves like a first-in-first-out pipeline: The
///   samples that are to be processed are fed into one of the pipe by calling
///   function 'putSamples', while the ready processed samples can be read
///   from the other end of the pipeline with function 'receiveSamples'.
///
/// - The SoundTouch processing classes require certain sized 'batches' of
///   samples in order to process the sound. For this reason the classes buffer
///   incoming samples until there are enough of samples available for
///   processing, then they carry out the processing step and consequently
///   make the processed samples available for outputting.
///
/// - For the above reason, the processing routines introduce a certain
///   'latency' between the input and output, so that the samples input to
///   SoundTouch may not be immediately available in the output, and neither
///   the amount of outputtable samples may not immediately be in direct
///   relationship with the amount of previously input samples.
///
/// - The tempo/pitch/rate control parameters can be altered during processing.
///   Please notice though that they aren't currently protected by semaphores,
///   so in multi-thread application external semaphore protection may be
///   required.
///
/// - This class utilizes classes 'TDStretch' for tempo change (without modifying
///   pitch) and 'RateTransposer' for changing the playback rate (that is, both
///   tempo and pitch in the same ratio) of the sound. The third available control
///   'pitch' (change pitch but maintain tempo) is produced by a combination of
///   combining the two other controls.
///
/// Author        : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed  : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
//  SoundTouch audio processing library
//  Copyright (c) Olli Parviainen
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
////////////////////////////////////////////////////////////////////////////////

#include <assert.h>
#include <stdlib.h>
#include <memory.h>
#include <math.h>
#include <stdexcept>
#include <stdio.h>

#include "SoundTouch.h"
#include "TDStretch.h"
#include "RateTransposer.h"
#include "cpu_detect.h"

using namespace soundtouch;

/// test if two floating point numbers are equal
#define TEST_FLOAT_EQUAL(a, b)  (fabs(a - b) < 1e-10)

/// Print library version string for autoconf
extern "C" void soundtouch_ac_test()
{
    printf("SoundTouch Version: %s\n",SOUNDTOUCH_VERSION);
}

SoundTouch::SoundTouch()
{
    // Initialize rate transposer and tempo changer instances

    pRateTransposer = RateTransposer::newInstance();
    pTDStretch = TDStretch::newInstance();

    setOutPipe(pTDStretch);

    rate = tempo = 0;

    virtualPitch =
    virtualRate =
    virtualTempo = 1.0;

    calcEffectiveRateAndTempo();

    channels = 0;
    bSrateSet = FALSE;
}

SoundTouch::~SoundTouch()
{
    delete pRateTransposer;
    delete pTDStretch;
}

/// Get SoundTouch library version string
const char *SoundTouch::getVersionString()
{
    static const char *_version = SOUNDTOUCH_VERSION;

    return _version;
}

/// Get SoundTouch library version Id
uint SoundTouch::getVersionId()
{
    return SOUNDTOUCH_VERSION_ID;
}

// Sets the number of channels, 1 = mono, 2 = stereo
void SoundTouch::setChannels(uint numChannels)
{
    if (numChannels != 1 && numChannels != 2)
    {
        throw std::runtime_error("Illegal number of channels");
    }
    channels = numChannels;
    pRateTransposer->setChannels((int)numChannels);
    pTDStretch->setChannels((int)numChannels);
}

// Sets new rate control value. Normal rate = 1.0, smaller values
// represent slower rate, larger faster rates.
void SoundTouch::setRate(float newRate)
{
    virtualRate = newRate;
    calcEffectiveRateAndTempo();
}

// Sets new rate control value as a difference in percents compared
// to the original rate (-50 .. +100 %)
void SoundTouch::setRateChange(float newRate)
{
    virtualRate = 1.0f + 0.01f * newRate;
    calcEffectiveRateAndTempo();
}

// Sets new tempo control value. Normal tempo = 1.0, smaller values
// represent slower tempo, larger faster tempo.
void SoundTouch::setTempo(float newTempo)
{
    virtualTempo = newTempo;
    calcEffectiveRateAndTempo();
}

// Sets new tempo control value as a difference in percents compared
// to the original tempo (-50 .. +100 %)
void SoundTouch::setTempoChange(float newTempo)
{
    virtualTempo = 1.0f + 0.01f * newTempo;
    calcEffectiveRateAndTempo();
}

// Sets new pitch control value. Original pitch = 1.0, smaller values
// represent lower pitches, larger values higher pitch.
void SoundTouch::setPitch(float newPitch)
{
    virtualPitch = newPitch;
    calcEffectiveRateAndTempo();
}

// Sets pitch change in octaves compared to the original pitch
// (-1.00 .. +1.00)
void SoundTouch::setPitchOctaves(float newPitch)
{
    virtualPitch = (float)exp(0.69314718056f * newPitch);
    calcEffectiveRateAndTempo();
}

// Sets pitch change in semi-tones compared to the original pitch
// (-12 .. +12)
void SoundTouch::setPitchSemiTones(int newPitch)
{
    setPitchOctaves((float)newPitch / 12.0f);
}

void SoundTouch::setPitchSemiTones(float newPitch)
{
    setPitchOctaves(newPitch / 12.0f);
}

// Calculates 'effective' rate and tempo values from the
// nominal control values.
void SoundTouch::calcEffectiveRateAndTempo()
{
    float oldTempo = tempo;
    float oldRate = rate;

    tempo = virtualTempo / virtualPitch;
    rate = virtualPitch * virtualRate;

    if (!TEST_FLOAT_EQUAL(rate,oldRate)) pRateTransposer->setRate(rate);
    if (!TEST_FLOAT_EQUAL(tempo, oldTempo)) pTDStretch->setTempo(tempo);

#ifndef PREVENT_CLICK_AT_RATE_CROSSOVER
    if (rate <= 1.0f)
    {
        if (output != pTDStretch)
        {
            FIFOSamplePipe *tempoOut;

            assert(output == pRateTransposer);
            // move samples in the current output buffer to the output of pTDStretch
            tempoOut = pTDStretch->getOutput();
            tempoOut->moveSamples(*output);
            // move samples in pitch transposer's store buffer to tempo changer's input
            pTDStretch->moveSamples(*pRateTransposer->getStore());

            output = pTDStretch;
        }
    }
    else
#endif
    {
        if (output != pRateTransposer)
        {
            FIFOSamplePipe *transOut;

            assert(output == pTDStretch);
            // move samples in the current output buffer to the output of pRateTransposer
            transOut = pRateTransposer->getOutput();
            transOut->moveSamples(*output);
            // move samples in tempo changer's input to pitch transposer's input
            pRateTransposer->moveSamples(*pTDStretch->getInput());

            output = pRateTransposer;
        }
    }
}

// Sets sample rate.
void SoundTouch::setSampleRate(uint srate)
{
    bSrateSet = TRUE;
    // set sample rate, leave other tempo changer parameters as they are.
    pTDStretch->setParameters((int)srate);
}

// Adds 'numSamples' pcs of samples from the 'samples' memory position into
// the input of the object.
void SoundTouch::putSamples(const SAMPLETYPE *samples, uint nSamples)
{
    if (bSrateSet == FALSE)
    {
        throw std::runtime_error("SoundTouch : Sample rate not defined");
    }
    else if (channels == 0)
    {
        throw std::runtime_error("SoundTouch : Number of channels not defined");
    }

    // Transpose the rate of the new samples if necessary
    /* Bypass the nominal setting - can introduce a click in sound when tempo/pitch control crosses the nominal value...
    if (rate == 1.0f)
    {
        // The rate value is same as the original, simply evaluate the tempo changer.
        assert(output == pTDStretch);
        if (pRateTransposer->isEmpty() == 0)
        {
            // yet flush the last samples in the pitch transposer buffer
            // (may happen if 'rate' changes from a non-zero value to zero)
            pTDStretch->moveSamples(*pRateTransposer);
        }
        pTDStretch->putSamples(samples, nSamples);
    }
    */
#ifndef PREVENT_CLICK_AT_RATE_CROSSOVER
    else if (rate <= 1.0f)
    {
        // transpose the rate down, output the transposed sound to tempo changer buffer
        assert(output == pTDStretch);
        pRateTransposer->putSamples(samples, nSamples);
        pTDStretch->moveSamples(*pRateTransposer);
    }
    else
#endif
    {
        // evaluate the tempo changer, then transpose the rate up,
        assert(output == pRateTransposer);
        pTDStretch->putSamples(samples, nSamples);
        pRateTransposer->moveSamples(*pTDStretch);
    }
}

// Flushes the last samples from the processing pipeline to the output.
// Clears also the internal processing buffers.
//
// Note: This function is meant for extracting the last samples of a sound
// stream. This function may introduce additional blank samples in the end
// of the sound stream, and thus it's not recommended to call this function
// in the middle of a sound stream.
void SoundTouch::flush()
{
    int i;
    uint nOut;
    SAMPLETYPE buff[128];

    nOut = numSamples();

    memset(buff, 0, 128 * sizeof(SAMPLETYPE));
    // "Push" the last active samples out from the processing pipeline by
    // feeding blank samples into the processing pipeline until new,
    // processed samples appear in the output (not however, more than
    // 8ksamples in any case)
    for (i = 0; i < 128; i ++)
    {
        putSamples(buff, 64);
        if (numSamples() != nOut) break;  // new samples have appeared in the output!
    }

    // Clear working buffers
    pRateTransposer->clear();
    pTDStretch->clearInput();
    // yet leave the 'tempoChanger' output intouched as that's where the
    // flushed samples are!
}

// Changes a setting controlling the processing system behaviour. See the
// 'SETTING_...' defines for available setting ID's.
BOOL SoundTouch::setSetting(int settingId, int value)
{
    int sampleRate, sequenceMs, seekWindowMs, overlapMs;

    // read current tdstretch routine parameters
    pTDStretch->getParameters(&sampleRate, &sequenceMs, &seekWindowMs, &overlapMs);

    switch (settingId)
    {
        case SETTING_USE_AA_FILTER :
            // enables / disabless anti-alias filter
            pRateTransposer->enableAAFilter((value != 0) ? TRUE : FALSE);
            return TRUE;

        case SETTING_AA_FILTER_LENGTH :
            // sets anti-alias filter length
            pRateTransposer->getAAFilter()->setLength(value);
            return TRUE;

        case SETTING_USE_QUICKSEEK :
            // enables / disables tempo routine quick seeking algorithm
            pTDStretch->enableQuickSeek((value != 0) ? TRUE : FALSE);
            return TRUE;

        case SETTING_SEQUENCE_MS:
            // change time-stretch sequence duration parameter
            pTDStretch->setParameters(sampleRate, value, seekWindowMs, overlapMs);
            return TRUE;

        case SETTING_SEEKWINDOW_MS:
            // change time-stretch seek window length parameter
            pTDStretch->setParameters(sampleRate, sequenceMs, value, overlapMs);
            return TRUE;

        case SETTING_OVERLAP_MS:
            // change time-stretch overlap length parameter
            pTDStretch->setParameters(sampleRate, sequenceMs, seekWindowMs, value);
            return TRUE;

        default :
            return FALSE;
    }
}

// Reads a setting controlling the processing system behaviour. See the
// 'SETTING_...' defines for available setting ID's.
//
// Returns the setting value.
int SoundTouch::getSetting(int settingId) const
{
    int temp;

    switch (settingId)
    {
        case SETTING_USE_AA_FILTER :
            return (uint)pRateTransposer->isAAFilterEnabled();

        case SETTING_AA_FILTER_LENGTH :
            return pRateTransposer->getAAFilter()->getLength();

        case SETTING_USE_QUICKSEEK :
            return (uint)   pTDStretch->isQuickSeekEnabled();

        case SETTING_SEQUENCE_MS:
            pTDStretch->getParameters(NULL, &temp, NULL, NULL);
            return temp;

        case SETTING_SEEKWINDOW_MS:
            pTDStretch->getParameters(NULL, NULL, &temp, NULL);
            return temp;

        case SETTING_OVERLAP_MS:
            pTDStretch->getParameters(NULL, NULL, NULL, &temp);
            return temp;

        default :
            return 0;
    }
}

// Clears all the samples in the object's output and internal processing
// buffers.
void SoundTouch::clear()
{
    pRateTransposer->clear();
    pTDStretch->clear();
}

/// Returns number of samples currently unprocessed.
uint SoundTouch::numUnprocessedSamples() const
{
    FIFOSamplePipe * psp;
    if (pTDStretch)
    {
        psp = pTDStretch->getInput();
        if (psp)
        {
            return psp->numSamples();
        }
    }
    return 0;
}
<|endoftext|>


<commit_before>// ---------------------------------------------------------------------
// $Id$
//
// Copyright (C) 2004 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

// TrilinosWrappers::SparseMatrix::print got column indices wrong

#include "../tests.h"
#include <deal.II/base/utilities.h>
#include <deal.II/base/index_set.h>
#include <deal.II/lac/trilinos_sparse_matrix.h>
#include <deal.II/lac/trilinos_sparsity_pattern.h>
#include <fstream>
#include <iostream>
#include <vector>

void test ()
{
  const unsigned int n_procs = Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);
  const unsigned int my_id = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);

  const unsigned int n_rows = 2;
  const unsigned int n_cols = 2;

  IndexSet row_partitioning (n_rows);
  IndexSet col_partitioning (n_cols);

  if (n_procs == 1)
    {
      row_partitioning.add_range(0, n_rows);
      col_partitioning.add_range(0, n_cols);
    }
  else if (n_procs == 2)
    {
      if (my_id == 0)
        {
          row_partitioning.add_range(0, 1);
          col_partitioning.add_range(0, 1);
        }
      else if (my_id == 1)
        {
          row_partitioning.add_range(1, n_rows);
          col_partitioning.add_range(1, n_cols);
        }
    }
  else
    Assert (false, ExcNotImplemented());

  /* A is

     0     1
     0     1
  */
  const unsigned int n_entries = 2;
  const unsigned int line [n_entries] = {0, 1};
  const unsigned int local_index [n_entries] = {1, 1};
  const double local_value [n_entries] = {1.0, 1.0};

  TrilinosWrappers::SparsityPattern sp (row_partitioning, col_partitioning, MPI_COMM_WORLD);
  for (unsigned int i = 0; i < n_entries; ++i)
    if (row_partitioning.is_element(line[i]))
      sp.add(line[i], local_index[i]);
  sp.compress();

  TrilinosWrappers::SparseMatrix A;
  A.clear ();
  A.reinit (sp);
  for (unsigned int i = 0; i<n_entries; ++i)
    if (row_partitioning.is_element(line[i]))
      A.add(line[i], local_index[i], local_value[i]);
  A.compress(VectorOperation::add);

  if (my_id == 0)
    {
      Assert(A.el(0, 0) == 0, ExcMessage("Wrong element in A!"));
      Assert(A.el(0, 1) == 1, ExcMessage("Wrong element in A!"));
    }
  if ((n_procs == 1) || (my_id == 1))
    {
      Assert(A.el(1, 0) == 0, ExcMessage("Wrong element in A!"));
      Assert(A.el(1, 1) == 1, ExcMessage("Wrong element in A!"));
    }

  TrilinosWrappers::SparseMatrix AtA;
  A.Tmmult (AtA, A);

  /* AtA should be

     0     0
     0     2
  */

  // checking AtA row partitioning
  if (n_procs == 2)
    {
      if (my_id == 0)
        {
          Assert(AtA.local_range().first == 0,
                 ExcMessage("AtA Local Range is not as expected."));
          Assert(AtA.local_range().second == 1,
                 ExcMessage("AtA Local Range is not as expected."));
        }
      if (my_id == 1)
        {
          Assert(AtA.local_range().first == 1,
                 ExcMessage("AtA Local Range is not as expected."));
          Assert(AtA.local_range().second == 2,
                 ExcMessage("AtA Local Range is not as expected."));
        }
    }

  // checking AtA elements. note that
  // the el() function either returns
  // the correct value, or zero in
  // case the element is stored on
  // other processors. consequently,
  // in the following we only test
  // that the values that *must* be
  // zero in AtA are indeed zero, but
  // not that the others have the
  // correct value
  Assert(AtA.el(0, 0) == 0, ExcMessage("Wrong element in AtA!"));
  Assert(AtA.el(0, 1) == 0, ExcMessage("Wrong element in AtA!"));
  Assert(AtA.el(1, 0) == 0, ExcMessage("Wrong element in AtA!"));

  // now also check the one nonzero
  // element
  if ((n_procs == 1) || (my_id == 1))
    Assert(AtA.el(1, 1) == 2, ExcMessage("Wrong element in AtA!"));

  deallog << "OK" << endl;
}

int main (int argc, char **argv)
{
  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv);

  unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);
  deallog.push(Utilities::int_to_string(myid));

  if (myid == 0)
    {
      std::ofstream logfile("output");
      deallog.attach(logfile);
      deallog << std::setprecision(4);
      deallog.depth_console(0);
      deallog.threshold_double(1.e-10);

      test();
    }
  else
    test();

}
<commit_msg>Catch an exception that apparently happens in 64-bit mode.<commit_after>// ---------------------------------------------------------------------
// $Id$
//
// Copyright (C) 2004 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

// TrilinosWrappers::SparseMatrix::print got column indices wrong

#include "../tests.h"
#include <deal.II/base/utilities.h>
#include <deal.II/base/index_set.h>
#include <deal.II/lac/trilinos_sparse_matrix.h>
#include <deal.II/lac/trilinos_sparsity_pattern.h>
#include <fstream>
#include <iostream>
#include <vector>

void test ()
{
  const unsigned int n_procs = Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);
  const unsigned int my_id = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);

  const unsigned int n_rows = 2;
  const unsigned int n_cols = 2;

  IndexSet row_partitioning (n_rows);
  IndexSet col_partitioning (n_cols);

  if (n_procs == 1)
    {
      row_partitioning.add_range(0, n_rows);
      col_partitioning.add_range(0, n_cols);
    }
  else if (n_procs == 2)
    {
      if (my_id == 0)
        {
          row_partitioning.add_range(0, 1);
          col_partitioning.add_range(0, 1);
        }
      else if (my_id == 1)
        {
          row_partitioning.add_range(1, n_rows);
          col_partitioning.add_range(1, n_cols);
        }
    }
  else
    Assert (false, ExcNotImplemented());

  /* A is

     0     1
     0     1
  */
  const unsigned int n_entries = 2;
  const unsigned int line [n_entries] = {0, 1};
  const unsigned int local_index [n_entries] = {1, 1};
  const double local_value [n_entries] = {1.0, 1.0};

  TrilinosWrappers::SparsityPattern sp (row_partitioning, col_partitioning, MPI_COMM_WORLD);
  for (unsigned int i = 0; i < n_entries; ++i)
    if (row_partitioning.is_element(line[i]))
      sp.add(line[i], local_index[i]);
  sp.compress();

  TrilinosWrappers::SparseMatrix A;
  A.clear ();
  A.reinit (sp);
  for (unsigned int i = 0; i<n_entries; ++i)
    if (row_partitioning.is_element(line[i]))
      A.add(line[i], local_index[i], local_value[i]);
  A.compress(VectorOperation::add);

  if (my_id == 0)
    {
      Assert(A.el(0, 0) == 0, ExcMessage("Wrong element in A!"));
      Assert(A.el(0, 1) == 1, ExcMessage("Wrong element in A!"));
    }
  if ((n_procs == 1) || (my_id == 1))
    {
      Assert(A.el(1, 0) == 0, ExcMessage("Wrong element in A!"));
      Assert(A.el(1, 1) == 1, ExcMessage("Wrong element in A!"));
    }

  TrilinosWrappers::SparseMatrix AtA;
  A.Tmmult (AtA, A);

  /* AtA should be

     0     0
     0     2
  */

  // checking AtA row partitioning
  if (n_procs == 2)
    {
      if (my_id == 0)
        {
          Assert(AtA.local_range().first == 0,
                 ExcMessage("AtA Local Range is not as expected."));
          Assert(AtA.local_range().second == 1,
                 ExcMessage("AtA Local Range is not as expected."));
        }
      if (my_id == 1)
        {
          Assert(AtA.local_range().first == 1,
                 ExcMessage("AtA Local Range is not as expected."));
          Assert(AtA.local_range().second == 2,
                 ExcMessage("AtA Local Range is not as expected."));
        }
    }

  // checking AtA elements. note that
  // the el() function either returns
  // the correct value, or zero in
  // case the element is stored on
  // other processors. consequently,
  // in the following we only test
  // that the values that *must* be
  // zero in AtA are indeed zero, but
  // not that the others have the
  // correct value
  Assert(AtA.el(0, 0) == 0, ExcMessage("Wrong element in AtA!"));
  Assert(AtA.el(0, 1) == 0, ExcMessage("Wrong element in AtA!"));
  Assert(AtA.el(1, 0) == 0, ExcMessage("Wrong element in AtA!"));

  // now also check the one nonzero
  // element
  if ((n_procs == 1) || (my_id == 1))
    Assert(AtA.el(1, 1) == 2, ExcMessage("Wrong element in AtA!"));

  deallog << "OK" << endl;
}

int main (int argc, char **argv)
{
  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv);

  unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);
  deallog.push(Utilities::int_to_string(myid));

  try
    {
      if (myid == 0)
	{
	  std::ofstream logfile("output");
	  deallog.attach(logfile);
	  deallog << std::setprecision(4);
	  deallog.depth_console(0);
	  deallog.threshold_double(1.e-10);

	  test();
	}
      else
	test();
    }
  catch (const char *p)
    {
      std::cerr << "Uncaught exception: " << p << std::endl;
      std::exit (1);
    }
}
<|endoftext|>


<commit_before>//
//  Typer.hpp
//  Clock Signal
//
//  Created by Thomas Harte on 19/06/2016.
//  Copyright © 2016 Thomas Harte. All rights reserved.
//

#ifndef Typer_hpp
#define Typer_hpp

#include <memory>
#include "KeyboardMachine.hpp"
#include "../ClockReceiver/ClockReceiver.hpp"

namespace Utility {

/*!
	An interface that provides a mapping from logical characters to the sequence of keys
	necessary to type that character on a given machine.
*/
class CharacterMapper {
	public:
		/// @returns The EndSequence-terminated sequence of keys that would cause @c character to be typed.
		virtual uint16_t *sequence_for_character(char character) = 0;

		/// Terminates a key sequence.
		static const uint16_t EndSequence = 0xffff;

		/*!
			If returned as the first entry in a key sequence, indicates that the requested character
			cannot be mapped.
		*/
		static const uint16_t NotMapped = 0xfffe;

	protected:
		typedef uint16_t KeySequence[16];

		/*!
			Provided in the base class as a convenience: given the lookup table of key sequences @c sequences,
			with @c length entries, returns the sequence for character @c character if it exists; otherwise
			returns @c nullptr.
		*/
		uint16_t *table_lookup_sequence_for_character(KeySequence *sequences, size_t length, char character);
};

/*!
	Provides a stateful mechanism for typing a sequence of characters. Each character is mapped to a key sequence
	by a character mapper. That key sequence is then replayed to a delegate.

	Being given a delay and frequency at construction, the run_for interface can be used to produce time-based
	typing. Alternatively, an owner may decline to use run_for and simply call type_next_character each time a
	fresh key transition is ready to be consumed.
*/
class Typer {
	public:
		class Delegate: public KeyboardMachine::Machine {
			public:
				virtual void typer_reset(Typer *typer) = 0;
		};

		Typer(const char *string, HalfCycles delay, HalfCycles frequency, std::unique_ptr<CharacterMapper> character_mapper, Delegate *delegate);
		~Typer();

		void run_for(const HalfCycles duration);
		bool type_next_character();

		bool is_completed();

		const char BeginString = 0x02;	// i.e. ASCII start of text
		const char EndString = 0x03;	// i.e. ASCII end of text

	private:
		char *string_;
		size_t string_pointer_;

		HalfCycles frequency_;
		HalfCycles counter_;
		int phase_;

		Delegate *delegate_;
		std::unique_ptr<CharacterMapper> character_mapper_;

		bool try_type_next_character();
};

/*!
	Provides a default base class for type recipients: classes that want to attach a single typer at a time and
	which may or may not want to nominate an initial delay and typing frequency.
*/
class TypeRecipient: public Typer::Delegate {
	public:
		/// Attaches a typer to this class that will type @c string using @c character_mapper as a source.
		void set_typer_for_string(const char *string, std::unique_ptr<CharacterMapper> character_mapper) {
			typer_.reset(new Typer(string, get_typer_delay(), get_typer_frequency(), std::move(character_mapper), this));
		}

		/*!
			Provided as a hook for subclasses to implement so that external callers can install a typer
			without needing inside knowledge as to where the character mapper comes from.
		*/
		virtual void set_typer_for_string(const char *string) = 0;

		/*!
			Provided in order to conform to that part of the Typer::Delegate interface that goes above and
			beyond KeyboardMachine::Machine; responds to the end of typing by clearing all keys.
		*/
		void typer_reset(Typer *typer) {
			clear_all_keys();
		}

	protected:
		virtual HalfCycles get_typer_delay() { return HalfCycles(0); }
		virtual HalfCycles get_typer_frequency() { return HalfCycles(0); }
		std::unique_ptr<Typer> typer_;
};

}

#endif /* Typer_hpp */
<commit_msg>Okay, even if releasing it is unsafe, I can at least move the typer so that it is no longer called.<commit_after>//
//  Typer.hpp
//  Clock Signal
//
//  Created by Thomas Harte on 19/06/2016.
//  Copyright © 2016 Thomas Harte. All rights reserved.
//

#ifndef Typer_hpp
#define Typer_hpp

#include <memory>
#include "KeyboardMachine.hpp"
#include "../ClockReceiver/ClockReceiver.hpp"

namespace Utility {

/*!
	An interface that provides a mapping from logical characters to the sequence of keys
	necessary to type that character on a given machine.
*/
class CharacterMapper {
	public:
		/// @returns The EndSequence-terminated sequence of keys that would cause @c character to be typed.
		virtual uint16_t *sequence_for_character(char character) = 0;

		/// Terminates a key sequence.
		static const uint16_t EndSequence = 0xffff;

		/*!
			If returned as the first entry in a key sequence, indicates that the requested character
			cannot be mapped.
		*/
		static const uint16_t NotMapped = 0xfffe;

	protected:
		typedef uint16_t KeySequence[16];

		/*!
			Provided in the base class as a convenience: given the lookup table of key sequences @c sequences,
			with @c length entries, returns the sequence for character @c character if it exists; otherwise
			returns @c nullptr.
		*/
		uint16_t *table_lookup_sequence_for_character(KeySequence *sequences, size_t length, char character);
};

/*!
	Provides a stateful mechanism for typing a sequence of characters. Each character is mapped to a key sequence
	by a character mapper. That key sequence is then replayed to a delegate.

	Being given a delay and frequency at construction, the run_for interface can be used to produce time-based
	typing. Alternatively, an owner may decline to use run_for and simply call type_next_character each time a
	fresh key transition is ready to be consumed.
*/
class Typer {
	public:
		class Delegate: public KeyboardMachine::Machine {
			public:
				virtual void typer_reset(Typer *typer) = 0;
		};

		Typer(const char *string, HalfCycles delay, HalfCycles frequency, std::unique_ptr<CharacterMapper> character_mapper, Delegate *delegate);
		~Typer();

		void run_for(const HalfCycles duration);
		bool type_next_character();

		bool is_completed();

		const char BeginString = 0x02;	// i.e. ASCII start of text
		const char EndString = 0x03;	// i.e. ASCII end of text

	private:
		char *string_;
		size_t string_pointer_;

		HalfCycles frequency_;
		HalfCycles counter_;
		int phase_;

		Delegate *delegate_;
		std::unique_ptr<CharacterMapper> character_mapper_;

		bool try_type_next_character();
};

/*!
	Provides a default base class for type recipients: classes that want to attach a single typer at a time and
	which may or may not want to nominate an initial delay and typing frequency.
*/
class TypeRecipient: public Typer::Delegate {
	public:
		/// Attaches a typer to this class that will type @c string using @c character_mapper as a source.
		void set_typer_for_string(const char *string, std::unique_ptr<CharacterMapper> character_mapper) {
			typer_.reset(new Typer(string, get_typer_delay(), get_typer_frequency(), std::move(character_mapper), this));
		}

		/*!
			Provided as a hook for subclasses to implement so that external callers can install a typer
			without needing inside knowledge as to where the character mapper comes from.
		*/
		virtual void set_typer_for_string(const char *string) = 0;

		/*!
			Provided in order to conform to that part of the Typer::Delegate interface that goes above and
			beyond KeyboardMachine::Machine; responds to the end of typing by clearing all keys.
		*/
		void typer_reset(Typer *typer) {
			clear_all_keys();

			// It's unsafe to deallocate typer right now, since it is the caller, but also it has a small
			// memory footprint and it's desireable not to imply that the subclass need call it any more.
			// So shuffle it off into a siding.
			previous_typer_ = std::move(typer_);
			typer_ = nullptr;
		}

	protected:
		virtual HalfCycles get_typer_delay() { return HalfCycles(0); }
		virtual HalfCycles get_typer_frequency() { return HalfCycles(0); }
		std::unique_ptr<Typer> typer_;

	private:
		std::unique_ptr<Typer> previous_typer_;
};

}

#endif /* Typer_hpp */
<|endoftext|>


<commit_before>#include "SkyBitmapGenerator.h"

#include <vector>
#include <algorithm>

namespace carto {

    SkyBitmapGenerator::SkyBitmapGenerator(int width, int height) :
        _width(width),
        _height(height)
    {
    }

    SkyBitmapGenerator::~SkyBitmapGenerator() {
    }

    std::shared_ptr<Bitmap> SkyBitmapGenerator::generateBitmap(const Color& backgroundColor, const Color& skyColor) const {
        std::vector<unsigned char> data(_width * _height * 4);

        unsigned char baseValue = std::max(128, 255 - std::max(backgroundColor.getR(), std::max(backgroundColor.getG(), backgroundColor.getB())));
        Color baseColor(
            std::max(skyColor.getR(), baseValue) - baseValue,
            std::max(skyColor.getG(), baseValue) - baseValue,
            std::max(skyColor.getB(), baseValue) - baseValue,
            skyColor.getA()
        );

        for (int y = 0; y < _height; y++) {
            float a = std::min(1.0f, y * 1.25f / _height) * baseColor.getA() / 255.0f;
            float s = static_cast<float>(y * y) / ((_height + 1) * (_height + 1));
            Color color(
                static_cast<unsigned char>(((1 - s) * baseColor.getR() + s * backgroundColor.getR()) * a),
                static_cast<unsigned char>(((1 - s) * baseColor.getG() + s * backgroundColor.getG()) * a),
                static_cast<unsigned char>(((1 - s) * baseColor.getB() + s * backgroundColor.getB()) * a),
                static_cast<unsigned char>(255 * a)
            );

            for (int x = 0; x < _width; x++) {
                data[(y * _width + x) * 4 + 0] = color.getR();
                data[(y * _width + x) * 4 + 1] = color.getG();
                data[(y * _width + x) * 4 + 2] = color.getB();
                data[(y * _width + x) * 4 + 3] = color.getA();
            }
        }

        return std::make_shared<Bitmap>(data.data(), _width, _height, ColorFormat::COLOR_FORMAT_RGBA, 4 * _width);
    }

}
<commit_msg>Tweaks<commit_after>#include "SkyBitmapGenerator.h"

#include <vector>
#include <algorithm>

namespace carto {

    SkyBitmapGenerator::SkyBitmapGenerator(int width, int height) :
        _width(width),
        _height(height)
    {
    }

    SkyBitmapGenerator::~SkyBitmapGenerator() {
    }

    std::shared_ptr<Bitmap> SkyBitmapGenerator::generateBitmap(const Color& backgroundColor, const Color& skyColor) const {
        std::vector<unsigned char> data(_width * _height * 4);

        unsigned char baseValue = std::min(128, 255 - std::max(backgroundColor.getR(), std::max(backgroundColor.getG(), backgroundColor.getB())));
        Color baseColor(
            std::max(skyColor.getR(), baseValue) - baseValue,
            std::max(skyColor.getG(), baseValue) - baseValue,
            std::max(skyColor.getB(), baseValue) - baseValue,
            skyColor.getA()
        );

        for (int y = 0; y < _height; y++) {
			float v = y / (_height - 1.0f);
            float a = v * baseColor.getA() / 255.0f;
            float t = v * v;
            Color color(
                static_cast<unsigned char>(((1 - t) * baseColor.getR() + t * backgroundColor.getR()) * a),
                static_cast<unsigned char>(((1 - t) * baseColor.getG() + t * backgroundColor.getG()) * a),
                static_cast<unsigned char>(((1 - t) * baseColor.getB() + t * backgroundColor.getB()) * a),
                static_cast<unsigned char>(255 * a)
            );

            for (int x = 0; x < _width; x++) {
                data[(y * _width + x) * 4 + 0] = color.getR();
                data[(y * _width + x) * 4 + 1] = color.getG();
                data[(y * _width + x) * 4 + 2] = color.getB();
                data[(y * _width + x) * 4 + 3] = color.getA();
            }
        }

        return std::make_shared<Bitmap>(data.data(), _width, _height, ColorFormat::COLOR_FORMAT_RGBA, 4 * _width);
    }

}
<|endoftext|>


<commit_before><commit_msg>Add code to replicate editing workflow from GUI to testContext in order to measure timing.<commit_after><|endoftext|>


<commit_before>#include "EditorCommunicator.h"

Resources::Status Communicator::Initialize(
	HWND hwnd,
	HINSTANCE hinstance,
	int w, int h,
	bool isPreview,
	std::vector<Resources::Model*>* modelPtr
)
{
	this->m_GraphicsHandler = new GraphicsHandler();
	this->m_hwnd = hwnd;
	this->m_hInstance = hinstance;
	this->m_Width = w;
	this->m_Height = h;
	this->m_IsPreview = isPreview;

	this->m_GraphicsHandler->Initialize(
		&this->m_hwnd,
		DirectX::XMINT2(m_Width, m_Height)
	);
	this->m_GraphicsHandler->InitializeGrid();

	this->m_Camera = new Camera();
	this->m_Camera->Initialize(this->m_Width / this->m_Height);
	Camera* oldCam = this->m_GraphicsHandler->SetCamera(this->m_Camera);
	delete oldCam;
	oldCam = nullptr;
	this->m_Camera->UpdateProjection();
	this->m_Camera->Update();

	if (!isPreview)
	{
		this->m_EditorInputHandler = new EditorInputHandler(
			this->m_hInstance,
			this->m_hwnd,
			this->m_Camera,
			this->m_Width,
			this->m_Height,
			this->m_GraphicsHandler,
			&this->m_currentLevel,
			modelPtr
		);
	}

	return Resources::ST_OK;
}

Communicator::Communicator()
{

}

Communicator::~Communicator()
{

}

Resources::Status Communicator::Release()
{
	this->m_GraphicsHandler->Shutdown();
	delete this->m_GraphicsHandler;

	if (!this->m_IsPreview)
	{
		delete this->m_EditorInputHandler;
	}
	return Resources::ST_OK;
}

Resources::Status Communicator::FindModel(int modelID, std::vector<Container>* modelPtr)
{
	//std::unordered_map<unsigned int, std::vector<Container>>::iterator got = m_ModelMap.find(modelID);
	//
	//if (got == m_ModelMap.end()) { // if  does not exists in memory
	//	return Resources::Status::ST_RES_MISSING;
	//}
	//else {
	//	modelPtr = &got->second;
		return Resources::Status::ST_OK;
	//}
}

Resources::Status Communicator::GetComponent(unsigned int modelID, unsigned int instanceID, Container& container)
{
	return m_currentLevel.GetModelEntity(modelID, instanceID, container);
}

Resources::Status Communicator::AddModel(unsigned int modelID, unsigned int instanceID, DirectX::XMVECTOR position, DirectX::XMVECTOR rotation)
{
	return m_currentLevel.AddModelEntity(modelID, instanceID, position, rotation);
}

Resources::Status Communicator::UpdateModel(unsigned int modelID, unsigned int instanceID, DirectX::XMVECTOR position, DirectX::XMVECTOR rotation)
{
	return m_currentLevel.UpdateModel(modelID, instanceID, position, rotation);
}

Resources::Status Communicator::RemoveModel(unsigned int modelID, unsigned int instanceID)
{
	return m_currentLevel.RemoveModel(modelID, instanceID);
}
<commit_msg>UPDATE: Initializing the editor renderer with the right flag<commit_after>#include "EditorCommunicator.h"

Resources::Status Communicator::Initialize(
	HWND hwnd,
	HINSTANCE hinstance,
	int w, int h,
	bool isPreview,
	std::vector<Resources::Model*>* modelPtr
)
{
	this->m_GraphicsHandler = new GraphicsHandler();
	this->m_hwnd = hwnd;
	this->m_hInstance = hinstance;
	this->m_Width = w;
	this->m_Height = h;
	this->m_IsPreview = isPreview;

	this->m_GraphicsHandler->Initialize(
		&this->m_hwnd,
		DirectX::XMINT2(m_Width, m_Height), true
	);
	this->m_GraphicsHandler->InitializeGrid();

	this->m_Camera = new Camera();
	this->m_Camera->Initialize(this->m_Width / this->m_Height);
	Camera* oldCam = this->m_GraphicsHandler->SetCamera(this->m_Camera);
	delete oldCam;
	oldCam = nullptr;
	this->m_Camera->UpdateProjection();
	this->m_Camera->Update();

	if (!isPreview)
	{
		this->m_EditorInputHandler = new EditorInputHandler(
			this->m_hInstance,
			this->m_hwnd,
			this->m_Camera,
			this->m_Width,
			this->m_Height,
			this->m_GraphicsHandler,
			&this->m_currentLevel,
			modelPtr
		);
	}

	return Resources::ST_OK;
}

Communicator::Communicator()
{

}

Communicator::~Communicator()
{

}

Resources::Status Communicator::Release()
{
	this->m_GraphicsHandler->Shutdown();
	delete this->m_GraphicsHandler;

	if (!this->m_IsPreview)
	{
		delete this->m_EditorInputHandler;
	}
	return Resources::ST_OK;
}

Resources::Status Communicator::FindModel(int modelID, std::vector<Container>* modelPtr)
{
	//std::unordered_map<unsigned int, std::vector<Container>>::iterator got = m_ModelMap.find(modelID);
	//
	//if (got == m_ModelMap.end()) { // if  does not exists in memory
	//	return Resources::Status::ST_RES_MISSING;
	//}
	//else {
	//	modelPtr = &got->second;
		return Resources::Status::ST_OK;
	//}
}

Resources::Status Communicator::GetComponent(unsigned int modelID, unsigned int instanceID, Container& container)
{
	return m_currentLevel.GetModelEntity(modelID, instanceID, container);
}

Resources::Status Communicator::AddModel(unsigned int modelID, unsigned int instanceID, DirectX::XMVECTOR position, DirectX::XMVECTOR rotation)
{
	return m_currentLevel.AddModelEntity(modelID, instanceID, position, rotation);
}

Resources::Status Communicator::UpdateModel(unsigned int modelID, unsigned int instanceID, DirectX::XMVECTOR position, DirectX::XMVECTOR rotation)
{
	return m_currentLevel.UpdateModel(modelID, instanceID, position, rotation);
}

Resources::Status Communicator::RemoveModel(unsigned int modelID, unsigned int instanceID)
{
	return m_currentLevel.RemoveModel(modelID, instanceID);
}
<|endoftext|>