예제 #1
0
int main(int argc, char *argv[])
{
	if (argc != 3)
	{
		std::cout << std::endl
				<< "Filter peptides is used to filter pep.xml files from blacklisted peptides after the search has been performed. For example shared peptides between two species or known containments."
				<< std::endl;
		std::cerr << "Usage: filterPeptides [file.pep.xml] [blacklist]" << std::endl;
		exit(1);
	}
	//Load the blacklist in our hashmap for fast acces
	std::unordered_set<std::string> blacklistSet(loadBlacklist(argv[2]));
	std::cout << "Blacklist (" << argv[2] << ") contains " << blacklistSet.size() << " peptides" << std::endl;

	std::string inFile(argv[1]);
	std::string extension(".pep.xml");
	std::string outFile(inFile.substr(0, inFile.length() - extension.length()));
	outFile.append(".filtered.pep.xml");
	std::ofstream outputStream(outFile, std::ofstream::out | std::ofstream::trunc);

	pugi::xml_document doc;
	pugi::xml_parse_result result = doc.load_file(argv[1]);

	if (result)
	{
		pugi::xml_object_range<pugi::xml_named_node_iterator> spectrumQueries =
				doc.child("msms_pipeline_analysis").child("msms_run_summary").children("spectrum_query");
		std::cout << "pugixml: [" << argv[1] << "] parsed without errors, total spectrum queries: "
				<< std::distance(spectrumQueries.begin(), spectrumQueries.end()) << "\n";
	}
	else
	{
		std::cout << "pugixml: [" << argv[1] << "] parsed with errors\n";
		std::cout << "Error description: " << result.description() << "\n";
		std::cout << "Error offset: " << result.offset;
		exit(1);
	}

	unsigned totalDeleted = 0;
	unsigned totalPeptides = 0;
	//Containers to store our nodes we need to delete afterwards
	std::vector<pugi::xml_node> spectrumToDelete;
	std::vector<pugi::xml_node> searchhitToDelete;
	//Initialize the searchhitNodes counter
	unsigned searchhitNodes = 0;

	for (pugi::xml_node spectrum : doc.child("msms_pipeline_analysis").child("msms_run_summary").children(
			"spectrum_query"))
	{
		//Temp variable for easier acces
		pugi::xml_object_range<pugi::xml_named_node_iterator> search_resultNodes =
				spectrum.child("search_result").children("search_hit");

		for (pugi::xml_node search_hit : search_resultNodes)
		{
			if (blacklistSet.find(search_hit.attribute("peptide").as_string()) != blacklistSet.end())
			{
				//notify the user of our node deletion
				std::cout << "Deleting from spectrum '" << spectrum.attribute("spectrum").as_string();
				std::cout << "' peptide hit '" << search_hit.attribute("peptide").as_string();
				std::cout << "' (rank:" << search_hit.attribute("hit_rank").as_uint() << ")" << "\n";
				searchhitToDelete.push_back(search_hit);

			}
			totalPeptides++;
		}

		if (searchhitToDelete.size() == 0)
		{
			//Short circuit and skip expensive deletion of nodes
			continue;
		}

		//Count the total amount of nodes
		searchhitNodes = std::distance(search_resultNodes.begin(), search_resultNodes.end());
		totalDeleted+=searchhitToDelete.size();

		if ((searchhitNodes - searchhitToDelete.size()) == 0)
		{
			//if the results are empty, delete the whole spectrum with it's query entries
			spectrumToDelete.push_back(spectrum);
		}
		else
		{
			//Remove the required nodes
			for (pugi::xml_node &search_hit : searchhitToDelete)
			{
				spectrum.child("search_result").remove_child(search_hit);
			}
			//TODO re-score the hit ranks of the other nodes
		}
		searchhitToDelete.clear();
	}

	//Clean up empty spectrum nodes
	for (pugi::xml_node &spectrum : spectrumToDelete)
	{
		doc.child("msms_pipeline_analysis").child("msms_run_summary").remove_child(spectrum);
	}

	//Pritn final results to the user
	std::cout << "Total peptides deleted: " << totalDeleted << " of " << totalPeptides << " peptide hits and removed "
			<< spectrumToDelete.size() << " empty spectrum_query results." << std::endl;
	std::cout << "Saving result: " << (doc.save_file(outFile.c_str(), "") ? outFile.c_str() : "failed") << std::endl
			<< std::endl;
}
예제 #2
0
void BandwidthMeter::render(int screenWidth, int screenHeight) {

    int x = BORDER_DISTANCE_HORIZ + (AREA_WIDTH >= 0 ? 0 : screenWidth + AREA_WIDTH);
    int y = BORDER_DISTANCE_VERT + (AREA_HEIGHT >= 0 ? 0 : screenHeight + AREA_HEIGHT);
    int w = glm::abs(AREA_WIDTH), h = glm::abs(AREA_HEIGHT);

    // Determine total
    float totalIn = 0.0f, totalOut = 0.0f;
    for (size_t i = 0; i < N_CHANNELS; ++i) {

        totalIn += inputStream(ChannelIndex(i)).getValue();
        totalOut += outputStream(ChannelIndex(i)).getValue();
    }
    totalIn *= UNIT_SCALE;
    totalOut *= UNIT_SCALE;
    float totalMax = glm::max(totalIn, totalOut);

    // Get font / caption metrics
    QFontMetrics const& fontMetrics = _textRenderer->metrics();
    int fontDescent = fontMetrics.descent(); 
    int labelWidthIn = fontMetrics.width(CAPTION_IN);
    int labelWidthOut = fontMetrics.width(CAPTION_OUT);
    int labelWidthInOut = glm::max(labelWidthIn, labelWidthOut);
    int labelHeight = fontMetrics.ascent() + fontDescent;
    int labelWidthUnit = fontMetrics.width(CAPTION_UNIT);
    int labelsWidth = labelWidthInOut + SPACING_RIGHT_CAPTION_IN_OUT + SPACING_LEFT_CAPTION_UNIT + labelWidthUnit;

    // Calculate coordinates and dimensions
    int barX = x + labelWidthInOut + SPACING_RIGHT_CAPTION_IN_OUT;
    int barWidth = w - labelsWidth;
    int barHeight = (h - SPACING_VERT_BARS) / 2;
    int textYcenteredLine = h - centered(labelHeight, h) - fontDescent;
    int textYupperLine = barHeight - centered(labelHeight, barHeight) - fontDescent;
    int textYlowerLine = h - centered(labelHeight, barHeight) - fontDescent;

    // Center of coordinate system -> upper left of bar
    glPushMatrix();
    glTranslatef((float)barX, (float)y, 0.0f);

    // Render captions
    glm::vec4 textColor = getColorRGBA(COLOR_TEXT);
    _textRenderer->draw(barWidth + SPACING_LEFT_CAPTION_UNIT, textYcenteredLine, CAPTION_UNIT, textColor);
    _textRenderer->draw(-labelWidthIn - SPACING_RIGHT_CAPTION_IN_OUT, textYupperLine, CAPTION_IN, textColor);
    _textRenderer->draw(-labelWidthOut - SPACING_RIGHT_CAPTION_IN_OUT, textYlowerLine, CAPTION_OUT, textColor);

    // Render vertical lines for the frame
    // TODO: I think there may be a bug in this newest code and/or the GeometryCache code, because it seems like
    // sometimes the bandwidth meter doesn't render the vertical lines
    renderVerticalLine(0, 0, h, COLOR_FRAME);
    renderVerticalLine(barWidth, 0, h, COLOR_FRAME);

    // Adjust scale
    int steps;
    double step, scaleMax;
    bool commit = false;
    do {
        steps = (_scaleMaxIndex % 9) + 2;
        step = pow(10.0, (_scaleMaxIndex / 9) - 10);
        scaleMax = step * steps;
        if (commit) {
//            printLog("Bandwidth meter scale: %d\n", _scaleMaxIndex);
            break;
        }
        if (totalMax < scaleMax * 0.5) {
            _scaleMaxIndex = glm::max(0, _scaleMaxIndex - 1);
            commit = true;
        } else if (totalMax > scaleMax) {
            _scaleMaxIndex += 1;
            commit = true;
        }
    } while (commit);

    step = scaleMax / NUMBER_OF_MARKERS;
    if (scaleMax < MIN_METER_SCALE) {
        scaleMax = MIN_METER_SCALE;
    }
    
    // Render scale indicators
    for (int j = NUMBER_OF_MARKERS; --j > 0;) {
        renderVerticalLine((barWidth * j) / NUMBER_OF_MARKERS, 0, h, COLOR_INDICATOR);
    }

    // Render bars
    int xIn = 0, xOut = 0;
    for (size_t i = 0; i < N_CHANNELS; ++i) {

        ChannelIndex chIdx = ChannelIndex(i);
        int wIn = (int)(barWidth * inputStream(chIdx).getValue() * UNIT_SCALE / scaleMax);
        int wOut = (int)(barWidth * outputStream(chIdx).getValue() * UNIT_SCALE / scaleMax);

        if (wIn > 0) {
            renderBox(xIn, 0, wIn, barHeight, channelInfo(chIdx).colorRGBA);
        }
        xIn += wIn;

        if (wOut > 0) {
            renderBox(xOut, h - barHeight, wOut, barHeight, channelInfo(chIdx).colorRGBA);
        }
        xOut += wOut;
    }

    // Render numbers
    char fmtBuf[8];
    sprintf(fmtBuf, "%0.1f", totalIn);
    _textRenderer->draw(glm::max(xIn - fontMetrics.width(fmtBuf) - PADDING_HORIZ_VALUE,
                                PADDING_HORIZ_VALUE),
                       textYupperLine, fmtBuf, textColor);
    sprintf(fmtBuf, "%0.1f", totalOut);
    _textRenderer->draw(glm::max(xOut - fontMetrics.width(fmtBuf) - PADDING_HORIZ_VALUE,
                                PADDING_HORIZ_VALUE),
                       textYlowerLine, fmtBuf, textColor);

    glPopMatrix();

    // After rendering, indicate that no data has been sent/received since the last feed.
    // This way, the meters fall when not continuously fed.
    for (size_t i = 0; i < N_CHANNELS; ++i) {
        inputStream(ChannelIndex(i)).updateValue(0);
        outputStream(ChannelIndex(i)).updateValue(0);
    }
}
synthclone::Sample *
SessionSampleData::updateSample(synthclone::Sample &sample, bool forceCopy,
                                QObject *parent)
{
    if (! sampleDirectory) {
        // The session is being unloaded.
        return 0;
    }

    synthclone::SampleInputStream inputStream(sample);

    ChannelConvertAlgorithm channelConvertAlgorithm;
    synthclone::SampleChannelCount inputChannels = inputStream.getChannels();
    if (sampleChannelCount == inputChannels) {
        channelConvertAlgorithm = CHANNELCONVERTALGORITHM_NONE;
    } else if (sampleChannelCount == 1) {
        channelConvertAlgorithm = CHANNELCONVERTALGORITHM_TO_MONO;
    } else if (inputChannels == 1) {
        channelConvertAlgorithm = CHANNELCONVERTALGORITHM_FROM_MONO;
    } else {
        // How does one convert a multi-channel sample to a different channel
        // count that isn't mono?  I'm open to ideas.
        return 0;
    }

    // If the sample rate isn't set, then set it to the sample rate of the new
    // sample.
    synthclone::SampleRate inputSampleRate = inputStream.getSampleRate();
    if (sampleRate == synthclone::SAMPLE_RATE_NOT_SET) {
        setSampleRate(inputSampleRate);
    }

    bool sampleConversionRequired = inputSampleRate != sampleRate;
    QString newPath = createUniqueFile(sampleDirectory);
    if ((channelConvertAlgorithm == CHANNELCONVERTALGORITHM_NONE) &&
            (! sampleConversionRequired) && (! forceCopy)) {
        if (sampleDirectory) {
            if (QFileInfo(sample.getPath()).absolutePath() ==
                    sampleDirectory->absolutePath()) {
                // Nothing needs to be done.
                return &sample;
            }
        }
    }

    // At this point, either some sort of conversion is required, the sample is
    // being moved from outside the sample directory into the sample directory,
    // or a forced copy was requested.

    float *channelBuffer;

    // For some reason, the empty QScopedArrayPointer constructor is not
    // available on the Mac OSX platform.
    QScopedArrayPointer<float> channelBufferPtr(static_cast<float *>(0));

    float *convertBuffer = new float[sampleChannelCount * 512];
    QScopedArrayPointer<float> convertBufferPtr(convertBuffer);
    SampleRateConverter *converter;
    QScopedPointer<SampleRateConverter> converterPtr;
    float *inputBuffer = new float[inputChannels * 512];
    QScopedArrayPointer<float> inputBufferPtr(inputBuffer);
    if (! sampleConversionRequired) {
        channelBuffer = convertBuffer;
        converter = 0;
    } else {
        if (channelConvertAlgorithm != CHANNELCONVERTALGORITHM_NONE) {
            channelBuffer = new float[sampleChannelCount];
            channelBufferPtr.reset(channelBuffer);
        } else {
            channelBuffer = inputBuffer;
        }
        double ratio = static_cast<double>(sampleRate) / inputSampleRate;
        converter = new SampleRateConverter(sampleChannelCount, ratio, this);
        converterPtr.reset(converter);
    }

    // Create the new sample object.
    synthclone::Sample *outputSample = new synthclone::Sample(newPath, parent);
    QScopedPointer<synthclone::Sample> outputSamplePtr(outputSample);
    synthclone::SampleOutputStream
    outputStream(*outputSample, sampleRate, sampleChannelCount);

    // Convert.
    synthclone::SampleFrameCount framesRead;
    long outputFramesUsed;
    do {

        // Get data from input stream.
        framesRead = inputStream.read(inputBuffer, 512);

        // Channel conversion.
        switch (channelConvertAlgorithm) {
        case CHANNELCONVERTALGORITHM_TO_MONO:
            for (int i = 0; i < framesRead; i++) {
                float n = 0.0;
                for (int j = 0; j < inputChannels; j++) {
                    n += inputBuffer[(i * inputChannels) + j];
                }
                channelBuffer[i] = n / inputChannels;
            }
            break;
        case CHANNELCONVERTALGORITHM_FROM_MONO:
            for (int i = 0; i < framesRead; i++) {
                float n = inputBuffer[i];
                for (int j = 0; j < sampleChannelCount; j++) {
                    channelBuffer[(i * sampleChannelCount) + j] = n;
                }
            }
            break;
        case 0:
            // There's no channel conversion.  Above, we assign the
            // 'channelBuffer' to 'inputBuffer' when there's no channel
            // conversion.  So, the data is already in 'channelBuffer'.
            ;
        }

        // Sample rate conversion.
        if (sampleConversionRequired) {
            long inputFramesUsed =
                converter->convert(channelBuffer, static_cast<long>(framesRead),
                                   convertBuffer, 512, outputFramesUsed,
                                   ! framesRead);
            if (inputFramesUsed != framesRead) {
                inputStream.seek(inputFramesUsed - framesRead,
                                 synthclone::SampleStream::OFFSET_CURRENT);
            }
        } else {
            // If sample rate conversion isn't required, then the data to write
            // is already in 'convertBuffer', as 'convertBuffer' and
            // 'channelBuffer' point to the same memory area.
            outputFramesUsed = framesRead;
        }

        // Write data to output stream.
        if (outputFramesUsed) {
            outputStream.write(convertBuffer,
                               static_cast<synthclone::SampleFrameCount>
                               (outputFramesUsed));
        }

    } while (framesRead);

    // Finish up sample rate conversion.
    if (sampleConversionRequired && outputFramesUsed) {
        for (;;) {
            converter->convert(channelBuffer, 0, convertBuffer, 512,
                               outputFramesUsed, true);
            if (! outputFramesUsed) {
                break;
            }
            outputStream.write(convertBuffer,
                               static_cast<synthclone::SampleFrameCount>
                               (outputFramesUsed));
        }
    }

    // Cleanup.
    outputStream.close();
    return outputSamplePtr.take();
}
예제 #4
0
void LogsDialog::exportToGoogleEarth()
{
  // filter data points
  QList<QStringList> dataPoints = filterGePoints(csvlog);
  int n = dataPoints.count(); // number of points to export
  if (n==0) return;

  int latcol=0, longcol=0, altcol=0, speedcol=0;
  QSet<int> nondataCols;
  for (int i=1; i<dataPoints.at(0).count(); i++) {
    // Long,Lat,Course,GPS Speed,GPS Alt
    if (dataPoints.at(0).at(i).contains("Long")) {
      longcol = i;
      nondataCols << i;
    }
    if (dataPoints.at(0).at(i).contains("Lat")) {
      latcol = i;
      nondataCols << i;
    }
    if (dataPoints.at(0).at(i).contains("GPS Alt") || dataPoints.at(0).at(i).contains("GAlt")) {
      altcol = i;
      nondataCols << i;
    }
    if (dataPoints.at(0).at(i).contains("GPS Speed")) {
      speedcol = i;
      nondataCols << i;
    }
  }

  if (longcol==0 || latcol==0) {
    return;
  }

  QString geIconFilename = generateProcessUniqueTempFileName("track0.png");
  if (QFile::exists(geIconFilename)) {
    QFile::remove(geIconFilename);
  }
  QFile::copy(":/images/track0.png", geIconFilename);

  QString geFilename = generateProcessUniqueTempFileName("flight.kml");
  if (QFile::exists(geFilename)) {
    QFile::remove(geFilename);
  }
  QFile geFile(geFilename);
  if (!geFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
    QMessageBox::warning(this, tr("Error"),
        tr("Cannot write file %1:\n%2.")
        .arg(geFilename)
        .arg(geFile.errorString()));
    return;
  }

  QTextStream outputStream(&geFile);

  // file header
  outputStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\">\n";
  outputStream << "\t<Document>\n\t\t<name>" << logFilename << "</name>\n";
  outputStream << "\t\t<Style id=\"multiTrack_n\">\n\t\t\t<IconStyle>\n\t\t\t\t<Icon>\n\t\t\t\t\t<href>file://" << geIconFilename << "</href>\n\t\t\t\t</Icon>\n\t\t\t</IconStyle>\n\t\t\t<LineStyle>\n\t\t\t\t<color>991081f4</color>\n\t\t\t\t<width>6</width>\n\t\t\t</LineStyle>\n\t\t</Style>\n";
  outputStream << "\t\t<Style id=\"multiTrack_h\">\n\t\t\t<IconStyle>\n\t\t\t\t<scale>0</scale>\n\t\t\t\t<Icon>\n\t\t\t\t\t<href>file://" << geIconFilename << "</href>\n\t\t\t\t</Icon>\n\t\t\t</IconStyle>\n\t\t\t<LineStyle>\n\t\t\t\t<color>991081f4</color>\n\t\t\t\t<width>8</width>\n\t\t\t</LineStyle>\n\t\t</Style>\n";
  outputStream << "\t\t<StyleMap id=\"multiTrack\">\n\t\t\t<Pair>\n\t\t\t\t<key>normal</key>\n\t\t\t\t<styleUrl>#multiTrack_n</styleUrl>\n\t\t\t</Pair>\n\t\t\t<Pair>\n\t\t\t\t<key>highlight</key>\n\t\t\t\t<styleUrl>#multiTrack_h</styleUrl>\n\t\t\t</Pair>\n\t\t</StyleMap>\n";
  outputStream << "\t\t<Style id=\"lineStyle\">\n\t\t\t<LineStyle>\n\t\t\t\t<color>991081f4</color>\n\t\t\t\t<width>6</width>\n\t\t\t</LineStyle>\n\t\t</Style>\n";
  outputStream << "\t\t<Schema id=\"schema\">\n";
  outputStream << "\t\t\t<gx:SimpleArrayField name=\"GPSSpeed\" type=\"float\">\n\t\t\t\t<displayName>GPS Speed</displayName>\n\t\t\t</gx:SimpleArrayField>\n";
  
  // declare additional fields
  for (int i=0; i<dataPoints.at(0).count()-2; i++) {
    if (ui->FieldsTW->item(0,i)->isSelected() && !nondataCols.contains(i+2)) {
      QString origName = dataPoints.at(0).at(i+2);
      QString safeName = origName;
      safeName.replace(" ","_");
      outputStream << "\t\t\t<gx:SimpleArrayField name=\""<< safeName <<"\" ";
      outputStream << "type=\"string\"";   // additional fields have fixed type: string
      outputStream << ">\n\t\t\t\t<displayName>" << origName << "</displayName>\n\t\t\t</gx:SimpleArrayField>\n";
    }
  }

  QString planeName;
  if (logFilename.indexOf("-")>0) {
    planeName=logFilename.left(logFilename.indexOf("-"));
  } else {
    planeName=logFilename;
  }

  outputStream << "\t\t</Schema>\n";
  outputStream << "\t\t<Folder>\n\t\t\t<name>Log Data</name>\n\t\t\t<Placemark>\n\t\t\t\t<name>" << planeName << "</name>";
  outputStream << "\n\t\t\t\t<styleUrl>#multiTrack</styleUrl>";
  outputStream << "\n\t\t\t\t<gx:Track>\n";
  outputStream << "\n\t\t\t\t\t<altitudeMode>absolute</altitudeMode>\n";

  // time data points
  for (int i=1; i<n; i++) {
    QString tstamp=dataPoints.at(i).at(0)+QString("T")+dataPoints.at(i).at(1)+QString("Z");
    outputStream << "\t\t\t\t\t<when>"<< tstamp <<"</when>\n";
  }

  // coordinate data points
  for (int i=1; i<n; i++) {
    QString latitude = dataPoints.at(i).at(latcol).trimmed();
    QString longitude = dataPoints.at(i).at(longcol).trimmed();
    int altitude = altcol ? dataPoints.at(i).at(altcol).toFloat() : 0;
    latitude.sprintf("%3.8f", toDecimalCoordinate(latitude));
    longitude.sprintf("%3.8f", toDecimalCoordinate(longitude));
    outputStream << "\t\t\t\t\t<gx:coord>" << longitude << " " << latitude << " " <<  altitude << " </gx:coord>\n" ;
  }

  // additional data for data points
  outputStream << "\t\t\t\t\t<ExtendedData>\n\t\t\t\t\t\t<SchemaData schemaUrl=\"#schema\">\n";

  if (speedcol) {
    // gps speed data points
    outputStream << "\t\t\t\t\t\t\t<gx:SimpleArrayData name=\"GPSSpeed\">\n";
    for (int i=1; i<n; i++) {
      outputStream << "\t\t\t\t\t\t\t\t<gx:value>"<< dataPoints.at(i).at(speedcol) <<"</gx:value>\n";
    }
    outputStream << "\t\t\t\t\t\t\t</gx:SimpleArrayData>\n";
  }

  // add values for additional fields
  for (int i=0; i<dataPoints.at(0).count()-2; i++) {
    if (ui->FieldsTW->item(0,i)->isSelected() && !nondataCols.contains(i+2)) {
      QString safeName = dataPoints.at(0).at(i+2);;
      safeName.replace(" ","_");
      outputStream << "\t\t\t\t\t\t\t<gx:SimpleArrayData name=\""<< safeName <<"\">\n";
      for (int j=1; j<n; j++) {
        outputStream << "\t\t\t\t\t\t\t\t<gx:value>"<< dataPoints.at(j).at(i+2) <<"</gx:value>\n";
      }
      outputStream << "\t\t\t\t\t\t\t</gx:SimpleArrayData>\n";
    }
  }

  outputStream << "\t\t\t\t\t\t</SchemaData>\n\t\t\t\t\t</ExtendedData>\n\t\t\t\t</gx:Track>\n\t\t\t</Placemark>\n\t\t</Folder>\n\t</Document>\n</kml>";
  geFile.close();

  QString gePath = g.gePath();
  QStringList parameters;
#ifdef __APPLE__
  parameters << "-a";
  parameters << gePath;
  gePath = "/usr/bin/open";
#endif
  parameters << geFilename;
  QProcess *process = new QProcess(this);
  process->start(gePath, parameters);
}
예제 #5
0
bool MdiChild::saveFile(const QString &fileName, bool setCurrent)
{
  QString myFile;
  myFile = fileName;
  if (IS_SKY9X(GetEepromInterface()->getBoard())) {
    myFile.replace(".eepe", ".bin");
  }
  QFile file(myFile);

  int fileType = getFileType(myFile);

  uint8_t *eeprom = (uint8_t*)malloc(GetEepromInterface()->getEEpromSize());
  int eeprom_size = 0;

  if (fileType != FILE_TYPE_XML) {
    eeprom_size = GetEepromInterface()->save(eeprom, radioData, GetCurrentFirmware()->getVariantNumber(), 0/*last version*/);
    if (!eeprom_size) {
      QMessageBox::warning(this, tr("Error"),tr("Cannot write file %1:\n%2.").arg(myFile).arg(file.errorString()));
      return false;
    }
  }

  if (!file.open(fileType == FILE_TYPE_BIN ? QIODevice::WriteOnly : (QIODevice::WriteOnly | QIODevice::Text))) {
    QMessageBox::warning(this, tr("Error"),tr("Cannot write file %1:\n%2.").arg(myFile).arg(file.errorString()));
    return false;
  }

  QTextStream outputStream(&file);

#if 0
    if (fileType==FILE_TYPE_XML) {
      if (!XmlInterface(outputStream).save(radioData)) {
        QMessageBox::warning(this, tr("Error"),tr("Cannot write file %1:\n%2.").arg(myFile).arg(file.errorString()));
        file.close();
        return false;
      }
    }
    else
#endif
  if (fileType==FILE_TYPE_HEX || fileType==FILE_TYPE_EEPE) { // write hex
    if (fileType==FILE_TYPE_EEPE)
      outputStream << EEPE_EEPROM_FILE_HEADER << "\n";

    if (!HexInterface(outputStream).save(eeprom, eeprom_size)) {
        QMessageBox::warning(this, tr("Error"),tr("Cannot write file %1:\n%2.").arg(myFile).arg(file.errorString()));
        file.close();
        return false;
    }
  }
  else if (fileType==FILE_TYPE_BIN) // write binary
  {
    long result = file.write((char*)eeprom, eeprom_size);
    if(result!=eeprom_size) {
      QMessageBox::warning(this, tr("Error"),tr("Error writing file %1:\n%2.").arg(myFile).arg(file.errorString()));
      return false;
    }
  }
  else {
    QMessageBox::warning(this, tr("Error"),tr("Error writing file %1:\n%2.").arg(myFile).arg("Unknown format"));
    return false;
  }

  free(eeprom); // TODO free in all cases ...
  file.close();
  if(setCurrent) setCurrentFile(myFile);

  return true;
}
예제 #6
0
void QgsSingleBandPseudoColorRendererWidget::on_mExportToFileButton_clicked()
{
  QSettings settings;
  QString lastDir = settings.value( "lastRasterFileFilterDir", "" ).toString();
  QString fileName = QFileDialog::getSaveFileName( this, tr( "Save file" ), lastDir, tr( "Textfile (*.txt)" ) );
  if ( !fileName.isEmpty() )
  {
    if ( !fileName.endsWith( ".txt", Qt::CaseInsensitive ) )
    {
      fileName = fileName + ".txt";
    }

    QFile outputFile( fileName );
    if ( outputFile.open( QFile::WriteOnly ) )
    {
      QTextStream outputStream( &outputFile );
      outputStream << "# " << tr( "QGIS Generated Color Map Export File" ) << "\n";
      outputStream << "INTERPOLATION:";
      if ( mColorInterpolationComboBox->currentText() == tr( "Linear" ) )
      {
        outputStream << "INTERPOLATED\n";
      }
      else if ( mColorInterpolationComboBox->currentText() == tr( "Discrete" ) )
      {
        outputStream << "DISCRETE\n";
      }
      else
      {
        outputStream << "EXACT\n";
      }

      int topLevelItemCount = mColormapTreeWidget->topLevelItemCount();
      QTreeWidgetItem* currentItem;
      QColor color;
      for ( int i = 0; i < topLevelItemCount; ++i )
      {
        currentItem = mColormapTreeWidget->topLevelItem( i );
        if ( !currentItem )
        {
          continue;
        }
        color = currentItem->background( 1 ).color();
        outputStream << currentItem->text( 0 ).toDouble() << ",";
        outputStream << color.red() << "," << color.green() << "," << color.blue() << "," << color.alpha() << ",";
        if ( currentItem->text( 2 ) == "" )
        {
          outputStream << "Color entry " << i + 1 << "\n";
        }
        else
        {
          outputStream << currentItem->text( 2 ) << "\n";
        }
      }
      outputStream.flush();
      outputFile.close();
    }
    else
    {
      QMessageBox::warning( this, tr( "Write access denied" ), tr( "Write access denied. Adjust the file permissions and try again.\n\n" ) );
    }
  }
}
예제 #7
0
	void CoreService::ProcessRequests (int inputFD, int outputFD)
	{
		try
		{
			Core = CoreDirect;

			shared_ptr <Stream> inputStream (new FileStream (inputFD != -1 ? inputFD : InputPipe->GetReadFD()));
			shared_ptr <Stream> outputStream (new FileStream (outputFD != -1 ? outputFD : OutputPipe->GetWriteFD()));

			while (true)
			{
				shared_ptr <CoreServiceRequest> request = Serializable::DeserializeNew <CoreServiceRequest> (inputStream);

				try
				{
					// ExitRequest
					if (dynamic_cast <ExitRequest*> (request.get()) != nullptr)
					{
						if (ElevatedServiceAvailable)
							request->Serialize (ServiceInputStream);
						return;
					}

					if (!ElevatedPrivileges && request->ElevateUserPrivileges)
					{
						if (!ElevatedServiceAvailable)
						{
							finally_do_arg (string *, &request->AdminPassword, { StringConverter::Erase (*finally_arg); });
							
							CoreService::StartElevated (*request);
							ElevatedServiceAvailable = true;
						}

						request->Serialize (ServiceInputStream);
						GetResponse <Serializable>()->Serialize (outputStream);
						continue;
					}

					// CheckFilesystemRequest
					CheckFilesystemRequest *checkRequest = dynamic_cast <CheckFilesystemRequest*> (request.get());
					if (checkRequest)
					{
						Core->CheckFilesystem (checkRequest->MountedVolumeInfo, checkRequest->Repair);
						
						CheckFilesystemResponse().Serialize (outputStream);
						continue;
					}

					// DismountFilesystemRequest
					DismountFilesystemRequest *dismountFsRequest = dynamic_cast <DismountFilesystemRequest*> (request.get());
					if (dismountFsRequest)
					{
						Core->DismountFilesystem (dismountFsRequest->MountPoint, dismountFsRequest->Force);

						DismountFilesystemResponse().Serialize (outputStream);
						continue;
					}

					// DismountVolumeRequest
					DismountVolumeRequest *dismountRequest = dynamic_cast <DismountVolumeRequest*> (request.get());
					if (dismountRequest)
					{
						DismountVolumeResponse response;
						response.DismountedVolumeInfo = Core->DismountVolume (dismountRequest->MountedVolumeInfo, dismountRequest->IgnoreOpenFiles, dismountRequest->SyncVolumeInfo);
						response.Serialize (outputStream);
						continue;
					}

					// GetDeviceSectorSizeRequest
					GetDeviceSectorSizeRequest *getDeviceSectorSizeRequest = dynamic_cast <GetDeviceSectorSizeRequest*> (request.get());
					if (getDeviceSectorSizeRequest)
					{
						GetDeviceSectorSizeResponse response;
						response.Size = Core->GetDeviceSectorSize (getDeviceSectorSizeRequest->Path);
						response.Serialize (outputStream);
						continue;
					}

					// GetDeviceSizeRequest
					GetDeviceSizeRequest *getDeviceSizeRequest = dynamic_cast <GetDeviceSizeRequest*> (request.get());
					if (getDeviceSizeRequest)
					{
						GetDeviceSizeResponse response;
						response.Size = Core->GetDeviceSize (getDeviceSizeRequest->Path);
						response.Serialize (outputStream);
						continue;
					}

					// GetHostDevicesRequest
					GetHostDevicesRequest *getHostDevicesRequest = dynamic_cast <GetHostDevicesRequest*> (request.get());
					if (getHostDevicesRequest)
					{
						GetHostDevicesResponse response;
						response.HostDevices = Core->GetHostDevices (getHostDevicesRequest->PathListOnly);
						response.Serialize (outputStream);
						continue;
					}

					// MountVolumeRequest
					MountVolumeRequest *mountRequest = dynamic_cast <MountVolumeRequest*> (request.get());
					if (mountRequest)
					{
						MountVolumeResponse (
							Core->MountVolume (*mountRequest->Options)
						).Serialize (outputStream);

						continue;
					}

					// SetFileOwnerRequest
					SetFileOwnerRequest *setFileOwnerRequest = dynamic_cast <SetFileOwnerRequest*> (request.get());
					if (setFileOwnerRequest)
					{
						CoreUnix *coreUnix = dynamic_cast <CoreUnix *> (Core.get());
						if (!coreUnix)
							throw ParameterIncorrect (SRC_POS);

						coreUnix->SetFileOwner (setFileOwnerRequest->Path, setFileOwnerRequest->Owner);
						SetFileOwnerResponse().Serialize (outputStream);
						continue;
					}

					throw ParameterIncorrect (SRC_POS);
				}
/**
* Slot called when the pbtnRunQuery button is pressed
*/
void eVisDatabaseConnectionGui::on_pbtnRunQuery_clicked( )
{
    //Check to see if we have a query
    if ( !teditSqlStatement->toPlainText( ).isEmpty( ) )
    {
        //Verify that we have an active database connection
        if ( 0 != mDatabaseConnection )
        {
            //Execute query
            QSqlQuery* myResults = mDatabaseConnection->query( teditSqlStatement->toPlainText( ) );
            if ( 0 == myResults )
            {
                teditConsole->append( tr( "Error: Query failed: %1" ).arg( mDatabaseConnection->lastError( ) ) );
            }
            else if ( myResults->isSelect( ) )
            {
                //if valid and a select query, save results into temporary file and load as layer
                myResults->next( );
                if ( myResults->isValid( ) )
                {
                    mTempOutputFileList->append( new QTemporaryFile( ) );
                    if ( mTempOutputFileList->last( )->open( ) )
                    {
                        QTextStream outputStream( mTempOutputFileList->last( ) );
                        QStringList fieldList;
                        /*
                         * Output column names
                         */
                        for ( int x = 0; x < myResults->record( ).count( ); x++ )
                        {
                            if ( 0 == x )
                            {
                                outputStream << myResults->record( ).fieldName( x );
                            }
                            else
                            {
                                outputStream << "\t" << myResults->record( ).fieldName( x );
                            }
                            fieldList << myResults->record( ).fieldName( x );
                        }
                        outputStream << endl;
                        /*
                         * Output Data
                         */
                        while ( myResults->isValid( ) )
                        {
                            for ( int x = 0; x < myResults->record( ).count( ); x++ )
                            {
                                if ( x == 0 )
                                {
                                    outputStream << myResults->value( x ).toString( );
                                }
                                else
                                {
                                    outputStream << "\t" << myResults->value( x ).toString( );
                                }
                            }
                            outputStream << endl;
                            myResults->next( );
                        }
                        mTempOutputFileList->last( )->close( );
                        mDatabaseLayerFieldSelector->setFieldList( &fieldList );
                        mDatabaseLayerFieldSelector->show( );
                    }
                    else
                    {
                        teditConsole->append( tr( "Error: Could not create temporary file, process halted" ) );
                    }
                }
            }
        }
        else
        {
            teditConsole->append( tr( "Error: A database connection is not currently established" ) );
        }
    }
}