Exemplo n.º 1
0
QJsonObject DemandListModel::representation() const{

	QJsonObject rep;

	rep.insert(nextInsertIdIndex, QJsonValue(_nextInsertId));

	rep.insert(numberOfChoicesIndex, QJsonValue((int) _numberOfChoices));

	QJsonArray additionalVars;

	for(QString varName : _additionalVariablesName){
		additionalVars.push_back(QJsonValue(varName));
	}

	rep.insert(additionalVarsIndex, additionalVars);

	QJsonArray tuples;

	for(DemandTuple tuple : _tuples){
		tuples.push_back(representTuple(tuple));
	}

	rep.insert(tuplesIndex, tuples);

	return rep;

}
Exemplo n.º 2
0
QJsonObject DemandListModel::representTuple(DemandTuple const& tuple) const{

	QJsonObject rep;

	rep.insert(idIndex, QJsonValue( (int) tuple.index));
	rep.insert(namesIndex, tuple.names);

	QJsonArray additionals;

	for(QString var : tuple.additionalVars){
		additionals.push_back(QJsonValue(var));
	}

	rep.insert(additionalVarsIndex, additionals);

	QJsonArray choices;

	for (int choice : tuple.preferences){
		choices.push_back(QJsonValue(choice));
	}

	rep.insert(choicesIndex, choices);

	return rep;

}
Exemplo n.º 3
0
QVariant ListTransactionsCommand::operator ()(const QVariantMap &request)
{
    QJsonArray result;

    TransactionStore & store = _database.getTransactions();

    if(request.contains("limit"))
    {
        DataRange<TransactionStore> range(store);
        range.setLimit(request["limit"].toInt());

        if(request.contains("offset"))
        {
            range.setOffset(request["offset"].toInt());
        }

        for(DataRange<TransactionStore>::ReverseIterator it = range.rbegin(), end = range.rend(); it!=end; ++it)
        {
            result.push_back(*it);
        }
    }
    else
    {
        for(TransactionStore::ReverseIterator  it = store.rbegin(), end = store.rend(); it!=end; ++it)
        {
            result.push_back(*it);
        }
    }

    return QVariant::fromValue(result.toVariantList());
}
Exemplo n.º 4
0
QJsonArray DomainServerNodeData::overrideValuesIfNeeded(const QJsonArray& newStats) {
    QJsonArray result;
    for (const auto& value : newStats) {
        if (value.isObject()) {
            result.push_back(overrideValuesIfNeeded(value.toObject()));
        } else if (value.isArray()) {
            result.push_back(overrideValuesIfNeeded(value.toArray()));
        } else {
            result.push_back(value);
        }
    }
    return result;
}
Exemplo n.º 5
0
void WorkspaceSerializer::Write(const QString& fileName, const SignalData& data, const PlotInfo& plotInfo, bool writeValues /*= true*/)
{
	QJsonObject json;
	json["background"] = plotInfo.getBackgroundColor().name();
	if (writeValues)
	{
		if (auto domain = data.getDomain())
			json["domain"] = domain->name;
	}
	
	QJsonArray signArray;
	data.onSignals([&](const Signal& signal){
		QJsonObject signObj;
		signObj["name"] = signal.name;
		signObj["color"] = signal.graphic.color.name();
		signObj["visible"] = signal.graphic.visible;
		signObj["range"] = ToJsonArray(QVector < qreal > {signal.graphic.rangeLower, signal.graphic.rangeUpper});
		if (writeValues)
			signObj["values"] = ToJsonArray(signal.y);
		signObj["ticks"] = ToJsonArray(signal.graphic.ticks);
		signObj["tickLabels"] = ToJsonArray(signal.graphic.tickLabels);
		signArray.push_back(std::move(signObj));
	});
	json["signals"] = signArray;
	
	QJsonDocument saveDoc(json);
	QFile outF(fileName);
	outF.open(QIODevice::WriteOnly);
	outF.write(saveDoc.toJson(QJsonDocument::Indented));
}
void Visitor<Reader<JSONObject>>::readFrom_impl(
        const Explorer::DeviceDocumentPlugin& plug)
{
    // Childrens of the root node are the devices
    // We don't save their children if they don't have canSerialize().

    m_obj["RootNode"] = QJsonObject{};
    QJsonArray children;
    for(auto& node : plug.rootNode().children())
    {
        QJsonObject this_node;

        ISCORE_ASSERT(node.is<Device::DeviceSettings>());
        const Device::DeviceSettings& dev = node.get<Device::DeviceSettings>();
        auto actual = plug.list().find(dev.name);
        ISCORE_ASSERT(actual != plug.list().devices().cend());
        if((*actual)->capabilities().canSerialize)
        {
            this_node = toJsonObject(node);
        }
        else
        {
            this_node = toJsonObject(node.impl());
        }


        children.push_back(std::move(this_node));
    }
    m_obj["Children"] = children;
}
Exemplo n.º 7
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DynamicTableData::writeJson(QJsonObject& json) const
{
  json["Dynamic Table Data"] = writeData();

  QJsonArray rHeaders;
  foreach(QString header, m_RowHeaders)
  {
    rHeaders.push_back(header);
  }
Exemplo n.º 8
0
QJsonObject Attributs::toJson() const
{
    QJsonObject json;
    json.insert("live", QJsonValue(live));
    json.insert("actionPoint", QJsonValue(actionPoint));
    json.insert("movePoint",QJsonValue(movePoint));
    json.insert("powerBonnus",QJsonValue(powerBonnus));
    json.insert("fixDamageBonnus",QJsonValue(fixDamageBonnus));

    QJsonArray valuesArray;
    for(Value v:values)
    {
        valuesArray.push_back(v.toJson());
    }
    json.insert("values",QJsonValue(valuesArray));

    QJsonArray fixResistancesArray;
    for(Value v:fixResistances)
    {
        fixResistancesArray.push_back(v.toJson());
    }
    json.insert("fixResistances",QJsonValue(fixResistancesArray));

    QJsonArray relativeResistancesArray;
    for(Value v:relativeResistances)
    {
        relativeResistancesArray.push_back(v.toJson());
    }
    json.insert("relativeResistances",QJsonValue(relativeResistancesArray));

    QJsonArray fixFightBonusArray;
    for(Value v:fixFightBonus)
    {
        fixFightBonusArray.push_back(v.toJson());
    }
    json.insert("fixFightBonus",QJsonValue(fixFightBonusArray));

    QJsonArray relativeFightBonusArray;
    for(Value v:relativeFightBonus)
    {
        relativeFightBonusArray.push_back(v.toJson());
    }
    json.insert("relativeFightBonus",QJsonValue(relativeFightBonusArray));
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QJsonArray DataContainerArrayProxy::writeMap(QMap<QString, DataContainerProxy> map) const
{
  QJsonArray dcArray;
  for (QMap<QString, DataContainerProxy>::iterator iter = map.begin(); iter != map.end(); ++iter)
  {
    QJsonObject obj;
    (*iter).writeJson(obj);
    dcArray.push_back(obj);
  }
  return dcArray;
}
Exemplo n.º 10
0
void Cockpit::savesettings()
{
     QFile saveFile(SETTINGSFILE);
     if(not overlay)
     {
         QJsonObject ss(settings.object());
         QJsonArray geo;
         geo.push_back(QJsonValue( this->pos().x()));
         geo.push_back(QJsonValue( this->pos().y()));
         geo.push_back(QJsonValue( this->width()));
         geo.push_back(QJsonValue( this->height()));
         geo.push_back(QJsonValue(double(this->isMaximized())));
         ss["window_geometry"] = geo;
         settings.setObject(ss);
     }
     saveFile.open(QIODevice::WriteOnly);
     saveFile.write(settings.toJson());
     cout << "writing json!" <<endl;
     saveFile.close();
}
Exemplo n.º 11
0
QJsonValue glmToJson(const T& t) {
    static const T DEFAULT_VALUE = T();
    if (t == DEFAULT_VALUE) {
        return QJsonValue();
    }
    QJsonArray result;
    for (auto i = 0; i < t.length(); ++i) {
        result.push_back(t[i]);
    }
    return result;
}
QJsonDocument SplicePicturesPanel::getConfiguration() {
    QJsonArray array;
    for (QVector<SplicePicturesImageItem>::iterator iter = imageList.begin(); iter != imageList.end(); iter++) {
        array.push_back(iter->toJsonObject());
    }
    QJsonObject json;
    json.insert("zoom", (double)imageZoom);
    json.insert("images", array);
    QJsonDocument doc;
    doc.setObject(json);
    return doc;
}
Exemplo n.º 13
0
static auto arrayToJson(Selected_T &&selected)
{
    QJsonArray array;
    if (!selected.empty())
    {
        for (const auto &element : selected)
        {
            array.push_back(marshall<JSONObject>(*element));
        }
    }

    return array;
}
Exemplo n.º 14
0
QJsonObject Project::toJSON() const
{
    QJsonArray eventTypes;
    for (auto it = mEventTypes.begin(); it != mEventTypes.end(); it++) {
        eventTypes.push_back(it->get()->toJSON());
    }

    QJsonObject project;
    project["name"] = mName;
    project["lastOpenedTimeline"] = QDir(root()).relativeFilePath(mLastOpenedTimeline);
    project["eventTypes"] = eventTypes;
    return project;
}
Exemplo n.º 15
0
void Experiment::write(QJsonObject& jo, bool withRuns) const {
	jo["title"] = title;
	jo["prepare"] = prepare;
	jo["cleanup"] = cleanup;
	jo["command"] = command;
	QJsonArray sets;
	for (const EnvironmentSet* s : envSets) {
		sets.push_back(s->name());
	}
	QJsonArray envs;
	for (const Environment* e : runs.keys()) {
		QJsonObject o;
		o["big"] = e->big;
		o["little"] = e->big;
		o["label"] = e->label;
		o["frequency"] = static_cast<qint64>(e->freq);
		o["frequency_max"] = static_cast<qint64>(e->freq_max);
		o["frequency_min"] = static_cast<qint64>(e->freq_min);
		o["governor"] = e->governor;
		if (withRuns) {
			QJsonArray runArray;
			for (QPair<double,double> run : runs[e]) {
				QJsonObject jr;
				jr["from"] = run.first;
				jr["to"] = run.second;
				runArray.push_back(jr);
			}
			o["runs"] = runArray;
		}
		envs.append(o);
	}
	jo["environment_sets"] = sets;
	jo["environments"] = envs;
	jo["cooldown_time"] = static_cast<qint64>(cooldown_time);
	jo["tail_time"] = static_cast<qint64>(tail_time);
}
Exemplo n.º 16
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void DREAM3DSettings::setValue(const QString& key, const QStringList& list)
{
  QJsonArray jsonArray;

  for (int i = 0; i < list.size(); i++)
  {
    jsonArray.push_back(list[i]);
  }

  m_Stack.top()->group.insert(key, jsonArray);

  // If this is the root, write to the file
  if (m_Stack.top()->groupName.isEmpty())
  {
    writeToFile();
  }
}
Exemplo n.º 17
0
QString deviceListToJson(QList<DeviceInfo> deviceList)
{
    QJsonArray array;
    for (auto device : deviceList) {
        QJsonObject obj;
        obj.insert("path", device.path);
        obj.insert("label", device.label);
        obj.insert("used", static_cast<int>(device.used));
        obj.insert("total", static_cast<int>(device.total));
        obj.insert("needformat", device.needFormat);
        qDebug() << device.needFormat;
        array.push_back(obj);
    }

    QJsonDocument doc;
    doc.setArray(array);
    return QString::fromUtf8(doc.toJson());
}
Exemplo n.º 18
0
void terrama2::core::ProcessLogger::addValue(const std::string& tag, const std::string& value, RegisterId registerId) const
{
  if(!isValid_)
    throw terrama2::core::LogException() << ErrorDescription("Error on log!");

  if(tableName_.empty())
  {
    QString errMsg = QObject::tr("Can not find log table name. Is it setted?");
    TERRAMA2_LOG_ERROR() << errMsg;
    throw terrama2::core::LogException() << ErrorDescription(errMsg);
  }

  std::string sql = "SELECT data FROM "+ tableName_ + " WHERE id = " + QString::number(registerId).toStdString();

  std::shared_ptr< te::da::DataSourceTransactor > transactor = dataSource_->getTransactor();

  std::shared_ptr<te::da::DataSet> tempDataSet(transactor->query(sql));

  if(!tempDataSet)
  {
    QString errMsg = QObject::tr("Can not find log message table name!");
    TERRAMA2_LOG_ERROR() << errMsg;
    throw terrama2::core::LogException() << ErrorDescription(errMsg);
  }

  if(!tempDataSet->moveNext())
  {
    QString errMsg = QObject::tr("Error to access log message table!");
    TERRAMA2_LOG_ERROR() << errMsg;
    throw terrama2::core::LogException() << ErrorDescription(errMsg);
  }

  QByteArray readJson = tempDataSet->getAsString("data").c_str();

  QJsonDocument docJson(QJsonDocument::fromJson(readJson));
  QJsonObject obj = docJson.object();
  QString qtag = QString::fromStdString(tag);
  QJsonArray array = obj[qtag].toArray();
  array.push_back(QString::fromStdString(value));
  obj.insert(qtag, array);

  updateData(registerId, obj);
}
Exemplo n.º 19
0
void QMetaObjectPublisher::sendPendingPropertyUpdates()
{
    if (blockUpdates || !clientIsIdle || pendingPropertyUpdates.isEmpty()) {
        return;
    }

    QJsonArray data;

    // convert pending property updates to JSON data
    const PendingPropertyUpdates::const_iterator end = pendingPropertyUpdates.constEnd();
    for (PendingPropertyUpdates::const_iterator it = pendingPropertyUpdates.constBegin(); it != end; ++it) {
        const QObject *object = it.key();
        const QMetaObject *const metaObject = object->metaObject();
        const SignalToPropertyNameMap &objectsSignalToPropertyMap = signalToPropertyMap.value(object);
        // maps property name to current property value
        QJsonObject properties;
        // maps signal index to list of arguments of the last emit
        QJsonObject sigs;
        const SignalToArgumentsMap::const_iterator sigEnd = it.value().constEnd();
        for (SignalToArgumentsMap::const_iterator sigIt = it.value().constBegin(); sigIt != sigEnd; ++sigIt) {
            // TODO: can we get rid of the int <-> string conversions here?
            foreach (const int propertyIndex, objectsSignalToPropertyMap.value(sigIt.key())) {
                const QMetaProperty &property = metaObject->property(propertyIndex);
                Q_ASSERT(property.isValid());
                properties[QString::number(propertyIndex)] = wrapResult(property.read(object));
            }
            sigs[QString::number(sigIt.key())] = QJsonArray::fromVariantList(sigIt.value());
        }
        QJsonObject obj;
        obj[KEY_OBJECT] = registeredObjectIds.value(object);
        obj[KEY_SIGNALS] = sigs;
        obj[KEY_PROPERTIES] = properties;
        data.push_back(obj);
    }

    pendingPropertyUpdates.clear();
    QJsonObject message;
    message[KEY_TYPE] = TypePropertyUpdate;
    message[KEY_DATA] = data;
    setClientIsIdle(false);
    broadcastMessage(message);
}
QJsonArray WhiteboardList::availableServers(void)
{
    QJsonArray data;
    QJsonObject buf;
    const auto &&currentTime = QDateTime::currentDateTime().toTime_t();

    for(const auto &now: m_availableServers)
    {
        if((currentTime - now.first) > 10) { continue; }

        buf["ip"] = QHostAddress(now.second.ip).toString();
        buf["hostName"] = now.second.hostName;
        buf["serverName"] = now.second.serverName;
        buf["password"] = now.second.password;
        buf["clientEdit"] = now.second.clientEdit;
        data.push_back(buf);
    }

    return data;
}
Exemplo n.º 21
0
void Ledger::historySuccess(QNetworkReply& reply) {
    // here we send a historyResult with some extra stuff in it
    // Namely, the styled text we'd like to show.  The issue is the
    // QML cannot do that easily since it doesn't know what the wallet
    // public key(s) are.  Let's keep it that way
    QByteArray response = reply.readAll();
    QJsonObject data = QJsonDocument::fromJson(response).object();
    qInfo(commerce) << "history" << "response" << QJsonDocument(data).toJson(QJsonDocument::Compact);

    // we will need the array of public keys from the wallet
    auto wallet = DependencyManager::get<Wallet>();
    auto keys = wallet->listPublicKeys();

    // now we need to loop through the transactions and add fancy text...
    auto historyArray = data.find("data").value().toObject().find("history").value().toArray();
    QJsonArray newHistoryArray;

    // TODO: do this with 0 copies if possible
    for (auto it = historyArray.begin(); it != historyArray.end(); it++) {
        // We have 2 text fields to synthesize, the one on the left is a listing
        // of the HFC in/out of your wallet.  The one on the right contains an explaination
        // of the transaction.  That could be just the memo (if it is a regular purchase), or
        // more text (plus the optional memo) if an hfc transfer
        auto valueObject = (*it).toObject();
        valueObject["hfc_text"] = hfcString(valueObject["sent_money"], valueObject["received_money"]);
        valueObject["transaction_text"] = transactionString(valueObject);
        newHistoryArray.push_back(valueObject);
    }
    // now copy the rest of the json -- this is inefficient
    // TODO: try to do this without making copies
    QJsonObject newData;
    newData["status"] = "success";
    QJsonObject newDataData;
    newDataData["history"] = newHistoryArray;
    newData["data"] = newDataData;
    newData["current_page"] = data["current_page"].toInt();
    emit historyResult(newData);
}
Exemplo n.º 22
0
bool UserBank::save()
{
    QJsonArray a;
    QList<QString> names;
    QList<int> values;
    names = record.keys();
    values = record.values();
    for (int i=0; i<record.size(); i++) {
        QJsonObject b ;
        b["name"] = names[i];
        b["money"] = values[i];
        a.push_back(b);
    }
    bool ok = saveJsonFile("giftrecord.json", QJsonDocument(a));
    if (!ok) {
        qDebug()<< " save record file failed!!";
        return false;
    }
    else {
         qDebug()<< " save record file succeed!!";
         return true;
    }
}
Exemplo n.º 23
0
QJsonObject ReadiumJSApi::getPackageJSON(PackagePtr pckg)
{
	QJsonObject obj;
#if _USE_READIUM

	// Level 0
	{
		obj["rootUrl"] = QString("/");			//[dict setObject : @"/" forKey:@"rootUrl"];
		obj["rendition_layout"] = QString("");	//[dict setObject : _rendition_layout forKey : @"rendition_layout"];
		obj["rendition_flow"] = QString("");	//[dict setObject : _rendition_flow forKey : @"rendition_flow"];

		QJsonObject spine;

		QJsonArray spineItems;

		size_t idx = 0;
		shared_ptr<SpineItem>   pSpineItem = pckg->SpineItemAt(idx++);
		while (pSpineItem != 0)
		{
			QJsonObject curItem;
			shared_ptr<ManifestItem>    manifestItem = pSpineItem->ManifestItem();
			if (manifestItem)
			{
				//qDebug() << QString(manifestItem->BaseHref().c_str());
				curItem["href"] = QString(manifestItem->BaseHref().c_str());	//[dict setObject : _href forKey : @"href"];
			}
			else
				curItem["href"] = QString("");


			curItem["idref"] = QString(pSpineItem->Idref().c_str());	//[dict setObject : _idref forKey : @"idref"];

			//pSpineItem->Spread()
			//enum class PageSpread
			//{
			//	Automatic,              ///< No value specified by the author.
			//	Left,                   ///< This is the left page of a spread.
			//	Right,                  ///< This is the right page of a spread.
			//	Center,                 ///< This is a double-width page, spread across both left & right.
			//};


			curItem["page_spread"] = QString("");//[dict setObject : _page_spread forKey : @"page_spread"];
			curItem["rendition_layout"] = QString("");;//[dict setObject : _rendition_layout forKey : @"rendition_layout"];
			curItem["rendition_spread"] = QString("");;//[dict setObject : _rendition_spread forKey : @"rendition_spread"];
			curItem["rendition_flow"] = QString("");;//[dict setObject : _rendition_flow forKey : @"rendition_flow"];
			curItem["media_overlay_id"] = QString("");;//[dict setObject : _media_overlay_id forKey : @"media_overlay_id"];
			spineItems.push_back(curItem);

			pSpineItem = pckg->SpineItemAt(idx++);
		}

		spine["items"] = spineItems;
		spine["direction"] = QString("default"); //[dict setObject : _direction forKey : @"direction"];
		obj["spine"] = spine;//[dict setObject : [_spine toDictionary] forKey : @"spine"];



		QJsonObject media_overlay;

		{
			std::shared_ptr<MediaOverlaysSmilModel>   smilModel = pckg->MediaOverlaysSmilModel();
			std::vector<std::shared_ptr<SMILData>>::size_type n = smilModel->GetSmilCount();
			QJsonArray smil_models;
			std::vector<std::shared_ptr<SMILData>>::size_type i = 0;
			for (i = 0; i < n; ++i)
			{
				std::shared_ptr<SMILData> curSmil = smilModel->GetSmil(i);
				QJsonObject smilModel;

				if (curSmil->XhtmlSpineItem())
					smilModel["spineItemId"] = QString(curSmil->XhtmlSpineItem()->Idref().c_str());
				else
					smilModel["spineItemId"] = QString("");

				//smilModel["id"]

				std::ostringstream stringStream;
				stringStream << curSmil->DurationMilliseconds_Calculated() / 1000.;
				std::string copyOfStr = stringStream.str();

				smilModel["duration"] = copyOfStr;

				if (curSmil->SmilManifestItem())
				{
					smilModel["id"] = QString(curSmil->SmilManifestItem()->Identifier().c_str());
					smilModel["href"] = QString(curSmil->SmilManifestItem()->Href().c_str());
				}
				else
				{
					smilModel["id"] = QString("");
					smilModel["href"] = QString("fake.smil");
				}

				smilModel["smilVersion"] = QString("3.0");
				//[dict setObject : self.children forKey : @"children"];


				shared_ptr<const ePub3::SMILData::Sequence> seqBody = curSmil->Body();
				QJsonArray arrChildren = getJSON(seqBody);
				smilModel["children"] = arrChildren;
				//qDebug() << smilModel;

				smil_models.push_back(smilModel);
			}

			/*
			[dict setObject : smilDictionaries forKey : @"smil_models"];
			{
			for (DNSmilModel *mo in _smilModels) {
			[smilDictionaries addObject : [mo toDictionary]];
			}
			[
			[dict setObject : self.id forKey : @"id"];
			[dict setObject : self.spineItemId forKey : @"spineItemId"];
			[dict setObject : self.href forKey : @"href"];
			[dict setObject : self.smilVersion forKey : @"smilVersion"];

			[dict setObject : self.duration forKey : @"duration"];

			[dict setObject : self.children forKey : @"children"];
			]
			}*/
			media_overlay["smil_models"] = smil_models;

			QJsonArray skippables;
			QJsonArray escapables;

			smilModel = pckg->MediaOverlaysSmilModel();
			
			if (smilModel)
			{
				std::vector<string>::size_type nCount = smilModel->GetSkippablesCount();
				for (std::vector<string>::size_type i = 0; i < nCount; ++i)
				{
					string sSkippable = smilModel->GetSkippable(i);
					skippables.push_back(sSkippable.c_str());
				}

				nCount = smilModel->GetEscapablesCount();
				for (std::vector<string>::size_type i = 0; i < nCount; ++i)
				{
					string sEsc = smilModel->GetEscapable(i);
					escapables.push_back(sEsc.c_str());
				}

			}
			media_overlay["skippables"] = skippables;//[dict setObject : self.skippables forKey : @"skippables"];
			media_overlay["escapables"] = escapables;//[dict setObject : self.escapables forKey : @"escapables"];
			media_overlay["duration"] = QString(pckg->MediaOverlays_DurationTotal().c_str()); //[dict setObject : self.duration forKey : @"duration"]; = 1403.5
			media_overlay["narrator"] = QString(pckg->MediaOverlays_Narrator().c_str());//[dict setObject : self.narrator forKey : @"narrator"];
			media_overlay["activeClass"] = QString(pckg->MediaOverlays_ActiveClass().c_str());//[dict setObject : self.activeClass forKey : @"activeClass"];, "activeClass" : "-epub-media-overlay-active",
			media_overlay["playbackActiveClass"] = QString(pckg->MediaOverlays_PlaybackActiveClass().c_str());//[dict setObject : self.playbackActiveClass forKey : @"playbackActiveClass"];
		}
		obj["media_overlay"] = media_overlay; //[dict setObject : [_mediaOverlay toDictionary] forKey : @"media_overlay"];

		return obj;
	}

#endif		
	return obj;
}
Exemplo n.º 24
0
//------------------------------------------------------------------------------
// Name:
//------------------------------------------------------------------------------
QJsonArray QJsonArray::fromStringList(const QStringList &list) {
	QJsonArray a;
	Q_FOREACH(const QString &s, list) {
		a.push_back(QJsonValue(s));
	}
Exemplo n.º 25
0
bool p_isolation_metrics(QStringList timeseries_list, QString firings_path, QString metrics_out_path, QString pair_metrics_out_path, P_isolation_metrics_opts opts)
{
    qDebug().noquote() << "Starting p_isolation_metrics";

    DiskReadMda32 X(2, timeseries_list);
    Mda firings(firings_path);

    int M = X.N1();
    int T = opts.clip_size;

    QMap<int, P_isolation_metrics::ClusterData> cluster_data;

    QVector<double> times(firings.N2());
    QVector<int> labels(firings.N2());
    for (bigint i = 0; i < firings.N2(); i++) {
        times[i] = firings.value(1, i);
        labels[i] = firings.value(2, i);
    }

    QSet<int> used_cluster_numbers_set;
    for (bigint i = 0; i < labels.count(); i++) {
        used_cluster_numbers_set.insert(labels[i]);
    }
    if (!opts.cluster_numbers.isEmpty()) {
        used_cluster_numbers_set = used_cluster_numbers_set.intersect(opts.cluster_numbers.toSet());
    }
    QList<int> cluster_numbers = used_cluster_numbers_set.toList();
    qSort(cluster_numbers);

    qDebug().noquote() << "Computing cluster metrics...";
#pragma omp parallel for
    for (int jj = 0; jj < cluster_numbers.count(); jj++) {
        DiskReadMda32 X0;
        QVector<double> times_k;
        int k;
        P_isolation_metrics_opts opts0;
#pragma omp critical
        {
            X0 = X;
            k = cluster_numbers[jj];
            for (bigint i = 0; i < labels.count(); i++) {
                if (labels[i] == k)
                    times_k << times[i];
            }
            opts0 = opts;
        }

        QJsonObject tmp = P_isolation_metrics::get_cluster_metrics(X0, times_k, opts0);

#pragma omp critical
        {
            P_isolation_metrics::ClusterData CD;
            CD.times = times_k;
            CD.cluster_metrics = tmp;
            cluster_data[k] = CD;
        }
    }

    //compute templates
    qDebug().noquote() << "Computing templates...";
    Mda32 templates0;
    {
        QSet<int> cluster_numbers_set = cluster_numbers.toSet();
        QVector<double> times;
        QVector<int> labels;
        for (bigint i = 0; i < firings.N2(); i++) {
            bigint label0 = (bigint)firings.value(2, i);
            if (cluster_numbers_set.contains(label0)) {
                //inds << i;
                times << firings.value(1, i);
                labels << label0;
            }
        }

        //templates0 = compute_templates_0(X, times, labels, opts.clip_size);
        templates0 = compute_templates_in_parallel(X, times, labels, opts.clip_size);
    }

    qDebug().noquote() << "Determining pairs to compare...";
    QJsonArray cluster_pairs;
    int num_comparisons_per_cluster = 10;
    QSet<QString> pairs_to_compare = P_isolation_metrics::get_pairs_to_compare(templates0, num_comparisons_per_cluster, cluster_numbers, opts);
    QList<QString> pairs_to_compare_list = pairs_to_compare.toList();
    qSort(pairs_to_compare_list);
#pragma omp parallel for
    for (int jj = 0; jj < pairs_to_compare_list.count(); jj++) {
        QString pairstr;
        int k1, k2;
        QVector<double> times_k1, times_k2;
        P_isolation_metrics_opts opts0;
        DiskReadMda32 X0;
#pragma omp critical
        {
            pairstr = pairs_to_compare_list[jj];
            QStringList vals = pairstr.split("-");
            k1 = vals[0].toInt();
            k2 = vals[1].toInt();
            times_k1 = cluster_data.value(k1).times;
            times_k2 = cluster_data.value(k2).times;
            opts0 = opts;
            X0 = X;
        }

        QJsonObject pair_metrics = P_isolation_metrics::get_pair_metrics(X0, times_k1, times_k2, opts0);

#pragma omp critical
        {
            QJsonObject tmp;
            tmp["label"] = QString("%1,%2").arg(k1).arg(k2);
            tmp["metrics"] = pair_metrics;
            double overlap = pair_metrics["overlap"].toDouble();
            if (1 - overlap < cluster_data[k1].isolation) {
                cluster_data[k1].isolation = 1 - overlap;
                cluster_data[k1].overlap_cluster = k2;
            }
            if (1 - overlap < cluster_data[k2].isolation) {
                cluster_data[k2].isolation = 1 - overlap;
                cluster_data[k2].overlap_cluster = k1;
            }
            cluster_pairs.push_back(tmp);
        }
    }

    if (opts.compute_bursting_parents) {
        qDebug().noquote() << "Computing bursting parents...";
        for (int jj = 0; jj < cluster_numbers.count(); jj++) {
            int k1 = cluster_numbers[jj];
            Mda32 template1;
            templates0.getChunk(template1, 0, 0, k1 - 1, M, T, 1);
            cluster_data[k1].bursting_parent = 0;
            for (int kk = 0; kk < cluster_numbers.count(); kk++) {
                int k2 = cluster_numbers[kk];
                Mda32 template2;
                templates0.getChunk(template2, 0, 0, k2 - 1, M, T, 1);
                if (P_isolation_metrics::is_bursting_parent_candidate(template1, template2, opts)) {
                    bool verbose = false;
                    if (P_isolation_metrics::test_bursting_timing(cluster_data[k1].times, cluster_data[k2].times, opts, verbose)) {
                        cluster_data[k1].bursting_parent = k2;
                    }
                }
            }
        }
    }

    qDebug().noquote() << "preparing clusters array";
    QJsonArray clusters;
    foreach (int k, cluster_numbers) {
        QJsonObject tmp;
        tmp["label"] = k;
        cluster_data[k].cluster_metrics["isolation"] = cluster_data[k].isolation;
        cluster_data[k].cluster_metrics["overlap_cluster"] = cluster_data[k].overlap_cluster;
        if (opts.compute_bursting_parents)
            cluster_data[k].cluster_metrics["bursting_parent"] = cluster_data[k].bursting_parent;
        tmp["metrics"] = cluster_data[k].cluster_metrics;
        clusters.push_back(tmp);
    }
Exemplo n.º 26
0
QJsonObject AudioMixerClientData::getAudioStreamStats() {
    QJsonObject result;

    QJsonObject downstreamStats;
    AudioStreamStats streamStats = _downstreamAudioStreamStats;
    downstreamStats["desired"] = streamStats._desiredJitterBufferFrames;
    downstreamStats["available_avg_10s"] = streamStats._framesAvailableAverage;
    downstreamStats["available"] = (double) streamStats._framesAvailable;
    downstreamStats["unplayed"] = (double) streamStats._unplayedMs;
    downstreamStats["starves"] = (double) streamStats._starveCount;
    downstreamStats["not_mixed"] = (double) streamStats._consecutiveNotMixedCount;
    downstreamStats["overflows"] = (double) streamStats._overflowCount;
    downstreamStats["lost%"] = streamStats._packetStreamStats.getLostRate() * 100.0f;
    downstreamStats["lost%_30s"] = streamStats._packetStreamWindowStats.getLostRate() * 100.0f;
    downstreamStats["min_gap"] = formatUsecTime(streamStats._timeGapMin);
    downstreamStats["max_gap"] = formatUsecTime(streamStats._timeGapMax);
    downstreamStats["avg_gap"] = formatUsecTime(streamStats._timeGapAverage);
    downstreamStats["min_gap_30s"] = formatUsecTime(streamStats._timeGapWindowMin);
    downstreamStats["max_gap_30s"] = formatUsecTime(streamStats._timeGapWindowMax);
    downstreamStats["avg_gap_30s"] = formatUsecTime(streamStats._timeGapWindowAverage);

    result["downstream"] = downstreamStats;

    AvatarAudioStream* avatarAudioStream = getAvatarAudioStream();

    if (avatarAudioStream) {
        QJsonObject upstreamStats;

        AudioStreamStats streamStats = avatarAudioStream->getAudioStreamStats();
        upstreamStats["mic.desired"] = streamStats._desiredJitterBufferFrames;
        upstreamStats["desired_calc"] = avatarAudioStream->getCalculatedJitterBufferFrames();
        upstreamStats["available_avg_10s"] = streamStats._framesAvailableAverage;
        upstreamStats["available"] = (double) streamStats._framesAvailable;
        upstreamStats["unplayed"] = (double) streamStats._unplayedMs;
        upstreamStats["starves"] = (double) streamStats._starveCount;
        upstreamStats["not_mixed"] = (double) streamStats._consecutiveNotMixedCount;
        upstreamStats["overflows"] = (double) streamStats._overflowCount;
        upstreamStats["silents_dropped"] = (double) streamStats._framesDropped;
        upstreamStats["lost%"] = streamStats._packetStreamStats.getLostRate() * 100.0f;
        upstreamStats["lost%_30s"] = streamStats._packetStreamWindowStats.getLostRate() * 100.0f;
        upstreamStats["min_gap"] = formatUsecTime(streamStats._timeGapMin);
        upstreamStats["max_gap"] = formatUsecTime(streamStats._timeGapMax);
        upstreamStats["avg_gap"] = formatUsecTime(streamStats._timeGapAverage);
        upstreamStats["min_gap_30s"] = formatUsecTime(streamStats._timeGapWindowMin);
        upstreamStats["max_gap_30s"] = formatUsecTime(streamStats._timeGapWindowMax);
        upstreamStats["avg_gap_30s"] = formatUsecTime(streamStats._timeGapWindowAverage);

        result["upstream"] = upstreamStats;
    } else {
        result["upstream"] = "mic unknown";
    }

    QJsonArray injectorArray;
    auto streamsCopy = getAudioStreams();
    for (auto& injectorPair : streamsCopy) {
        if (injectorPair.second->getType() == PositionalAudioStream::Injector) {
            QJsonObject upstreamStats;

            AudioStreamStats streamStats = injectorPair.second->getAudioStreamStats();
            upstreamStats["inj.desired"]  = streamStats._desiredJitterBufferFrames;
            upstreamStats["desired_calc"] = injectorPair.second->getCalculatedJitterBufferFrames();
            upstreamStats["available_avg_10s"] = streamStats._framesAvailableAverage;
            upstreamStats["available"] = (double) streamStats._framesAvailable;
            upstreamStats["unplayed"] = (double) streamStats._unplayedMs;
            upstreamStats["starves"] = (double) streamStats._starveCount;
            upstreamStats["not_mixed"] = (double) streamStats._consecutiveNotMixedCount;
            upstreamStats["overflows"] = (double) streamStats._overflowCount;
            upstreamStats["silents_dropped"] = (double) streamStats._framesDropped;
            upstreamStats["lost%"] = streamStats._packetStreamStats.getLostRate() * 100.0f;
            upstreamStats["lost%_30s"] = streamStats._packetStreamWindowStats.getLostRate() * 100.0f;
            upstreamStats["min_gap"] = formatUsecTime(streamStats._timeGapMin);
            upstreamStats["max_gap"] = formatUsecTime(streamStats._timeGapMax);
            upstreamStats["avg_gap"] = formatUsecTime(streamStats._timeGapAverage);
            upstreamStats["min_gap_30s"] = formatUsecTime(streamStats._timeGapWindowMin);
            upstreamStats["max_gap_30s"] = formatUsecTime(streamStats._timeGapWindowMax);
            upstreamStats["avg_gap_30s"] = formatUsecTime(streamStats._timeGapWindowAverage);

            injectorArray.push_back(upstreamStats);
        }
    }

    result["injectors"] = injectorArray;

    return result;
}
int main(int, char**)
{
  terrama2::core::TerraMA2Init terramaRaii("example", 0);
  terrama2::core::registerFactories();

  //DataProvider information
  terrama2::core::DataProvider* dataProvider = new terrama2::core::DataProvider();
  terrama2::core::DataProviderPtr dataProviderPtr(dataProvider);
  dataProvider->uri = "file://";
  dataProvider->uri+=TERRAMA2_DATA_DIR;

  dataProvider->intent = terrama2::core::DataProviderIntent::COLLECTOR_INTENT;
  dataProvider->dataProviderType = "FILE";
  dataProvider->active = true;

  //DataSeries information
  terrama2::core::DataSeries* dataSeries = new terrama2::core::DataSeries();
  terrama2::core::DataSeriesPtr dataSeriesPtr(dataSeries);
  auto& semanticsManager = terrama2::core::SemanticsManager::getInstance();
  dataSeries->semantics = semanticsManager.getSemantics("DCP-generic");


  terrama2::core::DataSetDcp* dataSet = new terrama2::core::DataSetDcp();
  dataSet->active = true;
  dataSet->format.emplace("folder", "/pcd_toa5/CPV/");
  dataSet->format.emplace("mask", "CPV_slow_%YYYY_%MM_%DD_%hh%mm.dat");
  dataSet->format.emplace("timezone", "+00");
  dataSet->format.emplace("srid", "4326");
  dataSet->format.emplace("header_size", "4");
  dataSet->format.emplace("properties_names_line", "2");
  dataSet->format.emplace("convert_all", "true");
  dataSet->format.emplace("default_type", "TEXT");

  QJsonArray fields;

  {
    QJsonObject obj;

    obj.insert("property_name", QString("TIMESTAMP"));
    obj.insert("alias", QString("datetime"));
    obj.insert("type", QString("DATETIME"));
    obj.insert("format", QString("%YYYY-%MM-%DD %hh:%mm:%ss"));

    fields.push_back(obj);
  }

  {
    QJsonObject obj;

    obj.insert("property_name", QString("RECORD"));
    obj.insert("alias", QString("record"));
    obj.insert("type", QString("INTEGER"));

    fields.push_back(obj);
  }

  {
    QJsonObject obj;

    obj.insert("property_name", QString("E_field_Avg"));
    obj.insert("alias", QString("efield"));
    obj.insert("type", QString("INTEGER"));

    fields.push_back(obj);
  }

  {
    QJsonObject obj;

    obj.insert("property_name", QString("panel_temp_Avg"));
    obj.insert("alias", QString("panel"));
    obj.insert("type", QString("INTEGER"));

    fields.push_back(obj);
  }

  {
    QJsonObject obj;

    obj.insert("property_name", QString("leakage_cur_Avg"));
    obj.insert("alias", QString("leak"));
    obj.insert("type", QString("FLOAT"));

    fields.push_back(obj);
  }

  {
    QJsonObject obj;

    obj.insert("property_name", QString("battery_volt_Avg"));
    obj.insert("alias", QString("bateria"));
    obj.insert("type", QString("FLOAT"));

    fields.push_back(obj);
  }

  {
    QJsonObject obj;

    obj.insert("property_name", QString("internal_RH_Avg"));
    obj.insert("alias", QString("interval"));
    obj.insert("type", QString("TEXT"));

    fields.push_back(obj);
  }

  QJsonObject obj;
  obj.insert("fields", fields);
  QJsonDocument doc(obj);

  dataSet->format.emplace("fields", QString(doc.toJson(QJsonDocument::Compact)).toStdString());

  dataSeries->datasetList.emplace_back(dataSet);

  //empty filter
  terrama2::core::Filter filter;

  //accessing data
  auto accessor = terrama2::core::DataAccessorFactory::getInstance().make(dataProviderPtr, dataSeriesPtr);
  auto remover = std::make_shared<terrama2::core::FileRemover>();
  auto uriMap = accessor->getFiles(filter, remover);

  auto dataMap = accessor->getSeries(uriMap, filter, remover);

  terrama2::core::DcpSeriesPtr dcpSeries = std::make_shared<terrama2::core::DcpSeries>();
  dcpSeries->addDcpSeries(dataMap);

  assert(dcpSeries->dcpSeriesMap().size() == 1);

  QUrl uri;
  uri.setScheme("postgis");
  uri.setHost("localhost");
  uri.setPort(5432);
  uri.setUserName("postgres");
  uri.setPassword("postgres");
  uri.setPath("/terrama2");

  //DataProvider information
  terrama2::core::DataProvider* dataProviderPostGIS = new terrama2::core::DataProvider();
  terrama2::core::DataProviderPtr dataProviderPostGISPtr(dataProviderPostGIS);
  dataProviderPostGIS->uri = uri.url().toStdString();

  dataProviderPostGIS->intent = terrama2::core::DataProviderIntent::PROCESS_INTENT;
  dataProviderPostGIS->dataProviderType = "POSTGIS";
  dataProviderPostGIS->active = true;

  //DataSeries information
  terrama2::core::DataSeries* outputDataSeries = new terrama2::core::DataSeries();
  terrama2::core::DataSeriesPtr outputDataSeriesPtr(outputDataSeries);
  outputDataSeries->semantics = semanticsManager.getSemantics("DCP-postgis");

  terrama2::core::DataSetDcp* dataSetOutput = new terrama2::core::DataSetDcp();
  terrama2::core::DataSetPtr dataSetOutputPtr(dataSetOutput);
  dataSetOutput->active = true;
  dataSetOutput->format.emplace("table_name", "dcp_generic");
  dataSetOutput->format.emplace("timestamp_column", "datetime");

  auto dataStorager = terrama2::core::DataStoragerFactory::getInstance().make(outputDataSeriesPtr, dataProviderPostGISPtr);

  for(auto& item : dataMap)
  {
    dataStorager->store( item.second, dataSetOutputPtr);
  }

  return 0;
}
Exemplo n.º 28
0
 foreach(QString header, m_ColHeaders)
 {
   cHeaders.push_back(header);
 }
Exemplo n.º 29
0
int main(int argc, char* argv[])
{
  terrama2::core::TerraMA2Init terramaRaii("example", 0);
  QCoreApplication app(argc, argv);

  QJsonObject obj;
  QJsonArray providersArray;
  providersArray.push_back(terrama2::core::toJson(buildInputProvider()));
  obj.insert("DataProviders", providersArray);

  QJsonArray seriesArray;
  seriesArray.push_back(terrama2::core::toJson(buildInputDataSeries()));
  obj.insert("DataSeries", seriesArray);

  QJsonDocument doc(obj);

  std::shared_ptr<terrama2::core::DataManager> dataManager = std::make_shared<MockDataManager>();
  terrama2::core::TcpManager tcpManager(dataManager, std::weak_ptr<terrama2::core::ProcessLogger>());
  tcpManager.listen(QHostAddress::Any, 30000);

  QByteArray bytearray;
  QDataStream out(&bytearray, QIODevice::WriteOnly);


  QJsonObject logDb;
  logDb.insert("PG_HOST", QString::fromStdString(TERRAMA2_DATABASE_HOST));
  logDb.insert("PG_PORT", QString::fromStdString(TERRAMA2_DATABASE_PORT));
  logDb.insert("PG_USER", QString::fromStdString(TERRAMA2_DATABASE_USERNAME));
  logDb.insert("PG_PASSWORD", QString::fromStdString(TERRAMA2_DATABASE_PASSWORD));
  logDb.insert("PG_DB_NAME", QString::fromStdString(TERRAMA2_DATABASE_DBNAME));

  QJsonObject serviceConf;
  serviceConf.insert("instance_id", 1);
  serviceConf.insert("log_database", logDb);

  QJsonDocument serviceConfDoc(serviceConf);
  QByteArray serviceConfBytearray;
  QDataStream out2(&serviceConfBytearray, QIODevice::WriteOnly);
  auto jsonServiceConf = serviceConfDoc.toJson(QJsonDocument::Compact);
  out2 << static_cast<uint32_t>(0);
  out2 << static_cast<uint32_t>(terrama2::core::TcpSignal::UPDATE_SERVICE_SIGNAL);
  out2 << jsonServiceConf;
  serviceConfBytearray.remove(8, 4);//Remove QByteArray header
  out2.device()->seek(0);
  out2 << static_cast<uint32_t>(serviceConfBytearray.size() - sizeof(uint32_t));



  auto json = doc.toJson(QJsonDocument::Compact);
  out << static_cast<uint32_t>(0);
  out << static_cast<uint32_t>(terrama2::core::TcpSignal::ADD_DATA_SIGNAL);
  out << json;
  bytearray.remove(8, 4);//Remove QByteArray header
  out.device()->seek(0);
  out << static_cast<uint32_t>(bytearray.size() - sizeof(uint32_t));



  QTcpSocket socket;
  socket.connectToHost("localhost", 30000);
  socket.write(serviceConfBytearray);
  socket.waitForBytesWritten();
  socket.write(bytearray);

  QTimer timer;
  QObject::connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit()));
  timer.start(10000);
  app.exec();

  

  return 0;
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addOptions({
            { "nogui", QString("Using command line arguments, do not show GUI.") },
            { { "p", "path" }, QString("Path for job files or shape files."), QString("path") },
            { { "g", "align" }, QString("Input is not aligned. Find lowest cost alignment.") },
            { { "s", "sourceShape" }, QString("Path for source shape file."), QString("source") },
            { { "t", "targetShape" }, QString("Path for target shape file."), QString("target") },
            { { "a", "auto" }, QString("Automatically try to find initial correspondence. Not used for job files.") },
			{ { "j", "job" }, QString("Job file to load."), QString("job") },
			{ { "f", "folder" }, QString("Folder for a shape dataset."), QString("folder") },
            { { "z", "output" }, QString("Folder for output JSON file."), QString("output") },
			{ { "q", "quiet" }, QString("Skip visualization.") },
            { { "m", "asymmetry" }, QString("Ignore symmetry groups. Used for evaluation.") },

            /* Actual paramteres */
            { { "k", "k" }, QString("(k) parameter for DP search."), QString("k") },
            { { "o", "roundtrip" }, QString("Compute least cost from source to target, and target to source.") },
            { { "c", "cut" }, QString("Allow part cuts/joins.") },

			/* Experiments */
			{ { "e", "experiment" }, QString("Perform hard coded experiments.") },
	});

    if (!parser.parse(QCoreApplication::arguments())) {
        QString errorText = parser.errorText();
        std::cout << qPrintable(errorText);
        return CommandLineError;
    }
	else
		parser.process(a);

	QString path = parser.value("p");
	QDir::setCurrent(path);

	/// Experiments:
	if (parser.isSet("e"))
	{
		QVariantMap options;
        //options["k"].setValue(6);
        //options["isQuietMode"].setValue(true);
		options["isOutputMatching"].setValue(true);
		options["isSaveReport"].setValue(true);
		options["isLogJobs"].setValue(true);

		QString sourceShape = "C:/Development/GeoTopo/standalone/ChairWood2/Woodchair2.xml";
		QString targetShape = "C:/Development/GeoTopo/standalone/chairVK2110/chair2110.xml";

		srand(time(nullptr));

        for (int i = 0; i < 1; i++)
		{
			auto bp = QSharedPointer<BatchProcess>(new BatchProcess(sourceShape, targetShape, options));
			bp->jobUID = (double(rand()) / RAND_MAX) * 10;
			bp->run();

			for (auto & report : bp->jobReports){
				int time = report["search_time"].toInt();
				double c = report["min_cost"].toDouble();

				std::cout << "cost = " << c << " , time = " << time << std::endl;
			}

			//std::swap(sourceShape, targetShape);
		}

		return 0;
	}

    /// Process shape sets:
    if(parser.isSet("folder"))
    {
		QElapsedTimer timer; timer.start();

        QString dataset = parser.value("folder");
        QDir d("");
        QString dir_name = QDir(dataset).dirName();

		// 1) get sorted set of pairs to compare
        QVector< QPair<int, int> > shapePairs;
		auto folders = shapesInDataset(dataset);
		auto folderKeys = folders.keys();
		for (int i = 0; i < folderKeys.size(); i++)
			for (int j = i + 1; j < folderKeys.size(); j++)
                shapePairs << qMakePair(i,j);
		int shapePairsCount = shapePairs.size();
		int curShapePair = 0;

        QMap< QString,QPair<int,int> > pair_idx;

		// 2) perform correspondence for shape pairs
		{
			// Remove previous log file
			d.remove("log.txt");

			// go over pairs
			for (auto shapePair : shapePairs)
			{
				QProcess p;
                QString source = folders[folders.keys().at(shapePair.first)]["graphFile"].toString();
                QString target = folders[folders.keys().at(shapePair.second)]["graphFile"].toString();

				auto sg = QFileInfo(source).baseName();
				auto tg = QFileInfo(target).baseName();

                pair_idx[sg+tg] = qMakePair(shapePair.first, shapePair.second);

				std::cout << QString("Now: %1 / %2").arg(sg).arg(tg).leftJustified(35, ' ', true).toStdString();

				QStringList pargs;

                // Inputs
				pargs << "-s" << source << "-t" << target;	

                // Forward search options
                if (parser.isSet("o")) pargs << "-o";
                if (parser.isSet("k")) pargs << "-k" << parser.value("k");
				if (parser.isSet("q")) pargs << "-q";
                if (parser.isSet("c")) pargs << "-c";
                if (parser.isSet("m")) pargs << "-m";

                // Execute as a seperate process
				p.start(a.applicationFilePath(), pargs);
				p.waitForFinished(-1);

                // Show progress to user
				auto percent = (double(curShapePair++) / shapePairsCount) * 100.0;
				std::cout << QString("[%1 %] - %2 - ").arg((int)percent).arg(shapePairsCount-curShapePair).toStdString();
				int secPerPercent = (timer.elapsed() / 1000) / (percent + 1);
				int timeMinLeft = (secPerPercent * (100 - percent)) / 60;
				std::cout << QString("Time (%1s=%2m) ETA(%3m)\n").arg(timer.elapsed() / 1000).arg(timer.elapsed() / 60000).arg(timeMinLeft).toStdString();
			}
		}

		// 3) prepare results folder
		QString job_name = QString("job_%1").arg(QDateTime::currentDateTime().toString("dd_MM_yyyy_hh_mm_ss"));
		d.mkpath(job_name);

        // 4) collect all pair-wise results
		{
            // output sorted set of shape names
			{
                QFile file(d.absolutePath() + "/" + job_name + "/" + "_" + dir_name + "_shapes.txt");
				if (file.open(QIODevice::WriteOnly | QIODevice::Text)){
					QTextStream out(&file);
					for (int i = 0; i < folderKeys.size(); i++)
						out << QString("%1 %2\n").arg(i).arg(folderKeys.at(i));
				}
			}

			// read log and record the minimum costs and correspondence results
			{
				QFile ff(d.absolutePath() + "/" + "log.txt");
				ff.open(QFile::ReadOnly | QFile::Text);
				QTextStream in(&ff);
				auto datasetLogLines = in.readAll().split("\n", QString::SkipEmptyParts);

				// Record final results
                QJsonArray results;

                for(int idx = 0; idx < datasetLogLines.size(); idx++)
                {
                    // Read matching pair info
                    auto log_line = datasetLogLines[idx].split(",", QString::SkipEmptyParts);
                    QJsonObject matching;
                    matching["source"] = log_line.at(0);
                    matching["target"] = log_line.at(1);
                    matching["cost"] = log_line.at(2).toDouble();

                    // Get correspondence data
                    QString correspondenceFile = log_line.at(3);
                    bool isSwapped = (log_line.at(4).toInt() % 2) == 0;
                    QJsonArray correspondence;
                    {
                        // Open correspondence file
                        QFile cf(correspondenceFile);
                        cf.open(QFile::ReadOnly | QFile::Text);
                        QTextStream cfin(&cf);
                        auto corrLines = cfin.readAll().split("\n", QString::SkipEmptyParts);

                        // Read correspondence file (swapping if needed)
                        for (auto line : corrLines)
                        {
                            auto matched_pair = line.split(" ", QString::SkipEmptyParts);
                            QString sid = matched_pair.at(0);
                            QString tid = matched_pair.at(1);
                            if (isSwapped) std::swap(sid, tid);

                            QJsonArray part_pair;
                            part_pair.push_back(sid);
                            part_pair.push_back(tid);
                            correspondence.push_back(part_pair);
                        }
                    }
                    matching["correspondence"] = correspondence;

                    // Thumbnail files if any
                    QString correspondenceThumb = log_line.back();
                    if(correspondenceThumb != "null"){
                        QString targetThumb = QFileInfo(correspondenceThumb).fileName();
                        targetThumb = QString(d.absolutePath() + "/" + job_name + "/" + targetThumb);
                        QFile::copy(correspondenceThumb, targetThumb);
                        matching["thumbnail"] = targetThumb;
                    }

                    // indexing
                    auto sg = QFileInfo(log_line.at(0)).baseName();
                    auto tg = QFileInfo(log_line.at(1)).baseName();
                    auto pi = pair_idx[sg+tg];
                    matching["i"] = pi.first;
                    matching["j"] = pi.second;

                    // Record result
                    results.push_back(matching);
                }

				// Write all results in JSON format
				{
					QJsonDocument saveDoc(results);

                    QString jsonFilename = d.absolutePath() + "/" + job_name + "/_" + dir_name + "_corr.json";

                    // User specified output folder
                    if(parser.isSet("output")) jsonFilename = parser.value("output") + "/" + dir_name + "_corr.json";

                    QFile saveFile( jsonFilename );
                    saveFile.open( QIODevice::WriteOnly );
                    saveFile.write( saveDoc.toJson() );
				}
			}
		}

		return folders.size();
    }

	MainWindow w;
	//w.show();

    /// Here we perform the actual pair-wise correspondence:
    QString jobs_filename;

    if(parser.isSet("nogui") || parser.isSet("auto") || parser.isSet("sourceShape"))
    {
        if (parser.isSet("auto") || parser.isSet("sourceShape") || parser.isSet("targetShape"))
		{
			QString sourceShape = parser.value("sourceShape");
			QString targetShape = parser.value("targetShape");
			QVariantMap options;

            if(parser.isSet("g")) options["align"].setValue(true);
            if(parser.isSet("o")) options["roundtrip"].setValue(true);
            if(parser.isSet("k")) options["k"].setValue(parser.value("k").toInt());
			if(parser.isSet("q")) options["isQuietMode"].setValue(true);
            if(parser.isSet("c")) options["isAllowCutsJoins"].setValue(true);
            if(parser.isSet("m")) options["isIgnoreSymmetryGroups"].setValue(true);

            if(options["roundtrip"].toBool() || options["align"].toBool())
			{
				options["isManyTypesJobs"].setValue(true);
				options["isOutputMatching"].setValue(true);

				QTimer::singleShot(1, [sourceShape, targetShape, options]
				{
					int numJobs = 0;

					auto cur_options = options;

					QVector< QVector<QVariantMap> > reports;

					int numIter = 1;

					// Command line now only supports two tests.. GUI has more options
					if (cur_options["align"].toBool()) numIter = 2;

					for (int iter = 0; iter < numIter; iter++)
					{
						auto bp = QSharedPointer<BatchProcess>(new BatchProcess(sourceShape, targetShape, cur_options));

						bp->jobUID = numJobs++;
						bp->run();

						reports << bp->jobReports;

						if (cur_options["roundtrip"].toBool())
						{
							auto bp2 = QSharedPointer<BatchProcess>(new BatchProcess(targetShape, sourceShape, cur_options));

							bp2->jobUID = numJobs++;
							bp2->run();

							reports << bp2->jobReports;
						}

						cur_options["isFlip"].setValue(true);
					}

					// Look at reports
					double minEnergy = 1.0;
					int totalTime = 0;
					QVariantMap minJob;
					for (auto & reportVec : reports)
					{
						for (auto & report : reportVec)
						{
							totalTime += report["search_time"].toInt();

							double c = report["min_cost"].toDouble();
							if (c < minEnergy){
								minEnergy = c;
								minJob = report;
							}
						}
					}

					std::cout << "\nJobs computed: " << numJobs << "\n";
					std::cout << minEnergy << " - " << qPrintable(minJob["img_file"].toString());

					// Aggregate results
					{
						QFile file("log.txt");
						if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
						{
                            QString thumb_filename = minJob["img_file"].toString();

							QTextStream out(&file);
                            out << sourceShape << "," << targetShape << "," << minJob["min_cost"].toDouble() << ","
                                << minJob["match_file"].toString() << "," << minJob["job_uid"].toInt() << ","
                                << (thumb_filename.isEmpty() ? "null" : thumb_filename) << "\n";
						}
                    }
                }); // end of QTimer::singleShot
            }
            else
            {
                auto bp = new BatchProcess(sourceShape, targetShape, options);
                QObject::connect(bp, SIGNAL(allJobsFinished()), &w, SLOT(close()));
                QObject::connect(bp, SIGNAL(finished()), bp, SLOT(deleteLater()));
                bp->start();
            }

			return a.exec();
		}
		else
		{
			jobs_filename = parser.value("job");
			if (jobs_filename.isEmpty()){
				std::cout << "Please provide a job file.";
				return CommandLineError;
			}
		}

		std::cout << "Not enough arguments.";
		return CommandLineError;
    }
    else
	{
		jobs_filename = QFileDialog::getOpenFileName(&w, "Load Jobs", "", "Jobs File (*.json)");
    }

    QTimer::singleShot(0, [&] {
        BatchProcess * bp = new BatchProcess(jobs_filename);
        QObject::connect(bp, SIGNAL(allJobsFinished()), &w, SLOT(close()));
		QObject::connect(bp, SIGNAL(finished()), bp, SLOT(deleteLater()));
        bp->start();
    });

    return a.exec();
}