Esempio n. 1
0
void FrmInformacionFarmaco::finishedSlotBuscarMedicamento(QNetworkReply* reply)
{
    //qDebug()<<reply->readAll();
    QString data=(QString)reply->readAll();
    QString cXML = data;

    // Extract values from XML
    QDomDocument document("XmlDoc");
    document.setContent(cXML);

    QDomElement root = document.documentElement();
    if (root .tagName() != "object")
        qDebug("Bad root element.");

    QDomNode drugList = root.firstChild();

    QDomNode n = drugList.firstChild();
    QDomNode n2 = n.firstChild();
    QDomNode n3 = n2.firstChild();
    while (!n.isNull()) {
        if (n.isElement()) {
            QDomNodeList attributes = n.childNodes();

            for (int i = 0; i < attributes.count(); i ++) {
                QDomElement e = attributes.at(i).toElement();

                if (e.tagName() == "name_speciality") {
                    ui->txtNombre->setText(e.text());
                }
                if (e.tagName() == "dosage_form") {
                    ui->txtDosificacion->setText(e.text());
                }
                if (e.tagName() == "national_code") {
                    ui->txtcodigo_nacional->setText(e.text());
                }
                if (e.tagName() == "name_laboratory") {
                    ui->txtLaboratorio->setText(e.text());
                }
                if (e.tagName() == "name_atc") {
                    ui->txtNombreATC->setText(e.text());
                }
                if (e.tagName() == "drug_type") {
                    ui->txtTipoMedicamento->setText(e.text());
                }
                if (e.tagName() == "package") {
                    ui->txtCaja->setText(e.text());
                }
                if (e.tagName() == "price") {
                    ui->txtPVP->setText(e.text());
                }
                if (e.tagName() == "laboratory_price") {
                    ui->txtPVC->setText(e.text());
                }
                if (e.tagName() == "TLD") {
                    ui->txtTLD->setText(e.text());
                }
                if (e.tagName() == "RECETA") {
                    ui->txtReceta->setText(e.text());
                }
                if (e.tagName() == "FINAN") {
                    ui->txtFinanciado->setText(e.text());
                }
                if (e.tagName() == "fecha_alta") {
                    QDate alta;
                    int ano,mes,dia;
                    ano = e.text().left(4).toInt();
                    mes = e.text().mid(5,2).toInt();
                    dia = e.text().mid(8,2).toInt();
                    alta.setDate(ano,mes,dia);
                    ui->txtfecha_alta->setDate(alta);
                }
                if (e.tagName() == "fecha_baja") {
                    if (e.text()!="0" && !e.text().isEmpty()) {
                        QDate baja;
                        int ano,mes,dia;
                        ano = e.text().left(4).toInt();
                        mes = e.text().mid(5,2).toInt();
                        dia = e.text().mid(8,2).toInt();
                        baja.setDate(ano,mes,dia);
                        ui->txtFechaBaja->setVisible(true);
                        ui->lblfechabaja->setVisible(true);
                        ui->txtFechaBaja->setDate(baja);
                    } else {
                        ui->txtFechaBaja->setVisible(false);
                        ui->lblfechabaja->setVisible(false);
                    }
                }
                if (e.tagName() == "baja") {
                    if(e.text()=="1")
                        ui->lblDadodeBaja->setVisible(true);
                    else
                        ui->lblDadodeBaja->setVisible(false);
                }

                if (e.tagName() == "id_laboratory") {
                    QUrl  uUrl;
                    QString cUrl = "http://svadcf.es/documentos/image/fotos/laboratorio/"+e.text().trimmed()+".gif";
                    uUrl.setUrl(cUrl);
                    ui->webLogoLaboratorio->load(uUrl);
                }

                if (e.tagName() == "id_speciality") {
                    connect(ui->webimagen1,SIGNAL(loadFinished(bool)),this, SLOT(cargaFinalizada1(bool)));
                    connect(ui->webimagen2,SIGNAL(loadFinished(bool)),this, SLOT(cargaFinalizada2(bool)));
                    connect(ui->webimagen3,SIGNAL(loadFinished(bool)),this, SLOT(cargaFinalizada3(bool)));
                    connect(ui->webLogoLaboratorio,SIGNAL(loadFinished(bool)),this, SLOT(cargaFinalizadaLogo(bool)));
                    QUrl  uUrl;
                    QString cUrl = "http://svadcf.es/documentos/image/fotos/medicamento/"+e.text().trimmed()+"_1.jpg";
                    uUrl.setUrl(cUrl);
                    ui->webimagen1->load(uUrl);

                    cUrl = "http://svadcf.es/documentos/image/fotos/medicamento/"+e.text().trimmed()+"_2.jpg";
                    uUrl.setUrl(cUrl);
                    ui->webimagen2->load(uUrl);
                    cUrl = "http://svadcf.es/documentos/image/fotos/medicamento/"+e.text().trimmed()+"_3.jpg";
                    uUrl.setUrl(cUrl);
                    ui->webimagen3->load(uUrl);
                }

                //----------------------------
                // Llenar tabla indicaciones
                //----------------------------

                if (e.tagName() == "Indications_set") {
                    ui->listaIndicaciones->setColumnCount(2);
                    ui->listaIndicaciones->setColumnWidth(0,200);
                    ui->listaIndicaciones->setColumnWidth(1,0);

                    int nrow = 0;
                    int pos = 0;
                    while (!n2.isNull()) {
                        if (n2.isElement()) {
                            QDomNodeList attributes = n2.childNodes();

                            for (int i = 0; i < attributes.count(); i ++) {
                                QDomElement e2 = attributes.at(i).toElement();
                                if (e2.tagName() == "")
                                    while (!n3.isNull()) {
                                        if (n3.isElement()) {
                                            QDomNodeList attributes = n3.childNodes();

                                            for (int i = 0; i < attributes.count(); i ++) {
                                                QDomElement e3 = attributes.at(i).toElement();
                                                if (e3.tagName() == "id_IND") {
                                                    ui->listaIndicaciones->setRowCount(pos+1);
                                                    QTableWidgetItem *newItem = new QTableWidgetItem(e3.text());
                                                    // para que los elementos no sean editables
                                                    newItem->setFlags(newItem->flags() & (~Qt::ItemIsEditable));
                                                    newItem->setTextColor(Qt::blue); // color de los items

                                                    ui->listaIndicaciones->setItem(pos,1,newItem);
                                                }
                                                if (e3.tagName() == "TITINDMIN") {
                                                    ui->listaIndicaciones->setRowCount(pos+1);
                                                    QTableWidgetItem *newItem = new QTableWidgetItem(e3.text());
                                                    // para que los elementos no sean editables
                                                    newItem->setFlags(newItem->flags() & (~Qt::ItemIsEditable));
                                                    newItem->setTextColor(Qt::blue); // color de los items

                                                    ui->listaIndicaciones->setItem(pos,0,newItem);
                                                }

                                            }

                                            pos++;

                                            //data.append(s);
                                        }
                                        n3 = n3.nextSibling();
                                    }

                            }
                            n2 = n2.nextSibling();
                        }
                    }

                }

            }
            n = n.nextSibling();
        }
RideFile *Computrainer3dpFileReader::openRideFile(QFile & file,
                                                  QStringList & errors)
    const
{
    if (!file.open(QFile::ReadOnly)) {
        errors << ("Could not open ride file: \"" + file.fileName() +
                   "\"");
        return NULL;
    }

    RideFile *rideFile = new RideFile();
    QDataStream is(&file);

    is.setByteOrder(QDataStream::LittleEndian);

    // looks like the first part is a header... ignore it.
    is.skipRawData(4);
    char perfStr[5];

    is.readRawData(perfStr, 4);
    perfStr[4] = NULL;
    is.skipRawData(0x8);
    char userName[65];
    is.readRawData(userName, 65);
    ubyte age;
    is >> age;
    is.skipRawData(6);
    float weight;
    is >> weight;
    int upperHR;
    is >> upperHR;
    int lowerHR;
    is >> lowerHR;
    int year;
    is >> year;
    ubyte month;
    is >> month;
    ubyte day;
    is >> day;
    ubyte hour;
    is >> hour;
    ubyte minute;
    is >> minute;
    int numberSamples;
    is >> numberSamples;
    // go back to the start, and go to the start of the data samples
    file.seek(0);
    is.skipRawData(0xf8);
    for (; numberSamples; numberSamples--) {
        ubyte hr;
        is >> hr;
        ubyte cad;
        is >> cad;
        unsigned short watts;
        is >> watts;
        float speed;
        is >> speed;
        speed = speed * KM_PER_MILE * 100;
        int ms;
        is >> ms;
        is.skipRawData(4);
        float miles;
        is >> miles;
        float km = miles * KM_PER_MILE;
        is.skipRawData(0x1c);
        rideFile->appendPoint((double) ms / 1000, (double) cad,
                              (double) hr, km, speed, 0.0, watts, 0, 0, 0);

    }
    QDateTime dateTime;
    QDate date;
    QTime time;
    date.setDate(year, month, day);
    time.setHMS(hour, minute, 0, 0);
    dateTime.setDate(date);
    dateTime.setTime(time);

    rideFile->setStartTime(dateTime);

    int n = rideFile->dataPoints().size();
    n = qMin(n, 1000);
    if (n >= 2) {
        QVector < double >secs(n - 1);
        for (int i = 0; i < n - 1; ++i) {
            double now = rideFile->dataPoints()[i]->secs;
            double then = rideFile->dataPoints()[i + 1]->secs;
            secs[i] = then - now;
        }
        std::sort(secs.begin(), secs.end());
        int mid = n / 2 - 1;
        double recint = round(secs[mid] * 1000.0) / 1000.0;
        rideFile->setRecIntSecs(recint);
    }
    rideFile->setDeviceType("Computrainer 3DP");
    file.close();
    return rideFile;
}
void MyDiagrammView::zeichneL3()
{
    //Punkte berechnen
    Linie3.clear();
    QDateTime dt;
    double d;
    QPoint po;
    double wby = maxWertL3 - minWertL3;
    QDate dmin = L3Datum.first().date();
    QDate dmax = L3Datum.last().date();
    if (!day) {
        dmin.setDate(dmin.year(),dmin.month(),1);
        dmax.setDate(dmax.year(),dmax.month(),dmax.daysInMonth());
    }
    int AnzahlTage = dmin.daysTo(dmax);

    for (int i=0; i < L3Daten.count(); i++) {
        //Y
        dt = L3Datum[i];
        d = L3Daten[i] - minWertL3;
        po.setY(qRound(nullY - (zhoehe / wby * d)));
        //X
        if (day) {
            QDateTime dtemp;
            dtemp.setDate(dt.date());
            dtemp.time().setHMS(0,0,0);
            //Zeitoffset berechnen
            int ZeitOffset = qRound(double(abstandX / (24*60*60)) * dtemp.time().secsTo(dt.time()));
            po.setX(qRound(double(nullX+ZeitOffset) + (double(zbreite) / double(AnzahlX) * double(dmin.daysTo(dt.date())))));
        }
        else {
            po.setX(qRound(double(nullX) + (double(zbreite) / double(AnzahlTage) * double(dmin.daysTo(dt.date())))));
        }
        Linie3.append(po);
    }

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing,true);
    QPen pen;
    QBrush brush;

    //Wert Linie zeichnen
    if (WertLinie3Aktiv) {
        d = WertLinie3 - minWertL3;
        pen.setColor(colorL3);
        pen.setWidth(2);
        pen.setStyle(Qt::DashLine);
        brush.setStyle(Qt::SolidPattern);
        painter.setPen(pen);
        painter.setBrush(brush);
        painter.drawLine(nullX+1, qRound(nullY - (zhoehe / wby * d)), nullX + zbreite, qRound(nullY - (zhoehe / wby * d)));
    }

    brush.setStyle(Qt::SolidPattern);
    brush.setColor(Qt::white);
    pen.setColor(colorL3);
    pen.setWidth(2);
    painter.setPen(pen);
    painter.setBrush(brush);
    //Linie Zeichnen
    for (int i=0; i < Linie3.count(); i++) {
        //painter.drawEllipse(Linie1[i],3,3);
        if (i>0)
            painter.drawLine(Linie3[i-1],Linie3[i]);
    }
    //Punkte Zeichnen
    for (int i=0; i < Linie3.count(); i++) {
        //Markierung zeichnen
        if (i == MarkierterPunkt - 1) {
            brush.setColor(Qt::red);
            painter.setBrush(brush);
            painter.drawEllipse(Linie3[i],3,3);
            brush.setColor(Qt::white);
            painter.setBrush(brush);
        }
        else
            painter.drawEllipse(Linie3[i],3,3);

    }
    //Bezeichnung
    if (!BezeichnungL3.isEmpty()) {
        painter.setFont(QFont("Ubuntu", 10));
        painter.drawText(QRectF(qRound(nullX + zbreite / 2.0),0,qRound(zbreite / 2.0),AbstandOben),Qt::AlignRight, BezeichnungL3);
    }
}
Esempio n. 4
0
void MainWindow::printLabel()
{
    QPrinter printer;
    printer.setOutputFormat(QPrinter::PdfFormat);
    printer.setOutputFileName("/tmp/labels.pdf");

    QPrintDialog printDialog(&printer);
    if (printDialog.exec() != QDialog::Accepted) {
        return;
    }
    painter.begin(&printer);

    QDate day;
    int month = ui->spinBoxMonth->value();
    int year = ui->spinBoxYear->value();
    int printed = 0;
    for(int i=1;i<=31;i++)
    {
        day.setDate(year,month,i);
        if(!day.isValid() || day.dayOfWeek() == 7)
            continue;
        printed++;

        if(printed%9 ==0)
        {
            printer.newPage();
            printed = 1;
        }

        QString text;

        if( day.dayOfWeek()  < 5)
        {
            text = "Semanal - ";
            text.append(QString::number(day.dayOfWeek()));
            text.append(" - ");
            text.append(day.toString("dd/MM/yyyy"));
        }
        else
        {
            text = "Full - ";
            text.append(QString::number(day.dayOfWeek()-4));
            text.append(" - ");
            text.append(day.toString("dd/MM/yyyy"));
        }


        int pos_x = 0;
        int factor = (printed-1)/2;

        int pos_y = 235*factor;

        if(printed%2 != 0)
            pos_x = 0;
        else
            pos_x = 265;


        QFont f = painter.font();
        f.setFamily("Helvetica [Cronyx]");
        f.setPointSize(15);
        f.setBold(true);
        painter.setFont(f);
        QRect rectOne( pos_x,5+pos_y,265,235 );
        painter.setBrush( Qt::NoBrush);
        painter.setPen(Qt::NoPen);
        painter.drawRect(rectOne);
        painter.setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap,    Qt::RoundJoin));
        painter.drawText(rectOne,Qt::AlignHCenter,text);
        QRect rect( pos_x,0+pos_y,265,235 );
        painter.drawRect(rect);
        if(pos_x == 0)
            painter.drawLine(pos_x,35+pos_y,265,35+pos_y);
        else
            painter.drawLine(pos_x,35+pos_y,265*2,35+pos_y);
        painter.drawText(rect,Qt::AlignCenter,text);

    }
    painter.end();
    close();
}
Esempio n. 5
0
QDateTime CalendarTiming::nextRun(const QDateTime &tzero) const
{
    QDateTime nextRun;
    QDateTime now;

    if (tzero.isValid())
    {
        now = tzero;
    }
    else
    {
        now = Client::instance()->ntpController()->currentDateTime();
    }

    QDate date = now.date();
    QTime time = now.time();
    bool found = false;

    QListIterator<int> monthIter(d->months);
    QListIterator<int> dayIter(d->daysOfMonth);
    QDate nextRunDate;
    QTime nextRunTime;

    //set millsec to 0
    time.setHMS(time.hour(), time.minute(), time.second());

    // Check if the start time is reached
    if (d->start.isValid() && d->start > now)
    {
        date.setDate(d->start.date().year(), d->start.date().month(), d->start.date().day());
        time.setHMS(d->start.time().hour(), d->start.time().minute(), d->start.time().second());
        now.setDate(date);
        now.setTime(time);
    }

    int year = date.year();
    int month = date.month();
    int day = date.day();

    while (!found) // years
    {
        while (monthIter.hasNext() && !found) // months
        {
            month = monthIter.next();
            if (QDate(year, month, 1) >= QDate(date.year(), date.month(), 1))
            {
                // change to first element
                dayIter.toFront();

                while (dayIter.hasNext() && !found) // days
                {
                    day = dayIter.next();
                    if (QDate(year, month, day) >= date)
                    {
                        // potential day found, check if day of week is okay
                        if (d->daysOfWeek.contains(QDate(year, month, day).dayOfWeek()))
                        {
                            // check if we have a matching time for that day
                            if ((nextRunDate = QDate(year, month, day)) != now.date())
                            {
                                // if the next run date is not today we can take the first items
                                // as this is the earliest allowed time on that day
                                nextRunTime = QTime(*d->hours.constBegin(), *d->minutes.constBegin(), *d->seconds.constBegin());
                                nextRun = QDateTime(nextRunDate, nextRunTime, Qt::UTC);
                                found = true;
                            }
                            else if ((nextRunTime = d->findTime(time)).isValid())
                            {
                                nextRun = QDateTime(nextRunDate, nextRunTime, Qt::UTC);

                                // check if the calculated next run was already executed
                                if (!m_lastExecution.isValid() || m_lastExecution.secsTo(nextRun) > 1)
                                {
                                    found = true;
                                }
                            }
                        }
                    }

                    // check if end of set reached (= end of month)
                    if (!dayIter.hasNext())
                    {
                        date.setDate(date.year(), date.month(), 1);
                        break;
                    }
                }
            }

            // end of set reached, the first element is the right
            if (!monthIter.hasNext())
            {
                monthIter.toFront();
                date.setDate(++year, 1, 1);
                break;
            }
        }

        // for saftey reasons
        if (year > now.date().year() + 2)
        {
            // no next run found
            return QDateTime();
        }
    }

    // Stop if we exceed the end time
    if (d->end.isValid() && d->end < nextRun)
    {
        return QDateTime();
    }

    return nextRun;
}
Esempio n. 6
0
/**
 * Apply variable modifiers to a QHash containing variables.
 * @param varModifierDefs	[in] Variable modifier definitions.
 * @param vars			[in, out] Variables to modify.
 * @param qDateTime		[out, opt] If specified, QDateTime for the timestamp.
 * @return 0 on success; non-zero if any modifiers failed.
 */
int VarReplace::ApplyModifiers(const QHash<QString, VarModifierDef> &varModifierDefs,
			       QHash<QString, QString> &vars,
			       QDateTime *qDateTime)
{
	// Timestamp construction.
	int year = -1, month = -1, day = -1;
	int hour = -1, minute = -1, second = -1;
	int ampm = -1;

	// TODO: Verify that all variables to be modified
	// were present in vars.

	QList<QString> varIDs = vars.keys();
	foreach (const QString &id, varIDs) {
		if (!varModifierDefs.contains(id))
			continue;

		QString var = vars.value(id);
		const VarModifierDef &varModifierDef = varModifierDefs[id];

		// Always convert the string to num and char,
		// in case it's needed for e.g. useAs==month.
		int num = strToInt(var);
		num += varModifierDef.addValue;
		char chr = 0;
		if (var.size() == 1) {
			chr = var.at(0).toLatin1();
			chr += varModifierDef.addValue;
		}

		// Apply the modifier.
		switch (varModifierDef.varType) {
			default:
			case VarModifierDef::VARTYPE_STRING:
				// Parse as a string.
				// Nothing special needs to be done here...
				break;

			case VarModifierDef::VARTYPE_NUMBER:
				// Parse as a number. (Base 10)
				var = QString::number(num, 10);
				break;

			case VarModifierDef::VARTYPE_CHAR:
				// Parse as an ASCII character.
				if (var.size() != 1)
					return -2;
				var = QChar::fromLatin1(chr);
				break;
		}

		// Pad the variable with fillChar, if necessary.
		if (var.size() < varModifierDef.minWidth) {
			var.reserve(varModifierDef.minWidth);
			QChar fillChar = QChar::fromLatin1(varModifierDef.fillChar);
			if (varModifierDef.fieldAlign == VarModifierDef::FIELDALIGN_LEFT) {
				while (var.size() < varModifierDef.minWidth)
					var.append(fillChar);
			} else /*if (variableDef.fieldAlign == VarModifierDef::FIELDALIGN_RIGHT)*/ {
				while (var.size() < varModifierDef.minWidth)
					var.prepend(fillChar);
			}
		}

		// Check if this variable should be used in the QDateTime.
		switch (varModifierDef.useAs) {
			default:
			case VarModifierDef::USEAS_FILENAME:
				// Not a QDateTime component.
				break;

			case VarModifierDef::USEAS_TS_YEAR:
				if (num >= 0 && num <= 99) {
					// 2-digit year.
					year = num + 2000;
				} else if (num >= 2000 && num <= 9999) {
					// 4-digit year.
					year = num;
				} else {
					// Invalid year.
					return -3;
				}
				break;

			case VarModifierDef::USEAS_TS_MONTH: {
				if (num >= 1 && num <= 12)
					month = num;
				else
					return -4;
				break;
			}

			case VarModifierDef::USEAS_TS_DAY:
				if (num >= 1 && num <= 31)
					day = num;
				else
					return -5;
				break;

			case VarModifierDef::USEAS_TS_HOUR:
				if (num >= 0 && num <= 23)
					hour = num;
				else
					return -6;
				break;

			case VarModifierDef::USEAS_TS_MINUTE:
				if (num >= 0 && num <= 59)
					minute = num;
				else
					return -7;
				break;

			case VarModifierDef::USEAS_TS_SECOND:
				if (num >= 0 && num <= 59)
					second = num;
				else
					return -8;
				break;

			case VarModifierDef::USEAS_TS_AMPM:
				// TODO: Implement this once I encounter
				// a save file that actually uses it.
				break;
		}

		// Update the variable in the hash.
		vars.insert(id, var);
	}

	if (qDateTime) {
		// Set the QDateTime to the current time for now.
		const QDateTime currentDateTime(QDateTime::currentDateTime());
		*qDateTime = currentDateTime;

		// Adjust the date.
		QDate date = qDateTime->date();
		const bool isDateSet = (year != -1 || month != -1 || day != -1);
		if (year == -1) {
			year = date.year();
		}
		if (month == -1) {
			month = date.month();
		}
		if (day == -1) {
			day = date.day();
		}
		date.setDate(year, month, day);
		qDateTime->setDate(date);

		// Adjust the time.
		QTime time = qDateTime->time();
		const bool isTimeSet = (hour != -1 || minute != -1);
		if (isDateSet && !isTimeSet) {
			// Date was set by the file, but time wasn't.
			// Assume default of 12:00 AM.
			time.setHMS(0, 0, 0);
		} else {
			if (hour == -1) {
				hour = time.hour();
			}
			if (minute == -1) {
				minute = time.minute();
			}
			if (second == -1) {
				second = 0;	// Don't bother using the current second.
			}
			if (ampm != -1) {
				hour %= 12;
				hour += ampm;
			}
			time.setHMS(hour, minute, second);
		}
		qDateTime->setTime(time);

		// If the QDateTime is more than one day
		// in the future, adjust its years value.
		// (One-day variance is allowed due to timezone differences.)
		const QDateTime tomorrow = QDateTime::fromMSecsSinceEpoch(
			currentDateTime.toMSecsSinceEpoch() + (86400*1000), Qt::UTC);

		if (*qDateTime > tomorrow) {
			QDate adjDate = qDateTime->date();
			int curYear = currentDateTime.date().year();
			// NOTE: Minimum year of 2000 for GCN,
			// but Dreamcast was released in 1998.
			if (curYear > 1995) {
				// Update the QDateTime.
				qDateTime->setDate(adjDate.addYears(-1));
			}
		}
	}

	// Variables modified successfully.
	return 0;
}
int CSVOldFormatConverter::getTroopId(
    QString troopName, QString graduatedFromMilitaryDepartmentDate,
    QString degreeEnrollmentNumber,
    QString graduatedFromMilitaryDepartmentInYear) {
  // TODO: refactor this stuff
  QString enteredAtMilitaryDepartmentDate;
  QString troopNamePrefix;
  QString troopNamePostfix;
  QRegExp shortPostfix = QRegExp("\\d\\d");
  QRegExp longPostfix = QRegExp("\\d\\d/\\d\\d");
  QRegExp degreeSplitter = QRegExp("№ ?\\d{1,4} ?(от)? ?");
  QDate dateEnteredAt;
  QDate dateGraduatedFrom;
  QString queryString;
  QSqlQuery query;
  QString formattedTroopName;
  int separatorPosition;
  int difference;
  troopName = troopName.toUpper().simplified();
  if (troopName == "АШ32") {
    troopName = "АШ-32";
  } else if (troopName.isEmpty()) {
    qDebug() << graduatedFromMilitaryDepartmentDate << degreeEnrollmentNumber <<
                graduatedFromMilitaryDepartmentInYear;
    return 0;
  }
  if (!graduatedFromMilitaryDepartmentDate.simplified().isEmpty()) {
    graduatedFromMilitaryDepartmentDate =
        graduatedFromMilitaryDepartmentDate.split(" ").at(0);
    dateGraduatedFrom = QDate::fromString(graduatedFromMilitaryDepartmentDate,
                                          "dd.MM.yyyy");
  } else if (!graduatedFromMilitaryDepartmentInYear.isEmpty()) {
    if (graduatedFromMilitaryDepartmentInYear != "0") {
      dateGraduatedFrom.setDate(
            graduatedFromMilitaryDepartmentInYear.toInt(), 9, 17);
    }
  }
  if (!degreeEnrollmentNumber.isEmpty()) {
    enteredAtMilitaryDepartmentDate = degreeEnrollmentNumber
        .split(degreeSplitter).last().replace("ю", ".").replace(" ", ".");
    if (enteredAtMilitaryDepartmentDate.endsWith("г.")) {
      enteredAtMilitaryDepartmentDate.chop(2);
    } else if (enteredAtMilitaryDepartmentDate.endsWith("г")) {
      enteredAtMilitaryDepartmentDate.chop(1);
    } else if (enteredAtMilitaryDepartmentDate.endsWith(".")) {
      enteredAtMilitaryDepartmentDate.chop(1);
    }
    if (enteredAtMilitaryDepartmentDate.split(".").last().length() == 2) {
      enteredAtMilitaryDepartmentDate = enteredAtMilitaryDepartmentDate.insert(
            enteredAtMilitaryDepartmentDate.length() - 2, "20");
    }
    dateEnteredAt = QDate::fromString(enteredAtMilitaryDepartmentDate,
                                      "d.MM.yyyy");
  }
  if (!dateGraduatedFrom.isValid() && !dateEnteredAt.isValid()) {
    qDebug() << "invalid dates" << dateEnteredAt << dateGraduatedFrom;
    return 0;
  } else if (dateGraduatedFrom.isValid()) {
    // guessing about entered date
    dateEnteredAt.setDate(dateGraduatedFrom.year() - 3, 6, 29);
  } else { // if (dateEnteredAt.isValid())
    dateGraduatedFrom.setDate(dateEnteredAt.year() + 3, 9, 17);
//    qDebug() << "invalid graduation date";
//    return 0;
  }
  int cyear = QDate::currentDate().year();
  if (cyear > dateGraduatedFrom.year()) {
    cyear = dateGraduatedFrom.year();
  }
  difference = cyear - dateEnteredAt.year() - 1;
  separatorPosition = troopName.indexOf('-');
  troopNamePrefix = troopName.left(separatorPosition);
  troopNamePostfix = troopName.mid(separatorPosition + 1);
  formattedTroopName = troopNamePrefix + "-";
  if (shortPostfix.exactMatch(troopNamePostfix)) {
    // TODO: make that more cleaner and optimized
    formattedTroopName +=
        "<N:" +
        QString::number(QString(troopNamePostfix.at(0)).toInt() - difference) +
        ">" + troopNamePostfix.at(1);
  } else if (longPostfix.exactMatch(troopNamePostfix)) {
    formattedTroopName +=
        "<N:" +
        QString::number(QString(troopNamePostfix.at(0)).toInt() - difference) +
        ">" + troopNamePostfix.at(1) + "/" + "<N:" +
        QString::number(QString(troopNamePostfix.at(3)).toInt() - difference) +
        ">" + troopNamePostfix.at(4);
  } else {
    qDebug() << "asshole" << troopNamePostfix << troopName;
    return 0;
  }
  troopName = formattedTroopName;
  queryString = "SELECT id FROM troop WHERE name = ? AND"
      " entered_at_military_department_date = ?";
  query.prepare(queryString);
  query.addBindValue(troopName);
  query.addBindValue(dateEnteredAt);
  if (!query.exec()) {
    qDebug() << query.lastError().text();
    return 0;
  }
  if (!query.next()) {
    queryString = "INSERT INTO troop (name,"
        " entered_at_military_department_date,"
        " graduated_from_military_department_date, military_profession_id)"
        " VALUES (?, ?, ?, ?)";
    query.prepare(queryString);
    query.addBindValue(troopName);
    query.addBindValue(dateEnteredAt);
    query.addBindValue(dateGraduatedFrom);
    query.addBindValue(1);
    if (!query.exec()) {
      qDebug() << query.lastError().text();
      return 0;
    }
    return query.lastInsertId().toInt();
  } else {
    return query.record().value("id").toInt();
  }
}
Esempio n. 8
0
void FillProgramInfo( DTC::Program *pProgram,
                      ProgramInfo  *pInfo,
                      bool          bIncChannel /* = true */,
                      bool          bDetails    /* = true */,
                      bool          bIncCast    /* = true */)
{
    if ((pProgram == NULL) || (pInfo == NULL))
        return;

    pProgram->setStartTime (  pInfo->GetScheduledStartTime());
    pProgram->setEndTime   (  pInfo->GetScheduledEndTime  ());
    pProgram->setTitle     (  pInfo->GetTitle()             );
    pProgram->setSubTitle  (  pInfo->GetSubtitle()          );
    pProgram->setCategory  (  pInfo->GetCategory()          );
    pProgram->setCatType   (  pInfo->GetCategoryTypeString());
    pProgram->setRepeat    (  pInfo->IsRepeat()             );
    pProgram->setVideoProps(  pInfo->GetVideoProperties()   );
    pProgram->setAudioProps(  pInfo->GetAudioProperties()   );
    pProgram->setSubProps  (  pInfo->GetSubtitleType()      );

    pProgram->setSerializeDetails( bDetails );

    if (bDetails)
    {
        pProgram->setSeriesId    ( pInfo->GetSeriesID()         );
        pProgram->setProgramId   ( pInfo->GetProgramID()        );
        pProgram->setStars       ( pInfo->GetStars()            );
        pProgram->setLastModified( pInfo->GetLastModifiedTime() );
        pProgram->setProgramFlags( pInfo->GetProgramFlags()     );

        // ----
        // DEPRECATED - See RecordingInfo instead
        pProgram->setFileName    ( pInfo->GetPathname()         );
        pProgram->setFileSize    ( pInfo->GetFilesize()         );
        pProgram->setHostName    ( pInfo->GetHostname()         );
        // ----

        if (pInfo->GetOriginalAirDate().isValid())
            pProgram->setAirdate( pInfo->GetOriginalAirDate() );
        else if (pInfo->GetYearOfInitialRelease() > 0)
        {
            QDate year;
            year.setDate(pInfo->GetYearOfInitialRelease(), 1, 1);
            pProgram->setAirdate( year );
        }

        pProgram->setDescription( pInfo->GetDescription() );
        pProgram->setInetref    ( pInfo->GetInetRef()     );
        pProgram->setSeason     ( pInfo->GetSeason()      );
        pProgram->setEpisode    ( pInfo->GetEpisode()     );
        pProgram->setTotalEpisodes( pInfo->GetEpisodeTotal() );
    }

    pProgram->setSerializeCast(bIncCast);
    if (bIncCast)
    {
        FillCastMemberList( pProgram->Cast(), pInfo );
    }

    pProgram->setSerializeChannel( bIncChannel );

    if ( bIncChannel )
    {
        // Build Channel Child Element
        if (!FillChannelInfo( pProgram->Channel(), pInfo->GetChanID(), bDetails ))
        {
            // The channel associated with a given recording may no longer exist
            // however the ChanID is one half of the unique identifier for the
            // recording and therefore MUST be included in the return data
            pProgram->Channel()->setChanId(pInfo->GetChanID());
        }
    }

    // Build Recording Child Element

    if ( pInfo->GetRecordingStatus() != RecStatus::Unknown )
    {
        pProgram->setSerializeRecording( true );

        DTC::RecordingInfo *pRecording = pProgram->Recording();

        const RecordingInfo pRecInfo(*pInfo);

        pRecording->setRecordedId ( pRecInfo.GetRecordingID()     );
        pRecording->setStatus  ( pRecInfo.GetRecordingStatus()    );
        pRecording->setPriority( pRecInfo.GetRecordingPriority()  );
        pRecording->setStartTs ( pRecInfo.GetRecordingStartTime() );
        pRecording->setEndTs   ( pRecInfo.GetRecordingEndTime()   );

        pRecording->setSerializeDetails( bDetails );

        if (bDetails)
        {
            pRecording->setFileName    ( pRecInfo.GetPathname() );
            pRecording->setFileSize    ( pRecInfo.GetFilesize() );
            pRecording->setHostName    ( pRecInfo.GetHostname() );
            pRecording->setLastModified( pRecInfo.GetLastModifiedTime() );

            pRecording->setRecordId    ( pRecInfo.GetRecordingRuleID()      );
            pRecording->setRecGroup    ( pRecInfo.GetRecordingGroup()       );
            pRecording->setPlayGroup   ( pRecInfo.GetPlaybackGroup()        );
            pRecording->setStorageGroup( pRecInfo.GetStorageGroup()         );
            pRecording->setRecType     ( pRecInfo.GetRecordingRuleType()    );
            pRecording->setDupInType   ( pRecInfo.GetDuplicateCheckSource() );
            pRecording->setDupMethod   ( pRecInfo.GetDuplicateCheckMethod() );
            pRecording->setEncoderId   ( pRecInfo.GetInputID()              );
            if (pProgram->Channel())
            {
                QString encoderName = CardUtil::GetDisplayName(pRecInfo.GetInputID());
                pRecording->setEncoderName( encoderName );
            }

            pRecording->setProfile( pRecInfo.GetProgramRecordingProfile() );
        }
    }

    if (!pInfo->GetInetRef().isEmpty() )
    {
        pProgram->setSerializeArtwork( true );

        FillArtworkInfoList( pProgram->Artwork(), pInfo->GetInetRef(),
                             pInfo->GetSeason());
    }
}