Esempio n. 1
0
void HtmlExport::createMonthView(QTextStream *ts)
{
    QDate start = fromDate();
    start.setYMD(start.year(), start.month(), 1);    // go back to first day in month

    QDate end(start.year(), start.month(), start.daysInMonth());

    int startmonth = start.month();
    int startyear = start.year();

    while (start < toDate()) {
        // Write header
        QDate hDate(start.year(), start.month(), 1);
        QString hMon = hDate.toString(QStringLiteral("MMMM"));
        QString hYear = hDate.toString(QStringLiteral("yyyy"));
        *ts << "<h2>"
            << i18nc("@title month and year", "%1 %2", hMon, hYear)
            << "</h2>" << endl;
        if (QLocale().firstDayOfWeek() == 1) {
            start = start.addDays(1 - start.dayOfWeek());
        } else {
            if (start.dayOfWeek() != 7) {
                start = start.addDays(-start.dayOfWeek());
            }
        }
        *ts << "<table border=\"1\">" << endl;

        // Write table header
        *ts << "  <tr>";
        for (int i = 0; i < 7; ++i) {
            *ts << "<th>" << QLocale().dayName(start.addDays(i).dayOfWeek()) << "</th>";
        }
        *ts << "</tr>" << endl;

        // Write days
        while (start <= end) {
            *ts << "  <tr>" << endl;
            for (int i = 0; i < 7; ++i) {
                *ts << "    <td valign=\"top\"><table border=\"0\">";

                *ts << "<tr><td ";
                if (d->mHolidayMap.contains(start) || start.dayOfWeek() == 7) {
                    *ts << "class=\"dateholiday\"";
                } else {
                    *ts << "class=\"date\"";
                }
                *ts << ">" << QString::number(start.day());

                if (d->mHolidayMap.contains(start)) {
                    *ts << " <em>" << d->mHolidayMap[start] << "</em>";
                }

                *ts << "</td></tr><tr><td valign=\"top\">";

                // Only print events within the from-to range
                if (start >= fromDate() && start <= toDate()) {
                    Event::List events = d->mCalendar->events(start, d->mCalendar->timeSpec(),
                                         EventSortStartDate,
                                         SortDirectionAscending);
                    if (events.count()) {
                        *ts << "<table>";
                        Event::List::ConstIterator it;
                        for (it = events.constBegin(); it != events.constEnd(); ++it) {
                            if (checkSecrecy(*it)) {
                                createEvent(ts, *it, start, false);
                            }
                        }
                        *ts << "</table>";
                    } else {
                        *ts << "&nbsp;";
                    }
                }

                *ts << "</td></tr></table></td>" << endl;
                start = start.addDays(1);
            }
            *ts << "  </tr>" << endl;
        }
        *ts << "</table>" << endl;
        startmonth += 1;
        if (startmonth > 12) {
            startyear += 1;
            startmonth = 1;
        }
        start.setYMD(startyear, startmonth, 1);
        end.setYMD(start.year(), start.month(), start.daysInMonth());
    }
}
Esempio n. 2
0
/**
* 
* @brief Open the log file for putting the voltage readings
* 
* @return bool true on success, false otherwise
*/
bool TestMgr::VoltageLogOpenFile(void) {
	int status = 0;
	std::string name;
	QDate cd = QDate::currentDate();
	QTime ct = QTime::currentTime();

	// Create the logs directory if it does not exist
	QDir dir("/opt/ES/VocPhase1Test/Logs");
	if (!dir.exists()) {
		if (!dir.mkpath("/op/ES/VocPhase1Test/Logs")) {
			// creation failed
			status = -1;
		}
	}

	// Attempt to open the file and write header
	if (status == 0) {

		m_VoltageLogEntryNumber = 0;
		char buf[1024];

		if (m_TestId.length() > 0) {
			// Name format is log_yyyy-mm-dd_hhmmss_testId
			sprintf(buf, "/opt/ES/VocPhase1Test/Logs/log_%4d-%02d-%02d_%02d%02d%02d_%s.csv",
					cd.year(), cd.month(), cd.day(),
					ct.hour(), ct.minute(), ct.second(),
					m_TestId.toLocal8Bit().constData());
		} else {
			// Name format is log_yyyy-mm-dd_hhmmss
			sprintf(buf, "/opt/ES/VocPhase1Test/Logs/log_%4d-%02d-%02d_%02d%02d%02d.csv",
					cd.year(), cd.month(), cd.day(), ct.hour(), ct.minute(), ct.second());
		}

		m_LogFileHandle = fopen(buf, "w");
		if (m_LogFileHandle) {

			printf("LOG FILE IS OPEN: %s\n", buf);

			sprintf(buf, "Run Date,%d/%d/%d %02d:%02d:%02d\n",
					cd.year(), cd.month(), cd.day(), ct.hour(), ct.minute(), ct.second());
			fprintf(m_LogFileHandle, buf, "%s");

			if (m_TestId.length() > 0) {
				sprintf(buf, "Test ID,%s\n", m_TestId.toLocal8Bit().constData());
				fprintf(m_LogFileHandle, buf, "%s");
			}

			if (m_TestNote.length() > 0) {
				sprintf(buf, "Test Note,%s\n", m_TestNote.toLocal8Bit().constData());
				fprintf(m_LogFileHandle, buf, "%s");
			}

			fprintf(m_LogFileHandle,
					"%s,%s,%s,%s,%s\n",
					"Entry", "Time(ms)", "Temp(C)", "VAC(volts)", "FREQ(HZ)");
		} else {
			std::cout << "ERROR:  Could not open file for logging: " << buf << std::endl;
			status = -1;
		}
	}
	return (status == 0) ? true : false;
}
void Calendar::updateData()
{
  if (m_weeks == 0) {
    return;
  }

  m_dayList.clear();
  m_weekList.clear();

  int totalDays = 7 * m_weeks;

  int daysBeforeCurrentMonth = 0;
  int daysAfterCurrentMonth = 0;

  QDate firstDay(m_startDate.year(), m_startDate.month(), 1);

  daysBeforeCurrentMonth = firstDay.dayOfWeek();

  int daysThusFar = daysBeforeCurrentMonth + m_startDate.daysInMonth();
  if (daysThusFar < totalDays) {
    daysAfterCurrentMonth = totalDays - daysThusFar;
  }

  if (daysBeforeCurrentMonth > 0) {
    QDate previousMonth = m_startDate.addMonths(-1);

    for (int i = 0; i < daysBeforeCurrentMonth; ++i) {
      DayData day;
      day.isCurrentMonth = false;
      day.isNextMonth = false;
      day.isPreviousMonth = true;
      day.dayNumber = previousMonth.daysInMonth() -
          (daysBeforeCurrentMonth - (i + 1));
      day.monthNumber = previousMonth.month();
      day.yearNumber = previousMonth.year();
      day.containsEventItems = false;
      m_dayList << day;
    }
  }

  for (int i = 0; i < m_startDate.daysInMonth(); ++i) {
    DayData day;
    day.isCurrentMonth = true;
    day.isNextMonth = false;
    day.isPreviousMonth = false;
    day.dayNumber = i + 1;
    day.monthNumber = m_startDate.month();
    day.yearNumber = m_startDate.year();
    day.containsEventItems = false;
    m_dayList << day;
  }

  if (daysAfterCurrentMonth > 0) {
    for (int i = 0; i < daysAfterCurrentMonth; ++i) {
      DayData day;
      day.isCurrentMonth = false;
      day.isNextMonth = true;
      day.isPreviousMonth = false;
      day.dayNumber = i + 1;
      day.monthNumber = m_startDate.addMonths(1).month();
      day.yearNumber = m_startDate.addMonths(1).year();
      day.containsEventItems = false;
      m_dayList << day;
    }
  }

  const int numOfDaysInCalendar = m_dayList.count();

  for (int i = 0; i < numOfDaysInCalendar; i += 7) {
    const DayData& data = m_dayList.at(i);
    m_weekList <<
      QDate(data.yearNumber, data.monthNumber, data.dayNumber).weekNumber();
  }

  m_model->update();
}
Esempio n. 4
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;
}
Esempio n. 5
0
void HtmlExport::createMonthView(QTextStream *ts)
{
    QDate start = fromDate();
    start.setYMD(start.year(), start.month(), 1);    // go back to first day in month

    QDate end(start.year(), start.month(), start.daysInMonth());

    int startmonth = start.month();
    int startyear = start.year();

    while(start < toDate())
    {
        // Write header
        *ts << "<h2>" << (i18n("month_year", "%1 %2").arg(KGlobal::locale()->calendar()->monthName(start))
                          .arg(start.year())) << "</h2>\n";
        if(KGlobal::locale()->weekStartDay() == 1)
        {
            start = start.addDays(1 - start.dayOfWeek());
        }
        else
        {
            if(start.dayOfWeek() != 7)
            {
                start = start.addDays(-start.dayOfWeek());
            }
        }
        *ts << "<table border=\"1\">\n";

        // Write table header
        *ts << "  <tr>";
        for(int i = 0; i < 7; ++i)
        {
            *ts << "<th>" << KGlobal::locale()->calendar()->weekDayName(start.addDays(i)) << "</th>";
        }
        *ts << "</tr>\n";

        // Write days
        while(start <= end)
        {
            *ts << "  <tr>\n";
            for(int i = 0; i < 7; ++i)
            {
                *ts << "    <td valign=\"top\"><table border=\"0\">";

                *ts << "<tr><td ";
                if(mHolidayMap.contains(start) || start.dayOfWeek() == 7)
                {
                    *ts << "class=\"dateholiday\"";
                }
                else
                {
                    *ts << "class=\"date\"";
                }
                *ts << ">" << QString::number(start.day());

                if(mHolidayMap.contains(start))
                {
                    *ts << " <em>" << mHolidayMap[start] << "</em>";
                }

                *ts << "</td></tr><tr><td valign=\"top\">";

                Event::List events = mCalendar->events(start,
                                                       EventSortStartDate,
                                                       SortDirectionAscending);
                if(events.count())
                {
                    *ts << "<table>";
                    Event::List::ConstIterator it;
                    for(it = events.begin(); it != events.end(); ++it)
                    {
                        if(checkSecrecy(*it))
                        {
                            createEvent(ts, *it, start, false);
                        }
                    }
                    *ts << "</table>";
                }
                else
                {
                    *ts << "&nbsp;";
                }

                *ts << "</td></tr></table></td>\n";
                start = start.addDays(1);
            }
            *ts << "  </tr>\n";
        }
        *ts << "</table>\n";
        startmonth += 1;
        if(startmonth > 12)
        {
            startyear += 1;
            startmonth = 1;
        }
        start.setYMD(startyear, startmonth, 1);
        end.setYMD(start.year(), start.month(), start.daysInMonth());
    }
}
// Testing get/set functions
void tst_QCalendarWidget::getSetCheck()
{
    QWidget topLevel;
    QCalendarWidget object(&topLevel);

    //horizontal header formats
    object.setHorizontalHeaderFormat(QCalendarWidget::NoHorizontalHeader);
    QCOMPARE(QCalendarWidget::NoHorizontalHeader, object.horizontalHeaderFormat());
    object.setHorizontalHeaderFormat(QCalendarWidget::SingleLetterDayNames);
    QCOMPARE(QCalendarWidget::SingleLetterDayNames, object.horizontalHeaderFormat());
    object.setHorizontalHeaderFormat(QCalendarWidget::ShortDayNames);
    QCOMPARE(QCalendarWidget::ShortDayNames, object.horizontalHeaderFormat());
    object.setHorizontalHeaderFormat(QCalendarWidget::LongDayNames);
    QCOMPARE(QCalendarWidget::LongDayNames, object.horizontalHeaderFormat());
    //vertical header formats
    object.setVerticalHeaderFormat(QCalendarWidget::ISOWeekNumbers);
    QCOMPARE(QCalendarWidget::ISOWeekNumbers, object.verticalHeaderFormat());
    object.setVerticalHeaderFormat(QCalendarWidget::NoVerticalHeader);
    QCOMPARE(QCalendarWidget::NoVerticalHeader, object.verticalHeaderFormat());
    //maximum Date
    QDate maxDate(2006, 7, 3);
    object.setMaximumDate(maxDate);
    QCOMPARE(maxDate, object.maximumDate());
    //minimum date
    QDate minDate(2004, 7, 3);
    object.setMinimumDate(minDate);
    QCOMPARE(minDate, object.minimumDate());
    //day of week
    object.setFirstDayOfWeek(Qt::Thursday);
    QCOMPARE(Qt::Thursday, object.firstDayOfWeek());
    //grid visible
    object.setGridVisible(true);
    QVERIFY(object.isGridVisible());
    object.setGridVisible(false);
    QVERIFY(!object.isGridVisible());
    //header visible
    object.setNavigationBarVisible(true);
    QVERIFY(object.isNavigationBarVisible());
    object.setNavigationBarVisible(false);
    QVERIFY(!object.isNavigationBarVisible());
    //selection mode
    QCOMPARE(QCalendarWidget::SingleSelection, object.selectionMode());
    object.setSelectionMode(QCalendarWidget::NoSelection);
    QCOMPARE(QCalendarWidget::NoSelection, object.selectionMode());
    object.setSelectionMode(QCalendarWidget::SingleSelection);
    QCOMPARE(QCalendarWidget::SingleSelection, object.selectionMode());
   //selected date
    QDate selectedDate(2005, 7, 3);
    QSignalSpy spy(&object, SIGNAL(selectionChanged()));
    object.setSelectedDate(selectedDate);
    QCOMPARE(spy.count(), 1);
    QCOMPARE(selectedDate, object.selectedDate());
    //month and year
    object.setCurrentPage(2004, 1);
    QCOMPARE(1, object.monthShown());
    QCOMPARE(2004, object.yearShown());
    object.showNextMonth();
    QCOMPARE(2, object.monthShown());
    object.showPreviousMonth();
    QCOMPARE(1, object.monthShown());
    object.showNextYear();
    QCOMPARE(2005, object.yearShown());
    object.showPreviousYear();
    QCOMPARE(2004, object.yearShown());
    //date range
    minDate = QDate(2006,1,1);
    maxDate = QDate(2010,12,31);
    object.setDateRange(minDate, maxDate);
    QCOMPARE(maxDate, object.maximumDate());
    QCOMPARE(minDate, object.minimumDate());

    //date should not go beyond the minimum.
    selectedDate = minDate.addDays(-10);
    object.setSelectedDate(selectedDate);
    QCOMPARE(minDate, object.selectedDate());
    QVERIFY(selectedDate != object.selectedDate());
    //date should not go beyond the maximum.
    selectedDate = maxDate.addDays(10);
    object.setSelectedDate(selectedDate);
    QCOMPARE(maxDate, object.selectedDate());
    QVERIFY(selectedDate != object.selectedDate());
    //show today
    QDate today = QDate::currentDate();
    object.showToday();
    QCOMPARE(today.month(), object.monthShown());
    QCOMPARE(today.year(), object.yearShown());
    //slect a different date and move.
    object.setSelectedDate(minDate);
    object.showSelectedDate();
    QCOMPARE(minDate.month(), object.monthShown());
    QCOMPARE(minDate.year(), object.yearShown());
}
Esempio n. 7
0
QDomElement Validity::saveXML(QDomDocument& doc, const ValueConverter *converter) const
{
    QDomElement validityElement = doc.createElement("validity");

    QDomElement param = doc.createElement("param");
    param.setAttribute("cond", (int)d->cond);
    param.setAttribute("action", (int)d->action);
    param.setAttribute("allow", (int)d->restriction);
    param.setAttribute("valmin", converter->asString(d->minValue).asString());
    param.setAttribute("valmax", converter->asString(d->maxValue).asString());
    param.setAttribute("displaymessage", d->displayMessage);
    param.setAttribute("displayvalidationinformation", d->displayValidationInformation);
    param.setAttribute("allowemptycell", d->allowEmptyCell);
    if (!d->listValidity.isEmpty())
        param.setAttribute("listvalidity", d->listValidity.join(";"));
    validityElement.appendChild(param);
    QDomElement titleElement = doc.createElement("title");
    titleElement.appendChild(doc.createTextNode(d->title));
    validityElement.appendChild(titleElement);
    QDomElement messageElement = doc.createElement("message");
    messageElement.appendChild(doc.createCDATASection(d->message));
    validityElement.appendChild(messageElement);

    QDomElement inputTitle = doc.createElement("inputtitle");
    inputTitle.appendChild(doc.createTextNode(d->titleInfo));
    validityElement.appendChild(inputTitle);

    QDomElement inputMessage = doc.createElement("inputmessage");
    inputMessage.appendChild(doc.createTextNode(d->messageInfo));
    validityElement.appendChild(inputMessage);



    QString tmp;
    if (d->restriction == Time) {
        QDomElement timeMinElement = doc.createElement("timemin");
        tmp = converter->asString(d->minValue).asString();
        timeMinElement.appendChild(doc.createTextNode(tmp));
        validityElement.appendChild(timeMinElement);

        if (d->cond == Conditional::Between || d->cond == Conditional::Different) {
            QDomElement timeMaxElement = doc.createElement("timemax");
            tmp = converter->asString(d->maxValue).asString();
            timeMaxElement.appendChild(doc.createTextNode(tmp));
            validityElement.appendChild(timeMaxElement);
        }
    }

    if (d->restriction == Date) {
        QDomElement dateMinElement = doc.createElement("datemin");
        const QDate minDate = d->minValue.asDate(converter->settings());
        QString tmp("%1/%2/%3");
        tmp = tmp.arg(minDate.year()).arg(minDate.month()).arg(minDate.day());
        dateMinElement.appendChild(doc.createTextNode(tmp));
        validityElement.appendChild(dateMinElement);

        if (d->cond == Conditional::Between || d->cond == Conditional::Different) {
            QDomElement dateMaxElement = doc.createElement("datemax");
            const QDate maxDate = d->maxValue.asDate(converter->settings());
            QString tmp("%1/%2/%3");
            tmp = tmp.arg(maxDate.year()).arg(maxDate.month()).arg(maxDate.day());
            dateMaxElement.appendChild(doc.createTextNode(tmp));
            validityElement.appendChild(dateMaxElement);
        }
    }
    return validityElement;
}
Esempio n. 8
0
bool AssetCache::SetLastModified(const QString &assetRef, const QDateTime &dateTime)
{
    if (!dateTime.isValid())
    {
        LogError("AssetCache::SetLastModified() DateTime is invalid: " + assetRef);
        return false;
    }

    QString absolutePath = FindInCache(assetRef);
    if (absolutePath.isEmpty())
        return false;

    QDate date = dateTime.date();
    QTime time = dateTime.time();

#ifdef Q_WS_WIN
    HANDLE fileHandle = (HANDLE)OpenFileHandle(absolutePath);
    if (fileHandle == INVALID_HANDLE_VALUE)
    {
        LogError("AssetCache: Failed to open cache file to update last modified time: " + assetRef);
        return false;
    }

    // Notes: For SYSTEMTIME Sunday is 0 and ignore msec.
    SYSTEMTIME sysTime;
    sysTime.wDay = (WORD)date.day();
    sysTime.wDayOfWeek = (WORD)date.dayOfWeek();
    if (sysTime.wDayOfWeek == 7)
        sysTime.wDayOfWeek = 0;
    sysTime.wMonth = (WORD)date.month();
    sysTime.wYear = (WORD)date.year();
    sysTime.wHour = (WORD)time.hour();
    sysTime.wMinute = (WORD)time.minute();
    sysTime.wSecond = (WORD)time.second();
    sysTime.wMilliseconds = 0; 

    // Set last write time
    FILETIME fileTime;
    BOOL success = SystemTimeToFileTime(&sysTime, &fileTime);
    if (success)
        success = SetFileTime(fileHandle, 0, 0, &fileTime);
    CloseHandle(fileHandle);
    if (!success)
    {
        LogError("AssetCache: Failed to update cache file last modified time: " + assetRef);
        return false;
    }
    return true;
#else
    QString nativePath = QDir::toNativeSeparators(absolutePath);
    utimbuf modTime;
    modTime.actime = (time_t)(dateTime.toMSecsSinceEpoch() / 1000);
    modTime.modtime = (time_t)(dateTime.toMSecsSinceEpoch() / 1000);
    if (utime(nativePath.toStdString().c_str(), &modTime) == -1)
    {
        LogError("AssetCache: Failed to read cache file last modified time: " + assetRef);
        return false;
    }
    else
        return true;
#endif
}
void RollingFileAppender::computeRollOverTime()
{
  Q_ASSERT_X(!m_datePatternString.isEmpty(), "DailyRollingFileAppender::computeRollOverTime()", "No active date pattern");

  QDateTime now = QDateTime::currentDateTime();
  QDate nowDate = now.date();
  QTime nowTime = now.time();
  QDateTime start;

  switch (m_frequency)
  {
    case MinutelyRollover:
    {
      start = QDateTime(nowDate, QTime(nowTime.hour(), nowTime.minute(), 0, 0));
      m_rollOverTime = start.addSecs(60);
    }
    break;
    case HourlyRollover:
    {
      start = QDateTime(nowDate, QTime(nowTime.hour(), 0, 0, 0));
      m_rollOverTime = start.addSecs(60*60);
    }
    break;
    case HalfDailyRollover:
    {
      int hour = nowTime.hour();
      if (hour >=  12)
        hour = 12;
      else
        hour = 0;
      start = QDateTime(nowDate, QTime(hour, 0, 0, 0));
      m_rollOverTime = start.addSecs(60*60*12);
    }
    break;
    case DailyRollover:
    {
      start = QDateTime(nowDate, QTime(0, 0, 0, 0));
      m_rollOverTime = start.addDays(1);
    }
    break;
    case WeeklyRollover:
    {
      // Qt numbers the week days 1..7. The week starts on Monday.
      // Change it to being numbered 0..6, starting with Sunday.
      int day = nowDate.dayOfWeek();
      if (day == Qt::Sunday)
        day = 0;
      start = QDateTime(nowDate, QTime(0, 0, 0, 0)).addDays(-1 * day);
      m_rollOverTime = start.addDays(7);
    }
    break;
    case MonthlyRollover:
    {
      start = QDateTime(QDate(nowDate.year(), nowDate.month(), 1), QTime(0, 0, 0, 0));
      m_rollOverTime = start.addMonths(1);
    }
    break;
    default:
      Q_ASSERT_X(false, "DailyRollingFileAppender::computeInterval()", "Invalid datePattern constant");
      m_rollOverTime = QDateTime::fromTime_t(0);
  }

  m_rollOverSuffix = start.toString(m_datePatternString);
  Q_ASSERT_X(now.toString(m_datePatternString) == m_rollOverSuffix,
      "DailyRollingFileAppender::computeRollOverTime()", "File name changes within interval");
  Q_ASSERT_X(m_rollOverSuffix != m_rollOverTime.toString(m_datePatternString),
      "DailyRollingFileAppender::computeRollOverTime()", "File name does not change with rollover");
}
QList<int> tradeDateCalendar::computeFrequencyTradeYearly(int date_, int minimumDate_, int maximumDate_)
{
    QList<int> tradeDates;

    QDate yearDayCounter = QDate::fromJulianDay(minimumDate_);
    int dayOfYear = QDate::fromJulianDay(date_).dayOfYear();

    forever
    {
        QDate yearDayComputation = yearDayCounter;
        int leapDayofYear = dayOfYear + (dayOfYear > 59 /* Feb 28th */ && QDate::isLeapYear(yearDayComputation.year()) ? 1 : 0);

        if (yearDayComputation.dayOfYear() > leapDayofYear)
        {
            yearDayComputation = yearDayComputation.addYears(1);
            leapDayofYear = dayOfYear + (dayOfYear > 59 /* Feb 28th */ && QDate::isLeapYear(yearDayComputation.year()) ? 1 : 0);
        }

        date_ = checkTradeDate(yearDayComputation.toJulianDay(), direction_ascending);
        if (date_ > maximumDate_)
            break;

        tradeDates.append(date_);
        yearDayCounter = yearDayCounter.addYears(1);
    }

    return tradeDates;
}
Esempio n. 11
0
void BestTimesImpl::on_calculateButton_clicked()
{
    enum period
    {
        ALL = 0,
        THISMONTH,
        THISYEAR,
        LASTMONTH,
        LASTYEAR
    };

    timesTable->clearContents();
    timesTable->setRowCount(0);

    // otherwise the rows move around while they are added
    // and we set the item in the wrong place
    timesTable->setSortingEnabled(false);

    int id = periodBox->currentIndex();

    const QString distStr = distanceBox->currentText();
    bool ok = false;
    const uint distance = distStr.toUInt(&ok);
    if (!ok || distance == 0)
    {
        return;
    }

    double bestSpeed = std::numeric_limits<double>::max();

    const std::vector<Workout>& workouts = ds->Workouts();

    for (size_t i = 0; i < workouts.size(); ++i)
    {
        const Workout & w = workouts[i];

        switch(id)
        {
        case ALL:
            break;

        case THISMONTH:
        {
            QDate now = QDate::currentDate();
            if (w.date.month() != now.month() ||
                    w.date.year() != now.year())
                continue;
            break;
        }

        case THISYEAR:
        {
            QDate now = QDate::currentDate();
            if (w.date.year() != now.year())
                continue;
            break;
        }

        case LASTMONTH:
        {
            QDate then = QDate::currentDate().addMonths(-1);
            if (w.date.month() != then.month() ||
                    w.date.year() != then.year())
                continue;
            break;
        }

        case LASTYEAR:
        {
            QDate then = QDate::currentDate().addYears(-1);
            if (w.date.year() != then.year())
                continue;
            break;
        }
        }

        if (w.type != "Swim" && w.type != "SwimHR")
        {
            continue;
        }

        const int pool = w.pool;

        if (pool <= 0)
        {
            continue;
        }

        // this is the number of lanes to get above or equal the desired distance
        const int numberOfLanes = (distance + pool - 1) / pool; // round up

        for (size_t j = 0; j < w.sets.size(); ++j)
        {
            const Set & set = w.sets[j];
            if (set.lens < numberOfLanes)
            {
                // not enough in this set
                continue;
            }

            addSet(set, w, numberOfLanes, bestSpeed, timesTable);
        }
    }

    // ensure the state of the "record progression" is correct
    on_progressionBox_clicked();
    timesTable->resizeColumnsToContents();
    timesTable->setSortingEnabled(true);
}
Esempio n. 12
0
//! Change the map expiration date
void AdditionalMap::setExpirationDate(QDate date)
{
  _data.expirationYear  = date.year();
  _data.expirationMonth = date.month();
  _data.expirationDay   = date.day();
}
Esempio n. 13
0
/**
	Affiche les factures
	@param filter, filtre a appliquer
	@param field, champ ou appliquer le filtre
*/
void DialogInvoiceList::listInvoicesToTable(QDate mdate) {
	invoice::InvoicesBook ilist;

	//Clear les items, attention tjs utiliser la fonction clear()
	ui->tableWidget_Invoices->clear();
	for (int i=ui->tableWidget_Invoices->rowCount()-1; i >= 0; --i)
		ui->tableWidget_Invoices->removeRow(i);
	for (int i=ui->tableWidget_Invoices->columnCount()-1; i>=0; --i)
		ui->tableWidget_Invoices->removeColumn(i);

	ui->tableWidget_Invoices->setSortingEnabled(false);
	//Style de la table de facture
	ui->tableWidget_Invoices->setColumnCount( COL_COUNT );
	ui->tableWidget_Invoices->setColumnWidth( COL_DESCRIPTION, 250 );
#ifdef QT_NO_DEBUG
	ui->tableWidget_Invoices->setColumnHidden(COL_ID , true); //cache la colonne ID ou DEBUG
#endif
	ui->tableWidget_Invoices->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui->tableWidget_Invoices->setSelectionMode(QAbstractItemView::SingleSelection);
	ui->tableWidget_Invoices->setEditTriggers(QAbstractItemView::NoEditTriggers);
	QStringList titles;
	titles  << tr("Id") << tr("sélection") << tr("Date") << tr("Code Facture") << tr("Client") << tr("Description")  << tr("Montant") << tr("TTC") << QLatin1String("Règlement");
	ui->tableWidget_Invoices->setHorizontalHeaderLabels( titles );
	if(!m_data->getIsTax()) {
		ui->tableWidget_Invoices->setColumnHidden(COL_PRICE_TAX , true);
	}
	//Recuperation des donnees presentent dans la bdd
	m_invoice->getInvoices(ilist, QString::number(mdate.year()), QString::number(mdate.month()));

	// list all customers
	QString typeP;
	for(int i=0; i<ilist.code.count(); i++){

		ItemOfTable *item_ID           = new ItemOfTable();
		ItemOfTable *item_State        = new ItemOfTable();
		ItemOfTable *item_DATE         = new ItemOfTable();
		ItemOfTable *item_CODE         = new ItemOfTable();
		ItemOfTable *item_CUSTOMER     = new ItemOfTable();
		ItemOfTable *item_DESCRIPTION  = new ItemOfTable();
		ItemOfTable *item_PRICE        = new ItemOfTable();
		ItemOfTable *item_PRICE_TAX    = new ItemOfTable();
		ItemOfTable *item_TYPE_PAYMENT = new ItemOfTable();
		
		item_ID->setData(Qt::DisplayRole, ilist.id.at(i));
		item_State -> setData(Qt::CheckStateRole, Qt::Checked);
		item_DATE->setData(Qt::DisplayRole, ilist.userDate.at(i)/*.toString(tr("dd/MM/yyyy"))*/);
		item_CODE->setData(Qt::DisplayRole, ilist.code.at(i));
		if(ilist.customerFirstName.at(i).isEmpty())
			item_CUSTOMER->setData(Qt::DisplayRole, ilist.customerLastName.at(i));
		else
			item_CUSTOMER->setData(Qt::DisplayRole, ilist.customerFirstName.at(i) +" "+ilist.customerLastName.at(i));

		item_DESCRIPTION->setData(Qt::DisplayRole, ilist.description.at(i));
		item_PRICE->setData(Qt::DisplayRole, ilist.price.at(i) - ilist.part_payment.at(i));
		item_PRICE_TAX->setData(Qt::DisplayRole, ilist.priceTax.at(i) - ilist.part_paymentTax.at(i));

		typeP="";
		if( ilist.typePayment.at(i) == MCERCLE::CASH)         typeP = tr("Espece");
		if( ilist.typePayment.at(i) == MCERCLE::CHECK)        typeP = tr("Cheque");
		if( ilist.typePayment.at(i) == MCERCLE::CREDIT_CARD)  typeP = tr("CB");
		if( ilist.typePayment.at(i) == MCERCLE::INTERBANK)    typeP = tr("TIP");
		if( ilist.typePayment.at(i) == MCERCLE::TRANSFER)     typeP = tr("Virement");
		if( ilist.typePayment.at(i) == MCERCLE::DEBIT)        typeP = tr("Prelevement");
		if( ilist.typePayment.at(i) == MCERCLE::OTHER)        typeP = tr("Autre");

		item_TYPE_PAYMENT->setData(Qt::DisplayRole, typeP);

		//definir le tableau
		ui->tableWidget_Invoices->setRowCount(i+1);

		//remplir les champs
		ui->tableWidget_Invoices->setItem(i, COL_ID, item_ID);
		ui->tableWidget_Invoices->setItem(i, COL_STATE, item_State);
		ui->tableWidget_Invoices->setItem(i, COL_DATE, item_DATE);
		ui->tableWidget_Invoices->setItem(i, COL_CODE, item_CODE);
		ui->tableWidget_Invoices->setItem(i, COL_CUSTOMER, item_CUSTOMER);
		ui->tableWidget_Invoices->setItem(i, COL_DESCRIPTION, item_DESCRIPTION);
		ui->tableWidget_Invoices->setItem(i, COL_PRICE, item_PRICE);
		ui->tableWidget_Invoices->setItem(i, COL_PRICE_TAX, item_PRICE_TAX);
		ui->tableWidget_Invoices->setItem(i, COL_TYPE_PAYMENT, item_TYPE_PAYMENT);
	}
	ui->tableWidget_Invoices->setSortingEnabled(true);
	ui->tableWidget_Invoices->selectRow(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. 15
0
void
DateSettingsEdit::setDateSettings()
{
    if (active) return;

    // first lets disable everything
    active = true;
    fromDateEdit->setEnabled(false);
    toDateEdit->setEnabled(false);
    startDateEdit->setEnabled(false);
    thisperiod->setEnabled(false);
    prevperiod->setEnabled(false);
    lastn->setEnabled(false);
    lastnx->setEnabled(false);

    // the date selection types have changed
    if (radioSelected->isChecked()) {

        // current selection
        emit useStandardRange();

    } else if (radioCustom->isChecked()) {

        // between x and y
        fromDateEdit->setEnabled(true);
        toDateEdit->setEnabled(true);

        // set date range using custom values
        emit useCustomRange(DateRange(fromDateEdit->date(), toDateEdit->date()));

    } else if (radioToday->isChecked()) {

        // current selected thru to today
        emit useThruToday();

    } else if (radioLast->isChecked()) {

        // last n 'weeks etc'
        lastn->setEnabled(true);
        lastnx->setEnabled(true);

        QDate from;
        QDate today = QDate::currentDate();

        // calculate range up to today...
        switch(lastnx->currentIndex()) {
            case 0 : // days
                from = today.addDays(lastn->value() * -1);
                break;

            case 1 :  // weeks
                from = today.addDays(lastn->value() * -7);
                break;

            case 2 :  // months
                from = today.addMonths(lastn->value() * -1);
                break;

            case 3 : // years
                from = today.addYears(lastn->value() * -1);
                break;
        }

        emit useCustomRange(DateRange(from, today));

    } else if (radioFrom->isChecked()) {

        // from date - today
        startDateEdit->setEnabled(true);
        emit useCustomRange(DateRange(startDateEdit->date(), QDate::currentDate()));

    } else if (radioThis->isChecked()) {

        thisperiod->setEnabled(true);
        prevperiod->setEnabled(true);

        QDate today = QDate::currentDate();
        QDate from, to;

        switch(thisperiod->currentIndex()) {

        case 0 : // weeks
            {
                int dow = today.dayOfWeek(); // 1-7, where 1=monday
                from = today.addDays(-1 * (dow-1));
                to = from.addDays(6);
                // prevperiods
                from = from.addDays(prevperiod->value() * -7);
                to = to.addDays(prevperiod->value() * -7);
            }
            break;

        case 1 : // months
            from = QDate(today.year(), today.month(), 1);
            to = from.addMonths(1).addDays(-1);
            from = from.addMonths(prevperiod->value() * -1);
            to = to.addMonths(prevperiod->value() * -1);
            break;

        case 2 : // years
            from = QDate(today.year(), 1, 1);
            to = from.addYears(1).addDays(-1);
            from = from.addYears(prevperiod->value() * -1);
            to = to.addYears(prevperiod->value() * -1);
            break;

        }
        emit useCustomRange(DateRange(from, to));
    }
    active = false;
}
Esempio n. 16
0
// Apply a simple variant type to a DOM property
static bool applySimpleProperty(const QVariant &v, bool translateString, DomProperty *dom_prop)
{
    switch (v.type()) {
    case QVariant::String: {
        DomString *str = new DomString();
        str->setText(v.toString());
        if (!translateString)
            str->setAttributeNotr(QLatin1String("true"));
        dom_prop->setElementString(str);
    }
        return true;

    case QVariant::ByteArray:
        dom_prop->setElementCstring(QString::fromUtf8(v.toByteArray()));
        return true;

    case QVariant::Int:
        dom_prop->setElementNumber(v.toInt());
        return true;

    case QVariant::UInt:
        dom_prop->setElementUInt(v.toUInt());
        return true;

    case QVariant::LongLong:
        dom_prop->setElementLongLong(v.toLongLong());
        return true;

    case QVariant::ULongLong:
        dom_prop->setElementULongLong(v.toULongLong());
        return true;

    case QVariant::Double:
        dom_prop->setElementDouble(v.toDouble());
        return true;

    case QVariant::Bool:
        dom_prop->setElementBool(v.toBool() ? QFormBuilderStrings::instance().trueValue : QFormBuilderStrings::instance().falseValue);
        return true;

    case QVariant::Char: {
        DomChar *ch = new DomChar();
        const QChar character = v.toChar();
        ch->setElementUnicode(character.unicode());
        dom_prop->setElementChar(ch);
    }
        return true;

    case QVariant::Point: {
        DomPoint *pt = new DomPoint();
        const QPoint point = v.toPoint();
        pt->setElementX(point.x());
        pt->setElementY(point.y());
        dom_prop->setElementPoint(pt);
    }
        return true;

    case QVariant::PointF: {
        DomPointF *ptf = new DomPointF();
        const QPointF pointf = v.toPointF();
        ptf->setElementX(pointf.x());
        ptf->setElementY(pointf.y());
        dom_prop->setElementPointF(ptf);
    }
        return true;

    case QVariant::Color: {
        DomColor *clr = new DomColor();
        const QColor color = qvariant_cast<QColor>(v);
        clr->setElementRed(color.red());
        clr->setElementGreen(color.green());
        clr->setElementBlue(color.blue());
        const int alphaChannel = color.alpha();
        if (alphaChannel != 255)
            clr->setAttributeAlpha(alphaChannel);
        dom_prop->setElementColor(clr);
    }
        return true;

    case QVariant::Size: {
        DomSize *sz = new DomSize();
        const QSize size = v.toSize();
        sz->setElementWidth(size.width());
        sz->setElementHeight(size.height());
        dom_prop->setElementSize(sz);
    }
        return true;

    case QVariant::SizeF: {
        DomSizeF *szf = new DomSizeF();
        const QSizeF sizef = v.toSizeF();
        szf->setElementWidth(sizef.width());
        szf->setElementHeight(sizef.height());
        dom_prop->setElementSizeF(szf);
    }
        return true;

    case QVariant::Rect: {
        DomRect *rc = new DomRect();
        const QRect rect = v.toRect();
        rc->setElementX(rect.x());
        rc->setElementY(rect.y());
        rc->setElementWidth(rect.width());
        rc->setElementHeight(rect.height());
        dom_prop->setElementRect(rc);
    }
        return true;

    case QVariant::RectF: {
        DomRectF *rcf = new DomRectF();
        const QRectF rectf = v.toRectF();
        rcf->setElementX(rectf.x());
        rcf->setElementY(rectf.y());
        rcf->setElementWidth(rectf.width());
        rcf->setElementHeight(rectf.height());
        dom_prop->setElementRectF(rcf);
    }
        return true;

    case QVariant::Font: {
        DomFont *fnt = new DomFont();
        const QFont font = qvariant_cast<QFont>(v);
        const uint mask = font.resolve();
        if (mask & QFont::WeightResolved) {
            fnt->setElementBold(font.bold());
            fnt->setElementWeight(font.weight());
        }
        if (mask & QFont::FamilyResolved)
            fnt->setElementFamily(font.family());
        if (mask & QFont::StyleResolved)
            fnt->setElementItalic(font.italic());
        if (mask & QFont::SizeResolved)
            fnt->setElementPointSize(font.pointSize());
        if (mask & QFont::StrikeOutResolved)
            fnt->setElementStrikeOut(font.strikeOut());
        if (mask & QFont::UnderlineResolved)
            fnt->setElementUnderline(font.underline());
        if (mask & QFont::KerningResolved)
            fnt->setElementKerning(font.kerning());
        if (mask & QFont::StyleStrategyResolved) {
            const QMetaEnum styleStrategy_enum = metaEnum<QAbstractFormBuilderGadget>("styleStrategy");
            fnt->setElementStyleStrategy(QLatin1String(styleStrategy_enum.valueToKey(font.styleStrategy())));
        }
        dom_prop->setElementFont(fnt);
    }
        return true;

#ifndef QT_NO_CURSOR
    case QVariant::Cursor: {
        const QMetaEnum cursorShape_enum = metaEnum<QAbstractFormBuilderGadget>("cursorShape");
        dom_prop->setElementCursorShape(QLatin1String(cursorShape_enum.valueToKey(qvariant_cast<QCursor>(v).shape())));
        }
        return true;
#endif

    case QVariant::KeySequence: {
        DomString *s = new DomString();
        s->setText(qvariant_cast<QKeySequence>(v).toString(QKeySequence::PortableText));
        dom_prop->setElementString(s);
        }
        return true;

    case QVariant::Locale: {
        DomLocale *dom = new DomLocale();
        const QLocale locale = qvariant_cast<QLocale>(v);

        const QMetaEnum language_enum = metaEnum<QAbstractFormBuilderGadget>("language");
        const QMetaEnum country_enum = metaEnum<QAbstractFormBuilderGadget>("country");

        dom->setAttributeLanguage(QLatin1String(language_enum.valueToKey(locale.language())));
        dom->setAttributeCountry(QLatin1String(country_enum.valueToKey(locale.country())));

        dom_prop->setElementLocale(dom);
        }
        return true;

    case QVariant::SizePolicy: {
        DomSizePolicy *dom = new DomSizePolicy();
        const QSizePolicy sizePolicy = qvariant_cast<QSizePolicy>(v);

        dom->setElementHorStretch(sizePolicy.horizontalStretch());
        dom->setElementVerStretch(sizePolicy.verticalStretch());

        const QMetaEnum sizeType_enum = metaEnum<QAbstractFormBuilderGadget>("sizeType");

        dom->setAttributeHSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.horizontalPolicy())));
        dom->setAttributeVSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.verticalPolicy())));

        dom_prop->setElementSizePolicy(dom);
    }
        return true;

    case QVariant::Date: {
        DomDate *dom = new DomDate();
        const QDate date = qvariant_cast<QDate>(v);

        dom->setElementYear(date.year());
        dom->setElementMonth(date.month());
        dom->setElementDay(date.day());

        dom_prop->setElementDate(dom);
        }
        return true;

    case QVariant::Time: {
        DomTime *dom = new DomTime();
        const QTime time = qvariant_cast<QTime>(v);

        dom->setElementHour(time.hour());
        dom->setElementMinute(time.minute());
        dom->setElementSecond(time.second());

        dom_prop->setElementTime(dom);
        }
        return true;

    case QVariant::DateTime: {
        DomDateTime *dom = new DomDateTime();
        const QDateTime dateTime = qvariant_cast<QDateTime>(v);

        dom->setElementHour(dateTime.time().hour());
        dom->setElementMinute(dateTime.time().minute());
        dom->setElementSecond(dateTime.time().second());
        dom->setElementYear(dateTime.date().year());
        dom->setElementMonth(dateTime.date().month());
        dom->setElementDay(dateTime.date().day());

        dom_prop->setElementDateTime(dom);
    }
        return true;

    case QVariant::Url: {
        DomUrl *dom = new DomUrl();
        const QUrl url = v.toUrl();

        DomString *str = new DomString();
        str->setText(url.toString());
        dom->setElementString(str);

        dom_prop->setElementUrl(dom);
    }
        return true;

    case QVariant::StringList: {
        DomStringList *sl = new DomStringList;
        sl->setElementString(qvariant_cast<QStringList>(v));
        dom_prop->setElementStringList(sl);
    }
        return true;

    default:
        break;
    }

    return false;
}
Esempio n. 17
0
QScriptValue NetworkAutomaticProxy::dateRange(QScriptContext *context, QScriptEngine *engine)
{
	Q_UNUSED(engine);

	if (context->argumentCount() < 1 || context->argumentCount() > 7)
	{
		return context->throwError(QLatin1String("Function dateRange takes 1 to 7 arguments!"));
	}

	QList<int> arguments;
	int amount = 0;
	const QDate currentDay = getDateTime(context, &amount).date();

	for (int i = 0; i < amount; ++i)
	{
		if (context->argument(i).isString())
		{
			const int month = (m_months.indexOf(context->argument(i).toString().toLower())  + 1);

			if (month < 1)
			{
				return false;
			}

			arguments.append(month);
		}
		else
		{
			arguments.append(context->argument(i).toInt32());
		}
	}

	if (amount == 1 && arguments.at(0) > 1500)
	{
		return (currentDay.year() == arguments.at(0));
	}

	if (amount == 1 && context->argument(0).isNumber())
	{
		return (currentDay.day() == arguments.at(0));
	}

	if (amount == 1)
	{
		return (currentDay.month() == arguments.at(0));
	}

	if (amount == 2 && arguments.at(0) > 1500 && arguments.at(1) > 1500)
	{
		return compareRange(arguments.at(0), arguments.at(1), currentDay.year());
	}

	if (amount == 2 && context->argument(0).isNumber() && context->argument(1).isNumber())
	{
		return compareRange(arguments.at(0), arguments.at(1), currentDay.day());
	}

	if (amount == 2)
	{
		return compareRange(arguments.at(0), arguments.at(1), currentDay.month());
	}

	if (amount == 3)
	{
		const QDate dateOne(arguments.at(2), arguments.at(1), arguments.at(0));

		return compareRange(dateOne, dateOne, currentDay);
	}

	if (amount == 4 && arguments.at(1) > 1500 && arguments.at(3) > 1500)
	{
		return compareRange(QDate(arguments.at(1), arguments.at(0), currentDay.day()), QDate(arguments.at(3), arguments.at(2), currentDay.day()), currentDay);
	}

	if (amount == 4)
	{
		return compareRange(QDate(currentDay.year(), arguments.at(1), arguments.at(0)), QDate(currentDay.year(), arguments.at(3), arguments.at(2)), currentDay);
	}

	if (amount == 6)
	{
		return compareRange(QDate(arguments.at(2), arguments.at(1), arguments.at(0)), QDate(arguments.at(5), arguments.at(4), arguments.at(3)), currentDay);
	}

	return false;
}
Esempio n. 18
0
void
DiarySidebar::setSummary()
{
    // are we metric?
    bool useMetricUnits = context->athlete->useMetricUnits;

    // where we construct the text
    QString summaryText("");

    QDate when;
    if (_ride && _ride->ride()) when = _ride->dateTime.date();
    else when = QDate::currentDate();

    // main totals
    static const QStringList totalColumn = QStringList()
        << "workout_time"
        << "time_riding"
        << "total_distance"
        << "total_work"
        << "elevation_gain";

    static const QStringList averageColumn = QStringList()
        << "average_speed"
        << "average_power"
        << "average_hr"
        << "average_cad";

    static const QStringList maximumColumn = QStringList()
        << "max_speed"
        << "max_power"
        << "max_heartrate"
        << "max_cadence";

    // user defined
    QString s = appsettings->value(this, GC_SETTINGS_SUMMARY_METRICS, GC_SETTINGS_SUMMARY_METRICS_DEFAULT).toString();

    // in case they were set tand then unset
    if (s == "") s = GC_SETTINGS_SUMMARY_METRICS_DEFAULT;
    QStringList metricColumn = s.split(",");

    // what date range should we use?
    QDate newFrom, newTo;

    switch(summarySelect->currentIndex()) {

        case 0 :
            // DAILY - just the date of the ride
            newFrom = newTo = when;
            break;
        case 1 :
            // WEEKLY - from Mon to Sun
            newFrom = when.addDays((when.dayOfWeek()-1)*-1);
            newTo = newFrom.addDays(6);
            break;

        default:
        case 2 : 
            // MONTHLY - all days in month
            newFrom = QDate(when.year(), when.month(), 1);
            newTo = newFrom.addMonths(1).addDays(-1);
            break;
    }

    if (newFrom != from || newTo != to) {

        // date range changed lets refresh
        from = newFrom;
        to = newTo;

        // lets get the metrics
        QList<SummaryMetrics>results = context->athlete->metricDB->getAllMetricsFor(QDateTime(from,QTime(0,0,0)), QDateTime(to, QTime(24,59,59)));

        // foreach of the metrics get an aggregated value
        // header of summary
        summaryText = QString("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2//EN\">"
                              "<html>"
                              "<head>"
                              "<title></title>"
                              "</head>"
                              "%1"
                              "<body>"
                              "<center>").arg(GCColor::css());

        for (int i=0; i<4; i++) { //taken out maximums -- too much info -- looks ugly

            QString aggname;
            QStringList list;

            switch(i) {
                case 0 : // Totals
                    aggname = tr("Totals");
                    list = totalColumn;
                    break;

                case 1 :  // Averages
                    aggname = tr("Averages");
                    list = averageColumn;
                    break;

                case 3 :  // Maximums
                    aggname = tr("Maximums");
                    list = maximumColumn;
                    break;

                case 2 :  // User defined.. 
                    aggname = tr("Metrics");
                    list = metricColumn;
                    break;

            }

            summaryText += QString("<p><table width=\"85%\">"
                                   "<tr>"
                                   "<td align=\"center\" colspan=\"2\">"
                                   "<b>%1</b>"
                                   "</td>"
                                   "</tr>").arg(aggname);

            foreach(QString metricname, list) {

                const RideMetric *metric = RideMetricFactory::instance().rideMetric(metricname);

                QStringList empty; // usually for filters, but we don't do that
                QString value = SummaryMetrics::getAggregated(context, metricname, results, empty, false, useMetricUnits);


                // Maximum Max and Average Average looks nasty, remove from name for display
                QString s = metric ? metric->name().replace(QRegExp(tr("^(Average|Max) ")), "") : "unknown";

                // don't show units for time values
                if (metric && (metric->units(useMetricUnits) == "seconds" ||
                               metric->units(useMetricUnits) == tr("seconds") ||
                               metric->units(useMetricUnits) == "")) {

                    summaryText += QString("<tr><td>%1:</td><td align=\"right\"> %2</td>")
                                            .arg(s)
                                            .arg(value);

                } else {
                    summaryText += QString("<tr><td>%1(%2):</td><td align=\"right\"> %3</td>")
                                            .arg(s)
                                            .arg(metric ? metric->units(useMetricUnits) : "unknown")
                                            .arg(value);
                }

            }
            summaryText += QString("</tr>" "</table>");

        }

        // finish off the html document
        summaryText += QString("</center>"
                               "</body>"
                               "</html>");

        // set webview contents
        summary->page()->mainFrame()->setHtml(summaryText);
    }
Esempio n. 19
0
bool MythTimeInputDialog::Create()
{
    if (!CopyWindowFromBase("MythTimeInputDialog", this))
        return false;

    MythUIText *messageText = NULL;
    MythUIButton *okButton = NULL;

    bool err = false;
    UIUtilE::Assign(this, messageText, "message", &err);
    UIUtilE::Assign(this, m_dateList, "dates", &err);
    UIUtilE::Assign(this, m_timeList, "times", &err);
    UIUtilE::Assign(this, okButton, "ok", &err);

    if (err)
    {
        LOG(VB_GENERAL, LOG_ERR, "Cannot load screen 'MythTimeInputDialog'");
        return false;
    }

    m_dateList->SetVisible(false);
    m_timeList->SetVisible(false);

    MythUIButtonListItem *item;
    // Date
    if (kNoDate != (m_resolution & 0xF))
    {
        const QDate startdate(m_startTime.toLocalTime().date());
        QDate date(startdate);

        int limit = 0;
        if (m_resolution & kFutureDates)
        {
            limit += m_rangeLimit;
        }
        if (m_resolution & kPastDates)
        {
            limit += m_rangeLimit;
            date = date.addDays(0-m_rangeLimit);
        }

        QString text;
        int flags;
        bool selected = false;
        for (int x = 0; x <= limit; x++)
        {
            selected = false;
            if (m_resolution & kDay)
            {
                date = date.addDays(1);
                flags = MythDate::kDateFull | MythDate::kSimplify;
                if (m_rangeLimit >= 356)
                    flags |= MythDate::kAddYear;
                text = MythDate::toString(date, flags);

                if (date == startdate)
                    selected = true;
            }
            else if (m_resolution & kMonth)
            {
                date = date.addMonths(1);
                text = date.toString("MMM yyyy");

                if ((date.month() == startdate.month()) &&
                    (date.year() == startdate.year()))
                    selected = true;
            }
            else if (m_resolution & kYear)
            {
                date = date.addYears(1);
                text = date.toString("yyyy");
                if (date.year() == startdate.year())
                    selected = true;
            }

            item = new MythUIButtonListItem(m_dateList, text, NULL, false);
            item->SetData(QVariant(date));

            if (selected)
                m_dateList->SetItemCurrent(item);
        }
        m_dateList->SetVisible(true);
    }

    // Time
    if (kNoTime != (m_resolution & 0xF0))
    {
        QDate startdate(m_startTime.toLocalTime().date());
        QTime starttime(m_startTime.toLocalTime().time());
        QTime time(0,0,0);
        QString text;
        bool selected = false;

        int limit = (m_resolution & kMinutes) ? (60 * 24) : 24;

        for (int x = 0; x < limit; x++)
        {
            selected = false;
            if (m_resolution & kMinutes)
            {
                time = time.addSecs(60);
                QDateTime dt = QDateTime(startdate, time, Qt::LocalTime);
                text = MythDate::toString(dt, MythDate::kTime);

                if (time == starttime)
                    selected = true;
            }
            else if (m_resolution & kHours)
            {
                time = time.addSecs(60*60);
                text = time.toString("hh:00");

                if (time.hour() == starttime.hour())
                    selected = true;
            }

            item = new MythUIButtonListItem(m_timeList, text, NULL, false);
            item->SetData(QVariant(time));

            if (selected)
                m_timeList->SetItemCurrent(item);
        }
        m_timeList->SetVisible(true);
    }

    if (messageText && !m_message.isEmpty())
        messageText->SetText(m_message);

    connect(okButton, SIGNAL(Clicked()), SLOT(okClicked()));

    BuildFocusList();

    return true;
}
Esempio n. 20
0
void MainWindow::showSwapNPV()
{
    //ui->lineEdit_SwapNPV->setText(tr("1000000000"));
    //ui->lineEdit_SwapFairRate->setText(QString::number(3.141659));
    //ui->lineEdit_SwapFairSpread->setText(QString::number(2.68796451));


    /*********************
    ***  MARKET DATA  ***
    *********************/

    Calendar calendar = TARGET();

    /////■ Date settlementDate(22, September, 2004);
    QDate qtFormSettlementDate = ui->dateEdit_settlementDate->date();
    QuantLib::Date settlementDate(22, September, 2004);
    if(!qtFormSettlementDate.isNull() && qtFormSettlementDate.isValid()) {
        QuantLib::Date settlementDate_(qtFormSettlementDate.day(), (QuantLib::Month)(qtFormSettlementDate.month()), qtFormSettlementDate.year());
        settlementDate = settlementDate_;
    }

    // must be a business day
    settlementDate = calendar.adjust(settlementDate);

    Integer fixingDays = 2;
    Date todaysDate = calendar.advance(settlementDate, -fixingDays, Days);
    // nothing to do with Date::todaysDate
    Settings::instance().evaluationDate() = todaysDate;


    todaysDate = Settings::instance().evaluationDate();
    std::cout << "Today: " << todaysDate.weekday()
              << ", " << todaysDate << std::endl;

    std::cout << "Settlement date: " << settlementDate.weekday()
              << ", " << settlementDate << std::endl;

    // deposits
    Rate d1wQuote=0.0382;
    d1wQuote = static_cast<Rate>(ui->tableWidget_RatesDeposites->item(-1,1)->text().toDouble()*0.01);
    Rate d1mQuote=0.0372;
    d1mQuote = static_cast<Rate>(ui->tableWidget_RatesDeposites->item(0,1)->text().toDouble()*0.01);
    Rate d3mQuote=0.0363;
    d3mQuote = static_cast<Rate>(ui->tableWidget_RatesDeposites->item(1,1)->text().toDouble()*0.01);
    Rate d6mQuote=0.0353;
    d6mQuote = static_cast<Rate>(ui->tableWidget_RatesDeposites->item(2,1)->text().toDouble()*0.01);
    Rate d9mQuote=0.0348;
    d9mQuote = static_cast<Rate>(ui->tableWidget_RatesDeposites->item(3,1)->text().toDouble()*0.01);
    Rate d1yQuote=0.0345;
    d1yQuote = static_cast<Rate>(ui->tableWidget_RatesDeposites->item(4,1)->text().toDouble()*0.01);

    // FRAs
    Rate fra3x6Quote=0.037125;
    fra3x6Quote = static_cast<Rate>(ui->tableWidget_RatesFRAs->item(-1,1)->text().toDouble()*0.01);
    Rate fra6x9Quote=0.037125;
    fra6x9Quote = static_cast<Rate>(ui->tableWidget_RatesFRAs->item(0,1)->text().toDouble()*0.01);
    Rate fra6x12Quote=0.037125;
    fra6x12Quote = static_cast<Rate>(ui->tableWidget_RatesFRAs->item(1,1)->text().toDouble()*0.01);

    // futures
    Real fut1Quote=96.2875;
    fut1Quote = static_cast<Real>(ui->tableWidget_RatesFutures->item(-1,1)->text().toDouble());
    Real fut2Quote=96.7875;
    fut2Quote = static_cast<Real>(ui->tableWidget_RatesFutures->item(0,1)->text().toDouble());
    Real fut3Quote=96.9875;
    fut3Quote = static_cast<Real>(ui->tableWidget_RatesFutures->item(1,1)->text().toDouble());
    Real fut4Quote=96.6875;
    fut4Quote = static_cast<Real>(ui->tableWidget_RatesFutures->item(2,1)->text().toDouble());
    Real fut5Quote=96.4875;
    fut5Quote = static_cast<Real>(ui->tableWidget_RatesFutures->item(3,1)->text().toDouble());
    Real fut6Quote=96.3875;
    fut6Quote = static_cast<Real>(ui->tableWidget_RatesFutures->item(4,1)->text().toDouble());
    Real fut7Quote=96.2875;
    fut7Quote = static_cast<Real>(ui->tableWidget_RatesFutures->item(5,1)->text().toDouble());
    Real fut8Quote=96.0875;
    fut8Quote = static_cast<Real>(ui->tableWidget_RatesFutures->item(6,1)->text().toDouble());

    // swaps
    Rate s2yQuote=0.037125;
    s2yQuote = static_cast<Rate>(ui->tableWidget_RatesSwaps->item(-1,1)->text().toDouble()*0.01);
    Rate s3yQuote=0.0398;
    s3yQuote = static_cast<Rate>(ui->tableWidget_RatesSwaps->item(0,1)->text().toDouble()*0.01);
    Rate s5yQuote=0.0443;
    s5yQuote = static_cast<Rate>(ui->tableWidget_RatesSwaps->item(1,1)->text().toDouble()*0.01);
    Rate s10yQuote=0.05165;
    s10yQuote = static_cast<Rate>(ui->tableWidget_RatesSwaps->item(2,1)->text().toDouble()*0.01);
    Rate s15yQuote=0.055175;
    s15yQuote = static_cast<Rate>(ui->tableWidget_RatesSwaps->item(3,1)->text().toDouble()*0.01);


    /********************
    ***    QUOTES    ***
    ********************/

    // SimpleQuote stores a value which can be manually changed;
    // other Quote subclasses could read the value from a database
    // or some kind of data feed.

    // deposits
    boost::shared_ptr<Quote> d1wRate(new SimpleQuote(d1wQuote));
    boost::shared_ptr<Quote> d1mRate(new SimpleQuote(d1mQuote));
    boost::shared_ptr<Quote> d3mRate(new SimpleQuote(d3mQuote));
    boost::shared_ptr<Quote> d6mRate(new SimpleQuote(d6mQuote));
    boost::shared_ptr<Quote> d9mRate(new SimpleQuote(d9mQuote));
    boost::shared_ptr<Quote> d1yRate(new SimpleQuote(d1yQuote));
    // FRAs
    boost::shared_ptr<Quote> fra3x6Rate(new SimpleQuote(fra3x6Quote));
    boost::shared_ptr<Quote> fra6x9Rate(new SimpleQuote(fra6x9Quote));
    boost::shared_ptr<Quote> fra6x12Rate(new SimpleQuote(fra6x12Quote));
    // futures
    boost::shared_ptr<Quote> fut1Price(new SimpleQuote(fut1Quote));
    boost::shared_ptr<Quote> fut2Price(new SimpleQuote(fut2Quote));
    boost::shared_ptr<Quote> fut3Price(new SimpleQuote(fut3Quote));
    boost::shared_ptr<Quote> fut4Price(new SimpleQuote(fut4Quote));
    boost::shared_ptr<Quote> fut5Price(new SimpleQuote(fut5Quote));
    boost::shared_ptr<Quote> fut6Price(new SimpleQuote(fut6Quote));
    boost::shared_ptr<Quote> fut7Price(new SimpleQuote(fut7Quote));
    boost::shared_ptr<Quote> fut8Price(new SimpleQuote(fut8Quote));
    // swaps
    boost::shared_ptr<Quote> s2yRate(new SimpleQuote(s2yQuote));
    boost::shared_ptr<Quote> s3yRate(new SimpleQuote(s3yQuote));
    boost::shared_ptr<Quote> s5yRate(new SimpleQuote(s5yQuote));
    boost::shared_ptr<Quote> s10yRate(new SimpleQuote(s10yQuote));
    boost::shared_ptr<Quote> s15yRate(new SimpleQuote(s15yQuote));


    /*********************
    	***  RATE HELPERS ***
    	*********************/

    // RateHelpers are built from the above quotes together with
    // other instrument dependant infos.  Quotes are passed in
    // relinkable handles which could be relinked to some other
    // data source later.

    // deposits
    DayCounter depositDayCounter = Actual360();

    boost::shared_ptr<RateHelper> d1w(new DepositRateHelper(
                                          Handle<Quote>(d1wRate),
                                          1*Weeks, fixingDays,
                                          calendar, ModifiedFollowing,
                                          true, depositDayCounter));
    boost::shared_ptr<RateHelper> d1m(new DepositRateHelper(
                                          Handle<Quote>(d1mRate),
                                          1*Months, fixingDays,
                                          calendar, ModifiedFollowing,
                                          true, depositDayCounter));
    boost::shared_ptr<RateHelper> d3m(new DepositRateHelper(
                                          Handle<Quote>(d3mRate),
                                          3*Months, fixingDays,
                                          calendar, ModifiedFollowing,
                                          true, depositDayCounter));
    boost::shared_ptr<RateHelper> d6m(new DepositRateHelper(
                                          Handle<Quote>(d6mRate),
                                          6*Months, fixingDays,
                                          calendar, ModifiedFollowing,
                                          true, depositDayCounter));
    boost::shared_ptr<RateHelper> d9m(new DepositRateHelper(
                                          Handle<Quote>(d9mRate),
                                          9*Months, fixingDays,
                                          calendar, ModifiedFollowing,
                                          true, depositDayCounter));
    boost::shared_ptr<RateHelper> d1y(new DepositRateHelper(
                                          Handle<Quote>(d1yRate),
                                          1*Years, fixingDays,
                                          calendar, ModifiedFollowing,
                                          true, depositDayCounter));


    // setup FRAs
    boost::shared_ptr<RateHelper> fra3x6(new FraRateHelper(
            Handle<Quote>(fra3x6Rate),
            3, 6, fixingDays, calendar, ModifiedFollowing,
            true, depositDayCounter));
    boost::shared_ptr<RateHelper> fra6x9(new FraRateHelper(
            Handle<Quote>(fra6x9Rate),
            6, 9, fixingDays, calendar, ModifiedFollowing,
            true, depositDayCounter));
    boost::shared_ptr<RateHelper> fra6x12(new FraRateHelper(
            Handle<Quote>(fra6x12Rate),
            6, 12, fixingDays, calendar, ModifiedFollowing,
            true, depositDayCounter));


    // setup futures
    // Rate convexityAdjustment = 0.0;
    Integer futMonths = 3;
    Date imm = IMM::nextDate(settlementDate);
    boost::shared_ptr<RateHelper> fut1(new FuturesRateHelper(
                                           Handle<Quote>(fut1Price),
                                           imm,
                                           futMonths, calendar, ModifiedFollowing,
                                           true, depositDayCounter));
    imm = IMM::nextDate(imm+1);
    boost::shared_ptr<RateHelper> fut2(new FuturesRateHelper(
                                           Handle<Quote>(fut2Price),
                                           imm,
                                           futMonths, calendar, ModifiedFollowing,
                                           true, depositDayCounter));
    imm = IMM::nextDate(imm+1);
    boost::shared_ptr<RateHelper> fut3(new FuturesRateHelper(
                                           Handle<Quote>(fut3Price),
                                           imm,
                                           futMonths, calendar, ModifiedFollowing,
                                           true, depositDayCounter));
    imm = IMM::nextDate(imm+1);
    boost::shared_ptr<RateHelper> fut4(new FuturesRateHelper(
                                           Handle<Quote>(fut4Price),
                                           imm,
                                           futMonths, calendar, ModifiedFollowing,
                                           true, depositDayCounter));
    imm = IMM::nextDate(imm+1);
    boost::shared_ptr<RateHelper> fut5(new FuturesRateHelper(
                                           Handle<Quote>(fut5Price),
                                           imm,
                                           futMonths, calendar, ModifiedFollowing,
                                           true, depositDayCounter));
    imm = IMM::nextDate(imm+1);
    boost::shared_ptr<RateHelper> fut6(new FuturesRateHelper(
                                           Handle<Quote>(fut6Price),
                                           imm,
                                           futMonths, calendar, ModifiedFollowing,
                                           true, depositDayCounter));
    imm = IMM::nextDate(imm+1);
    boost::shared_ptr<RateHelper> fut7(new FuturesRateHelper(
                                           Handle<Quote>(fut7Price),
                                           imm,
                                           futMonths, calendar, ModifiedFollowing,
                                           true, depositDayCounter));
    imm = IMM::nextDate(imm+1);
    boost::shared_ptr<RateHelper> fut8(new FuturesRateHelper(
                                           Handle<Quote>(fut8Price),
                                           imm,
                                           futMonths, calendar, ModifiedFollowing,
                                           true, depositDayCounter));


    // setup swaps
    Frequency swFixedLegFrequency = Annual;
    BusinessDayConvention swFixedLegConvention = Unadjusted;
    DayCounter swFixedLegDayCounter = Thirty360(Thirty360::European);
    boost::shared_ptr<IborIndex> swFloatingLegIndex(new Euribor6M);

    boost::shared_ptr<RateHelper> s2y(new SwapRateHelper(
                                          Handle<Quote>(s2yRate), 2*Years,
                                          calendar, swFixedLegFrequency,
                                          swFixedLegConvention, swFixedLegDayCounter,
                                          swFloatingLegIndex));
    boost::shared_ptr<RateHelper> s3y(new SwapRateHelper(
                                          Handle<Quote>(s3yRate), 3*Years,
                                          calendar, swFixedLegFrequency,
                                          swFixedLegConvention, swFixedLegDayCounter,
                                          swFloatingLegIndex));
    boost::shared_ptr<RateHelper> s5y(new SwapRateHelper(
                                          Handle<Quote>(s5yRate), 5*Years,
                                          calendar, swFixedLegFrequency,
                                          swFixedLegConvention, swFixedLegDayCounter,
                                          swFloatingLegIndex));
    boost::shared_ptr<RateHelper> s10y(new SwapRateHelper(
                                           Handle<Quote>(s10yRate), 10*Years,
                                           calendar, swFixedLegFrequency,
                                           swFixedLegConvention, swFixedLegDayCounter,
                                           swFloatingLegIndex));
    boost::shared_ptr<RateHelper> s15y(new SwapRateHelper(
                                           Handle<Quote>(s15yRate), 15*Years,
                                           calendar, swFixedLegFrequency,
                                           swFixedLegConvention, swFixedLegDayCounter,
                                           swFloatingLegIndex));


    /*********************
    	**  CURVE BUILDING **
    	*********************/

    // Any DayCounter would be fine.
    // ActualActual::ISDA ensures that 30 years is 30.0
    DayCounter termStructureDayCounter =
        ActualActual(ActualActual::ISDA);


    double tolerance = 1.0e-15;

    // A depo-swap curve
    std::vector<boost::shared_ptr<RateHelper> > depoSwapInstruments;
    depoSwapInstruments.push_back(d1w);
    depoSwapInstruments.push_back(d1m);
    depoSwapInstruments.push_back(d3m);
    depoSwapInstruments.push_back(d6m);
    depoSwapInstruments.push_back(d9m);
    depoSwapInstruments.push_back(d1y);
    depoSwapInstruments.push_back(s2y);
    depoSwapInstruments.push_back(s3y);
    depoSwapInstruments.push_back(s5y);
    depoSwapInstruments.push_back(s10y);
    depoSwapInstruments.push_back(s15y);
    boost::shared_ptr<YieldTermStructure> depoSwapTermStructure(
        new PiecewiseYieldCurve<Discount,LogLinear>(
            settlementDate, depoSwapInstruments,
            termStructureDayCounter,
            tolerance));


    // A depo-futures-swap curve
    std::vector<boost::shared_ptr<RateHelper> > depoFutSwapInstruments;
    depoFutSwapInstruments.push_back(d1w);
    depoFutSwapInstruments.push_back(d1m);
    depoFutSwapInstruments.push_back(fut1);
    depoFutSwapInstruments.push_back(fut2);
    depoFutSwapInstruments.push_back(fut3);
    depoFutSwapInstruments.push_back(fut4);
    depoFutSwapInstruments.push_back(fut5);
    depoFutSwapInstruments.push_back(fut6);
    depoFutSwapInstruments.push_back(fut7);
    depoFutSwapInstruments.push_back(fut8);
    depoFutSwapInstruments.push_back(s3y);
    depoFutSwapInstruments.push_back(s5y);
    depoFutSwapInstruments.push_back(s10y);
    depoFutSwapInstruments.push_back(s15y);
    boost::shared_ptr<YieldTermStructure> depoFutSwapTermStructure(
        new PiecewiseYieldCurve<Discount,LogLinear>(
            settlementDate, depoFutSwapInstruments,
            termStructureDayCounter,
            tolerance));


    // A depo-FRA-swap curve
    std::vector<boost::shared_ptr<RateHelper> > depoFRASwapInstruments;
    depoFRASwapInstruments.push_back(d1w);
    depoFRASwapInstruments.push_back(d1m);
    depoFRASwapInstruments.push_back(d3m);
    depoFRASwapInstruments.push_back(fra3x6);
    depoFRASwapInstruments.push_back(fra6x9);
    depoFRASwapInstruments.push_back(fra6x12);
    depoFRASwapInstruments.push_back(s2y);
    depoFRASwapInstruments.push_back(s3y);
    depoFRASwapInstruments.push_back(s5y);
    depoFRASwapInstruments.push_back(s10y);
    depoFRASwapInstruments.push_back(s15y);
    boost::shared_ptr<YieldTermStructure> depoFRASwapTermStructure(
        new PiecewiseYieldCurve<Discount,LogLinear>(
            settlementDate, depoFRASwapInstruments,
            termStructureDayCounter,
            tolerance));


    // Term structures that will be used for pricing:
    // the one used for discounting cash flows
    RelinkableHandle<YieldTermStructure> discountingTermStructure;
    // the one used for forward rate forecasting
    RelinkableHandle<YieldTermStructure> forecastingTermStructure;


    /*********************
    * SWAPS TO BE PRICED *
    **********************/

    // constant nominal 1,000,000 Euro
    /////■ Real nominal = 1000000.0;
    Real nominal = static_cast<Real>(ui->doubleSpinBox_Notional->value());

    // fixed leg
    /////■ Frequency fixedLegFrequency = Annual;
    Frequency fixedLegFrequency = Annual;
    /////■ BusinessDayConvention fixedLegConvention = Unadjusted;
    BusinessDayConvention fixedLegConvention = Unadjusted;
    /////■ DayCounter fixedLegDayCounter = Thirty360(Thirty360::European);
    DayCounter fixedLegDayCounter = Thirty360(Thirty360::European);
    /////■ Rate fixedRate = 0.04;
    Rate fixedRate = static_cast<Real>((ui->doubleSpinBox_fixedRate->value())*0.01);

    // floating leg
    /////■ Frequency floatingLegFrequency = Semiannual;
    Frequency floatingLegFrequency = Semiannual;
    int comboBoxFloatingLegFrequency = ui->comboBox_FloatingLegFrequency->currentIndex();
    switch(comboBoxFloatingLegFrequency) {
    case 0: // Semiannual
        floatingLegFrequency = Semiannual;
        break;
    case 1: // Annual
        floatingLegFrequency = Annual;
        break;
    case 2: // Quarterly
        floatingLegFrequency = Quarterly;
        break;
    }

    /////■ BusinessDayConvention floatingLegConvention = ModifiedFollowing;
    BusinessDayConvention floatingLegConvention = ModifiedFollowing;
    /////■ DayCounter floatingLegDayCounter = Actual360();
    DayCounter floatingLegDayCounter = Actual360();

    boost::shared_ptr<IborIndex> euriborIndex(
        new Euribor6M(forecastingTermStructure));
    /////■ Spread spread = 0.0;
    Spread spread = static_cast<Spread>((ui->doubleSpinBox_spread->value())*0.01);
    /////■ Integer lenghtInYears = 5;
    Integer lenghtInYears =  (Integer)(ui->doubleSpinBox_lenghtInYears->value());
    /////■ VanillaSwap::Type swapType = VanillaSwap::Payer;
    int comboBoxPayerReceiver = ui->comboBox_swapType->currentIndex();
    VanillaSwap::Type swapType = VanillaSwap::Receiver;
    switch(comboBoxPayerReceiver) {
    case 0: // Fix Payer
        swapType = VanillaSwap::Payer;
        break; // VanillaSwap::Payer=1
    case 1: // Fix Receiver
        swapType = VanillaSwap::Receiver;
        break; // VanillaSwap::Receiver=-1
    }

    Date maturity = settlementDate + lenghtInYears*Years;
    Schedule fixedSchedule(settlementDate, maturity,
                           Period(fixedLegFrequency),
                           calendar, fixedLegConvention,
                           fixedLegConvention,
                           DateGeneration::Forward, false);
    Schedule floatSchedule(settlementDate, maturity,
                           Period(floatingLegFrequency),
                           calendar, floatingLegConvention,
                           floatingLegConvention,
                           DateGeneration::Forward, false);
    VanillaSwap spot5YearSwap(swapType, nominal,
                              fixedSchedule, fixedRate, fixedLegDayCounter,
                              floatSchedule, euriborIndex, spread,
                              floatingLegDayCounter);

    Date fwdStart = calendar.advance(settlementDate, 1, Years);
    Date fwdMaturity = fwdStart + lenghtInYears*Years;
    Schedule fwdFixedSchedule(fwdStart, fwdMaturity,
                              Period(fixedLegFrequency),
                              calendar, fixedLegConvention,
                              fixedLegConvention,
                              DateGeneration::Forward, false);
    Schedule fwdFloatSchedule(fwdStart, fwdMaturity,
                              Period(floatingLegFrequency),
                              calendar, floatingLegConvention,
                              floatingLegConvention,
                              DateGeneration::Forward, false);
    VanillaSwap oneYearForward5YearSwap(swapType, nominal,
                                        fwdFixedSchedule, fixedRate, fixedLegDayCounter,
                                        fwdFloatSchedule, euriborIndex, spread,
                                        floatingLegDayCounter);


    /***************
    * SWAP PRICING *
    ****************/

    Real NPV;
    Rate fairRate;
    Spread fairSpread;

    boost::shared_ptr<PricingEngine> swapEngine(
        new DiscountingSwapEngine(discountingTermStructure));

    spot5YearSwap.setPricingEngine(swapEngine);
    oneYearForward5YearSwap.setPricingEngine(swapEngine);

    int swapTermStructureType(0);
    swapTermStructureType = ui->comboBox_TermStructureType->currentIndex();
    //QMessageBox msgBoxTmp(this); msgBoxTmp.setText(QString::number(swapTermStructureType)); msgBoxTmp.exec();
    switch(swapTermStructureType) {
    case 0:
        forecastingTermStructure.linkTo(depoSwapTermStructure);
        discountingTermStructure.linkTo(depoSwapTermStructure);
        break;
    case 1:
        forecastingTermStructure.linkTo(depoFutSwapTermStructure);
        discountingTermStructure.linkTo(depoFutSwapTermStructure);
        break;
    case 2:
        forecastingTermStructure.linkTo(depoFRASwapTermStructure);
        discountingTermStructure.linkTo(depoFRASwapTermStructure);
        break;
    }

    NPV = spot5YearSwap.NPV();
    fairRate = spot5YearSwap.fairRate();
    fairSpread = spot5YearSwap.fairSpread();


    ui->lineEdit_SwapNPV->setText(QString::number(static_cast<double>(NPV),'f'));
    ui->lineEdit_SwapFairRate->setText(QString::number(static_cast<double>(fairRate*100.0),'f'));
    ui->lineEdit_SwapFairSpread->setText(QString::number(static_cast<double>(fairSpread*100.0),'f'));


}
void MainWindow::updateFinancialMonthText()
{
    QDate date = ui->calendar->selectedDate();
    ui->label_financeMonthE->setText(QDate::longMonthName(date.month()) + ' ' + toString(date.year()).c_str());
}
Esempio n. 22
0
/*!
  \internal
*/
int Event::monthDiff( const QDate& first, const QDate& second )
{
    return ( second.year() - first.year() ) * 12 +
        second.month() - first.month();
}
Esempio n. 23
0
//! [17]
void MainWindow::setYear(QDate date)
{
    selectedDate = QDate(date.year(), selectedDate.month(), selectedDate.day());
    insertCalendar();
}
Esempio n. 24
0
//
// Manage the seasons array
//
void
Seasons::readSeasons()
{
    QFile seasonFile(home.absolutePath() + "/seasons.xml");
    QXmlInputSource source( &seasonFile );
    QXmlSimpleReader xmlReader;
    SeasonParser handler;
    xmlReader.setContentHandler(&handler);
    xmlReader.setErrorHandler(&handler);
    xmlReader.parse( source );
    seasons = handler.getSeasons();

    Season season;
    QDate today = QDate::currentDate();
    QDate eom = QDate(today.year(), today.month(), today.daysInMonth());

    // add Default Date Ranges
    season.setName(tr("All Dates"));
    season.setType(Season::temporary);
    season.setStart(QDate::currentDate().addYears(-50));
    season.setEnd(QDate::currentDate().addYears(50));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000001}"));
    seasons.append(season);

    season.setName(tr("This Year"));
    season.setType(Season::temporary);
    season.setStart(QDate(today.year(), 1,1));
    season.setEnd(QDate(today.year(), 12, 31));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000002}"));
    seasons.append(season);

    season.setName(tr("This Month"));
    season.setType(Season::temporary);
    season.setStart(QDate(today.year(), today.month(),1));
    season.setEnd(eom);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000003}"));
    seasons.append(season);

    season.setName(tr("This Week"));
    season.setType(Season::temporary);
    // from Mon-Sun
    QDate wstart = QDate::currentDate();
    wstart = wstart.addDays(Qt::Monday - wstart.dayOfWeek());
    QDate wend = wstart.addDays(6); // first day + 6 more
    season.setStart(wstart);
    season.setEnd(wend);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000004}"));
    seasons.append(season);

    season.setName(tr("Last 7 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-6)); // today plus previous 6
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000005}"));
    seasons.append(season);

    season.setName(tr("Last 14 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-13));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000006}"));
    seasons.append(season);

    season.setName(tr("Last 21 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-20));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000011}"));
    seasons.append(season);

    season.setName(tr("Last 28 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-27));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000007}"));
    seasons.append(season);

    season.setName(tr("Last 3 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-3));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000008}"));
    seasons.append(season);

    season.setName(tr("Last 6 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-6));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000009}"));
    seasons.append(season);

    season.setName(tr("Last 12 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-12));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000010}"));
    seasons.append(season);

    seasonsChanged(); // signal!
}
Esempio n. 25
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. 26
0
//Sets the maximum year for birth- and death-input equal to current year
void AddCS::setMaxYear(){
    QDate today = QDate::currentDate();
    int year = today.year();
    ui->input_cs_yob->setMaximum(year);
    ui->input_cs_yod->setMaximum(year);
}
Esempio n. 27
0
// =====================================================================
// DUMP alle Tabellen oder eine einzelne Tabelle
// ---------------------------------------------
void admin::dbDump()
{
    if(SavePathEdit->text().count() == 0) {       // ist ein Path gewaehlt ?
      QMessageBox::information( this,
        tr("INFO"),
        tr("\nBitte DUMP-Ordner waehlen !!"),
        QMessageBox::Ok);
      return;
    }
        QString pathToMysql="";
#ifdef Q_WS_WIN
    pathToMysql=settings.value("mySQLPath","").toString();
#endif
    if(checkBoxDb->isChecked() == TRUE ) {     // gesetzt - Alle Tabellen Dumpen
        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
        s = pathToMysql+"mysqldump -u"+settings.value("dbuser").toString()+" -p";
        s += settings.value("dbpasswd").toString();
        s += " --opt "+settings.value("dbname").toString()+" > "+SavePathEdit->text()+"backup-db.sql"; 
        StartProcess(s.toAscii());
        QApplication::restoreOverrideCursor();
    }
    else {                                   // LOG_tabelle dumpen
       QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
       if(lItem) {
         s = pathToMysql+"mysqldump -u"+settings.value("dbuser").toString()+" -p"+settings.value("dbpasswd").toString()+" --opt "+settings.value("dbname").toString()+" ";
          s += lItem->text(0)+" ";          // fun
          s += lItem->text(0)+"qsl ";       // fun_qsl
          s += lItem->text(0)+"om ";        // fun_om
          s += lItem->text(0)+"awd ";       // fun_awd
          s += lItem->text(0)+"card ";      // fun_qslcard
          s += lItem->text(0)+"dx ";        // fun_dx
          s += "wawdlist > ";               
          s+= SavePathEdit->text()+"backup-"+lItem->text(0)+".sql";
          StartProcess(s.toAscii());         // DUMP
	  
          QString tag, monat, jahr, dform;
          QDate d = QDate::currentDate();   // Datum von heute
          tag = s.setNum(d.day());
          monat = s.setNum(d.month());
          jahr = s.setNum(d.year());
	  
          if(tag.count() < 2) tag = "0"+tag;
          if(monat.count() < 2) monat = "0"+monat;
	  
          // Datum_Datensicherung
          qy = "UPDATE dblogs SET saved='"+jahr+"-"+monat+"-"+tag;
          qy += "' WHERE logname='"+lItem->text(0)+"'";
          QSqlQuery query;
          query.exec(qy);
          s = jahr+"-"+monat+"-"+tag;
          lItem->setText(3,s);
       }
       else
         if(sItem) {                          // System_tabelle dumpen
            s = pathToMysql + "mysqldump -u"+settings.value("dbuser").toString()+" -p"+settings.value("dbpasswd").toString()+" --opt "+settings.value("dbname").toString();
            s += " "+sItem->text(0)+" > ";
            s+= SavePathEdit->text()+"backup-"+sItem->text(0)+".sql";
            StartProcess(s.toAscii());        // DUMP
         }
       else {
          QApplication::restoreOverrideCursor();
          QMessageBox::information( this,
          tr("INFO"),
          tr("\nErst eine Tabelle im Logbook- oder QtLog-Ordner waehlen"),
          QMessageBox::Ok);
          return;
       }
    }
    
    s = "cp "+QDir::homePath();             // sichere immer auch qtlog.ini
    s += "/.config/QtLog/qtlog.ini "+SavePathEdit->text();
    StartProcess(s.toAscii());
    
    QApplication::restoreOverrideCursor();
}
Esempio n. 28
0
void MainWindow::change_graph(int i)
{
    QDate simera;
    simera=QDate::currentDate();
    QList <int> minut;
    QList <QString> label;
    QSqlQuery query(db1);

    switch(i)
    {

    case 0:
    {
        int dayno=simera.dayOfWeek();


        for (int i=0;i<dayno;++i)
        {

            query.exec("select dayname(start_time),sum(TIMESTAMPDIFF(MINUTE,t.start_time,t.end_time)) from tasks t where date(start_time)='"+simera.addDays(-i).toString("yy/M/d")+"' group by dayname(start_time)");
            if(query.next())
            {

                minut.prepend(query.value(1).toInt());
                label.prepend(query.value(0).toString());
            }

        }

        //if(query.size()>=0)
        //{
        //WeekGraph *drb=new WeekGraph(this);
        drb->set_list(minut,label);

        //drb->setFixedWidth(611);
        // drb->setFixedHeight(181);
        drb->repaint();
        //}
        break;
    }

    case 1:
    {

        QVariant month,year;
        for (int i=1;i<=simera.month();++i)
        {
            month=i;
            year=simera.year();

            query.exec("select monthname(start_time),sum(TIMESTAMPDIFF(MINUTE,t.start_time,t.end_time)) from tasks t where month(start_time)="+month.toString()+" and year(start_time)="+year.toString()+" group by monthname(start_time)");
            if(query.next())
            {
            minut.append(query.value(1).toInt());
            label.append(query.value(0).toString());
            }
        }
        if(query.size()>0)
        {
        drb->set_list(minut,label);
        drb->repaint();
        }
        break;
    }

    case 2:
    {
        query.exec("select max(year(start_time))-2 from tasks");
        query.next();
        QVariant min_year=query.value(0);
        query.exec("select max(year(start_time)) from tasks");
        query.next();
        QVariant max_year=query.value(0);
        QVariant month,year;
        for (int i=min_year.toInt();i<=max_year.toInt();++i)
        {
            year=i;

            for (int j=1;j<=12;++j)
            {
                month=j;
                query.exec("select concat_ws('/',month(start_time),substr(year(start_time) from 3)),sum(TIMESTAMPDIFF(MINUTE,t.start_time,t.end_time)) from tasks t where month(start_time)="+month.toString()+" and year(start_time)="+year.toString()+" group by concat_ws('/',month(start_time),substr(year(start_time) from 3))");

                if (query.next())
                {
                    minut.append(query.value(1).toInt());
                    label.append(query.value(0).toString());
                }
            }
            drb->set_list(minut,label);
            drb->repaint();
        }

    }


    }
}
Esempio n. 29
0
Date::Date(const QDate& D){
    this->setDate(D.year(), D.month(), D.day());
}
Esempio n. 30
0
QByteArray contactToXML(const ContactPtr& contact)
{
    QByteArray output;

    QStringList parsedCustoms;

    /* Name */
    output.append("<gd:name>");
    if (!contact->givenName().isEmpty()) {
        output.append("<gd:givenName>").append(Qt::escape(contact->givenName()).toUtf8()).append("</gd:givenName>");
    }
    if (!contact->familyName().isEmpty()) {
        output.append("<gd:familyName>").append(Qt::escape(contact->familyName()).toUtf8()).append("</gd:familyName>");
    }
    if (!contact->assembledName().isEmpty()) {
        output.append("<gd:fullName>").append(Qt::escape(contact->assembledName()).toUtf8()).append("</gd:fullName>");
    }
    if (!contact->additionalName().isEmpty()) {
        output.append("<gd:additionalName>").append(Qt::escape(contact->additionalName()).toUtf8()).append("</gd:additionalName>");
    }
    if (!contact->prefix().isEmpty()) {
        output.append("<gd:namePrefix>").append(Qt::escape(contact->prefix()).toUtf8()).append("</gd:namePrefix>");
    }
    if (!contact->suffix().isEmpty()) {
        output.append("<gd:nameSuffix>").append(Qt::escape(contact->suffix()).toUtf8()).append("</gd:nameSuffix>");
    }
    output.append("</gd:name>");

    /* Notes */
    if (!contact->note().isEmpty()) {
        output.append("<atom:content type='text'>").append(Qt::escape(contact->note()).toUtf8()).append("</atom:content>");
    }

    /* Organization (work) */
    QByteArray org;
    const QString office = contact->office();
    if (!contact->organization().isEmpty()) {
        org.append("<gd:orgName>").append(Qt::escape(contact->organization()).toUtf8()).append("</gd:orgName>");
    }
    if (!contact->department().isEmpty()) {
        org.append("<gd:orgDepartment>").append(Qt::escape(contact->department()).toUtf8()).append("</gd:orgDepartment>");
    }
    if (!contact->title().isEmpty()) {
        org.append("<gd:orgTitle>").append(Qt::escape(contact->title()).toUtf8()).append("</gd:orgTitle>");
    }
    if (!office.isEmpty()) {
        org.append("<gd:where>").append(Qt::escape(office).toUtf8()).append("</gd:where>");
        parsedCustoms << QStringLiteral("KADDRESSBOOK-X-Office");
    }
    if (!org.isEmpty()) {
        output.append("<gd:organization rel=\"http://schemas.google.com/g/2005#work\">").append(org).append("</gd:organization>");
    }

    /* Nickname */
    if (!contact->nickName().isEmpty()) {
        output.append("<gContact:nickname>").append(Qt::escape(contact->nickName()).toUtf8()).append("</gContact:nickname>");
    }

    /* Occupation */
    if (!contact->profession().isEmpty()) {
        output.append("<gContact:occupation>").append(Qt::escape(contact->profession()).toUtf8()).append("</gContact:occupation>");
        parsedCustoms << QStringLiteral("KADDRESSBOOK-X-Profession");
    }

    /* Spouse */
    const QString spouse = contact->spousesName();
    if (!spouse.isEmpty()) {
        output.append("<gContact:relation rel=\"spouse\">").append(Qt::escape(spouse).toUtf8()).append("</gContact:relation>");
        parsedCustoms << QStringLiteral("KADDRESSBOOK-X-SpousesName");
    }

    /* Manager */
    const QString manager = contact->managersName();
    if (!manager.isEmpty()) {
        output.append("<gContact:relation rel=\"manager\">").append(Qt::escape(manager).toUtf8()).append("</gContact:relation>");
        parsedCustoms << QStringLiteral("KADDRESSBOOK-X-ManagersName");
    }

    /* Assistant */
    const QString assistant = contact->assistantsName();
    if (!assistant.isEmpty()) {
        output.append("<gContact:relation rel=\"assistant\">").append(Qt::escape(assistant).toUtf8()).append("</gContact:relation>");
        parsedCustoms << QStringLiteral("KADDRESSBOOK-X-AssistantsName");
    }

    /* Anniversary */
    const QString anniversary = contact->anniversary();
    if (!anniversary.isEmpty()) {
        output.append("<gContact:event rel=\"anniversary\"><gd:when startTime=\"").append(Qt::escape(anniversary).toUtf8()).append("\" /></gContact:event>");
        parsedCustoms << QStringLiteral("KADDRESSBOOK-X-Anniversary");
    }

    /* Homepage */
    if (!contact->url().url().isEmpty()) {
        output.append("<gContact:website rel=\"home-page\" href=\"").append(Qt::escape(contact->url().toString()).toUtf8()).append("\" />");
    }

    /* Blog */
    const QString blog = contact->blogFeed();
    if (!blog.isEmpty()) {
        output.append("<gContact:website rel=\"blog\" href=\"").append(Qt::escape(blog).toUtf8()).append("\" />");
        parsedCustoms << QStringLiteral("KADDRESSBOOK-BlogFeed");
    }

    /* Emails */
    Q_FOREACH(const QString &email, contact->emails()) {
        output.append("<gd:email rel='http://schemas.google.com/g/2005#home' address='").append(Qt::escape(email).toUtf8()).append("' />");
    }

    /* IMs */
    const QString im_str = QStringLiteral("<gd:im address=\"%1\" protocol=\"%2\" rel=\"http://schemas.google.com/g/2005#other\" primary=\"%3\"/>");
    Q_FOREACH(const QString &im, contact->customs()) {
        if (im.startsWith(QLatin1String("messaging/"))) {
            QString key = im.left(im.indexOf(QLatin1Char(':')));
            QString value = im.mid(im.indexOf(QLatin1Char(':')) + 1);
            QString proto = key.mid(10);
            proto.chop(4);
            bool primary = (contact->custom(QStringLiteral("KADDRESSBOOK"), QStringLiteral("X-IMAddress")) == value);
            output.append(im_str.arg(value, Contact::IMProtocolNameToScheme(proto),
                                     (primary ? QStringLiteral("true") : QStringLiteral("false"))).toUtf8());
            parsedCustoms << key;
        /* X-messaging is probably a new key (?) used by KAddressbook when importing
         * contacts from vCard. */
        } else if (im.startsWith(QLatin1String("X-messaging"))) {
            const QString key = im.left(im.indexOf(QLatin1Char(':')));
            const QString value = im.mid(im.indexOf(QLatin1Char(':')) + 1);
            QString proto = key.mid(12); /* strlen("X-messaging/") */
            if (proto.endsWith(QLatin1String("-All"))) {
                proto.chop(4);
            }
            output.append(im_str.arg(value, proto, QStringLiteral("false")).toUtf8());
            parsedCustoms << key;
        }
    }
    parsedCustoms << QStringLiteral("KADDRESSBOOK-X-IMAddress");

    /* Phone numbers */
    const QString phone_str = QStringLiteral("<gd:phoneNumber rel=\"%1\">%2</gd:phoneNumber>");
    Q_FOREACH(const KContacts::PhoneNumber &number, contact->phoneNumbers()) {
        output.append(phone_str.arg(Contact::phoneTypeToScheme(number.type()), number.number()).toUtf8());
    }

    /* Address */
    Q_FOREACH(const KContacts::Address &address, contact->addresses()) {
        output.append("<gd:structuredPostalAddress rel='")
        .append(Contact::addressTypeToScheme(address.type()).toUtf8())
        .append("'>");

        if (!address.locality().isEmpty())
            output.append("<gd:city>").append(Qt::escape(address.locality()).toUtf8()).append("</gd:city>");
        if (!address.street().isEmpty())
            output.append("<gd:street>").append(Qt::escape(address.street()).toUtf8()).append("</gd:street>");
        if (!address.region().isEmpty())
            output.append("<gd:region>").append(Qt::escape(address.region()).toUtf8()).append("</gd:region>");
        if (!address.postalCode().isEmpty())
            output.append("<gd:postcode>").append(Qt::escape(address.postalCode()).toUtf8()).append("</gd:postcode>");
        if (!address.country().isEmpty())
            output.append("<gd:country>").append(Qt::escape(address.country()).toUtf8()).append("</gd:country>");
        if (!address.formattedAddress().isEmpty())
            output.append("<gd:formattedAddress>").append(Qt::escape(address.formattedAddress()).toUtf8()).append("</gd:formattedAddress>");
        output.append("</gd:structuredPostalAddress>");
    }

    /* Birthday */
    const QDate birthday = contact->birthday().date();
    if (birthday.isValid()) {
        QString birthdayStr;
        /* We use year 1900 as a fake year for birthdays without a year specified.
            * Here we assume that nobody actually has a contact born in 1900 and so
            * we replace 1900 by "-", so that we get "--MM-dd" date, which is a valid
            * birthday date according to RFC6350 */
        if (birthday.year() == 1900) {
            birthdayStr = birthday.toString(QStringLiteral("--MM-dd"));
        } else {
            birthdayStr = birthday.toString(QStringLiteral("yyyy-MM-dd"));
        }
        output.append("<gContact:birthday when='").append(birthdayStr.toUtf8()).append("'/>");
    }

    const QStringList groups = contact->custom(QStringLiteral("GCALENDAR"), QStringLiteral("groupMembershipInfo")).split(QLatin1Char(','));
    qCDebug(KGAPIDebug) << groups;
    if ((groups.length() > 0) && !groups.at(0).isEmpty()) {
        Q_FOREACH(const QString & group, groups) {
            bool removed = contact->groupIsDeleted(group);
            if (!removed)
                output.append(QStringLiteral("<gContact:groupMembershipInfo deleted=\"false\" href=\"%2\" />").arg(group).toUtf8());
        }