QString ValueFormatter::dateFormat(const QDate &date, Format::Type fmtType, const QString& formatString )
{
    if( !formatString.isEmpty() ) {
        return date.toString( formatString );
    }

    QString tmp;
    if (fmtType == Format::ShortDate) {
        tmp = m_converter->settings()->locale()->formatDate(date, KLocale::ShortDate);
    } else if (fmtType == Format::TextDate) {
        tmp = m_converter->settings()->locale()->formatDate(date, KLocale::LongDate);
    } else if (fmtType == Format::Date1) { /*18-Feb-99 */
        tmp = QString().sprintf("%02d", date.day()) +
              '-' + m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '-' + QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date2) { /*18-Feb-1999 */
        tmp = QString().sprintf("%02d", date.day()) +
              '-' + m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '-' + QString::number(date.year());
    } else if (fmtType == Format::Date3) { /*18-Feb */
        tmp = QString().sprintf("%02d", date.day()) +
              '-' + m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber);
    } else if (fmtType == Format::Date4) { /*18-05 */
        tmp = QString().sprintf("%02d", date.day());
        tmp += '-' + QString().sprintf("%02d", date.month());
    } else if (fmtType == Format::Date5) { /*18/05/00 */
        tmp = QString().sprintf("%02d", date.day());
        tmp += '/' + QString().sprintf("%02d", date.month()) + '/';
        tmp += QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date6) { /*18/05/1999 */
        tmp = QString().sprintf("%02d", date.day());
        tmp += '/' + QString().sprintf("%02d", date.month()) + '/';
        tmp += QString::number(date.year());
    } else if (fmtType == Format::Date7) { /*Feb-99 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '-' + QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date8) { /*February-99 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::LongNumber) +
              '-' + QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date9) { /*February-1999 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::LongNumber) +
              '-' + QString::number(date.year());
    } else if (fmtType == Format::Date10) { /*F-99 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::LongNumber).at(0) +
              '-' + QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date11) { /*18/Feb */
        tmp = QString().sprintf("%02d", date.day())
              + '/' + m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber);
    } else if (fmtType == Format::Date12) { /*18/02 */
        tmp = QString().sprintf("%02d", date.day()) + '/';
        tmp += QString().sprintf("%02d", date.month());
    } else if (fmtType == Format::Date13) { /*18/Feb/1999 */
        tmp = QString().sprintf("%02d", date.day()) +
              '/' + m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '/' + QString::number(date.year());
    } else if (fmtType == Format::Date14) { /*2000/Feb/18 */
        tmp = QString::number(date.year()) +
              '/' + m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '/' + QString().sprintf("%02d", date.day());
    } else if (fmtType == Format::Date15) { /*2000-Feb-18 */
        tmp = QString::number(date.year()) +
              '-' + m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '-' + QString().sprintf("%02d", date.day());
    } else if (fmtType == Format::Date16) { /*2000-02-18 */
        tmp = QString::number(date.year());
        tmp += '-' + QString().sprintf("%02d", date.month()) + '-';
        tmp += QString().sprintf("%02d", date.day());
    } else if (fmtType == Format::Date17) { /*2 february 2000 */
        tmp = QString().sprintf("%d", date.day()) +
              ' ' + m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::LongNumber) +
              ' ' + QString::number(date.year());
    } else if (fmtType == Format::Date18) { /*02/18/1999 */
        tmp = QString().sprintf("%02d", date.month());
        tmp += '/' + QString().sprintf("%02d", date.day());
        tmp += '/' + QString::number(date.year());
    } else if (fmtType == Format::Date19) { /*02/18/99 */
        tmp = QString().sprintf("%02d", date.month());
        tmp += '/' + QString().sprintf("%02d", date.day());
        tmp += '/' + QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date20) { /*Feb/18/99 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '/' + QString().sprintf("%02d", date.day()) +
              '/' + QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date21) { /*Feb/18/1999 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '/' + QString().sprintf("%02d", date.day()) +
              '/' + QString::number(date.year());
    } else if (fmtType == Format::Date22) { /*Feb-1999 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '-' + QString::number(date.year());
    } else if (fmtType == Format::Date23) { /*1999 */
        tmp = QString::number(date.year());
    } else if (fmtType == Format::Date24) { /*99 */
        tmp = QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date25) { /*2000/02/18 */
        tmp = QString::number(date.year());
        tmp += '/' + QString().sprintf("%02d", date.month());
        tmp += '/' + QString().sprintf("%02d", date.day());
    } else if (fmtType == Format::Date26) { /*2000/Feb/18 */
        tmp = QString::number(date.year()) +
              '/' + m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '/' + QString().sprintf("%02d", date.day());
    } else if (fmtType == Format::Date27) { /*Feb/99 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '/' + QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date28) { /*Feb/1999 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::ShortNumber) +
              '/' + QString::number(date.year());
    } else if (fmtType == Format::Date29) { /*February/99 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::LongNumber) +
              '/' + QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date30) { /*February/1999 */
        tmp = m_converter->settings()->locale()->calendar()->formatDate(date, KLocale::Month, KLocale::LongNumber) +
              '/' + QString::number(date.year());
    } else if (fmtType == Format::Date31) { /*18-02 */
        tmp = QString().sprintf("%02d", date.day()) + '-';
        tmp += QString().sprintf("%02d", date.month());
    } else if (fmtType == Format::Date32) { /*02/99 */
        tmp = QString().sprintf("%02d", date.month()) + '/';
        tmp += QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date33) { /*02-99 */
        tmp = QString().sprintf("%02d", date.month()) + '-';
        tmp += QString::number(date.year()).right(2);
    } else if (fmtType == Format::Date34 || fmtType == Format::Date35) { /*Mon, 2 Feb 2000 and Mon, 2 February 2000 */
        QLocale l(QLocale::English);
        tmp = l.toString(date, fmtType == Format::Date34 ? "ddd d MMM yy" : "dddd d MMM yyyy");
    } else { /*fallback... */
        tmp = m_converter->settings()->locale()->formatDate(date, KLocale::ShortDate);
    }

    // Missing compared with gnumeric:
    //  "m/d/yy h:mm",    /* 20 */
    //  "m/d/yyyy h:mm",  /* 21 */
    //  "mmm/ddd/yy",    /* 12 */
    //  "mmm/ddd/yyyy",    /* 13 */
    //  "mm/ddd/yy",    /* 14 */
    //  "mm/ddd/yyyy",    /* 15 */

    return tmp;
}
EmploiDuTemps::EmploiDuTemps(QDate d, QWidget *parent) :
    QDialog(parent), lundi(d),
    ui(new Ui::EmploiDuTemps)
{
    ui->setupUi(this);
    ui->stackedWidget->setHidden(true);

    ui->labelNumero->setText(QDate::shortDayName(d.dayOfWeek())+d.toString(Qt::SystemLocaleShortDate)+" au "+QDate::shortDayName(d.addDays(6).dayOfWeek())+d.addDays(6).toString(Qt::SystemLocaleShortDate));

    ui->tableWidget->setColumnCount(7);
    QStringList jours(QDate::shortDayName(d.dayOfWeek())+d.toString(Qt::SystemLocaleShortDate));
        for (unsigned int i=1; i<7; i++) {
            jours.append((QDate::shortDayName(d.addDays(i).dayOfWeek()))+(d.addDays(i)).toString(Qt::SystemLocaleShortDate));
        }
    ui->tableWidget->setHorizontalHeaderLabels(jours);
    ui->tableWidget->verticalHeader()->setHidden(true);

    unsigned int nbRow =0;
    ui->tableWidget->setRowCount(nbRow);



    QDate jour1(d.year(), d.month(), d.day());
    QDate jour7=d.addDays(7);
    unsigned int prog = 0;


    QBrush coulEvt (QColor(191,117,255));
    QBrush coulTache (QColor(85,255,127));

    for (QDate jour=jour1; jour<jour7; jour = jour.addDays(1)){
            unsigned int nb=0;
            for(QMap<QDateTime, Programmation*>::const_iterator it = ProgrammationManager::getInstance().getProgrammations().cbegin();
                it != ProgrammationManager::getInstance().getProgrammations().cend();
                it++){
                if(it.key().date()== jour){
                    //afficher
                    QTableWidgetItem* item = new QTableWidgetItem;
                    if(it.value()->getEvenement()!=0){
                        item->setWhatsThis(it.value()->getEvenement()->getNom());
                        item->setText((*it)->getTime().toString("HH:mm")+" : "+(*it)->getEvenement()->getNom()+"\n\ndurée : "+(*it)->getDuree().stringDuree()+"\n\n");
                        item->setBackground(coulEvt);
                        prog++;
                    }
                    else if (it.value()->getTache()!=0){
                        item->setWhatsThis(it.value()->getTache()->getId());
                        item->setText((*it)->getTime().toString("HH:mm")+" : "+(*it)->getTache()->getId()+"\n\ndurée : "+(*it)->getDuree().stringDuree()+" \n\n");
                        item->setBackground(coulTache);
                        prog++;
                    }
                    if(nb>=nbRow){
                        nbRow+=5;
                        ui->tableWidget->setRowCount(nbRow);
                    }
                    ui->tableWidget->setItem(nb,(jour.dayOfWeek()-1),item);

                    nb++;
                }
            }

        }


    ui->tableWidget->resizeRowsToContents();
    if(prog==0)
        QMessageBox::information(this, "Message", "Il n'y a pas encore de programmation pour la semaine choisie.");



    QObject::connect(ui->pushButtonFermer, SIGNAL(clicked()),this,SLOT(close()));
    QObject::connect(ui->pushButtonChange, SIGNAL(clicked()),this,SLOT(changeEdt()));
    QObject::connect(ui->tableWidget, SIGNAL(cellClicked(int,int)),this,SLOT(afficheInfos(int, int)));

}
bool RDReport::ExportTechnical(const QString &filename,const QDate &startdate,
			       const QDate &enddate,bool incl_hdr,bool incl_crs,
			       const QString &mixtable)
{
  QString sql;
  RDSqlQuery *q;
  QString cut;
  QString str;
  QString cart_fmt;
  QString cart_num;
  char eol[3]="\n";

  if(incl_crs) {
    strcpy(eol,"\r\n");
  }

  QFile *file=new QFile(filename);
  if(!file->open(QIODevice::WriteOnly|QIODevice::Truncate)) {
    report_error_code=RDReport::ErrorCantOpen;
    delete file;
    return false;
  }
  Q3TextStream *strm=new Q3TextStream(file);
  strm->setEncoding(Q3TextStream::UnicodeUTF8);
  if(useLeadingZeros()) {
    cart_fmt=QString().sprintf("%%0%uu",cartDigits());
  }
  else {
    cart_fmt="%6u";
  }
  sql=QString("select ")+
    "ELR_LINES.LENGTH,"+          // 00
    "ELR_LINES.CART_NUMBER,"+     // 01
    "ELR_LINES.EVENT_DATETIME,"+  // 02
    "ELR_LINES.EVENT_TYPE,"+      // 03
    "ELR_LINES.EXT_START_TIME,"+  // 04
    "ELR_LINES.EXT_LENGTH,"+      // 05
    "ELR_LINES.EXT_DATA,"+        // 06
    "ELR_LINES.EXT_EVENT_ID,"+    // 07
    "ELR_LINES.TITLE,"+           // 08
    "CART.FORCED_LENGTH,"+        // 09
    "ELR_LINES.STATION_NAME,"+    // 10
    "ELR_LINES.PLAY_SOURCE,"+     // 11
    "ELR_LINES.CUT_NUMBER,"+      // 12
    "ELR_LINES.START_SOURCE,"+    // 13
    "ELR_LINES.ONAIR_FLAG "+      // 14
    "from ELR_LINES left join CART "+
    "on ELR_LINES.CART_NUMBER=CART.NUMBER where "+
    "SERVICE_NAME=\""+RDEscapeString(mixtable)+"\" "+
    "order by EVENT_DATETIME";
  q=new RDSqlQuery(sql);

  //
  // Write File Header
  //
  if(incl_hdr) {
    if(startdate==enddate) {
      *strm << RDReport::center("Rivendell RDAirPlay Technical Playout Report for "+
				 startdate.toString("MM/dd/yyyy"),96);
      *strm << eol;
    }
    else {
      *strm << RDReport::center("Rivendell RDAirPlay Technical Playout Report for "+
		      startdate.toString("MM/dd/yyyy")+" - "+
		      enddate.toString("MM/dd/yyyy"),96);
      *strm << eol;
    }
    *strm << RDReport::center(name()+" -- "+description(),96);
    *strm << eol;
    *strm << "--Time--  -Cart-  Cut  --Title----------------  A-Len  N-Len  --Host----  Srce  StartedBy  OnAir";
    *strm << eol;
  }

  //
  // Write Data Rows
  //
  while(q->next()) {
    if(q->value(12).toInt()>0) {
      cut=QString().sprintf("%03d",q->value(12).toInt());
    }
    else {
      if((RDAirPlayConf::TrafficAction)q->value(3).toInt()==
	 RDAirPlayConf::TrafficMacro) {
	cut="rml";
      }
      else {
	cut="   ";
      }
    }
    cart_num=QString().sprintf(cart_fmt,q->value(1).toUInt());
    *strm << q->value(2).toTime().toString("hh:mm:ss")+"  ";
    *strm << cart_num+"  ";
    *strm << cut+"  ";
    *strm << RDReport::leftJustify(q->value(8).toString(),23)+"  ";
    *strm << RDGetTimeLength(q->value(0).toInt(),true,false).right(5)+"  ";
    *strm << RDGetTimeLength(q->value(9).toInt(),true,false).right(5)+"  ";
    *strm << RDReport::leftJustify(q->value(10).toString(),10)+"  ";
    switch((RDLogLine::PlaySource)q->value(11).toInt()) {
    case RDLogLine::MainLog:
      *strm << "Main   ";
      break;

    case RDLogLine::AuxLog1:
      *strm << "Aux1   ";
      break;

    case RDLogLine::AuxLog2:
      *strm << "Aux2   ";
      break;

    case RDLogLine::SoundPanel:
      *strm << "SPnl    ";
      break;

    case RDLogLine::CartSlot:
      *strm << "Slot   ";
      break;

    default:
      *strm << "       ";
      break;
    }
    *strm << RDReport::leftJustify(RDLogLine::startSourceText((RDLogLine::StartSource)q->value(13).toInt()),7)+"  ";
    if(q->value(14).toString()=="Y") {
      *strm << "  Yes ";
    }
    else {
      *strm << "  No  ";
    }
    *strm << eol;
  }
  delete q;

  delete strm;
  delete file;
  report_error_code=RDReport::ErrorOk;
  return true;
}
Example #4
0
QString QgsExpression::formatPreviewString( const QVariant &value, const bool htmlOutput )
{
  static const int MAX_PREVIEW = 60;

  const QString startToken = htmlOutput ? QStringLiteral( "<i>&lt;" ) : QStringLiteral( "<" );
  const QString endToken = htmlOutput ? QStringLiteral( "&gt;</i>" ) : QStringLiteral( ">" );

  if ( value.canConvert<QgsGeometry>() )
  {
    //result is a geometry
    QgsGeometry geom = value.value<QgsGeometry>();
    if ( geom.isNull() )
      return startToken + tr( "empty geometry" ) + endToken;
    else
      return startToken + tr( "geometry: %1" ).arg( QgsWkbTypes::displayString( geom.constGet()->wkbType() ) )
             + endToken;
  }
  else if ( value.value< QgsWeakMapLayerPointer >().data() )
  {
    return startToken + tr( "map layer" ) + endToken;
  }
  else if ( !value.isValid() )
  {
    return htmlOutput ? tr( "<i>NULL</i>" ) : QString();
  }
  else if ( value.canConvert< QgsFeature >() )
  {
    //result is a feature
    QgsFeature feat = value.value<QgsFeature>();
    return startToken + tr( "feature: %1" ).arg( feat.id() ) + endToken;
  }
  else if ( value.canConvert< QgsInterval >() )
  {
    //result is a feature
    QgsInterval interval = value.value<QgsInterval>();
    return startToken + tr( "interval: %1 days" ).arg( interval.days() ) + endToken;
  }
  else if ( value.canConvert< QgsGradientColorRamp >() )
  {
    return startToken + tr( "gradient ramp" ) + endToken;
  }
  else if ( value.type() == QVariant::Date )
  {
    QDate dt = value.toDate();
    return startToken + tr( "date: %1" ).arg( dt.toString( QStringLiteral( "yyyy-MM-dd" ) ) ) + endToken;
  }
  else if ( value.type() == QVariant::Time )
  {
    QTime tm = value.toTime();
    return startToken + tr( "time: %1" ).arg( tm.toString( QStringLiteral( "hh:mm:ss" ) ) ) + endToken;
  }
  else if ( value.type() == QVariant::DateTime )
  {
    QDateTime dt = value.toDateTime();
    return startToken + tr( "datetime: %1" ).arg( dt.toString( QStringLiteral( "yyyy-MM-dd hh:mm:ss" ) ) ) + endToken;
  }
  else if ( value.type() == QVariant::String )
  {
    const QString previewString = value.toString();
    if ( previewString.length() > MAX_PREVIEW + 3 )
    {
      return tr( "'%1…'" ).arg( previewString.left( MAX_PREVIEW ) );
    }
    else
    {
      return '\'' + previewString + '\'';
    }
  }
  else if ( value.type() == QVariant::Map )
  {
    QString mapStr = QStringLiteral( "{" );
    const QVariantMap map = value.toMap();
    QString separator;
    for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
    {
      mapStr.append( separator );
      if ( separator.isEmpty() )
        separator = QStringLiteral( "," );

      mapStr.append( QStringLiteral( " '%1': %2" ).arg( it.key(), formatPreviewString( it.value(), htmlOutput ) ) );
      if ( mapStr.length() > MAX_PREVIEW - 3 )
      {
        mapStr = tr( "%1…" ).arg( mapStr.left( MAX_PREVIEW - 2 ) );
        break;
      }
    }
    if ( !map.empty() )
      mapStr += QStringLiteral( " " );
    mapStr += QStringLiteral( "}" );
    return mapStr;
  }
  else if ( value.type() == QVariant::List || value.type() == QVariant::StringList )
  {
    QString listStr = QStringLiteral( "[" );
    const QVariantList list = value.toList();
    QString separator;
    for ( const QVariant &arrayValue : list )
    {
      listStr.append( separator );
      if ( separator.isEmpty() )
        separator = QStringLiteral( "," );

      listStr.append( " " );
      listStr.append( formatPreviewString( arrayValue, htmlOutput ) );
      if ( listStr.length() > MAX_PREVIEW - 3 )
      {
        listStr = QString( tr( "%1…" ) ).arg( listStr.left( MAX_PREVIEW - 2 ) );
        break;
      }
    }
    if ( !list.empty() )
      listStr += QStringLiteral( " " );
    listStr += QStringLiteral( "]" );
    return listStr;
  }
  else
  {
    return value.toString();
  }
}
Example #5
0
void CSV::parse ()
{
  Setting rule;
  getRule(rule);

  if (! rule.count())
  {
    QString s(tr("Empty rule"));
    printStatusLogMessage(s);
    downloadComplete();
    return;
  }

  QString ts = "Rule";
  QString ts2, s;
  rule.getData(ts, ts2);
  if (! ts2.contains("Date:"))
  {
    QString ss(tr("Rule missing Date field"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  ts = "Delimiter";
  rule.getData(ts, s);
  if (! s.length())
  {
    QString ss(tr("Delimiter not found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }
  setDelimiter(s);

  if (dateRange->isChecked())
  {
    if (sdate->date() >= edate->date() || edate->date() <= sdate->date())
    {
      QString ss = stringDone + " " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
      printStatusLogMessage(ss);
      downloadComplete();
      return;
    }
  }

  QString type;
  ts = "Type";
  rule.getData(ts, type);
  if (! type.length())
  {
    QString ss(tr("Type not found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  ts = "Rule";
  rule.getData(ts, ts2);
  QStringList fieldList = QStringList::split(",", ts2, FALSE);
  if (! fieldList.count())
  {
    QString ss(tr("No rule found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  // get the directory path offset
  ts = "Directory";
  QString directory;
  rule.getData(ts, directory);
  if (! directory.length())
  {
    QString ss(tr("Directory not found"));
    printStatusLogMessage(ss);
    downloadComplete();
    return;
  }

  // get the symbol filter
  ts = "SymbolFilter";
  rule.getData(ts, ts2);
  QStringList symbolFilter = QStringList::split(",", ts2, FALSE);

  // check for time field and set the tickflag
  bool tickFlag = FALSE;
  ts = "Rule";
  rule.getData(ts, ts2);
  if (ts2.contains("Time"))
    tickFlag = TRUE;
  else
  {
    if (ts2.contains("HHMMSS"))
      tickFlag = TRUE;
  }

  QStringList list;
  file->getFile(list);

  int loop;
  for (loop = 0; loop < (int) list.count(); loop++)
  {
    if (cancelFlag)
      break;

    QFile f(list[loop]);
    if (! f.open(QIODevice::ReadOnly))
      continue;
    Q3TextStream stream(&f);

    QString symbol = symbolOveride;
    if (! symbol.length() && fieldList.findIndex("Symbol") == -1)
    {
      QStringList l = QStringList::split("/", list[loop], FALSE);
      symbol = l[l.count() - 1];

      if (symbol.right(4).contains(".txt"))
        symbol.truncate(symbol.length() - 4);

      if (symbol.right(4).contains(".TXT"))
        symbol.truncate(symbol.length() - 4);

      while (symbol.contains("_"))
        symbol = symbol.remove(symbol.find("_", 0, TRUE), 1);
    }

    QString path;
    if (! type.compare("Stocks"))
    {
      QString tmp = "Stocks/" + directory;
      createDirectory(tmp, path);
      if (! path.length())
      {
        QString ss(tr("CSVPlugin::Unable to create directory"));
        printStatusLogMessage(ss);
        downloadComplete();
        f.close();
        return;
      }
    }
    else
    {
      if (! type.compare("Futures"))
      {
        QString tmp = "Futures/" + directory;
        createDirectory(tmp, path);
        if (! path.length())
        {
          QString ss(tr("CSVPlugin::Unable to create directory"));
          printStatusLogMessage(ss);
          downloadComplete();
          f.close();
          return;
        }
      }
    }

    path.append("/");

    if (symbol.length())
    {
      QString s = path;
      s.append(symbol);
      if (openDb(s, symbol, type, tickFlag))
        continue;
//      QString ss = tr("Updating") + " " + symbol;
//      printStatusLogMessage(ss);
        progressBar->setProgress(loop, (int) list.count());
    }

    int lineCount = 0;
    QFileInfo fi(f);
    QString fName = fi.fileName();
    while(stream.atEnd() == 0)
    {
      QString ts = stream.readLine();
      QStringList l = QStringList::split( '\n', substituteSeparator(ts, delim, '\n'), FALSE);

      lineCount++;
      if (l.count() != fieldList.count())
      {
        QString ss = QString().sprintf(
          "%s - %s - %s: %s Number of fields in file (%i) != rule format (%i)",
          fName.latin1(), symbol.latin1(), tr("Line").latin1(),
          QString::number(lineCount).latin1(),  l.count(), fieldList.count()
          );
        printStatusLogMessage(ss);
        continue;
      }

      int fieldLoop;
      bool flag = FALSE;
      Setting r;
      for (fieldLoop = 0; fieldLoop < (int) fieldList.count(); fieldLoop++)
      {
        QString listItem = l[fieldLoop].stripWhiteSpace();
        if (fieldList[fieldLoop].contains("Date:"))
	{
          QDate dt;
          getDate(fieldList[fieldLoop], listItem, r, dt);
          if (! dt.isValid())
	  {
            QString ss = QString().sprintf("%s - %s - %s: %s %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), QString::number(lineCount).latin1(),
              tr("Bad date").latin1(), listItem.latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }

          if (dateRange->isChecked())
          {
            if (dt < sdate->date() || dt > edate->date())
	    {
	      flag = TRUE;
	      break;
	    }
          }
          ts = "Date";
          ts2 = dt.toString("yyyyMMdd");
	  r.setData(ts, ts2);
	  continue;
	}

        if (! fieldList[fieldLoop].compare("Time"))
	{
          getTime(listItem, s);
          if (! s.length())
	  {
            QString ss = QString().sprintf("%s - %s - %s: %s %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), QString::number(lineCount).latin1(),
              tr("Bad time").latin1(), listItem.latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }
          ts = "Time";
	  r.setData(ts, s);
	  continue;
	}

        if (! fieldList[fieldLoop].compare("Symbol"))
	{
	  if (symbolFilter.count())
	  {
	    if (symbolFilter.findIndex(listItem) == -1)
	    {
	      flag = TRUE;
	      break;
	    }
	  }

          ts = "Symbol";
	  r.setData(ts, listItem);
	  continue;
	}

        if (! fieldList[fieldLoop].compare("Name"))
	{
          ts = "Name";
	  r.setData(ts, listItem);
	  continue;
	}

	if (! fieldList[fieldLoop].compare("Open") ||
	    ! fieldList[fieldLoop].compare("High") ||
	    ! fieldList[fieldLoop].compare("Low") ||
	    ! fieldList[fieldLoop].compare("Close"))
	{
          if (setTFloat(listItem, TRUE))
	  {
            QString ss = QString().sprintf("%s - %s - %s: %i %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), lineCount,
              tr("Bad value").latin1(), tr(fieldList[fieldLoop]).latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }
          ts = QString::number(tfloat);
	  r.setData(fieldList[fieldLoop], ts);
	  continue;
	}

	if (! fieldList[fieldLoop].compare("Volume") ||
	    ! fieldList[fieldLoop].compare("OI"))
	{
          if (setTFloat(listItem, FALSE))
	  {
            QString ss = QString().sprintf("%s - %s - %s: %s %s: %s",
              fName.latin1(), symbol.latin1(), tr("Line").latin1(), QString::number(lineCount).latin1(),
              tr("Bad value").latin1(), tr(fieldList[fieldLoop]).latin1()
              );
            printStatusLogMessage(ss);
	    flag = TRUE;
	    break;
	  }
          ts = QString::number(tfloat);
	  r.setData(fieldList[fieldLoop], ts);
	  continue;
	}
      }

      if (flag)
	continue;

      ts = "Date";
      r.getData(ts, s);
      if (! s.length())
	continue;

      ts = "Time";
      r.getData(ts, ts2);
      if (ts2.length())
        s.append(ts2);
      else
        s.append("000000");

      Bar bar;
      if (bar.setDate(s))
      {
        ts = "Date";
        r.getData(ts, ts2);
        QString ss = tr("Bad date") + " " + ts2;
        printStatusLogMessage(ss);
        continue;
      }
      bar.setTickFlag(tickFlag);
      ts = "Open";
      bar.setOpen(r.getDouble(ts));
      ts = "High";
      bar.setHigh(r.getDouble(ts));
      ts = "Low";
      bar.setLow(r.getDouble(ts));
      ts = "Close";
      bar.setClose(r.getDouble(ts));
      ts = "Volume";
      bar.setVolume(r.getDouble(ts));
      ts = "OI";
      bar.setOI(r.getInt(ts));

      DBIndexItem item;

      if (! symbol.length())
      {
        ts = "Symbol";
        QString t;
        r.getData(ts, t);
	s = path;
	s.append(t);
	if (openDb(s, t, type, tickFlag))
	  continue;

        ts = "Name";
	r.getData(ts, s);
	if (s.length())
        {
          chartIndex->getIndexItem(t, item);
          item.setTitle(s);
	  chartIndex->setIndexItem(t, item);
        }

        db.setBar(bar);

        ts = "Symbol";
        r.getData(ts, ts2);
//        QString ss = tr("Updating") + " " + ts2;
//        printStatusLogMessage(ss);
	config.closePlugin(type);

        db.close();

        emit signalWakeup();
      }
      else
      {
        ts = "Name";
	r.getData(ts, s);
	if (s.length())
        {
          chartIndex->getIndexItem(symbol, item);
          item.setTitle(s);
	  chartIndex->setIndexItem(symbol, item);
        }
        db.setBar(bar);

        emit signalWakeup();
      }
    }

    db.close();
    f.close();
  }

  progressBar->setProgress((int) list.count(), (int) list.count());
  downloadComplete();
  if (cancelFlag)
  {
    cancelFlag = FALSE;
    printStatusLogMessage(stringCanceled);
  }
  else {
    QString ss = stringDone + " " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    printStatusLogMessage(ss);
  }
  progressBar->reset();
}
Example #6
0
int main(int argc, char *argv[])
{
    int debugMode = DEBUGMODE;


    if(debugMode)
    {

    } else {
        qInstallMessageHandler(myMessageOutputDisable);

    }

    QDEBUG() << "number of arguments:" << argc;
    QStringList args;
    QDEBUGVAR(RAND_MAX);
    if(argc > 1) {
        QCoreApplication a(argc, argv);
        args = a.arguments();

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();



        QDEBUG() << "Running command line mode.";

        Packet sendPacket;
        sendPacket.init();
        QString outBuilder;

        QTextStream o(&outBuilder);


        QTextStream out(stdout);

        QDate vDate = QDate::fromString(QString(__DATE__).simplified(), "MMM d yyyy");
        QCoreApplication::setApplicationName("Packet Sender");
        QCoreApplication::setApplicationVersion("version " + vDate.toString("yyyy-MM-dd"));

        QCommandLineParser parser;
        parser.setApplicationDescription("Packet Sender is a Network TCP and UDP Test Utility by Dan Nagle\nSee http://PacketSender.com/ for more information.");
        parser.addHelpOption();
        parser.addVersionOption();

        // A boolean option with a single name (-p)
        QCommandLineOption quietOption(QStringList() << "q" << "quiet", "Quiet mode. Only output received data.");
        parser.addOption(quietOption);


        QCommandLineOption hexOption(QStringList() << "x" << "hex", "Parse data as hex (default).");
        parser.addOption(hexOption);

        QCommandLineOption asciiOption(QStringList() << "a" << "ascii", "Parse data as mixed-ascii (like the GUI).");
        parser.addOption(asciiOption);

        QCommandLineOption pureAsciiOption(QStringList() << "A" << "ASCII", "Parse data as pure ascii (no \\xx translation).");
        parser.addOption(pureAsciiOption);

        // An option with a value
        QCommandLineOption waitOption(QStringList() << "w" << "wait",
                "Wait up to <milliseconds> for a response after sending. Zero means do not wait (Default).",
                "milliseconds");
        parser.addOption(waitOption);

        // An option with a value
        QCommandLineOption fileOption(QStringList() << "f" << "file",
                "Send contents of specified path. Max 1024 for UDP, 10 MiB for TCP.",
                "path");
        parser.addOption(fileOption);


        // An option with a value
        QCommandLineOption bindPortOption(QStringList() << "b" << "bind",
                "Bind port. Default is 0 (dynamic).",
                "port");
        parser.addOption(bindPortOption);


        QCommandLineOption tcpOption(QStringList() << "t" << "tcp", "Send TCP (default).");
        parser.addOption(tcpOption);

        // A boolean option with multiple names (-f, --force)
        QCommandLineOption udpOption(QStringList() << "u" << "udp", "Send UDP.");
        parser.addOption(udpOption);

        // An option with a value
        QCommandLineOption nameOption(QStringList() << "n" << "name",
                                      "Send previously saved packet named <name>. Other options overrides saved packet parameters.",
                                      "name");
        parser.addOption(nameOption);


        parser.addPositionalArgument("address", "Destination address. Optional for saved packet.");
        parser.addPositionalArgument("port", "Destination port. Optional for saved packet.");
        parser.addPositionalArgument("data", "Data to send. Optional for saved packet.");


        // Process the actual command line arguments given by the user
        parser.process(a);

        const QStringList args = parser.positionalArguments();

        bool quiet = parser.isSet(quietOption);
        bool hex = parser.isSet(hexOption);
        bool mixedascii = parser.isSet(asciiOption);
        bool ascii = parser.isSet(pureAsciiOption);
        unsigned int wait = parser.value(waitOption).toUInt();
        unsigned int bind = parser.value(bindPortOption).toUInt();
        bool tcp = parser.isSet(tcpOption);
        bool udp = parser.isSet(udpOption);
        bool ipv6  = false;

        QString name = parser.value(nameOption);

        QString filePath = parser.value(fileOption);


        QString address = "";
        unsigned int port = 0;

        int argssize = args.size();
        QString data, dataString;
        data.clear();
        dataString.clear();
        if(argssize >= 1) {
            address = args[0];
        }
        if(argssize >= 2) {
            port = args[1].toUInt();
        }
        if(argssize >= 3) {
            data = (args[2]);
        }

        //check for invalid options..

        if(argssize > 3) {
            OUTIF() << "Warning: Extra parameters detected. Try surrounding your data with quotes.";
        }

        if(hex && mixedascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            mixedascii = false;
        }

        if(hex && ascii) {
            OUTIF() << "Warning: both hex and pure ascii set. Defaulting to hex.";
            ascii = false;
        }

        if(mixedascii && ascii) {
            OUTIF() << "Warning: both mixed ascii and pure ascii set. Defaulting to pure ascii.";
            mixedascii = false;
        }

        if(tcp && udp) {
            OUTIF() << "Warning: both TCP and UDP set. Defaulting to TCP.";
            udp = false;
        }

        if(!filePath.isEmpty() && !QFile::exists(filePath)) {
            OUTIF() << "Error: specified path "<< filePath <<" does not exist.";
            filePath.clear();
            OUTPUT();
            return -1;
        }

        //bind is now default 0

        if(!bind && parser.isSet(bindPortOption)) {
            OUTIF() << "Warning: Binding to port zero is dynamic.";
        }


        if(!port && name.isEmpty()) {
            OUTIF() << "Warning: Sending to port zero.";
        }

        //set default choices
        if(!hex && !ascii && !mixedascii) {
            hex = true;
        }

        if(!tcp && !udp) {
            tcp = true;
        }

        //Create the packet to send.
        if(!name.isEmpty()) {
            sendPacket = Packet::fetchFromDB(name);
            if(sendPacket.name.isEmpty()) {
                OUTIF() << "Error: Saved packet \""<< name <<"\" not found.";
                OUTPUT();
                return -1;
            } else {
                if(data.isEmpty()) {
                    data  = sendPacket.hexString;
                    hex = true;
                    ascii = false;
                    mixedascii = false;
                }
                if(!port) {
                    port  = sendPacket.port;
                }
                if(address.isEmpty()) {
                    address  = sendPacket.toIP;
                }
                if(!parser.isSet(tcpOption) && !parser.isSet(udpOption)) {

                    if(sendPacket.tcpOrUdp.toUpper() == "TCP") {
                        tcp=true;
                        udp = false;
                    } else {
                        tcp=false;
                        udp = true;
                    }

                }

            }

        }

        if(!parser.isSet(bindPortOption)) {
            bind = 0;
        }

        if(!filePath.isEmpty() && QFile::exists(filePath)) {
            QFile dataFile(filePath);
            if(dataFile.open(QFile::ReadOnly)) {

                if(tcp) {
                    QByteArray dataArray = dataFile.read(1024*1024*10);;
                    dataString = Packet::byteArrayToHex(dataArray);
                } else {

                    QByteArray dataArray = dataFile.read(1024);
                    dataString = Packet::byteArrayToHex(dataArray);
                }

                //data format is raw.
                ascii = 0;
                hex = 0;
                mixedascii = 0;

            }
        }



        QDEBUGVAR(argssize);
        QDEBUGVAR(quiet);
        QDEBUGVAR(hex);
        QDEBUGVAR(mixedascii);
        QDEBUGVAR(ascii);
        QDEBUGVAR(address);
        QDEBUGVAR(port);
        QDEBUGVAR(wait);
        QDEBUGVAR(bind);
        QDEBUGVAR(tcp);
        QDEBUGVAR(udp);
        QDEBUGVAR(name);
        QDEBUGVAR(data);
        QDEBUGVAR(filePath);

        //NOW LETS DO THIS!

        if(ascii) { //pure ascii
            dataString = Packet::byteArrayToHex(data.toLatin1());
        }

        if(hex) { //hex
            dataString = Packet::byteArrayToHex(Packet::HEXtoByteArray(data));
        }
        if(mixedascii) { //mixed ascii
            dataString = Packet::ASCIITohex(data);
        }

        if(dataString.isEmpty()) {
            OUTIF() << "Warning: No data to send. Is your formatting correct?";
        }

        QHostAddress addy;
        if(!addy.setAddress(address)) {
            QHostInfo info = QHostInfo::fromName(address);
            if (info.error() != QHostInfo::NoError)
            {
                OUTIF() << "Error: Could not resolve address:" + address;
                OUTPUT();
                return -1;
            } else {
                addy = info.addresses().at(0);
                address = addy.toString();
            }
        }

        QHostAddress theAddress(address);
        if (QAbstractSocket::IPv6Protocol == theAddress.protocol())
        {
           QDEBUG() << "Valid IPv6 address.";
           ipv6 = true;
        }


        QByteArray sendData = sendPacket.HEXtoByteArray(dataString);
        QByteArray recvData;
        recvData.clear();
        int bytesWriten = 0;
        int bytesRead = 0;


        if(tcp) {
            QTcpSocket sock;


            if(ipv6) {
                sock.bind(QHostAddress::AnyIPv6, bind);
            } else {
                sock.bind(QHostAddress::AnyIPv4, bind);
            }
            sock.connectToHost(addy, port);
            sock.waitForConnected(1000);
            if(sock.state() == QAbstractSocket::ConnectedState)
            {
                OUTIF() << "TCP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;
                bytesWriten = sock.write(sendData);
                sock.waitForBytesWritten(1000);
                //OUTIF() << "Sent:" << Packet::byteArrayToHex(sendData);
                if(wait) {
                    sock.waitForReadyRead(wait);
                    recvData = sock.readAll();
                    bytesRead = recvData.size();
                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
                sock.disconnectFromHost();
                sock.waitForDisconnected(1000);
                sock.close();

                OUTPUT();
                return bytesWriten;


            } else {
                OUTIF() << "Error: Failed to connect to " << address;

                OUTPUT();
                return -1;
            }


        } else {
            QUdpSocket sock;
            if(ipv6) {
                if(!sock.bind(QHostAddress::AnyIPv6, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            } else {
                if(!sock.bind(QHostAddress::AnyIPv4, bind)) {
                    OUTIF() << "Error: Could not bind to " << bind;

                    OUTPUT();
                    return -1;
                }

            }
            OUTIF() << "UDP (" <<sock.localPort() <<")://" << address << ":" << port << " " << dataString;

            bytesWriten = sock.writeDatagram(sendData, addy, port);
            //OUTIF() << "Wrote " << bytesWriten << " bytes";
            sock.waitForBytesWritten(1000);

            if(wait) {
                sock.waitForReadyRead(wait);

                if(sock.hasPendingDatagrams()) {
                    QHostAddress sender;
                    quint16 senderPort;
                    recvData.resize(sock.pendingDatagramSize());

                    sock.readDatagram(recvData.data(), recvData.size(),
                                            &sender, &senderPort);

                    QString hexString = Packet::byteArrayToHex(recvData);
                    if(quiet) {
                        o << "\n" << hexString;
                    } else {
                        o << "\nResponse Time:" << QDateTime::currentDateTime().toString(DATETIMEFORMAT);
                        o << "\nResponse HEX:" << hexString;
                        o << "\nResponse ASCII:" << Packet::hexToASCII(hexString);
                    }
                }
            }

            sock.close();

            OUTPUT();
            return bytesWriten;

        }





        OUTPUT();



    } else {
        QApplication a(argc, argv);

        QDEBUGVAR(args);

        qRegisterMetaType<Packet>();

        QFile file(":/packetsender.css");
        if(file.open(QFile::ReadOnly)) {
           QString StyleSheet = QLatin1String(file.readAll());
         //  qDebug() << "stylesheet: " << StyleSheet;
           a.setStyleSheet(StyleSheet);
        }

        MainWindow w;


        w.show();

        return a.exec();

    }



    return 0;

}
Example #7
0
void viewEmploi::loadEmploi(Stowe *admin, QString _promo, QDate _day, int _view, QString _prof)
{
    ui->affEmploi->clearContents();
    int prom, col, ligne;
    int cpt = 0;
    QDate day = _day;

    QTime sample(8,0);
    QColor gray("lightGray");
    QBrush color(gray);

    //Affichage eleve
    if(_view == 0)
    {
        for(int i = 0; i < admin->getPromos().size(); ++i)
        {
            if (admin->getPromos().at(i)->getName() == _promo) prom = i;
        }

        for(int i = 0; i < (7*(admin->getPromos().at(prom)->get().size())); i++)
        {
            if (i%admin->getPromos().at(prom)->get().size() == 0)
            {
                ui->affEmploi->insertColumn(i);
                QTableWidgetItem *item = new QTableWidgetItem(day.toString("dddd dd/MM/yy"));
                ui->affEmploi->setHorizontalHeaderItem(i, item);
                day = day.addDays(1);
            }
            else
            {
                ui->affEmploi->insertColumn(i);
                QTableWidgetItem *item = new QTableWidgetItem("");
                ui->affEmploi->setHorizontalHeaderItem(i, item);
            }
        }

        for(int j = 0; j < 7; ++j)
        {
            for(int i = 0; i < admin->getPromos().at(prom)->get().size(); ++i)
            {
                QTableWidgetItem *item = new QTableWidgetItem(admin->getPromos().at(prom)->get().at(i)->getName());
                ui->affEmploi->setItem(0, cpt, item);
                cpt++;
            }
        }

        for(int tim = 0; tim < admin->getTimeList().size(); ++tim)
        {

            if ((admin->getTimeList().at(tim)->getDebut().date().daysTo(_day) <= 0) && (admin->getTimeList().at(tim)->getDebut().date().daysTo(_day) > -7 ))
            {


                if (findPos(admin, admin->getTimeList().at(tim)->getPeople()->getName(), prom) > -2)
                {

                    col = admin->getTimeList().at(tim)->getDebut().date().daysTo(_day) * admin->getPromos().at(prom)->get().size() * (-1) + findPos(admin, admin->getTimeList().at(tim)->getPeople()->getName(), prom);
                    if (findPos(admin, admin->getTimeList().at(tim)->getPeople()->getName(), prom) == -1)
                    {
                        col++;
                        for(int i = col; i < col + admin->getPromos().at(prom)->get().size(); ++i)
                        {
                            for (int k = (-admin->getTimeList().at(tim)->getDebut().time().secsTo(sample))/900 +1; k <= (-admin->getTimeList().at(tim)->getFin().time().secsTo(sample))/900 ; k++)
                            {
                                QTableWidgetItem *item = new QTableWidgetItem("");
                                item->setBackground(color);
                                ui->affEmploi->setItem(k, i, item);
                            }
                            ligne = (-admin->getTimeList().at(tim)->getDebut().time().secsTo(sample))/900;
                            QTableWidgetItem *item1 = new QTableWidgetItem(admin->getTimeList().at(tim)->getLesson()->getName());
                            item1->setBackground(color);
                            ui->affEmploi->setItem(ligne+1, i, item1);
                            ligne = (-admin->getTimeList().at(tim)->getFin().time().secsTo(sample))/900;
                            QTableWidgetItem *item2 = new QTableWidgetItem(admin->getTimeList().at(tim)->getRoom()->getName());
                            item2->setBackground(color);
                            ui->affEmploi->setItem(ligne, i, item2);
                        }
                    }
                    else
                    {
                        for (int k = (-admin->getTimeList().at(tim)->getDebut().time().secsTo(sample))/900 +1; k <= (-admin->getTimeList().at(tim)->getFin().time().secsTo(sample))/900 ; k++)
                        {
                            QTableWidgetItem *item = new QTableWidgetItem("");
                            item->setBackground(color);
                            ui->affEmploi->setItem(k, col-1, item);
                        }
                        ligne = (-admin->getTimeList().at(tim)->getDebut().time().secsTo(sample))/900;
                        QTableWidgetItem *item1 = new QTableWidgetItem(admin->getTimeList().at(tim)->getLesson()->getName());
                        item1->setBackground(color);
                        ui->affEmploi->setItem(ligne+1, col-1, item1);
                        ligne = (-admin->getTimeList().at(tim)->getFin().time().secsTo(sample))/900;
                        QTableWidgetItem *item2 = new QTableWidgetItem(admin->getTimeList().at(tim)->getRoom()->getName());
                        item2->setBackground(color);
                        ui->affEmploi->setItem(ligne, col-1, item2);
                    }
                }

            }
        }
    }

    else
    {
        setWindowTitle(_prof);
        for(int i = 0; i<7; i++)
        {
            ui->affEmploi->insertColumn(i);
            QTableWidgetItem *item = new QTableWidgetItem(day.toString("dddd dd/MM/yy"));
            ui->affEmploi->setHorizontalHeaderItem(i, item);
            day = day.addDays(1);
        }
        for(int tim = 0; tim < admin->getTimeList().size(); ++tim)
        {
            if ((admin->getTimeList().at(tim)->getDebut().date().daysTo(_day) <= 0) && (admin->getTimeList().at(tim)->getDebut().date().daysTo(_day) > -7 ))
            {
                if(admin->getTimeList().at(tim)->getProf()->getName() == _prof)
                {

                    col = -admin->getTimeList().at(tim)->getDebut().date().daysTo(_day);

                    for (int k = (-admin->getTimeList().at(tim)->getDebut().time().secsTo(sample))/900 +1; k <= (-admin->getTimeList().at(tim)->getFin().time().secsTo(sample))/900 ; k++)
                    {
                        QTableWidgetItem *item = new QTableWidgetItem("");
                        item->setBackground(color);
                        ui->affEmploi->setItem(k, col, item);
                    }
                    ligne = (-admin->getTimeList().at(tim)->getDebut().time().secsTo(sample))/900;
                    QTableWidgetItem *item1 = new QTableWidgetItem(admin->getTimeList().at(tim)->getLesson()->getName());
                    item1->setBackground(color);
                    ui->affEmploi->setItem(ligne+1, col, item1);
                    ligne = (-admin->getTimeList().at(tim)->getFin().time().secsTo(sample))/900;
                    QTableWidgetItem *item2 = new QTableWidgetItem(admin->getTimeList().at(tim)->getRoom()->getName());
                    item2->setBackground(color);
                    ui->affEmploi->setItem(ligne, col, item2);
                }
            }
        }
    }

}
Example #8
0
QVariant TableModel::data(const QModelIndex &index, int role) const
{
	QVariant ret;
	if(!index.isValid())
		return ret;
	if(role == RawValueRole) {
		ret = value(index.row(), index.column());
	}
	else if(role == ValueIsDirtyRole) {
		ret = isDirty(index.row(), index.column());
	}
	else if(role == SortRole) {
		int type = columnType(index.column());
		if(type == QVariant::Bool)
			ret = value(index.row(), index.column()).toBool();
		else
			ret = data(index, Qt::DisplayRole);
	}
	else if(role == Qt::DisplayRole) {
		ColumnDefinition cd = m_columns.value(index.column());
		if(cd.isNull()) {
			return QString("!%1").arg(index.column());
		}
		if(data(index, ValueIsNullRole).toBool()) {
			if(isNullReportedAsString())
				return QStringLiteral("null");
			return QVariant();
		}
		ret = data(index, Qt::EditRole);
		int type = columnType(index.column());
		if(type == QVariant::Invalid)
			type = ret.type(); /// pokud jsou sloupce virtualni (sloupce se pocitaji, nemusi byt pro ne definovan typ)
		if(type == QVariant::ByteArray) {
			const static QString blob_string = "{blob %1%2}";
			int size = ret.toByteArray().size();
			if(size < 1024) ret = blob_string.arg(size).arg(" B");
			else ret = blob_string.arg(size/1024).arg("kB");
		}
		else if(type == QVariant::Bool) {
			/// display check
			ret = QString();
		}
		QString format = cd.format();
		if(format.isEmpty()) {
			if(type == QVariant::Date) {
				format = m_defaultDateFormat;
			}
			else if(type == QVariant::Time) {
				format = m_defaultTimeFormat;
				//qfInfo() << "format" << format;
			}
			else if(type == QVariant::DateTime) {
				format = m_defaultDateTimeFormat;
				//qfInfo() << "format" << format;
			}
		}
		if(!format.isEmpty()) {
			if(type == QVariant::Time) {
				QTime t = ret.toTime();
				ret = t.toString(format);
			}
			else if(type == QVariant::Date) {
				QDate d = ret.toDate();
				ret = d.toString(format);
			}
			else if(type == QVariant::DateTime) {
				QDateTime dt = ret.toDateTime();
				ret = dt.toString(format);
			}
		}
	}
	else if(role == Qt::EditRole) {
		ret = data(index, RawValueRole);
		ret = rawValueToEdit(index.column(), ret);
	}
	else if (role == ValueIsNullRole) {
		ret = data(index, RawValueRole);
		return ret.isNull() && ret.isValid();
	}
	else if (role == Qt::TextAlignmentRole) {
		const ColumnDefinition cd = m_columns.value(index.column());
		Qt::Alignment al = cd.alignment();
		if(!!al)
			ret = (int)al;
		else {
			if(!data(index, ValueIsNullRole).toBool()) {
				ret = data(index, RawValueRole);
				if(ret.type() > QVariant::Bool && ret.type() <= QVariant::Double)
					ret = Qt::AlignRight;
				else
					ret = Qt::AlignLeft;
			}
		}
	}
	else if(role == Qt::TextColorRole) {
		int type = columnType(index.column());
		if(type == QVariant::ByteArray)
			return QColor(Qt::blue);
		if(data(index, ValueIsNullRole).toBool()) {
			return QColor(Qt::blue);
		}
		ret = QVariant();
	}
	else if (role == Qt::BackgroundColorRole) {
		/// delegate does it
	}
	else if (role == Qt::CheckStateRole) {
		int type = columnType(index.column());
		if(type == QVariant::Bool) {
			//qfInfo() << "BOOL";
			return (data(index, Qt::EditRole).toBool()? Qt::Checked: Qt::Unchecked);
		}
		return QVariant();
	}
	else if (role == Qt::ToolTipRole) {
		QString s = data(index, Qt::DisplayRole).toString();
		//s = "<pre>" + s + "</pre>"; /// kvuli chybe v Qt 4.6.3, kdy aplikace pada pokud je v textu za sebou 0x09 0x0A
		s.replace("\t\n", "\n");
		ret = s;
		//ret = data(index, Qt::DisplayRole);
		//qfInfo() << ret.toString();
	}
	return ret;
}
int DicomImageSet::readDatasetFile(const QString &datasetFileName, QTreeWidget *treeWidget)
{
    HRESULT hr = S_OK;
    IXMLDOMDocument *pXMLDom = NULL;
    IXMLDOMNodeList *pPatients = NULL;
    IXMLDOMNode *pPatient = NULL;
	DOMNodeType nodeType;
    VARIANT_BOOL varStatus;
    VARIANT varFileName;
	VARIANT varValue;
	BSTR bstrQuery;

    VariantInit(&varFileName);
    VariantInit(&varValue);

	QString queryPatient, queryDate, queryProtocol, queryCollection;

    CHK_HR(CreateAndInitDOM(&pXMLDom));

	CHK_HR(VariantFromString(datasetFileName.toStdWString().c_str(), varFileName));
    CHK_HR(pXMLDom->load(varFileName, &varStatus));
    if (varStatus != VARIANT_TRUE)
    {
        CHK_HR(ReportParseError(pXMLDom, "Failed to load DOM from stocks.xml."));
    }

	treeWidget->clear();
	treeWidget->setColumnCount(1);
	CHK_HR(pXMLDom->getElementsByTagName(L"Patient", &pPatients));
	if (pPatients)
	{
		long nPatients;
		CHK_HR(pPatients->get_length(&nPatients));
		for (long i=0; i<nPatients; ++i)
		{
			CHK_HR(pPatients->get_item(i, &pPatient));
			CHK_HR(GetAttributeFromNode(pPatient, L"patients_name", &varValue));
			queryPatient = QString::fromWCharArray(_bstr_t(varValue));
			QTreeWidgetItem * patientItem = new QTreeWidgetItem(treeWidget, QStringList(queryPatient));
			patientItem->setExpanded(true);

			IXMLDOMNodeList * pDates = NULL;
			CHK_HR(pPatient->get_childNodes(&pDates));
			long nDates;
			CHK_HR(pDates->get_length(&nDates));
			for (long j=0; j<nDates; ++j)
			{
				IXMLDOMNode * pDate = NULL;
				CHK_HR(pDates->get_item(j, &pDate));
				CHK_HR(pDate->get_nodeType(&nodeType));
				if(nodeType!=NODE_ELEMENT)
				{
					continue;
				}
				CHK_HR(GetAttributeFromNode(pDate, L"acquisition_date", &varValue));
				queryDate = QString::fromWCharArray(_bstr_t(varValue));
				int intDate = queryDate.toInt();
				QDate date = (QDate::fromString("1900-01-01", "yyyy-MM-dd")).addDays(intDate-693962);
				QTreeWidgetItem * dateItem = new QTreeWidgetItem(patientItem, QStringList(date.toString("yyyy-MM-dd")));
				dateItem->setExpanded(true);

				IXMLDOMNodeList * pProtocols = NULL;
				CHK_HR(pDate->get_childNodes(&pProtocols));
				long nProtocols;
				CHK_HR(pProtocols->get_length(&nProtocols));
				for (long j=0; j<nProtocols; ++j)
				{
					IXMLDOMNode * pProtocol = NULL;
					CHK_HR(pProtocols->get_item(j, &pProtocol));
					CHK_HR(pProtocol->get_nodeType(&nodeType));
					if(nodeType!=NODE_ELEMENT)
					{
						continue;
					}
					CHK_HR(GetAttributeFromNode(pProtocol, L"protocol_name", &varValue));
					queryProtocol = QString::fromWCharArray(_bstr_t(varValue));
					QTreeWidgetItem * protocolItem = new QTreeWidgetItem(dateItem, QStringList(queryProtocol));
					protocolItem->setExpanded(true);

					IXMLDOMNodeList * pCollections = NULL;
					CHK_HR(pProtocol->get_childNodes(&pCollections));
					long nCollections;
					CHK_HR(pCollections->get_length(&nCollections));
					for (long j=0; j<nCollections; ++j)
					{
						IXMLDOMNode * pCollection = NULL;
						CHK_HR(pCollections->get_item(j, &pCollection));
						CHK_HR(pCollection->get_nodeType(&nodeType));
						if(nodeType!=NODE_ELEMENT)
						{
							continue;
						}
						CHK_HR(GetAttributeFromNode(pCollection, L"acquisition_number", &varValue));
						queryCollection = QString::fromWCharArray(_bstr_t(varValue));
						QTreeWidgetItem * collectionItem = new QTreeWidgetItem(protocolItem);
						QString queryStr = QString("root/Patient[@patients_name = '%1']/Date[@acquisition_date = '%2']/Protocol[@protocol_name = '%3']/Collection[@acquisition_number = '%4']")
							.arg(queryPatient).arg(queryDate).arg(queryProtocol).arg(queryCollection);

						IXMLDOMElement * pDtiNode = NULL;
						bstrQuery = SysAllocString(QString(queryStr+"/DTI").toStdWString().c_str());
						CHK_ALLOC(bstrQuery);
						CHK_HR(pXMLDom->selectSingleNode(bstrQuery, (IXMLDOMNode**)&pDtiNode));
						SysFreeString(bstrQuery);
						if (pDtiNode)
						{
							collectionItem->setText(0,queryCollection+"*");
						} else
						{
							collectionItem->setText(0, queryCollection);
						}

						collectionItem->setData(0, Qt::UserRole, queryStr);
						collectionItem->setExpanded(true);


						protocolItem->addChild(collectionItem);
						SAFE_RELEASE(pCollection);
					}

					dateItem->addChild(protocolItem);
					SAFE_RELEASE(pProtocol);
				}

				patientItem->addChild(dateItem);
				SAFE_RELEASE(pDate);
			}
			treeWidget->insertTopLevelItem(i, patientItem);
			SAFE_RELEASE(pPatient);
		}
	}

CleanUp:
    SAFE_RELEASE(pXMLDom);
    SAFE_RELEASE(pPatients);
    SAFE_RELEASE(pPatient);
    VariantClear(&varFileName);

	return SUCCEEDED(hr);
}
Example #10
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    a.setApplicationName("Jupiter Reporter");
    a.setOrganizationName("XE-QT Solutions");
    a.setOrganizationDomain("xe-qt-solutions.com");

    QxtCommandOptions options;
    options.add("version", "show version number and build date");
    options.alias("version", "ver");
    options.add("help", "show this help text");

    options.addSection("printing and PDF");
    options.add("print", "print a report to a specific printer (blank for default)", QxtCommandOptions::ValueOptional);
    options.add("pdf", "save a report as a PDF file", QxtCommandOptions::ValueRequired);

    options.addSection("email");
    options.add("to", "list of email recipients", QxtCommandOptions::ValueRequired);
    options.add("cc", "list of email cc recipients", QxtCommandOptions::ValueRequired);
    options.add("subject", "the email subject", QxtCommandOptions::ValueRequired);
    options.add("body", "the body of the email message", QxtCommandOptions::ValueRequired);
    options.add("server", "the email smtp server", QxtCommandOptions::ValueRequired);
    options.add("port", "the smtp server port", QxtCommandOptions::ValueRequired);
    options.add("ssl", "use a secure socket when sending email");
    options.add("account", "the name of the smtp account", QxtCommandOptions::ValueRequired);
    options.add("password", "the smtp account password", QxtCommandOptions::ValueRequired);
    options.add("from", "the email address of the email sender", QxtCommandOptions::ValueRequired);

    options.addSection("licensing");
    options.add("lic", "display license details");
    options.add("name", "the licensee name", QxtCommandOptions::ValueRequired);
    options.add("email", "the licensee email address", QxtCommandOptions::ValueRequired);
    options.add("expires", "the license expiry date (YYYY-MM-DD format)", QxtCommandOptions::ValueRequired);
    options.add("key", "the activation key to unlock advanced features", QxtCommandOptions::ValueRequired);
    options.parse(a.arguments());

    if (options.count("version"))
    {
	std::cout << "Jupiter Reporter v" << VER_MAJOR << "." << VER_MINOR << ", built on " << __DATE__ << " at " << __TIME__ << std::endl;
	std::cout << "Copyright (c) 2010 XE-QT Solutions Ltd., All rights reserved." << std::endl;
	return 0;
    }

    QSettings settings(QString("%1/license.ini").arg(QDesktopServices::storageLocation(QDesktopServices::DataLocation)), QSettings::IniFormat);

    // Generate license?
    if (options.count("name") || options.count("email") || options.count("expires"))
    {
	const QString name = options.value("name").toString();
	const QString email = options.value("email").toString();
	const QString expires = options.value("expires").toString();

	if (name.isEmpty() || email.isEmpty() || expires.isEmpty())
	{
	    options.showUsage();
	    return 0;
	}

	settings.setValue("License/name", name);
	settings.setValue("License/email", email);
	settings.setValue("License/expires", expires);
	settings.setValue("License/license", NodeLockedLicense::licenseFile(name, email, QDate::fromString(expires, Qt::ISODate)));

	std::cout << "Generated " << qPrintable(settings.fileName()) << std::endl;

	return 0;
    }

    if (options.count("key"))
    {
	settings.setValue("License/key", options.value("key").toString());
	settings.remove("License/license");
	std::cout << "Updated " << qPrintable(settings.fileName()) << std::endl;
	return 0;
    }

    // Read license
    const QString name = settings.value("License/name").toString();
    const QString email = settings.value("License/email").toString();
    const QDate expires = QDate::fromString(settings.value("License/expires").toString(), Qt::ISODate);
    const QString key = settings.value("License/key").toString();

    bool isLicensed = NodeLockedLicense::isValid(name, email, expires, key);

    if (options.count("lic"))
    {
	std::cout << "License: " << qPrintable(settings.fileName()) << std::endl;

	if (!isLicensed)
	{
	    std::cout << "No valid license exists.  Advanced functionality will be disabled." << std::endl;
	}
	else
	{
	    std::cout << "Licensed to " << qPrintable(name) << " (" << qPrintable(email) << "), expires on " << qPrintable(expires.toString()) << std::endl;
	}
	return 0;
    }

    if (options.positional().isEmpty() || options.count("help") || options.showUnrecognizedWarning() ||
	(options.count("print") == 0 && options.count("pdf") == 0 && options.count("to") == 0))
    {
	options.showUsage();
	return 0;
    }

    const QString fileName = options.positional().first();
    Q_ASSERT(fileName != "");

    if (options.count("print"))
    {
	Print print;
	QObject::connect(&print, SIGNAL(finished()), &a, SLOT(quit()));
	print.print(fileName, options.value("print").toString());
	return a.exec();
    }

    if (options.count("pdf"))
    {
	if (isLicensed)
	{
	    Pdf pdf;
	    QObject::connect(&pdf, SIGNAL(finished()), &a, SLOT(quit()));
	    pdf.create(fileName, options.value("pdf").toString());
	    return a.exec();
	}
	else
	{
	    std::cout << "PDF support requires a license!" << std::endl;
	    return 0;
	}
    }

    if (options.count("to") || options.count("cc"))
    {
	if (isLicensed)
	{
	    Email email;
	    email.send(fileName, parseSendSettings(options), parseEmailSettings(options));
	    QObject::connect(&email, SIGNAL(finished()), &a, SLOT(quit()));
	    return a.exec();
	}
	else
	{
	    std::cout << "Email support requires a license!" << std::endl;
	    return 0;
	}
    }

    return 0;
}
// the code here is tedious. checking for conditions about total ride time
// and if it fits in a day, then distributing them over the day, but
// only if the time is not set, and then if its being set to today
// then start must be before the current time cause you can't log
// data for future rides ... and so on.
//
// but then this feature is gonna save a lot of typing over time ...
//
void
RideImportWizard::todayClicked(int index)
{
    QDate selectedDate; // the date we're gonna apply to the row(s) highlighted

    // 0 = nothing selected, 1 = Today - 2 = last monday thru to 8 = last sunday
    if (index == 0) { // no selection
        return;
    } else if (index == 1) { // today
        selectedDate = QDate().currentDate();
    } else if (index == 10) { // other date - set focus on first highlighted date
        for (int i=0; i<filenames.count(); i++) {
            if (tableWidget->item(i,0)->isSelected() ||
                tableWidget->item(i,1)->isSelected() ||
                tableWidget->item(i,2)->isSelected() ||
                tableWidget->item(i,3)->isSelected() ||
                tableWidget->item(i,4)->isSelected() ||
                tableWidget->item(i,5)->isSelected()) {
                if (blanks[i]) {
                    tableWidget->editItem(tableWidget->item(i,1));
                    return;
                }
            }
        }
        return;
    } else { // last mon/tue/wed/thu/fri/sat/sun
        int daysago =  (QDate().currentDate().dayOfWeek() - index + 8) % 7;
        if (!daysago) daysago=7; // e.g.last wednesday is 7 days ago if today is wednesday
        selectedDate = QDate().fromJulianDay(QDate().currentDate().toJulianDay()-daysago);
    }

    // Only apply to selected date - set time to current time - ride duration
    // pretty daft but at least it sets it to something, anything is gonna be random
    int countselected = 0;
    int totalduration = 0;
    for (int i=0; i< filenames.count(); i++) {
        if (tableWidget->item(i,0)->isSelected() ||
            tableWidget->item(i,1)->isSelected() ||
            tableWidget->item(i,2)->isSelected() ||
            tableWidget->item(i,3)->isSelected() ||
            tableWidget->item(i,4)->isSelected() ||
            tableWidget->item(i,5)->isSelected()) {
            countselected++;

            QTime duration = QTime().fromString(tableWidget->item(i,3)->text(), tr("hh:mm:ss"));
            totalduration += duration.hour() * 3600 +
                             duration.minute() * 60 +
                             duration.second();
        }
    }

    // More than a days worth of rides so can't squeeze into a single day!
    if (totalduration > (24 * 3600)) {
        QMessageBox::warning ( this, tr ( "Invalid Selection" ), tr ( "More than 24hrs of rides to fit into a day" ));
        return;
    }

    // if it is today then start from now - total rides duration
    // if that goes negative then just do the std thing
    int rstart=0;
    if (index == 1) {

        QTime timenow = QTime().currentTime();

        int now  = timenow.hour() * 3600 +
                   timenow.minute() * 60 +
                   timenow.second();

        rstart = now - totalduration;

    }

    if (rstart <= 0) { // i.e. still not set properly...
        // if it is not being set to "today" then spread them across the
        // day back to back with equal time before and after noon.
        rstart = ((24*3600) - totalduration) /2;
    }

    // zip through the rows and where highlighted set the date
    // if the start time is not set set it to rstart and increment
    // by the duration of the ride.
    for (int i=0; i< filenames.count(); i++) {
        if (tableWidget->item(i,0)->isSelected() ||
            tableWidget->item(i,1)->isSelected() ||
            tableWidget->item(i,2)->isSelected() ||
            tableWidget->item(i,3)->isSelected() ||
            tableWidget->item(i,4)->isSelected() ||
            tableWidget->item(i,5)->isSelected()) {

            // set the date to date selected
            tableWidget->item(i,1)->setText(selectedDate.toString(tr("dd MMM yyyy")));
            // look at rides with missing start time - we need to populate those

            // ride duration
            QTime duration = QTime().fromString(tableWidget->item(i,3)->text(), tr("hh:mm:ss"));

            // ride start time
            QTime time(rstart/3600, rstart%3600/60, rstart%60);
            tableWidget->item(i,2)->setText(time.toString(tr("hh:mm:ss a")));
            rstart += duration.hour() * 3600 +
                      duration.minute() * 60 +
                      duration.second();
        }
    }
    // phew! - repaint!
    QApplication::processEvents();
    tableWidget->repaint();
}
Example #12
0
void ChatForm::loadHistory(QDateTime since, bool processUndelivered)
{
    QDateTime now = QDateTime::currentDateTime();

    if (since > now)
        return;

    if (earliestMessage)
    {
        if (*earliestMessage < since)
            return;
        if (*earliestMessage < now)
        {
            now = *earliestMessage;
            now = now.addMSecs(-1);
        }
    }

    auto msgs = HistoryKeeper::getInstance()->getChatHistory(HistoryKeeper::ctSingle, f->getToxID().publicKey, since, now);

    ToxID storedPrevId;
    std::swap(storedPrevId, previousId);
    QList<ChatActionPtr> historyMessages;

    QDate lastDate(1,0,0);
    for (const auto &it : msgs)
    {
        // Show the date every new day
        QDateTime msgDateTime = it.timestamp.toLocalTime();
        QDate msgDate = msgDateTime.date();
        if (msgDate > lastDate)
        {
            lastDate = msgDate;
            historyMessages.append(genSystemInfoAction(msgDate.toString(),"",QDateTime()));
        }

        // Show each messages
        ToxID msgSender = ToxID::fromString(it.sender);
        MessageActionPtr ca = genMessageActionAction(msgSender, it.message, false, msgDateTime);
        if (it.isSent || !msgSender.isMine())
        {
            ca->markAsSent();
        } else {
            if (processUndelivered)
            {
                int rec;
                if (ca->isAction())
                    rec = Core::getInstance()->sendAction(f->getFriendID(), ca->getRawMessage());
                else
                    rec = Core::getInstance()->sendMessage(f->getFriendID(), ca->getRawMessage());
                registerReceipt(rec, it.id, ca);
            }
        }
        historyMessages.append(ca);
    }
    std::swap(storedPrevId, previousId);

    int savedSliderPos = chatWidget->verticalScrollBar()->maximum() - chatWidget->verticalScrollBar()->value();

    if (earliestMessage != nullptr)
        *earliestMessage = since;

    chatWidget->insertMessagesTop(historyMessages);

    savedSliderPos = chatWidget->verticalScrollBar()->maximum() - savedSliderPos;
    chatWidget->verticalScrollBar()->setValue(savedSliderPos);
}
Example #13
0
int main(int argc, char *argv[])
{

	QApplication::addLibraryPath("./plugins");
	QTextCodec::setCodecForTr(   QTextCodec::codecForName("GB2312")   );

	QApplication a(argc, argv);

	StartExceptionReport();
        //添加QT的中文编码库跟ODBC库等
        QApplication::addLibraryPath("./plugins");

	QTextCodec::setCodecForTr(   QTextCodec::codecForName("GB2312")   );

	g_MainThread = QThread::currentThread();

	system("md D:\\开关机日志");
	mkPlayListPath();
	mkMediaPath();
	mkVolumeListPath();

	if(!SetupSocketLib())
	{
		qDebug()<<"Setup socket lib error";
		return 1;
	}

	MainWindow* mainWindow = MainWindow::instance();
	mainWindow->show();
	mainWindow->splitWindow(g_SplitConfigFileName);

//	int no = 1;
//	ValuePacket packet;

//	packet.insert(LocalVideoPlayer::VideoFilePathName, "wildlife.wmv");
//	mainWindow->setSubWindowContent(no, LocalVideo, packet);

//	no = 2;
//	packet.clear();
//	mainWindow->setSubWindowContent(no, LocalTime, packet);

//	no = 3;
//	packet.clear();
//	packet.insert(LocalVideoPlayer::VideoFilePathName, "q.flv");
////	mainWindow->setSubWindowContent(no, LocalVideo, packet);

//	no = 4;
//	packet.clear();
//	packet.insert(TextPlayer::TextFilePathName, "text.txt");
//	mainWindow->setSubWindowContent(no, LocalText, packet);

	try{
		QDate currentDate = QDate::currentDate();
		std::wstring captureFileName = currentDate.toString("yyyy_MM_dd.mkv").toStdWString();
		CaptureAndSendAd::instance(); //让其初始化,防止出现问题
		boost::shared_ptr<CaptureToFileAd> captureToFile = CaptureToFileAd::instance();
		if(!captureToFile->start(captureFileName))
		{
			qDebug()<<"Start capture to file error";
		}
	}catch(...)
	{
		qDebug()<<"Start capture error";
	}

	try
	{
		g_RealTimeVideoReceiveAndPlay = new ReceiveAndPlayAd(true, true);
		g_RealTimeVideoReceiveAndPlay->setPlayMode(1);

		// 		g_RealTimeAudioReceiveAndPlay = new ReceiveAndPlayAd;
		// 		g_RealTimeAudioReceiveAndPlay->setPlayMode(1);

		g_RealTimeAudioReceiveAndPlay = g_RealTimeVideoReceiveAndPlay;
	}catch(...)
	{
		qDebug()<<"Create receive and play error";
	}

	//读取云台串口,并配置云台参数
	int comNo = ReadCameraCom(g_xmlFileName);
	if(comNo == -1)
		qDebug()<<"Camera com configure error";
	else
	{
		if(!InitComInfo(2,PROTOCOL_P,40,comNo,BSPEED_9600,NONE,DATA_8,STOP_ONE)) //云台初始化
			qDebug()<<"Fail to open Camera Com, ComNo is COM"<<comNo+1;
		else
			qDebug()<<"Camera ComNo is"<<comNo + 1;
	}

	//读取单片机串口
	QString singlechipCom = ReadSingleChipCom(g_xmlFileName);
	if(singlechipCom == NULL)
		qDebug()<<"Singlechip com configure error";
	else
	{
		qDebug()<<"Singlechip ComNo is:"<<singlechipCom;
		SetComm(singlechipCom.toLocal8Bit().data());
	}

	g_PlayScheduler = new Scheduler;
	g_VolumeScheduler = new Scheduler;

	Reloader reloader;
	reloader.reloadPlayList();
	reloader.reloadVolumeList();

	CheckMediaFilesReferenced();

	FileServerThread* fileServerThread = FileServerThread::instance();
	fileServerThread->start();
	fileServerThread->waitForStart(); //等待文件服务线程初始化完毕

	RealTimeServerThread* realTimeServerThread = RealTimeServerThread::instance();
	realTimeServerThread->start();
	realTimeServerThread->waitForStart(); //等到实时播放服务线程初始化完毕


	//TimingSwitch::createTimingSwitch()->start();
	ConnectServer::createConnectServer()->start();
	//TimingSwitch::createTimingSwitch()->terminate();

    return a.exec();
}
Example #14
0
void ChatForm::loadHistory(QDateTime since, bool processUndelivered)
{
    QDateTime now = historyBaselineDate.addMSecs(-1);

    if (since > now)
        return;

    if (!earliestMessage.isNull())
    {
        if (earliestMessage < since)
            return;

        if (earliestMessage < now)
        {
            now = earliestMessage;
            now = now.addMSecs(-1);
        }
    }

    auto msgs = Nexus::getProfile()->getHistory()->getChatHistory(f->getToxId().publicKey, since, now);

    ToxId storedPrevId = previousId;
    ToxId prevId;

    QList<ChatLine::Ptr> historyMessages;

    QDate lastDate(1,0,0);
    for (const auto &it : msgs)
    {
        // Show the date every new day
        QDateTime msgDateTime = it.timestamp.toLocalTime();
        QDate msgDate = msgDateTime.date();

        if (msgDate > lastDate)
        {
            lastDate = msgDate;
            historyMessages.append(ChatMessage::createChatInfoMessage(msgDate.toString(Settings::getInstance().getDateFormat()), ChatMessage::INFO, QDateTime()));
        }

        // Show each messages
        ToxId authorId = ToxId(it.sender);
        QString authorStr = !it.dispName.isEmpty() ? it.dispName : (authorId.isSelf() ? Core::getInstance()->getUsername() : resolveToxId(authorId));
        bool isAction = it.message.startsWith(ACTION_PREFIX, Qt::CaseInsensitive);
        bool needSending = !it.isSent && authorId.isSelf();

        ChatMessage::Ptr msg = ChatMessage::createChatMessage(authorStr,
                                                              isAction ? it.message.mid(4) : it.message,
                                                              isAction ? ChatMessage::ACTION : ChatMessage::NORMAL,
                                                              authorId.isSelf(),
                                                              needSending ? QDateTime() : msgDateTime);

        if (!isAction && (prevId == authorId) && (prevMsgDateTime.secsTo(msgDateTime) < getChatLog()->repNameAfter) )
            msg->hideSender();

        prevId = authorId;
        prevMsgDateTime = msgDateTime;

        if (needSending)
        {
            if (processUndelivered)
            {
                int rec;
                if (!isAction)
                    rec = Core::getInstance()->sendMessage(f->getFriendID(), msg->toString());
                else
                    rec = Core::getInstance()->sendAction(f->getFriendID(), msg->toString());

                getOfflineMsgEngine()->registerReceipt(rec, it.id, msg);
            }
        }
        historyMessages.append(msg);
    }

    previousId = storedPrevId;
    int savedSliderPos = chatWidget->verticalScrollBar()->maximum() - chatWidget->verticalScrollBar()->value();

    earliestMessage = since;

    chatWidget->insertChatlineOnTop(historyMessages);

    savedSliderPos = chatWidget->verticalScrollBar()->maximum() - savedSliderPos;
    chatWidget->verticalScrollBar()->setValue(savedSliderPos);
}
Example #15
0
/** Formats a date using one of the pre-defined formats */
QString MUtil::formatDate(const QDate& value, int format){
    QString string;
    QString month, day, year;

	// Reformat date parts - not necessarily required
    month.setNum(value.month());
    day.setNum(value.day());

	// Add leading zeros to month and day
    if (value.month() < 10) month = "0" + month;
    if (value.day() < 10) day = "0" + day;

	// Create a two digit year
    year.setNum(value.year());
    year = year.right(2);

	// Create the formatted date string
    switch(format){
        case MUtil::MDY_SLASH:
            string = QObject::tr("%1/%2/%3").arg(value.month()).arg(value.day()).arg(year);
            break;
        case MUtil::MDY_DASH:
            string = QObject::tr("%1-%2-%3").arg(value.month()).arg(value.day()).arg(year);
            break;
        case MUtil::MMDDY_SLASH:
	    string = QObject::tr("%1/%2/%3").arg(month).arg(day).arg(year);
            break;
        case MUtil::MMDDY_DASH:
	    string = QObject::tr("%1-%2-%3").arg(month).arg(day).arg(year);
            break;
        case MUtil::MDYYYY_SLASH:
	    string = QObject::tr("%1/%2/%3").arg(value.month()).arg(value.day()).arg(value.year());
            break;
        case MUtil::MDYYYY_DASH:
	    string = QObject::tr("%1-%2-%3").arg(value.month()).arg(value.day()).arg(value.year());
            break;
        case MUtil::MMDDYYYY_SLASH:
	    string = QObject::tr("%1/%2/%3").arg(month).arg(day).arg(value.year());
            break;
        case MUtil::MMDDYYYY_DASH:
	    string = QObject::tr("%1-%2-%3").arg(month).arg(day).arg(value.year());
            break;
        case MUtil::YYYYMD_SLASH:
	    string = QObject::tr("%1/%2/%3").arg(value.year()).arg(value.month()).arg(value.day());
            break;
        case MUtil::YYYYMD_DASH:
	    string = QObject::tr("%1-%2-%3").arg(value.year()).arg(value.month()).arg(value.day());
            break;
        case MUtil::DMY_SLASH:
            string = QObject::tr("%1/%2/%3").arg(value.day()).arg(value.month()).arg(year);
            break;
        case MUtil::DMY_DASH:
            string = QObject::tr("%1-%2-%3").arg(value.day()).arg(value.month()).arg(year);
            break;
        case MUtil::DDMMY_SLASH:
	    string = QObject::tr("%1/%2/%3").arg(day).arg(month).arg(year);
            break;
        case MUtil::DDMMY_DASH:
	    string = QObject::tr("%1-%2-%3").arg(day).arg(month).arg(year);
            break;
        case MUtil::DMYYYY_SLASH:
	    string = QObject::tr("%1/%2/%3").arg(value.day()).arg(value.month()).arg(value.year());
            break;
        case MUtil::DMYYYY_DASH:
	    string = QObject::tr("%1-%2-%3").arg(value.day()).arg(value.month()).arg(value.year());
            break;
        case MUtil::DDMMYYYY_SLASH:
	    string = QObject::tr("%1/%2/%3").arg(day).arg(month).arg(value.year());
            break;
        case MUtil::DDMMYYYY_DASH:
	    string = QObject::tr("%1-%2-%3").arg(day).arg(month).arg(value.year());
            break;
        default:
            string = value.toString();
    }
    return string;
}
void tst_QContactDetail::values()
{
    QContactDetail p;

    QCOMPARE(p.variantValues(), QVariantMap());

    QDateTime dt = QDateTime::currentDateTime();
    QTime t = dt.time();
    t.setHMS(t.hour(), t.minute(), t.second(), 0); // milliseconds don't round trip through ISODate
    dt.setTime(t);
    QDate d = dt.date();

    QDateTime ddt(d); // DateTime version of a Date (QTime())

    p.setValue("string", "This is a string");
    p.setValue("date", d);
    p.setValue("datetime", dt);
    p.setValue("int", (int)6);

    p.setValue("stringdate", d.toString(Qt::ISODate));
    p.setValue("stringdatetime", dt.toString(Qt::ISODate));

    // Test the setter that takes a QString
    p.setValue(QLatin1String("stringint"), "123");

    // and the setter that takes a QL1C
    p.setValue(QContactPhoneNumber::FieldNumber, "1234");

    /* Presence test (const char * version) */
    QVERIFY(p.hasValue("string"));
    QVERIFY(p.hasValue("date"));
    QVERIFY(p.hasValue("datetime"));
    QVERIFY(p.hasValue("int"));
    QVERIFY(p.hasValue("stringdate"));
    QVERIFY(p.hasValue("stringdatetime"));
    QVERIFY(p.hasValue("stringint"));
    QVERIFY(p.hasValue(QContactPhoneNumber::FieldNumber.latin1()));
    QVERIFY(!p.hasValue("non existent field"));

    /* QLatin1Constant version */
    QVERIFY(p.hasValue(QContactPhoneNumber::FieldNumber));
    QVERIFY(!p.hasValue(QContactAddress::FieldCountry));

    /* Again with QString version */
    QVERIFY(p.hasValue(QLatin1String("string")));
    QVERIFY(p.hasValue(QLatin1String("date")));
    QVERIFY(p.hasValue(QLatin1String("datetime")));
    QVERIFY(p.hasValue(QLatin1String("int")));
    QVERIFY(p.hasValue(QLatin1String("stringdate")));
    QVERIFY(p.hasValue(QLatin1String("stringdatetime")));
    QVERIFY(p.hasValue(QLatin1String("stringint")));
    QVERIFY(p.hasValue(QString(QLatin1String(QContactPhoneNumber::FieldNumber))));
    QVERIFY(!p.hasValue(QLatin1String("non existent field")));

    /* string accessors with const char* key */
    QCOMPARE(p.value("string"), QString("This is a string"));
    QCOMPARE(p.value("date"), d.toString(Qt::ISODate));
    QCOMPARE(p.value("datetime"), dt.toString(Qt::ISODate));
    QCOMPARE(p.value("int"), QString("6"));
    QCOMPARE(p.value("stringdate"), d.toString(Qt::ISODate));
    QCOMPARE(p.value("stringdatetime"), dt.toString(Qt::ISODate));
    QCOMPARE(p.value("stringint"), QString("123"));
    QCOMPARE(p.value(QContactPhoneNumber::FieldNumber.latin1()), QString("1234"));

    /* string accessor with QL1C key */
    QCOMPARE(p.value(QContactPhoneNumber::FieldNumber), QString("1234"));

    /* string accessors with QString key */
    QCOMPARE(p.value(QLatin1String("string")), QString("This is a string"));
    QCOMPARE(p.value(QLatin1String("date")), d.toString(Qt::ISODate));
    QCOMPARE(p.value(QLatin1String("datetime")), dt.toString(Qt::ISODate));
    QCOMPARE(p.value(QLatin1String("int")), QString("6"));
    QCOMPARE(p.value(QLatin1String("stringdate")), d.toString(Qt::ISODate));
    QCOMPARE(p.value(QLatin1String("stringdatetime")), dt.toString(Qt::ISODate));
    QCOMPARE(p.value(QLatin1String("stringint")), QString("123"));
    QCOMPARE(p.value(QString(QLatin1String(QContactPhoneNumber::FieldNumber))), QString("1234"));

    /* Variant accessor with const char * key */
    QCOMPARE(p.variantValue("string"), QVariant(QString("This is a string")));
    QCOMPARE(p.variantValue("date"), QVariant(d));
    QCOMPARE(p.variantValue("datetime"), QVariant(dt));
    QCOMPARE(p.variantValue("int"), QVariant((int)6));
    QCOMPARE(p.variantValue("stringdate"), QVariant(d.toString(Qt::ISODate)));
    QCOMPARE(p.variantValue("stringdatetime"), QVariant(dt.toString(Qt::ISODate)));
    QCOMPARE(p.variantValue("stringint"), QVariant(QString("123")));
    QCOMPARE(p.variantValue(QContactPhoneNumber::FieldNumber.latin1()), QVariant(QString("1234")));

    /* Variant accessor with QL1C key */
    QCOMPARE(p.variantValue(QContactPhoneNumber::FieldNumber), QVariant(QString("1234")));

    /* Variant accessor with QString key */
    QCOMPARE(p.variantValue(QLatin1String("string")), QVariant(QString("This is a string")));
    QCOMPARE(p.variantValue(QLatin1String("date")), QVariant(d));
    QCOMPARE(p.variantValue(QLatin1String("datetime")), QVariant(dt));
    QCOMPARE(p.variantValue(QLatin1String("int")), QVariant((int)6));
    QCOMPARE(p.variantValue(QLatin1String("stringdate")), QVariant(d.toString(Qt::ISODate)));
    QCOMPARE(p.variantValue(QLatin1String("stringdatetime")), QVariant(dt.toString(Qt::ISODate)));
    QCOMPARE(p.variantValue(QLatin1String("stringint")), QVariant(QString("123")));
    QCOMPARE(p.variantValue(QLatin1String(QContactPhoneNumber::FieldNumber)), QVariant(QString("1234")));

    /* Typed accessors, string first, const char* key */
    QCOMPARE(p.value<QString>("string"), QString("This is a string"));
    QCOMPARE(p.value<QString>("date"), d.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>("datetime"), dt.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>("int"), QString("6"));
    QCOMPARE(p.value<QString>("stringdate"), d.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>("stringdatetime"), dt.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>("stringint"), QString("123"));
    QCOMPARE(p.value<QString>(QContactPhoneNumber::FieldNumber.latin1()), QString("1234"));

    /* Now individual original types */
    QCOMPARE(p.value<QDate>("date"), d);
    QCOMPARE(p.value<QDateTime>("datetime"), dt);
    QCOMPARE(p.value<int>("int"), 6);

    /* now latin constant keys */
    QCOMPARE(p.value<QString>(QContactPhoneNumber::FieldNumber), QString("1234"));

    /* Typed accessors, string first, QString key */
    QCOMPARE(p.value<QString>(QLatin1String("string")), QString("This is a string"));
    QCOMPARE(p.value<QString>(QLatin1String("date")), d.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>(QLatin1String("datetime")), dt.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>(QLatin1String("int")), QString("6"));
    QCOMPARE(p.value<QString>(QLatin1String("stringdate")), d.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>(QLatin1String("stringdatetime")), dt.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>(QLatin1String("stringint")), QString("123"));
    QCOMPARE(p.value<QString>(QLatin1String(QContactPhoneNumber::FieldNumber)), QString("1234"));
    QCOMPARE(p.value<QDate>(QLatin1String("date")), d);
    QCOMPARE(p.value<QDateTime>(QLatin1String("datetime")), dt);
    QCOMPARE(p.value<int>(QLatin1String("int")), 6);

    /* Now cross types that should fail */
    QDate id;
    QDateTime idt;
    QCOMPARE(p.value<QDate>("string"), id);
    QCOMPARE(p.value<QDate>("int"), id);
    QCOMPARE(p.value<QDate>("stringint"), id);
    QCOMPARE(p.value<QDateTime>("string"), idt);
    QCOMPARE(p.value<QDateTime>("int"), idt);
    QCOMPARE(p.value<QDateTime>("stringint"), idt);
    QCOMPARE(p.value<int>("date"), 0);
    QCOMPARE(p.value<int>("datetime"), 0);
    QCOMPARE(p.value<int>("string"), 0);
    QCOMPARE(p.value<int>("stringdate"), 0);
    QCOMPARE(p.value<int>("stringdatetime"), 0);

    /* Cross types that should work.. */
    QCOMPARE(p.value<int>("stringint"), 123);
    QCOMPARE(p.value<QDate>("stringdate"), d);
    QCOMPARE(p.value<QDateTime>("stringdatetime"), dt);
    QCOMPARE(p.value<QDate>("datetime"), d);
    QCOMPARE(p.value<QDate>("stringdatetime"), d);
    QCOMPARE(p.value<QDateTime>("date"), ddt);
    QCOMPARE(p.value<QDateTime>("stringdate"), ddt);

    /* Now set everything again */
    QVariantMap emptyValues;
    QVariantMap values = p.variantValues();
    QStringList keys = values.keys();
    foreach (const QString& key, keys)
        QVERIFY(p.setValue(key, QVariant()));

    QCOMPARE(p.variantValues(), emptyValues);
    QVERIFY(p.variantValues().count() == 0);
    QVERIFY(!p.hasValue("string"));
    QVERIFY(!p.hasValue("date"));
    QVERIFY(!p.hasValue("datetime"));
    QVERIFY(!p.hasValue("int"));
    QVERIFY(!p.hasValue("stringdate"));
    QVERIFY(!p.hasValue("stringdatetime"));
    QVERIFY(!p.hasValue("stringint"));
    QVERIFY(!p.hasValue("non existent field"));

    QVERIFY(p.value("string") == QString());
    QVERIFY(p.variantValue("string") == QVariant());

    values.insert("string", "This is a string");
    values.insert("date", d);
    values.insert("datetime", dt);
    values.insert("int", (int)6);

    values.insert("stringdate", d.toString(Qt::ISODate));
    values.insert("stringdatetime", dt.toString(Qt::ISODate));
    values.insert("stringint", "123");
    values.insert("string", QString("This is a string"));

    /* Set values */
    keys = values.keys();
    foreach (const QString& key, keys)
        QVERIFY(p.setValue(key, values.value(key)));

    /* Now repeat the tests with our bulk set map */
    QVERIFY(p.hasValue("string"));
    QVERIFY(p.hasValue("date"));
    QVERIFY(p.hasValue("datetime"));
    QVERIFY(p.hasValue("int"));
    QVERIFY(p.hasValue("stringdate"));
    QVERIFY(p.hasValue("stringdatetime"));
    QVERIFY(p.hasValue("stringint"));
    QVERIFY(!p.hasValue("non existent field"));

    /* String accessors */
    QCOMPARE(p.value("string"), QString("This is a string"));
    QCOMPARE(p.value("date"), d.toString(Qt::ISODate));
    QCOMPARE(p.value("datetime"), dt.toString(Qt::ISODate));
    QCOMPARE(p.value("int"), QString("6"));
    QCOMPARE(p.value("stringdate"), d.toString(Qt::ISODate));
    QCOMPARE(p.value("stringdatetime"), dt.toString(Qt::ISODate));
    QCOMPARE(p.value("stringint"), QString("123"));

    /* Typed accessors, string first */
    QCOMPARE(p.value<QString>("string"), QString("This is a string"));
    QCOMPARE(p.value<QString>("date"), d.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>("datetime"), dt.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>("int"), QString("6"));
    QCOMPARE(p.value<QString>("stringdate"), d.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>("stringdatetime"), dt.toString(Qt::ISODate));
    QCOMPARE(p.value<QString>("stringint"), QString("123"));

    /* Now individual original types */
    QCOMPARE(p.value<QDate>("date"), d);
    QCOMPARE(p.value<QDateTime>("datetime"), dt);
    QCOMPARE(p.value<int>("int"), 6);

    /* Now cross types that should fail */
    QCOMPARE(p.value<QDate>("string"), id);
    QCOMPARE(p.value<QDate>("int"), id);
    QCOMPARE(p.value<QDate>("stringint"), id);
    QCOMPARE(p.value<QDateTime>("string"), idt);
    QCOMPARE(p.value<QDateTime>("int"), idt);
    QCOMPARE(p.value<QDateTime>("stringint"), idt);
    QCOMPARE(p.value<int>("date"), 0);
    QCOMPARE(p.value<int>("datetime"), 0);
    QCOMPARE(p.value<int>("string"), 0);
    QCOMPARE(p.value<int>("stringdate"), 0);
    QCOMPARE(p.value<int>("stringdatetime"), 0);

    /* Cross types that should work.. */
    QCOMPARE(p.value<int>("stringint"), 123);
    QCOMPARE(p.value<QDate>("stringdate"), d);
    QCOMPARE(p.value<QDateTime>("stringdatetime"), dt);
    QCOMPARE(p.value<QDate>("datetime"), d);
    QCOMPARE(p.value<QDate>("stringdatetime"), d);
    QCOMPARE(p.value<QDateTime>("date"), ddt);
    QCOMPARE(p.value<QDateTime>("stringdate"), ddt);

    /* Reset again */
    values = p.variantValues();
    keys = values.keys();
    foreach (const QString& key, keys)
        QVERIFY(p.setValue(key, QVariant()));
    QCOMPARE(p.variantValues(), emptyValues);

    /* Check that we can add a null variant */
    //QVERIFY(p.setValue("nullvariant", QVariant()));
    //QVERIFY(p.hasValue("nullvariant"));
    //QCOMPARE(p.value("nullvariant"), QString());
    //QCOMPARE(p.variantValue("nullvariant"), QVariant());
    //QVERIFY(p.removeValue("nullvariant"));
    //QVERIFY(p.values().count() == 0);

    /* Check that adding a value, then setting it to null updates it */
    //QVERIFY(p.setValue("string", QString("string value")));
    //QCOMPARE(p.values().count(), 1);
    //QCOMPARE(p.value("string"), QString("string value"));
    //QVERIFY(p.setValue("string", QVariant()));
    //QCOMPARE(p.values().count(), 1);
    //QVERIFY(p.hasValue("string"));
    //QVERIFY(p.removeValue("string"));
    //QCOMPARE(p.values().count(), 0);

    /* See if adding a null QString triggers the same behaviour */
    //QVERIFY(p.setValue("string", QString("string value")));
    //QCOMPARE(p.values().count(), 1);
    //QCOMPARE(p.value("string"), QString("string value"));
    //QVERIFY(p.setValue("string", QString()));
    //QCOMPARE(p.values().count(), 1);
    //QVERIFY(p.hasValue("string"));
    //QVERIFY(p.removeValue("string"));
    //QCOMPARE(p.values().count(), 0);

    /* Check adding a null value removes the field */
    p.setValue("string", "stringvalue");
    QVERIFY(p.variantValues().contains("string"));
    QVERIFY(p.value("string") == QString("stringvalue"));
    p.setValue("string", QVariant());
    QVERIFY(!p.variantValues().contains("string"));

    /* Check adding a field whose value is an empty string */
    p.setValue("string", "");
    QVERIFY(p.variantValues().contains("string"));
    QVERIFY(p.value("string") == QString(""));

    /* Check accessing a missing value */
    QCOMPARE(p.value("nonexistent"), QString());
    QVERIFY(p.setValue("nonexistent", "changed my mind"));
    QCOMPARE(p.value("nonexistent"), QString("changed my mind"));

    /* Check removing a missing value */
    QVERIFY(!p.removeValue("does not exist"));
    QVERIFY(!p.removeValue(QLatin1String("does not exist")));
    QVERIFY(!p.removeValue(QContactAddress::FieldCountry));

    p.setValue("stringint", "555");
    p.setValue(QContactPhoneNumber::FieldNumber, "1234");

    /* Check removing a real value */
    QVERIFY(p.removeValue("string"));
    QVERIFY(p.removeValue(QLatin1String("stringint")));
    QVERIFY(p.removeValue(QContactPhoneNumber::FieldNumber));
}
Example #17
0
  FileName FileName::version(QDate versionDate) const {
    QString newName = versionDate.toString(fileNameQDatePattern());

    return FileName(originalPath() + "/" + newName);
  }
Example #18
0
#include "../src/budget.h"
#include "../src/sqlite/sqlite.hpp"
#include <QUrl>
#include <QDate>
#include <iostream>
#include <QDebug>
#include <QJsonArray>
#include <QJsonObject>
#include "../src/account.h"
#include "../src/accountmanager.h"

QUrl dirPath = QUrl::fromLocalFile(".");
QUrl budgetFilePath = QUrl::fromLocalFile("BudgetTestAccount.mbgt");

QDate currentDate = QDate::currentDate();
QString currentMonth = currentDate.toString("yyyy-MM");
QString monthPlusOne = currentDate.addMonths(1).toString("yyyy-MM");
QString monthPlusTwo = currentDate.addMonths(2).toString("yyyy-MM");
QString monthMinusOne = currentDate.addMonths(-1).toString("yyyy-MM");
QString monthMinusTwo = currentDate.addMonths(-2).toString("yyyy-MM");

TEST_CASE("Can add budget categories", "[addCategory]") {
    AccountManager accManager;
    Budget budget;
    accManager.createBudget(dirPath, "BudgetTestAccount");

    SECTION("Give file path, name, and initial amount") {
        budget.addCategory(budgetFilePath, "Test Budget", 10000);

        io::sqlite::db mbgt("BudgetTestAccount.mbgt");
        io::sqlite::stmt query(mbgt, "SELECT categoryName, monthOne,"
Example #19
0
void KEquityPriceUpdateDlg::slotReceivedQuote(const QString& _id, const QString& _symbol, const QDate& _date, const double& _price)
{
  QList<QTreeWidgetItem*> foundItems = lvEquityList->findItems(_id, Qt::MatchExactly, ID_COL);
  QTreeWidgetItem* item = 0;

  if (! foundItems.empty())
    item = foundItems.at(0);

  QTreeWidgetItem* next = 0;

  if (item) {
    if (_price > 0.0f && _date.isValid()) {
      QDate date = _date;
      if (date > QDate::currentDate())
        date = QDate::currentDate();

      double price = _price;
      QString id = _id.toUtf8();
      MyMoneySecurity sec;
      if (_id.contains(" ") == 0) {
        MyMoneySecurity security = MyMoneyFile::instance()->security(id);
        QString factor = security.value("kmm-online-factor");
        if (!factor.isEmpty()) {
          price *= MyMoneyMoney(factor).toDouble();
        }
        try {
          sec = MyMoneyFile::instance()->security(id);
          sec = MyMoneyFile::instance()->security(sec.tradingCurrency());
        } catch (const MyMoneyException &) {
          sec = MyMoneySecurity();
        }

      } else {
        QRegExp splitrx("([0-9a-z\\.]+)[^a-z0-9]+([0-9a-z\\.]+)", Qt::CaseInsensitive);
        if (splitrx.indexIn(_id) != -1) {
          try {
            sec = MyMoneyFile::instance()->security(splitrx.cap(2).toUtf8());
          } catch (const MyMoneyException &) {
            sec = MyMoneySecurity();
          }
        }
      }
      item->setText(PRICE_COL, KGlobal::locale()->formatMoney(price, sec.tradingSymbol(), KMyMoneyGlobalSettings::pricePrecision()));
      item->setText(DATE_COL, date.toString(Qt::ISODate));
      logStatusMessage(i18n("Price for %1 updated (id %2)", _symbol, _id));
      // make sure to make OK button available
      btnOK->setEnabled(true);
    } else {
      logErrorMessage(i18n("Received an invalid price for %1, unable to update.", _symbol));
    }

    prgOnlineProgress->setValue(prgOnlineProgress->value() + 1);
    item->setSelected(false);

    // launch the NEXT one ... in case of m_fUpdateAll == false, we
    // need to parse the list to find the next selected one
    next = lvEquityList->invisibleRootItem()->child(lvEquityList->invisibleRootItem()->indexOfChild(item) + 1);
    if (!m_fUpdateAll) {
      while (next && !next->isSelected()) {
        prgOnlineProgress->setValue(prgOnlineProgress->value() + 1);
        next = lvEquityList->invisibleRootItem()->child(lvEquityList->invisibleRootItem()->indexOfChild(next) + 1);
      }
    }
  } else {
    logErrorMessage(i18n("Received a price for %1 (id %2), but this symbol is not on the list. Aborting entire update.", _symbol, _id));
  }

  if (next) {
    m_webQuote.launch(next->text(SYMBOL_COL), next->text(ID_COL), next->text(SOURCE_COL));
  } else {
    finishUpdate();
  }
}
Example #20
0
 /*------------------------------------------------------------------------------*
   Get previous date with a trace stored in Catalog
  *------------------------------------------------------------------------------*/
 QDate Database::getPrevDate(QDate currentDate)
 {
     QSqlDatabase db = QSqlDatabase::database();
     QString sql = "SELECT track_date FROM gpsbook_track WHERE (track_date < \"" + currentDate.toString(Qt::ISODate) + "\") ORDER BY track_date DESC LIMIT 1";
     QSqlQuery queryGpsData(sql, db);
     if (queryGpsData.first())
       return queryGpsData.value(0).toDate();
     else
       return QDate();
 } //Database::getPrevDate
void ScheduleWidget::on_date_clicked(QDate date)
{
    QDateSessionsManager *widget = new QDateSessionsManager(date,0);
    widget->setWindowTitle(date.toString("d MMMM yyyy"));
    widget->show();
}
Example #22
0
QString DLineEdit::toISOString()
{
    QDate mydate = _lineedit.date();
    return mydate.toString(Qt::ISODate);
}
Example #23
0
QString HrZones::getEndDateString(int rnum) const
{
    assert(rnum >= 0);
    QDate d = ranges[rnum].end;
    return (d.isNull() ? "END" : d.toString());
}
void SvgView::loadPlan(vlePlan *plan)
{
    qWarning() << "SvgView::loadPlan";

    if ( mTplHeader.isNull() )
    {
        // ToDo : improve error handling
        qWarning() << "SvgView::loadPlan() Template error";
        return;
    }

    // Compute the height of a group
    if (mTplHeader.hasAttribute("height"))
        mGroupHeight = mTplHeader.attribute("height").toDouble();
    else
        mGroupHeight = 100;

    // Compute size of the whole plan
    int planHeight = mGroupHeight * (1 + plan->countGroups());
    int planWidth  = (mMaxWidth * mZoomLevel);

    // Create SVG document
    QDomDocument planSVG("xml");
    // Create root element
    QDomElement e = planSVG.createElement("svg");
    e.setAttribute("width",   QString(planWidth));
    e.setAttribute("height",  QString(planHeight));
    e.setAttribute("viewBox", QString("0 0 %1 %2").arg(planWidth).arg(planHeight));
    e.setAttribute("version", "1.1");

    QDate dateStart = plan->dateStart();
    QDate dateEnd   = plan->dateEnd();
    int nbDays = dateStart.daysTo(dateEnd);

    // In the plan duration is more than 1500 days
    if (nbDays > mMaxWidth)
    {
        // Update "pixel-per-day" to avoid very large picture
        qreal widgetSize = mMaxWidth;
        mPixelPerDay = (widgetSize / nbDays);
    }

    if (plan != mPlan)
    {
    qWarning() << "Plan period is from" << dateStart.toString("dd/MM/yyyy")
            << "to" << dateEnd.toString("dd/MM/yyyy")
            << "(" << nbDays<< "days)"
            << "[" << mPixelPerDay << "pixel per day]";
    }

    // First insert the time rule
    QDomElement timeGrp = mTplHeader.cloneNode().toElement();
    updateField(timeGrp, "{{name}}", "");
    updatePos  (timeGrp, 0, 0);
    updateAttr (timeGrp, "header_background", "width", QString::number(planWidth));
    float yLen = (mPixelPerDay * 365 * mZoomLevel);
    // Show Weeks
    if (yLen > 2000)
    {
        QDate r;
        if (dateStart.daysInMonth() == 1)
            r.setDate(dateStart.year(), dateStart.month(), dateStart.day());
        else
            r.setDate(dateStart.year(), dateStart.month() + 1, 1);
        while (r < dateEnd)
        {
            QDomElement newTimeStep = mTplTime.cloneNode().toElement();
            if (yLen < 5000)
                updateField(newTimeStep, "{{name}}", r.toString("dd/MM") );
            else
                updateField(newTimeStep, "{{name}}", r.toString("dd/MM/yy") );
            updateAttr (newTimeStep, "step_block", "width", QString::number(4));

            int offset = dateStart.daysTo(r);
            int aPos = (offset * mPixelPerDay * mZoomLevel);
            updatePos(newTimeStep, aPos, 0);
            timeGrp.appendChild(newTimeStep);
            r = r.addDays(7);
        }
    }
    // Show month
    else if (yLen > 500)
    {
        QDate r;
        if (dateStart.daysInMonth() == 1)
            r.setDate(dateStart.year(), dateStart.month(), dateStart.day());
        else
            r.setDate(dateStart.year(), dateStart.month() + 1, 1);
        while (r < dateEnd)
        {
            QDomElement newTimeStep = mTplTime.cloneNode().toElement();
            if (yLen < 1000)
                updateField(newTimeStep, "{{name}}", r.toString("MMM") );
            else
                updateField(newTimeStep, "{{name}}", r.toString("MMM yy") );
            updateAttr (newTimeStep, "step_block", "width", QString::number(4));

            int offset = dateStart.daysTo(r);
            int aPos = (offset * mPixelPerDay * mZoomLevel);
            updatePos(newTimeStep, aPos, 0);
            timeGrp.appendChild(newTimeStep);
            r = r.addMonths(1);
        }
    }
    // Show Year
    else
    {
        QDate r;
        if (dateStart.dayOfYear() == 1)
            r.setDate(dateStart.year(), dateStart.month(), dateStart.day());
        else
            r.setDate(dateStart.year() + 1, 1, 1);
        while (r < dateEnd)
        {
            QDomElement newTimeStep = mTplTime.cloneNode().toElement();
            updateField(newTimeStep, "{{name}}", QString::number(r.year()) );
            updateAttr (newTimeStep, "step_block", "width", QString::number(4));

            int offset = dateStart.daysTo(r);
            int aPos = (offset * mPixelPerDay * mZoomLevel);
            updatePos(newTimeStep, aPos, 0);
            timeGrp.appendChild(newTimeStep);
            r = r.addYears(1);
        }
    }
    e.appendChild(timeGrp);

    // Insert all the known groups
    for (int i=0; i < plan->countGroups(); i++)
    {
        vlePlanGroup *planGroup = plan->getGroup(i);
        vlePlanActivity *prevActivity = 0;
        int prevLen = 0;
        int prevOffset = 0;

        // Create a new Group
        QDomElement newGrp = mTplHeader.cloneNode().toElement();
        updateField(newGrp, "{{name}}", planGroup->getName());
        updatePos  (newGrp, 0, ((i + 1) * mGroupHeight));
        updateAttr (newGrp, "header_background", "width", QString::number(planWidth));

        for (int j = 0; j < planGroup->count(); j++)
        {
            vlePlanActivity *planActivity = planGroup->getActivity(j);

            QDate actStart = planActivity->dateStart();
            QDate actEnd   = planActivity->dateEnd();

            qreal actLength = (mPixelPerDay * actStart.daysTo(actEnd) * mZoomLevel);
            if (actLength < 1)
                actLength = 1;

            QDomElement newAct = mTplTask.cloneNode().toElement();
            updateField(newAct, "{{name}}", planActivity->getName());
            updateAttr (newAct, "activity_block", "width", QString::number(actLength));

            QString cfgColor("#00edda");
            QString activityClass = planActivity->getClass();
            if ( ! activityClass.isEmpty() )
            {
                QString cfg = getConfig("color", activityClass);
                if ( ! cfg.isEmpty() )
                    cfgColor = cfg;
            }
            QString fillStyle = QString(";fill:%1").arg(cfgColor);
            updateAttr (newAct, "activity_block", "style", fillStyle, false);

            int date = dateStart.daysTo(planActivity->dateStart());
            int aPos = (date * mPixelPerDay * mZoomLevel);

            if (prevActivity)
            {
                if (prevLen > aPos)
                {
                    if (prevOffset < 40)
                        prevOffset += 15;
                    updateAttr(newAct, "activity_name", "y", QString::number(prevOffset));
                }
                else
                    prevOffset = 15;
            }

            updatePos(newAct, aPos, 0);
            newGrp.appendChild(newAct);

            prevActivity = planActivity;
            prevLen = aPos + (planActivity->getName().size() * 8);
        }

        e.appendChild(newGrp);
    }
    planSVG.appendChild( e );

    QByteArray data;
    QTextStream stream(&data);
    planSVG.save(stream, QDomNode::EncodingFromTextStream);

#ifdef PLAN_OUT
    QFile File("planOut.svg");
    File.open( QIODevice::WriteOnly );
    QTextStream TextStream(&File);
    planSVG.save(TextStream, 0);
    File.close();
    mFilename = "planOut.svg";
#else
    mFilename.clear();
#endif

    mPlan = plan;

    QXmlStreamReader xData(data);
    mSvgRenderer->load(&xData);
    refresh();
}
Example #25
0
QString QgsExpression::formatPreviewString( const QVariant &value )
{
  static const int MAX_PREVIEW = 60;

  if ( value.canConvert<QgsGeometry>() )
  {
    //result is a geometry
    QgsGeometry geom = value.value<QgsGeometry>();
    if ( geom.isNull() )
      return tr( "<i>&lt;empty geometry&gt;</i>" );
    else
      return tr( "<i>&lt;geometry: %1&gt;</i>" ).arg( QgsWkbTypes::displayString( geom.constGet()->wkbType() ) );
  }
  else if ( !value.isValid() )
  {
    return tr( "<i>NULL</i>" );
  }
  else if ( value.canConvert< QgsFeature >() )
  {
    //result is a feature
    QgsFeature feat = value.value<QgsFeature>();
    return tr( "<i>&lt;feature: %1&gt;</i>" ).arg( feat.id() );
  }
  else if ( value.canConvert< QgsInterval >() )
  {
    //result is a feature
    QgsInterval interval = value.value<QgsInterval>();
    return tr( "<i>&lt;interval: %1 days&gt;</i>" ).arg( interval.days() );
  }
  else if ( value.canConvert< QgsGradientColorRamp >() )
  {
    return tr( "<i>&lt;gradient ramp&gt;</i>" );
  }
  else if ( value.type() == QVariant::Date )
  {
    QDate dt = value.toDate();
    return tr( "<i>&lt;date: %1&gt;</i>" ).arg( dt.toString( QStringLiteral( "yyyy-MM-dd" ) ) );
  }
  else if ( value.type() == QVariant::Time )
  {
    QTime tm = value.toTime();
    return tr( "<i>&lt;time: %1&gt;</i>" ).arg( tm.toString( QStringLiteral( "hh:mm:ss" ) ) );
  }
  else if ( value.type() == QVariant::DateTime )
  {
    QDateTime dt = value.toDateTime();
    return tr( "<i>&lt;datetime: %1&gt;</i>" ).arg( dt.toString( QStringLiteral( "yyyy-MM-dd hh:mm:ss" ) ) );
  }
  else if ( value.type() == QVariant::String )
  {
    QString previewString = value.toString();
    if ( previewString.length() > MAX_PREVIEW + 3 )
    {
      return tr( "'%1…'" ).arg( previewString.left( MAX_PREVIEW ) );
    }
    else
    {
      return previewString.prepend( '\'' ).append( '\'' );
    }
  }
  else if ( value.type() == QVariant::Map )
  {
    QString mapStr;
    const QVariantMap map = value.toMap();
    for ( QVariantMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it )
    {
      if ( !mapStr.isEmpty() ) mapStr.append( ", " );
      mapStr.append( it.key() ).append( ": " ).append( formatPreviewString( it.value() ) );
      if ( mapStr.length() > MAX_PREVIEW + 3 )
      {
        mapStr = QString( tr( "%1…" ) ).arg( mapStr.left( MAX_PREVIEW ) );
        break;
      }
    }
    return tr( "<i>&lt;map: %1&gt;</i>" ).arg( mapStr );
  }
  else if ( value.type() == QVariant::List || value.type() == QVariant::StringList )
  {
    QString listStr;
    const QVariantList list = value.toList();
    for ( QVariantList::const_iterator it = list.constBegin(); it != list.constEnd(); ++it )
    {
      if ( !listStr.isEmpty() ) listStr.append( ", " );
      listStr.append( formatPreviewString( *it ) );
      if ( listStr.length() > MAX_PREVIEW + 3 )
      {
        listStr = QString( tr( "%1…" ) ).arg( listStr.left( MAX_PREVIEW ) );
        break;
      }
    }
    return tr( "<i>&lt;array: %1&gt;</i>" ).arg( listStr );
  }
  else
  {
    return value.toString();
  }
}
Example #26
0
void SettingsDBManager::setLastUpdateDate(const QDate& currentDate) {
    config["last-updated-date"] = currentDate.toString(SettingsDBManager::getDateFormat()).toStdString();
}
vCardProperty vCardProperty::createBirthday(const QDate& birthday, const vCardParamList& params)
{
    return vCardProperty(VC_BIRTHDAY, birthday.toString("yyyy-MM-dd"), params);
}
Example #28
0
void MainWindow::saveInfo()
{
    if (myDB.isOpen())
    {
        // Проверяем заполнение обязательных полей

        QString surname = ui->surname->text().simplified().replace(QRegularExpression("-{2,}"), "-");
        QString name = ui->name->text().simplified().replace(QRegularExpression("-{2,}"), "-");
        QString docNum = ui->docNum->text().simplified().replace(QRegularExpression("-{2,}"), "-");
        QString schoolNum = ui->schoolNum->text().simplified().replace(QRegularExpression("-{2,}"), "-");
        QString phone = ui->phone->text().simplified().replace(QRegularExpression("-{2,}"), "-");

        QString docType = ui->docType->currentText();
        QString gender = ui->gender->currentText();

        if (surname == "" || name == "" || docNum == "" || schoolNum == "" || phone == "" || docType == "" || gender == "" || (ui->ass1->currentIndex() == 0 && ui->ass2->currentIndex() == 0 && ui->ass3->currentIndex() == 0) || ui->gender->currentIndex() == 0)
        {
            // Если одно или несколько обязательных полей не заполнены
            // Сообщаем об этом пользователю
            QMessageBox messageBox(QMessageBox::Warning,
                                   tr("Сохранение"),
                                   tr("Ошибка сохранения: Не заполнено одно или несколько обязательных полей!"),
                                   QMessageBox::Yes,
                                   this);
            messageBox.setButtonText(QMessageBox::Yes, tr("ОК"));
            messageBox.exec();
            // Выходим
            return;
        }

        QDate currentDate;
        QString strCurrentDate = currentDate.currentDate().toString(Qt::ISODate);

        QString patrname = ui->patrname->text().simplified().replace(QRegularExpression("-{2,}"), "-");
        QString schoolArea = ui->schoolArea->text().simplified().replace(QRegularExpression("-{2,}"), "-");
        QString classNum = ui->classNum->text().simplified().replace(QRegularExpression("-{2,}"), "-");
        QString mail = ui->mail->text().simplified().replace(QRegularExpression("-{2,}"), "-");
        QString parents;
        if (ui->parentType1->currentIndex() != 0)
            parents.append(ui->parentType1->currentText() + ": " + ui->parent1->text().simplified().replace(QRegularExpression("-{2,}"), "-") + "; ");

        if (ui->parentType2->currentIndex() != 0)
            parents.append(ui->parentType2->currentText() + ": " + ui->parent2->text().simplified().replace(QRegularExpression("-{2,}"), "-")  + "; ");

        QString address = ui->address->toPlainText().simplified().replace(QRegularExpression("-{2,}"), "-");

        QString birthday;

        if (ui->bday->currentIndex() != 0 && ui->bmon->currentIndex() != 0)
        {
            QDate bdate;
            bdate.setDate(ui->byear->value(), ui->bmon->currentText().toInt(), ui->bday->currentText().toInt());
            birthday.append("'" + bdate.toString(Qt::ISODate) + "'");
        }
        else
        {
            birthday = "NULL";
        }

        QString police = getDataCheckBox(ui->police);
        QString inv = getDataCheckBox(ui->inv);
        QString large = getDataCheckBox(ui->large);
        QString migr = getDataCheckBox(ui->migr);
        QString incom = getDataCheckBox(ui->incom);
        QString needy = getDataCheckBox(ui->needy);
        QString health = getDataCheckBox(ui->health);
        QString orph = getDataCheckBox(ui->orph);

        bool isName = true;
        bool isSurname = true;
        bool isPatrName = true;

        QRegularExpressionMatch match = names->match(name);
        isName = match.hasMatch();

        match = names->match(surname);
        isSurname = match.hasMatch();

        if (!patrname.isEmpty())
        {
            match = names->match(patrname);
            isPatrName = match.hasMatch();
        }

        if (!isName || !isSurname || !isPatrName || (ui->parentType1->currentIndex() == 0 && ui->parentType2->currentIndex() == 0) || ((ui->ass1->currentIndex() == ui->ass2->currentIndex()  || ui->ass1->currentIndex() == ui->ass3->currentIndex()) && ui->ass1->currentIndex()!=0) || (ui->ass2->currentIndex() == ui->ass3->currentIndex() && ui->ass2->currentIndex()!=0))
        {
            QMessageBox messageBox(QMessageBox::Warning,
                                   tr("Сохранение"),
                                   tr("Ошибка сохранения: Одно или несколько полей заполнены неверно!"),
                                   QMessageBox::Yes,
                                   this);
            messageBox.setButtonText(QMessageBox::Yes, tr("ОК"));
            messageBox.exec();
            return;
        }

        // Создаём окно, запрашивающее подтверждение действия
        QMessageBox messageBox(QMessageBox::Question,
                    tr("Сохранение"),
                    tr("Сохранить введённые данные?"),
                    QMessageBox::Yes | QMessageBox::No,
                    this);

        messageBox.setButtonText(QMessageBox::Yes, tr("Да"));
        messageBox.setButtonText(QMessageBox::No, tr("Нет"));

        // Если действие подтверждено
        if (messageBox.exec() == QMessageBox::Yes)
        {
            QString strQuery = "INSERT INTO Учащийся (";
            strQuery.append("`Фамилия`, `Имя`, `Отчество`, `Тип документа`, `Номер документа`, `Пол`, `Дата рождения`, `Район школы`, `Школа`, `Класс`, `Родители`, `Домашний адрес`, `Телефон`, ");
            strQuery.append("`e-mail`, `С ослабленным здоровьем`, `Сирота`, `Инвалид`, `На учёте в полиции`, `Многодетная семья`, `Неполная семья`, `Малообеспеченная семья`, `Мигранты`, `Дата заявления`) VALUES ('");
            strQuery.append(surname + "', '" + name  + "', '" + patrname  + "', '" + docType  + "', '" + docNum  + "', '" + gender  + "', " + birthday  + ", '");
            strQuery.append(schoolArea  + "', '" + schoolNum  + "', '" + classNum  + "', '" + parents  + "', '" + address  + "', '" + phone  + "', '" + mail + "', ");
            strQuery.append(health  + ", " + orph  + ", " + inv  + ", " + police  + ", " + large  + ", " + incom  + ", " + needy  + ", " + migr + ", '" + strCurrentDate + "');");

            QSqlQuery query;
            QStringList qsl;
            getDataAss(&qsl, ui->ass1);
            getDataAss(&qsl, ui->ass2);
            getDataAss(&qsl, ui->ass3);

            if (query.exec(strQuery))
            {
                strQuery.clear();
                for (QString & newCours : qsl)
                {
                    strQuery.append("INSERT INTO Запись (`Тип документа`, `Номер документа`, `Объединение`) VALUES ('");
                    strQuery.append(docType  + "', '" + docNum  + "', '" + newCours + "');");
                    if (!query.exec(strQuery))
                    {
                        // Если запрос не выполнился, выводим сообщение об ошибке
                        QMessageBox messageBox(QMessageBox::Warning,
                                               tr("Ошибка выполнения запроса"),
                                               tr("В ходе выполнения запроса на добавление в объединение ") + newCours + tr(" возникла ошибка: ") + query.lastError().text(),
                                               QMessageBox::Yes,
                                               this);
                        messageBox.setButtonText(QMessageBox::Yes, tr("ОК"));
                        messageBox.exec();
                    }
                    strQuery.clear();
                }
            }
            else
            {
                // Если запрос не выполнился, выводим сообщение об ошибке
                QMessageBox messageBox(QMessageBox::Warning,
                                       tr("Ошибка выполнения запроса"),
                                       tr("В ходе выполнения запроса возникла ошибка: ") + query.lastError().text(),
                                       QMessageBox::Yes,
                                       this);
                messageBox.setButtonText(QMessageBox::Yes, tr("ОК"));
                messageBox.exec();
                return; // Выходим вообще
            }

            // ------------------------------------------
            // Создание файла для печати
            // шаблон: Other/template.txt

            QFile file("Other/template.txt");
            QString declaration;
            if(file.open(QIODevice::ReadOnly))
            {
                QTextStream stream(&file);
                declaration = stream.readAll();
                file.close();
            }

            declaration.replace("%surname%", surname);
            declaration.replace("%name%", name);
            declaration.replace("%patrname%", patrname);

            declaration.replace("%parent1_type%", ui->parentType1->currentText());
            declaration.replace("%parent1%", ui->parent1->text().simplified());
            declaration.replace("%parent2_type%", ui->parentType2->currentText());
            declaration.replace("%parent2%", ui->parent2->text().simplified());

            declaration.replace("%birthday%", birthday);
            declaration.replace("%classNum%", classNum);
            declaration.replace("%schoolNum%", schoolNum);
            declaration.replace("%schoolArea%", schoolArea);
            declaration.replace("%address%", address);
            declaration.replace("%phone%", phone);
            declaration.replace("%email%", mail);
            declaration.replace("%doctype%", docType);
            declaration.replace("%docnum%", docNum);
            declaration.replace("%сurrentDate%", strCurrentDate);

            QString ass;
            for (int i = 1; i<=qsl.size(); i++)
                ass.append(QString::number(i) + ".&nbsp;<u>" + qsl.at(i-1) +"</u><br />");

            declaration.replace("%ass%", ass);

            replaceBoolData(&declaration, "%large%", large);
            replaceBoolData(&declaration, "%incom%", incom);
            replaceBoolData(&declaration, "%needy%", needy);
            replaceBoolData(&declaration, "%orph%", orph);
            replaceBoolData(&declaration, "%migr%", migr);

            if (inv == "true" || health == "true")
                declaration.replace("%health%", "Да");
            else
                declaration.replace("%health%", "Нет");

            QString filename = surname + "_" + name + "_" + docNum + ".html";
            QFile file2(filename);
            if(file2.open(QIODevice::WriteOnly))
            {
                QTextStream stream(&file2);
                stream << declaration;
                file2.close();
            }

            // ------------------------------------------

            cleaner();
        }
    }
    else
    {
        // Выводим сообщение с инфой
        ui->lblStatus->setText(tr("Ошибка сохранения: отсутсвует соединение с базой"));
        QMessageBox messageBox(QMessageBox::Information,
                               tr("Сохранение"),
                               tr("Сохранение невозможно: отсутсвует соединение с базой."),
                               QMessageBox::Yes,
                               this);
        messageBox.setButtonText(QMessageBox::Yes, tr("ОК"));
        messageBox.exec();
    }
}
Example #29
0
QString HrZones::getStartDateString(int rnum) const
{
    assert(rnum >= 0);
    QDate d = ranges[rnum].begin;
    return (d.isNull() ? "BEGIN" : d.toString());
}
void MainWindow::on_MU_update_endDate_DtEdit_dateChanged(const QDate &date)
{
    writeIni("sysParams/endDate",date.toString("yyyy-MM-dd"));
}