struct tsp * readmsg(int type, char *machfrom, struct timeval *intvl, struct netinfo *netfrom) { int length; fd_set ready; static struct tsplist *head = &msgslist; static struct tsplist *tail = &msgslist; static int msgcnt = 0; struct tsplist *prev; struct netinfo *ntp; struct tsplist *ptr; ssize_t n; if (trace) { fprintf(fd, "readmsg: looking for %s from %s, %s\n", tsptype[type], machfrom == NULL ? "ANY" : machfrom, netfrom == NULL ? "ANYNET" : inet_ntoa(netfrom->net)); if (head->p != 0) { length = 1; for (ptr = head->p; ptr != 0; ptr = ptr->p) { /* do not repeat the hundreds of messages */ if (++length > 3) { if (ptr == tail) { fprintf(fd,"\t ...%d skipped\n", length); } else { continue; } } fprintf(fd, length > 1 ? "\t" : "queue:\t"); print(&ptr->info, &ptr->addr); } } } ptr = head->p; prev = head; /* * Look for the requested message scanning through the * linked list. If found, return it and free the space */ while (ptr != NULL) { if (LOOKAT(ptr->info, type, machfrom, netfrom, ptr->addr)) { again: msgin = ptr->info; from = ptr->addr; from_when = ptr->when; prev->p = ptr->p; if (ptr == tail) tail = prev; free((char *)ptr); fromnet = NULL; if (netfrom == NULL) for (ntp = nettab; ntp != NULL; ntp = ntp->next) { if ((ntp->mask & from.sin_addr.s_addr) == ntp->net.s_addr) { fromnet = ntp; break; } } else fromnet = netfrom; if (trace) { fprintf(fd, "readmsg: found "); print(&msgin, &from); } /* The protocol can get far behind. When it does, it gets * hopelessly confused. So delete duplicate messages. */ for (ptr = prev; (ptr = ptr->p) != NULL; prev = ptr) { if (ptr->addr.sin_addr.s_addr == from.sin_addr.s_addr && ptr->info.tsp_type == msgin.tsp_type) { if (trace) fprintf(fd, "\tdup "); goto again; } } msgcnt--; return(&msgin); } else { prev = ptr; ptr = ptr->p; } } /* * If the message was not in the linked list, it may still be * coming from the network. Set the timer and wait * on a select to read the next incoming message: if it is the * right one, return it, otherwise insert it in the linked list. */ gettimeofday(&rtout, 0); timevaladd(&rtout, intvl); FD_ZERO(&ready); for (;;) { gettimeofday(&rtime, 0); timevalsub(&rwait, &rtout, &rtime); if (rwait.tv_sec < 0) rwait.tv_sec = rwait.tv_usec = 0; else if (rwait.tv_sec == 0 && rwait.tv_usec < 1000000/CLK_TCK) rwait.tv_usec = 1000000/CLK_TCK; if (trace) { fprintf(fd, "readmsg: wait %ld.%6ld at %s\n", rwait.tv_sec, rwait.tv_usec, date()); /* Notice a full disk, as we flush trace info. * It is better to flush periodically than at * every line because the tracing consists of bursts * of many lines. Without care, tracing slows * down the code enough to break the protocol. */ if (rwait.tv_sec != 0 && EOF == fflush(fd)) traceoff("Tracing ended for cause at %s\n"); } FD_SET(sock, &ready); if (!select(sock+1, &ready, NULL, NULL, &rwait)) { if (rwait.tv_sec == 0 && rwait.tv_usec == 0) return(0); continue; } length = sizeof(from); if ((n = recvfrom(sock, (char *)&msgin, sizeof(struct tsp), 0, (struct sockaddr*)&from, &length)) < 0) { syslog(LOG_ERR, "recvfrom: %m"); exit(1); } /* * The 4.3BSD protocol spec had a 32-byte tsp_name field, and * this is still OS-dependent. Demand that the packet is at * least long enough to hold a 4.3BSD packet. */ if (n < (ssize_t)(sizeof(struct tsp) - MAXHOSTNAMELEN + 32)) { syslog(LOG_NOTICE, "short packet (%zd/%zu bytes) from %s", n, sizeof(struct tsp) - MAXHOSTNAMELEN + 32, inet_ntoa(from.sin_addr)); continue; } gettimeofday(&from_when, NULL); bytehostorder(&msgin); if (msgin.tsp_vers > TSPVERSION) { if (trace) { fprintf(fd,"readmsg: version mismatch\n"); /* should do a dump of the packet */ } continue; } if (memchr(msgin.tsp_name, '\0', sizeof msgin.tsp_name) == NULL) { syslog(LOG_NOTICE, "hostname field not NUL terminated " "in packet from %s", inet_ntoa(from.sin_addr)); continue; } fromnet = NULL; for (ntp = nettab; ntp != NULL; ntp = ntp->next) if ((ntp->mask & from.sin_addr.s_addr) == ntp->net.s_addr) { fromnet = ntp; break; } /* * drop packets from nets we are ignoring permanently */ if (fromnet == NULL) { /* * The following messages may originate on * this host with an ignored network address */ if (msgin.tsp_type != TSP_TRACEON && msgin.tsp_type != TSP_SETDATE && msgin.tsp_type != TSP_MSITE && msgin.tsp_type != TSP_TEST && msgin.tsp_type != TSP_TRACEOFF) { if (trace) { fprintf(fd,"readmsg: discard null net "); print(&msgin, &from); } continue; } } /* * Throw away messages coming from this machine, * unless they are of some particular type. * This gets rid of broadcast messages and reduces * master processing time. */ if (!strcmp(msgin.tsp_name, hostname) && msgin.tsp_type != TSP_SETDATE && msgin.tsp_type != TSP_TEST && msgin.tsp_type != TSP_MSITE && msgin.tsp_type != TSP_TRACEON && msgin.tsp_type != TSP_TRACEOFF && msgin.tsp_type != TSP_LOOP) { if (trace) { fprintf(fd, "readmsg: discard own "); print(&msgin, &from); } continue; } /* * Send acknowledgements here; this is faster and * avoids deadlocks that would occur if acks were * sent from a higher level routine. Different * acknowledgements are necessary, depending on * status. */ if (fromnet == NULL) /* do not de-reference 0 */ ignoreack(); else if (fromnet->status == MASTER) masterack(); else if (fromnet->status == SLAVE) slaveack(); else ignoreack(); if (LOOKAT(msgin, type, machfrom, netfrom, from)) { if (trace) { fprintf(fd, "readmsg: "); print(&msgin, &from); } return(&msgin); } else if (++msgcnt > NHOSTS*3) { /* The protocol gets hopelessly confused if it gets too far * behind. However, it seems able to recover from all cases of lost * packets. Therefore, if we are swamped, throw everything away. */ if (trace) fprintf(fd, "readmsg: discarding %d msgs\n", msgcnt); msgcnt = 0; while ((ptr=head->p) != NULL) { head->p = ptr->p; free((char *)ptr); } tail = head; } else { tail->p = (struct tsplist *) malloc(sizeof(struct tsplist)); tail = tail->p; tail->p = NULL; tail->info = msgin; tail->addr = from; /* timestamp msgs so SETTIMEs are correct */ tail->when = from_when; } } }
void datum_to_bson(const char* field_name, mongo::BSONObjBuilder& builder, Datum val, bool is_null, Oid typid) { PGBSON_LOG << "BEGIN datum_to_bson, field_name=" << field_name << ", typeid=" << typid << PGBSON_ENDL; if (field_name == NULL) { field_name = ""; } if (is_null) { builder.appendNull(field_name); } else { switch(typid) { case BOOLOID: builder.append(field_name, DatumGetBool(val)); break; case CHAROID: { char c = DatumGetChar(val); builder.append(field_name, &c, 1); break; } case INT8OID: builder.append(field_name, (long long)DatumGetInt64(val)); break; case INT2OID: builder.append(field_name, DatumGetInt16(val)); break; case INT4OID: builder.append(field_name, DatumGetInt32(val)); break; case TEXTOID: case JSONOID: case XMLOID: { text* t = DatumGetTextP(val); builder.append(field_name, VARDATA(t), VARSIZE(t)-VARHDRSZ+1); break; } case FLOAT4OID: builder.append(field_name, DatumGetFloat4(val)); break; case FLOAT8OID: builder.append(field_name, DatumGetFloat8(val)); break; case RECORDOID: { mongo::BSONObjBuilder sub(builder.subobjStart(field_name)); composite_to_bson(sub, val); sub.done(); break; } case TIMESTAMPOID: { Timestamp ts = DatumGetTimestamp(val); #ifdef HAVE_INT64_TIMESTAMP mongo::Date_t date(ts); #else mongo::Date_t date(ts * 1000); #endif builder.append(field_name, date); break; } default: { PGBSON_LOG << "datum_to_bson - unknown type, using text output." << PGBSON_ENDL; PGBSON_LOG << "datum_to_bson - type=" << get_typename(typid) << PGBSON_ENDL; if (get_typename(typid) == "bson") { bytea* data = DatumGetBson(val); mongo::BSONObj obj(VARDATA_ANY(data)); builder.append(field_name, obj); } else { // use text output for the type bool typisvarlena = false; Oid typoutput; getTypeOutputInfo(typid, &typoutput, &typisvarlena); PGBSON_LOG << "datum_to_bson - typisvarlena=" << std::boolalpha << typisvarlena << PGBSON_ENDL; Datum out_val = val; /* * If we have a toasted datum, forcibly detoast it here to avoid * memory leakage inside the type's output routine. */ if (typisvarlena) { out_val = PointerGetDatum(PG_DETOAST_DATUM(val)); PGBSON_LOG << "datum_to_bson - var len valuie detoasted" << PGBSON_ENDL; } char* outstr = OidOutputFunctionCall(typoutput, out_val); builder.append(field_name, outstr); /* Clean up detoasted copy, if any */ if (val != out_val) pfree(DatumGetPointer(out_val)); } } } // switch } // if not null PGBSON_LOG << "END datum_to_bson, field_name=" << field_name << PGBSON_ENDL; }
void Main_Window::ADDREVIEW() { if(DateLine->text().isEmpty() || TextLine->text().isEmpty() || RatingLine->text().isEmpty()) { QMessageBox::warning(this, "Error Add Review", "ENTER SOMETHING IN DATE, TEXT REVIEW, AND RATING"); } else if(RatingLine->text().isEmpty() == false && (DateLine->text().isEmpty() == false && TextLine->text().isEmpty() == false)) { std::string date (DateLine->text().toStdString()); int rating1 (RatingLine->text().toInt()); std::string text (TextLine->text().toStdString()); if(rating1 <1 || rating1 >5) { QMessageBox::warning(this, "ERROR", "DID NOT ENTER VALID RATING RANGE"); } int position = 0; int position1 = 5; int position2 = 8; for(unsigned int i=0; i<6; i++) { if(date[i] == '-') { std::string year = date.substr(position,(i-position)); if(year.size() !=4) { QMessageBox::warning(this, "ERROR", "ENTER VALID YEAR RANGE AND FORMAT"); } position = i+1; } } for(unsigned int i=5; i<date.size(); i++) { if(date[i] == '-') { std:: string month = date.substr(position1, (i-position1)); if(month.size() != 2) { QMessageBox::warning(this, "ERROR", "ENTER VALID YEAR RANGE AND FORMAT"); } position = i+1; } } for(unsigned int i=8; i<date.size(); i++) { if(date[i] == '-') { std:: string month = date.substr(position2, (i-position2)); if(month.size() != 2) { QMessageBox::warning(this, "ERROR", "ENTER VALID MONTH/DAY RANGE AND FORMAT"); } position = i+1; } } Review *r = new Review(); r->prodName = hits[ProductList->currentRow()]->getName(); r->rating = rating1; r->date = date; r->reviewText = text; ds.addReview(r); displayReviews(); } DateLine->clear(); TextLine->clear(); RatingLine->clear(); }
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; }
Form::Form(QWidget*parent) :QWidget(parent)//,ui(new Ui::Form) { #ifdef DEBUG setWindowTitle("DEBUG_MODE"); #else setGeometry(0,0,480,272); setWindowFlags(Qt::Popup);// убираем окно состояния setFixedSize(480,272); #endif ui.setupUi(this); ui.comboBox_menu->setFocus(); connect(ui.comboBox_menu,SIGNAL(currentIndexChanged(QString )),this,SLOT(generator()));//выбор главного меню connect(ui.comboBox_settings_param,SIGNAL(currentIndexChanged(QString )),this,SLOT(parametri()));//выбор параметры connect(ui.comboBox_settings_extParam,SIGNAL(currentIndexChanged(QString)),this,SLOT(dop_nastr()));// выбор доп.параметров connect(ui.comboBox_settings_timeSet,SIGNAL(currentIndexChanged(QString)),this,SLOT(date()));//выбор дата/время connect(ui.comboBox_settings_2chann,SIGNAL(currentIndexChanged(QString)),this,SLOT(channel_kanal()));//выбор параметров канала //connect(ui.comboBox_settings_2chann_2,SIGNAL(currentIndexChanged(QString)),this,SLOT(change_language()));//выбор языка connect(ui.pushButton,SIGNAL(clicked()),this,SLOT(priemnik())); connect(ui.pushButton_resiever_settings,SIGNAL(clicked()),this,SLOT(vrc())); connect(ui.pushButton_Graph_on,SIGNAL(clicked()),this,SLOT(graph_on())); connect(ui.pushButton_Graph_off,SIGNAL(clicked()),this,SLOT(graph_off())); ui.page_3->setHidden(true); ui.page_2->setHidden(true); ui.page_4->setHidden(true); ui.page_5->setHidden(true); ui.page_6->setHidden(true); ui.page_7->setHidden(true); ui.page_8->setHidden(true); ui.page_10->setHidden(true); ui.page_15->setHidden(true); ui.page->setShown(true); ui.page_16->setHidden(true); ui.page_11->setHidden(true); ui.page_9->setHidden(true); ui.page_10->setHidden(true); ui.customPlot->setHidden(true);//GRAPH }
/* Virtual function, from EDA_ITEM. * display module info on MsgPanel */ void MODULE::GetMsgPanelInfo( std::vector< MSG_PANEL_ITEM >& aList ) { int nbpad; wxString msg; aList.push_back( MSG_PANEL_ITEM( m_Reference->GetShownText(), m_Value->GetShownText(), DARKCYAN ) ); // Display last date the component was edited (useful in Module Editor). wxDateTime date( m_LastEditTime ); if( m_LastEditTime && date.IsValid() ) // Date format: see http://www.cplusplus.com/reference/ctime/strftime msg = date.Format( wxT( "%b %d, %Y" ) ); // Abbreviated_month_name Day, Year else msg = _( "Unknown" ); aList.push_back( MSG_PANEL_ITEM( _( "Last Change" ), msg, BROWN ) ); // display schematic path aList.push_back( MSG_PANEL_ITEM( _( "Netlist Path" ), m_Path, BROWN ) ); aList.push_back( MSG_PANEL_ITEM( _( "Layer" ), GetLayerName(), RED ) ); EDA_ITEM* PtStruct = m_Pads; nbpad = 0; while( PtStruct ) { nbpad++; PtStruct = PtStruct->Next(); } msg.Printf( wxT( "%d" ), nbpad ); aList.push_back( MSG_PANEL_ITEM( _( "Pads" ), msg, BLUE ) ); msg = wxT( ".." ); if( IsLocked() ) msg[0] = 'L'; if( m_ModuleStatus & MODULE_is_PLACED ) msg[1] = 'P'; aList.push_back( MSG_PANEL_ITEM( _( "Status" ), msg, MAGENTA ) ); msg.Printf( wxT( "%.1f" ), m_Orient / 10.0 ); aList.push_back( MSG_PANEL_ITEM( _( "Angle" ), msg, BROWN ) ); // Controls on right side of the dialog switch( m_Attributs & 255 ) { case 0: msg = _( "Normal" ); break; case MOD_CMS: msg = _( "Insert" ); break; case MOD_VIRTUAL: msg = _( "Virtual" ); break; default: msg = wxT( "???" ); break; } aList.push_back( MSG_PANEL_ITEM( _( "Attributes" ), msg, BROWN ) ); aList.push_back( MSG_PANEL_ITEM( _( "Footprint" ), FROM_UTF8( m_fpid.Format().c_str() ), BLUE ) ); msg = _( "No 3D shape" ); // Search the first active 3D shape in list for( S3D_MASTER* struct3D = m_3D_Drawings; struct3D; struct3D = struct3D->Next() ) { if( !struct3D->GetShape3DName().IsEmpty() ) { msg = struct3D->GetShape3DName(); break; } } aList.push_back( MSG_PANEL_ITEM( _( "3D-Shape" ), msg, RED ) ); wxString doc, keyword; doc.Printf( _( "Doc: %s" ), GetChars( m_Doc ) ); keyword.Printf( _( "Key Words: %s" ), GetChars( m_KeyWord ) ); aList.push_back( MSG_PANEL_ITEM( doc, keyword, BLACK ) ); }
time_type operator+=(const date_duration_type& dd) { time_ = (time_system::get_time_rep(date() + dd, time_of_day())); return time_type(time_); }
/* Parse all the date formats that Firefox can. The official format is: expires=ddd(d)?, dd-MMM-yyyy hh:mm:ss GMT But browsers have been supporting a very wide range of date strings. To work on many sites we need to support more then just the official date format. For reference see Firefox's PR_ParseTimeStringToExplodedTime in prtime.c. The Firefox date parser is coded in a very complex way and is slightly over ~700 lines long. While this implementation will be slightly slower for the non standard dates it is smaller, more readable, and maintainable. Or in their own words: "} // else what the hell is this." */ static QDateTime parseDateString(const QByteArray &dateString) { QTime time; // placeholders for values when we are not sure it is a year, month or day int unknown[3] = {-1, -1, -1}; int month = -1; int day = -1; int year = -1; int zoneOffset = -1; // hour:minute:second.ms pm QRegExp timeRx(QLatin1String("(\\d{1,2}):(\\d{1,2})(:(\\d{1,2})|)(\\.(\\d{1,3})|)((\\s{0,}(am|pm))|)")); int at = 0; while (at < dateString.length()) { #ifdef PARSEDATESTRINGDEBUG qDebug() << dateString.mid(at); #endif bool isNum = isNumber(dateString[at]); // Month if (!isNum && checkStaticArray(month, dateString, at, months, sizeof(months)- 1)) { ++month; #ifdef PARSEDATESTRINGDEBUG qDebug() << "Month:" << month; #endif at += 3; continue; } // Zone if (!isNum && zoneOffset == -1 && checkStaticArray(zoneOffset, dateString, at, zones, sizeof(zones)- 1)) { int sign = (at >= 0 && dateString[at - 1] == '-') ? -1 : 1; zoneOffset = sign * zoneOffsets[zoneOffset] * 60 * 60; #ifdef PARSEDATESTRINGDEBUG qDebug() << "Zone:" << month; #endif at += 3; continue; } // Zone offset if (!isNum && (zoneOffset == -1 || zoneOffset == 0) // Can only go after gmt && (dateString[at] == '+' || dateString[at] == '-') && (at == 0 || isWhitespace(dateString[at - 1]) || dateString[at - 1] == ',' || (at >= 3 && (dateString[at - 3] == 'g') && (dateString[at - 2] == 'm') && (dateString[at - 1] == 't')))) { int end = 1; while (end < 5 && dateString.length() > at+end && dateString[at + end] >= '0' && dateString[at + end] <= '9') ++end; int minutes = 0; int hours = 0; switch (end - 1) { case 4: minutes = atoi(dateString.mid(at + 3, 2).constData()); // fall through case 2: hours = atoi(dateString.mid(at + 1, 2).constData()); break; case 1: hours = atoi(dateString.mid(at + 1, 1).constData()); break; default: at += end; continue; } if (end != 1) { int sign = dateString[at] == '-' ? -1 : 1; zoneOffset = sign * ((minutes * 60) + (hours * 60 * 60)); #ifdef PARSEDATESTRINGDEBUG qDebug() << "Zone offset:" << zoneOffset << hours << minutes; #endif at += end; continue; } } // Time if (isNum && time.isNull() && dateString.length() >= at + 3 && (dateString[at + 2] == ':' || dateString[at + 1] == ':')) { // While the date can be found all over the string the format // for the time is set and a nice regexp can be used. int pos = timeRx.indexIn(QLatin1String(dateString), at); if (pos != -1) { QStringList list = timeRx.capturedTexts(); int h = atoi(list.at(1).toLatin1().constData()); int m = atoi(list.at(2).toLatin1().constData()); int s = atoi(list.at(4).toLatin1().constData()); int ms = atoi(list.at(6).toLatin1().constData()); if (h < 12 && !list.at(9).isEmpty()) if (list.at(9) == QLatin1String("pm")) h += 12; time = QTime(h, m, s, ms); #ifdef PARSEDATESTRINGDEBUG qDebug() << "Time:" << list << timeRx.matchedLength(); #endif at += timeRx.matchedLength(); continue; } } // 4 digit Year if (isNum && year == -1 && dateString.length() > at + 3) { if (isNumber(dateString[at + 1]) && isNumber(dateString[at + 2]) && isNumber(dateString[at + 3])) { year = atoi(dateString.mid(at, 4).constData()); at += 4; #ifdef PARSEDATESTRINGDEBUG qDebug() << "Year:" << year; #endif continue; } } // a one or two digit number // Could be month, day or year if (isNum) { int length = 1; if (dateString.length() > at + 1 && isNumber(dateString[at + 1])) ++length; int x = atoi(dateString.mid(at, length).constData()); if (year == -1 && (x > 31 || x == 0)) { year = x; } else { if (unknown[0] == -1) unknown[0] = x; else if (unknown[1] == -1) unknown[1] = x; else if (unknown[2] == -1) unknown[2] = x; } at += length; #ifdef PARSEDATESTRINGDEBUG qDebug() << "Saving" << x; #endif continue; } // Unknown character, typically a weekday such as 'Mon' ++at; } // Once we are done parsing the string take the digits in unknown // and determine which is the unknown year/month/day int couldBe[3] = { 0, 0, 0 }; int unknownCount = 3; for (int i = 0; i < unknownCount; ++i) { if (unknown[i] == -1) { couldBe[i] = ADAY | AYEAR | AMONTH; unknownCount = i; continue; } if (unknown[i] >= 1) couldBe[i] = ADAY; if (month == -1 && unknown[i] >= 1 && unknown[i] <= 12) couldBe[i] |= AMONTH; if (year == -1) couldBe[i] |= AYEAR; } // For any possible day make sure one of the values that could be a month // can contain that day. // For any possible month make sure one of the values that can be a // day that month can have. // Example: 31 11 06 // 31 can't be a day because 11 and 6 don't have 31 days for (int i = 0; i < unknownCount; ++i) { int currentValue = unknown[i]; bool findMatchingMonth = couldBe[i] & ADAY && currentValue >= 29; bool findMatchingDay = couldBe[i] & AMONTH; if (!findMatchingMonth || !findMatchingDay) continue; for (int j = 0; j < 3; ++j) { if (j == i) continue; for (int k = 0; k < 2; ++k) { if (k == 0 && !(findMatchingMonth && (couldBe[j] & AMONTH))) continue; else if (k == 1 && !(findMatchingDay && (couldBe[j] & ADAY))) continue; int m = currentValue; int d = unknown[j]; if (k == 0) qSwap(m, d); if (m == -1) m = month; bool found = true; switch(m) { case 2: // When we get 29 and the year ends up having only 28 // See date.isValid below // Example: 29 23 Feb if (d <= 29) found = false; break; case 4: case 6: case 9: case 11: if (d <= 30) found = false; break; default: if (d > 0 && d <= 31) found = false; } if (k == 0) findMatchingMonth = found; else if (k == 1) findMatchingDay = found; } } if (findMatchingMonth) couldBe[i] &= ~ADAY; if (findMatchingDay) couldBe[i] &= ~AMONTH; } // First set the year/month/day that have been deduced // and reduce the set as we go along to deduce more for (int i = 0; i < unknownCount; ++i) { int unset = 0; for (int j = 0; j < 3; ++j) { if (couldBe[j] == ADAY && day == -1) { day = unknown[j]; unset |= ADAY; } else if (couldBe[j] == AMONTH && month == -1) { month = unknown[j]; unset |= AMONTH; } else if (couldBe[j] == AYEAR && year == -1) { year = unknown[j]; unset |= AYEAR; } else { // common case break; } couldBe[j] &= ~unset; } } // Now fallback to a standardized order to fill in the rest with for (int i = 0; i < unknownCount; ++i) { if (couldBe[i] & AMONTH && month == -1) month = unknown[i]; else if (couldBe[i] & ADAY && day == -1) day = unknown[i]; else if (couldBe[i] & AYEAR && year == -1) year = unknown[i]; } #ifdef PARSEDATESTRINGDEBUG qDebug() << "Final set" << year << month << day; #endif if (year == -1 || month == -1 || day == -1) { #ifdef PARSEDATESTRINGDEBUG qDebug() << "Parser failure" << year << month << day; #endif return QDateTime(); } // Y2k behavior int y2k = 0; if (year < 70) y2k = 2000; else if (year < 100) y2k = 1900; QDate date(year + y2k, month, day); // When we were given a bad cookie that when parsed // set the day to 29 and the year to one that doesn't // have the 29th of Feb rather then adding the extra // complicated checking earlier just swap here. // Example: 29 23 Feb if (!date.isValid()) date = QDate(day + y2k, month, year); QDateTime dateTime(date, time, Qt::UTC); if (zoneOffset != -1) { dateTime = dateTime.addSecs(zoneOffset); } if (!dateTime.isValid()) return QDateTime(); return dateTime; }
//! [5] void MainWindow::insertCalendar() { editor->clear(); QTextCursor cursor = editor->textCursor(); cursor.beginEditBlock(); QDate date(selectedDate.year(), selectedDate.month(), 1); //! [5] //! [6] QTextTableFormat tableFormat; tableFormat.setAlignment(Qt::AlignHCenter); tableFormat.setBackground(QColor("#e0e0e0")); tableFormat.setCellPadding(2); tableFormat.setCellSpacing(4); //! [6] //! [7] QVector<QTextLength> constraints; constraints << QTextLength(QTextLength::PercentageLength, 14) << QTextLength(QTextLength::PercentageLength, 14) << QTextLength(QTextLength::PercentageLength, 14) << QTextLength(QTextLength::PercentageLength, 14) << QTextLength(QTextLength::PercentageLength, 14) << QTextLength(QTextLength::PercentageLength, 14) << QTextLength(QTextLength::PercentageLength, 14); tableFormat.setColumnWidthConstraints(constraints); //! [7] //! [8] QTextTable *table = cursor.insertTable(1, 7, tableFormat); //! [8] //! [9] QTextFrame *frame = cursor.currentFrame(); QTextFrameFormat frameFormat = frame->frameFormat(); frameFormat.setBorder(1); frame->setFrameFormat(frameFormat); //! [9] //! [10] QTextCharFormat format = cursor.charFormat(); format.setFontPointSize(fontSize); QTextCharFormat boldFormat = format; boldFormat.setFontWeight(QFont::Bold); QTextCharFormat highlightedFormat = boldFormat; highlightedFormat.setBackground(Qt::yellow); //! [10] //! [11] for (int weekDay = 1; weekDay <= 7; ++weekDay) { QTextTableCell cell = table->cellAt(0, weekDay-1); //! [11] //! [12] QTextCursor cellCursor = cell.firstCursorPosition(); cellCursor.insertText(QString("%1").arg(QDate::longDayName(weekDay)), boldFormat); } //! [12] //! [13] table->insertRows(table->rows(), 1); //! [13] while (date.month() == selectedDate.month()) { int weekDay = date.dayOfWeek(); QTextTableCell cell = table->cellAt(table->rows()-1, weekDay-1); QTextCursor cellCursor = cell.firstCursorPosition(); if (date == QDate::currentDate()) cellCursor.insertText(QString("%1").arg(date.day()), highlightedFormat); else cellCursor.insertText(QString("%1").arg(date.day()), format); date = date.addDays(1); if (weekDay == 7 && date.month() == selectedDate.month()) table->insertRows(table->rows(), 1); } cursor.endEditBlock(); //! [14] setWindowTitle(tr("Calendar for %1 %2" ).arg(QDate::longMonthName(selectedDate.month()) ).arg(selectedDate.year())); }
int slave(void) { int tries; long electiontime, refusetime, looktime, looptime, adjtime; u_short seq; long fastelection; #define FASTTOUT 3 struct in_addr cadr; struct timeval otime; struct sockaddr_in taddr; char tname[MAXHOSTNAMELEN]; struct tsp *msg, to; struct timeval ntime, wait, tmptv; time_t tsp_time_sec; struct tsp *answer; int timeout(); char olddate[32]; char newdate[32]; struct netinfo *ntp; struct hosttbl *htp; struct utmpx utx; old_slavenet = 0; seq = 0; refusetime = 0; adjtime = 0; (void)gettimeofday(&ntime, NULL); electiontime = ntime.tv_sec + delay2; fastelection = ntime.tv_sec + FASTTOUT; if (justquit) looktime = electiontime; else looktime = fastelection; looptime = fastelection; if (slavenet) xmit(TSP_SLAVEUP, 0, &slavenet->dest_addr); if (status & MASTER) { for (ntp = nettab; ntp != NULL; ntp = ntp->next) { if (ntp->status == MASTER) masterup(ntp); } } loop: get_goodgroup(0); (void)gettimeofday(&ntime, NULL); if (ntime.tv_sec > electiontime) { if (trace) fprintf(fd, "election timer expired\n"); longjmp(jmpenv, 1); } if (ntime.tv_sec >= looktime) { if (trace) fprintf(fd, "Looking for nets to master\n"); if (Mflag && nignorednets > 0) { for (ntp = nettab; ntp != NULL; ntp = ntp->next) { if (ntp->status == IGNORE || ntp->status == NOMASTER) { lookformaster(ntp); if (ntp->status == MASTER) { masterup(ntp); } else if (ntp->status == MASTER) { ntp->status = NOMASTER; } } if (ntp->status == MASTER && --ntp->quit_count < 0) ntp->quit_count = 0; } makeslave(slavenet); /* prune extras */ setstatus(); } (void)gettimeofday(&ntime, NULL); looktime = ntime.tv_sec + delay2; } if (ntime.tv_sec >= looptime) { if (trace) fprintf(fd, "Looking for loops\n"); for (ntp = nettab; ntp != NULL; ntp = ntp->next) { if (ntp->status == MASTER) { to.tsp_type = TSP_LOOP; to.tsp_vers = TSPVERSION; to.tsp_seq = sequence++; to.tsp_hopcnt = MAX_HOPCNT; (void)strcpy(to.tsp_name, hostname); bytenetorder(&to); if (sendto(sock, (char *)&to, sizeof(struct tsp), 0, (struct sockaddr*)&ntp->dest_addr, sizeof(ntp->dest_addr)) < 0) { trace_sendto_err(ntp->dest_addr.sin_addr); } } } (void)gettimeofday(&ntime, NULL); looptime = ntime.tv_sec + delay2; } wait.tv_sec = min(electiontime,min(looktime,looptime)) - ntime.tv_sec; if (wait.tv_sec < 0) wait.tv_sec = 0; wait.tv_sec += FASTTOUT; wait.tv_usec = 0; msg = readmsg(TSP_ANY, ANYADDR, &wait, 0); if (msg != NULL) { /* * filter stuff not for us */ switch (msg->tsp_type) { case TSP_SETDATE: case TSP_TRACEOFF: case TSP_TRACEON: /* * XXX check to see they are from ourself */ break; case TSP_TEST: case TSP_MSITE: break; case TSP_MASTERUP: if (!fromnet) { if (trace) { fprintf(fd, "slave ignored: "); print(msg, &from); } goto loop; } break; default: if (!fromnet || fromnet->status == IGNORE || fromnet->status == NOMASTER) { if (trace) { fprintf(fd, "slave ignored: "); print(msg, &from); } goto loop; } break; } /* * now process the message */ switch (msg->tsp_type) { case TSP_ADJTIME: if (fromnet != slavenet) break; if (!good_host_name(msg->tsp_name)) { syslog(LOG_NOTICE, "attempted time adjustment by %s", msg->tsp_name); suppress(&from, msg->tsp_name, fromnet); break; } /* * Speed up loop detection in case we have a loop. * Otherwise the clocks can race until the loop * is found. */ (void)gettimeofday(&otime, NULL); if (adjtime < otime.tv_sec) looptime -= (looptime-otime.tv_sec)/2 + 1; setmaster(msg); if (seq != msg->tsp_seq) { seq = msg->tsp_seq; synch(tvtomsround(msg->tsp_time)); } (void)gettimeofday(&ntime, NULL); electiontime = ntime.tv_sec + delay2; fastelection = ntime.tv_sec + FASTTOUT; adjtime = ntime.tv_sec + SAMPLEINTVL*2; break; case TSP_SETTIME: if (fromnet != slavenet) break; if (seq == msg->tsp_seq) break; seq = msg->tsp_seq; /* adjust time for residence on the queue */ (void)gettimeofday(&otime, NULL); adj_msg_time(msg,&otime); /* * the following line is necessary due to syslog * calling ctime() which clobbers the static buffer */ (void)strcpy(olddate, date()); tsp_time_sec = msg->tsp_time.tv_sec; (void)strcpy(newdate, ctime(&tsp_time_sec)); if (!good_host_name(msg->tsp_name)) { syslog(LOG_NOTICE, "attempted time setting by untrusted %s to %s", msg->tsp_name, newdate); suppress(&from, msg->tsp_name, fromnet); break; } setmaster(msg); tmptv.tv_sec = msg->tsp_time.tv_sec; tmptv.tv_usec = msg->tsp_time.tv_usec; timevalsub(&ntime, &tmptv, &otime); if (ntime.tv_sec < MAXADJ && ntime.tv_sec > -MAXADJ) { /* * do not change the clock if we can adjust it */ synch(tvtomsround(ntime)); } else { utx.ut_type = OLD_TIME; gettimeofday(&utx.ut_tv, NULL); pututxline(&utx); (void)settimeofday(&tmptv, 0); utx.ut_type = NEW_TIME; gettimeofday(&utx.ut_tv, NULL); pututxline(&utx); syslog(LOG_NOTICE, "date changed by %s from %s", msg->tsp_name, olddate); if (status & MASTER) spreadtime(); } (void)gettimeofday(&ntime, NULL); electiontime = ntime.tv_sec + delay2; fastelection = ntime.tv_sec + FASTTOUT; /* This patches a bad protocol bug. Imagine a system with several networks, * where there are a pair of redundant gateways between a pair of networks, * each running timed. Assume that we start with a third machine mastering * one of the networks, and one of the gateways mastering the other. * Imagine that the third machine goes away and the non-master gateway * decides to replace it. If things are timed just 'right,' we will have * each gateway mastering one network for a little while. If a SETTIME * message gets into the network at that time, perhaps from the newly * masterful gateway as it was taking control, the SETTIME will loop * forever. Each time a gateway receives it on its slave side, it will * call spreadtime to forward it on its mastered network. We are now in * a permanent loop, since the SETTIME msgs will keep any clock * in the network from advancing. Normally, the 'LOOP' stuff will detect * and correct the situation. However, with the clocks stopped, the * 'looptime' timer cannot expire. While they are in this state, the * masters will try to saturate the network with SETTIME packets. */ looptime = ntime.tv_sec + (looptime-otime.tv_sec)/2-1; break; case TSP_MASTERUP: if (slavenet && fromnet != slavenet) break; if (!good_host_name(msg->tsp_name)) { suppress(&from, msg->tsp_name, fromnet); if (electiontime > fastelection) electiontime = fastelection; break; } makeslave(fromnet); setmaster(msg); setstatus(); answerdelay(); xmit(TSP_SLAVEUP, 0, &from); (void)gettimeofday(&ntime, NULL); electiontime = ntime.tv_sec + delay2; fastelection = ntime.tv_sec + FASTTOUT; refusetime = 0; break; case TSP_MASTERREQ: if (fromnet->status != SLAVE) break; (void)gettimeofday(&ntime, NULL); electiontime = ntime.tv_sec + delay2; break; case TSP_SETDATE: tsp_time_sec = msg->tsp_time.tv_sec; (void)strcpy(newdate, ctime(&tsp_time_sec)); schgdate(msg, newdate); break; case TSP_SETDATEREQ: if (fromnet->status != MASTER) break; tsp_time_sec = msg->tsp_time.tv_sec; (void)strcpy(newdate, ctime(&tsp_time_sec)); htp = findhost(msg->tsp_name); if (0 == htp) { syslog(LOG_WARNING, "DATEREQ from uncontrolled machine"); break; } if (!htp->good) { syslog(LOG_WARNING, "attempted date change by untrusted %s to %s", htp->name, newdate); spreadtime(); break; } schgdate(msg, newdate); break; case TSP_TRACEON: traceon(); break; case TSP_TRACEOFF: traceoff("Tracing ended at %s\n"); break; case TSP_SLAVEUP: newslave(msg); break; case TSP_ELECTION: if (fromnet->status == SLAVE) { (void)gettimeofday(&ntime, NULL); electiontime = ntime.tv_sec + delay2; fastelection = ntime.tv_sec + FASTTOUT; seq = 0; if (!good_host_name(msg->tsp_name)) { syslog(LOG_NOTICE, "suppress election of %s", msg->tsp_name); to.tsp_type = TSP_QUIT; electiontime = fastelection; } else if (cadr.s_addr != from.sin_addr.s_addr && ntime.tv_sec < refusetime) { /* if the candidate has to repeat itself, the old code would refuse it * the second time. That would prevent elections. */ to.tsp_type = TSP_REFUSE; } else { cadr.s_addr = from.sin_addr.s_addr; to.tsp_type = TSP_ACCEPT; refusetime = ntime.tv_sec + 30; } taddr = from; (void)strcpy(tname, msg->tsp_name); (void)strcpy(to.tsp_name, hostname); answerdelay(); if (!acksend(&to, &taddr, tname, TSP_ACK, 0, 0)) syslog(LOG_WARNING, "no answer from candidate %s\n", tname); } else { /* fromnet->status == MASTER */ htp = addmach(msg->tsp_name, &from,fromnet); to.tsp_type = TSP_QUIT; (void)strcpy(to.tsp_name, hostname); if (!acksend(&to, &htp->addr, htp->name, TSP_ACK, 0, htp->noanswer)) { syslog(LOG_ERR, "no reply from %s to ELECTION-QUIT", htp->name); (void)remmach(htp); } } break; case TSP_CONFLICT: if (fromnet->status != MASTER) break; /* * After a network partition, there can be * more than one master: the first slave to * come up will notify here the situation. */ (void)strcpy(to.tsp_name, hostname); /* The other master often gets into the same state, * with boring results. */ ntp = fromnet; /* (acksend() can leave fromnet=0 */ for (tries = 0; tries < 3; tries++) { to.tsp_type = TSP_RESOLVE; answer = acksend(&to, &ntp->dest_addr, ANYADDR, TSP_MASTERACK, ntp, 0); if (answer == NULL) break; htp = addmach(answer->tsp_name,&from,ntp); to.tsp_type = TSP_QUIT; answer = acksend(&to, &htp->addr, htp->name, TSP_ACK, 0, htp->noanswer); if (!answer) { syslog(LOG_WARNING, "conflict error: no reply from %s to QUIT", htp->name); (void)remmach(htp); } } masterup(ntp); break; case TSP_MSITE: if (!slavenet) break; taddr = from; to.tsp_type = TSP_MSITEREQ; to.tsp_vers = TSPVERSION; to.tsp_seq = 0; (void)strcpy(to.tsp_name, hostname); answer = acksend(&to, &slavenet->dest_addr, ANYADDR, TSP_ACK, slavenet, 0); if (answer != NULL && good_host_name(answer->tsp_name)) { setmaster(answer); to.tsp_type = TSP_ACK; (void)strcpy(to.tsp_name, answer->tsp_name); bytenetorder(&to); if (sendto(sock, (char *)&to, sizeof(struct tsp), 0, (struct sockaddr*)&taddr, sizeof(taddr)) < 0) { trace_sendto_err(taddr.sin_addr); } } break; case TSP_MSITEREQ: break; case TSP_ACCEPT: case TSP_REFUSE: case TSP_RESOLVE: break; case TSP_QUIT: doquit(msg); /* become a slave */ break; case TSP_TEST: electiontime = 0; break; case TSP_LOOP: /* looking for loops of masters */ if (!(status & MASTER)) break; if (fromnet->status == SLAVE) { if (!strcmp(msg->tsp_name, hostname)) { /* * Someone forwarded our message back to * us. There must be a loop. Tell the * master of this network to quit. * * The other master often gets into * the same state, with boring results. */ ntp = fromnet; for (tries = 0; tries < 3; tries++) { to.tsp_type = TSP_RESOLVE; answer = acksend(&to, &ntp->dest_addr, ANYADDR, TSP_MASTERACK, ntp,0); if (answer == NULL) break; taddr = from; (void)strcpy(tname, answer->tsp_name); to.tsp_type = TSP_QUIT; (void)strcpy(to.tsp_name, hostname); if (!acksend(&to, &taddr, tname, TSP_ACK, 0, 1)) { syslog(LOG_ERR, "no reply from %s to slave LOOP-QUIT", tname); } else { electiontime = 0; } } (void)gettimeofday(&ntime, NULL); looptime = ntime.tv_sec + FASTTOUT; } else { if (msg->tsp_hopcnt-- < 1) break; bytenetorder(msg); for (ntp = nettab; ntp != 0; ntp = ntp->next) { if (ntp->status == MASTER && 0 > sendto(sock, (char *)msg, sizeof(struct tsp), 0, (struct sockaddr*)&ntp->dest_addr, sizeof(ntp->dest_addr))) trace_sendto_err(ntp->dest_addr.sin_addr); } } } else { /* fromnet->status == MASTER */ /* * We should not have received this from a net * we are master on. There must be two masters, * unless the packet was really from us. */ if (from.sin_addr.s_addr == fromnet->my_addr.s_addr) { if (trace) fprintf(fd,"discarding forwarded LOOP\n"); break; } /* * The other master often gets into the same * state, with boring results. */ ntp = fromnet; for (tries = 0; tries < 3; tries++) { to.tsp_type = TSP_RESOLVE; answer = acksend(&to, &ntp->dest_addr, ANYADDR, TSP_MASTERACK, ntp,0); if (!answer) break; htp = addmach(answer->tsp_name, &from,ntp); to.tsp_type = TSP_QUIT; (void)strcpy(to.tsp_name, hostname); if (!acksend(&to,&htp->addr,htp->name, TSP_ACK, 0, htp->noanswer)) { syslog(LOG_ERR, "no reply from %s to master LOOP-QUIT", htp->name); (void)remmach(htp); } } (void)gettimeofday(&ntime, NULL); looptime = ntime.tv_sec + FASTTOUT; } break; default: if (trace) { fprintf(fd, "garbage message: "); print(msg, &from); } break; } } goto loop; }
void SessionsBox::gotAuthorizations(const MTPaccount_Authorizations &result) { _shortPollRequest = 0; setLoading(false); auto availCurrent = st::boxWideWidth - st::sessionPadding.left() - st::sessionTerminateSkip; auto availOther = availCurrent - st::sessionTerminate.iconPosition.x();// -st::sessionTerminate.width - st::sessionTerminateSkip; _list.clear(); if (result.type() != mtpc_account_authorizations) { return; } auto &v = result.c_account_authorizations().vauthorizations.c_vector().v; _list.reserve(v.size()); const CountriesByISO2 &countries(countriesByISO2()); for_const (auto &auth, v) { if (auth.type() != mtpc_authorization) { continue; } auto &d = auth.c_authorization(); Data data; data.hash = d.vhash.v; QString appName, appVer = qs(d.vapp_version), systemVer = qs(d.vsystem_version), deviceModel = qs(d.vdevice_model); if (d.vapi_id.v == 2040 || d.vapi_id.v == 17349) { appName = (d.vapi_id.v == 2040) ? qstr("Telegram Desktop") : qstr("Telegram Desktop (GitHub)"); // if (systemVer == qstr("windows")) { // deviceModel = qsl("Windows"); // } else if (systemVer == qstr("os x")) { // deviceModel = qsl("OS X"); // } else if (systemVer == qstr("linux")) { // deviceModel = qsl("Linux"); // } if (appVer == QString::number(appVer.toInt())) { int32 ver = appVer.toInt(); appVer = QString("%1.%2").arg(ver / 1000000).arg((ver % 1000000) / 1000) + ((ver % 1000) ? ('.' + QString::number(ver % 1000)) : QString()); } else { appVer = QString(); } } else { appName = qs(d.vapp_name);// +qsl(" for ") + qs(d.vplatform); if (appVer.indexOf('(') >= 0) appVer = appVer.mid(appVer.indexOf('(')); } data.name = appName; if (!appVer.isEmpty()) data.name += ' ' + appVer; data.nameWidth = st::sessionNameFont->width(data.name); QString country = qs(d.vcountry), platform = qs(d.vplatform); //CountriesByISO2::const_iterator j = countries.constFind(country); //if (j != countries.cend()) country = QString::fromUtf8(j.value()->name); MTPint active = d.vdate_active.v ? d.vdate_active : d.vdate_created; data.activeTime = active.v; data.info = qs(d.vdevice_model) + qstr(", ") + (platform.isEmpty() ? QString() : platform + ' ') + qs(d.vsystem_version); data.ip = qs(d.vip) + (country.isEmpty() ? QString() : QString::fromUtf8(" \xe2\x80\x93 ") + country); if (!data.hash || (d.vflags.v & 1)) { data.active = lang(lng_sessions_header); data.activeWidth = st::sessionWhenFont->width(lang(lng_sessions_header)); int32 availForName = availCurrent - st::sessionPadding.right() - data.activeWidth; if (data.nameWidth > availForName) { data.name = st::sessionNameFont->elided(data.name, availForName); data.nameWidth = st::sessionNameFont->width(data.name); } data.infoWidth = st::sessionInfoFont->width(data.info); if (data.infoWidth > availCurrent) { data.info = st::sessionInfoFont->elided(data.info, availCurrent); data.infoWidth = st::sessionInfoFont->width(data.info); } data.ipWidth = st::sessionInfoFont->width(data.ip); if (data.ipWidth > availCurrent) { data.ip = st::sessionInfoFont->elided(data.ip, availCurrent); data.ipWidth = st::sessionInfoFont->width(data.ip); } _current = data; } else { QDateTime now(QDateTime::currentDateTime()), lastTime(date(active)); QDate nowDate(now.date()), lastDate(lastTime.date()); QString dt; if (lastDate == nowDate) { data.active = lastTime.toString(cTimeFormat()); } else if (lastDate.year() == nowDate.year() && lastDate.weekNumber() == nowDate.weekNumber()) { data.active = langDayOfWeek(lastDate); } else { data.active = lastDate.toString(qsl("d.MM.yy")); } data.activeWidth = st::sessionWhenFont->width(data.active); int32 availForName = availOther - st::sessionPadding.right() - data.activeWidth; if (data.nameWidth > availForName) { data.name = st::sessionNameFont->elided(data.name, availForName); data.nameWidth = st::sessionNameFont->width(data.name); } data.infoWidth = st::sessionInfoFont->width(data.info); if (data.infoWidth > availOther) { data.info = st::sessionInfoFont->elided(data.info, availOther); data.infoWidth = st::sessionInfoFont->width(data.info); } data.ipWidth = st::sessionInfoFont->width(data.ip); if (data.ipWidth > availOther) { data.ip = st::sessionInfoFont->elided(data.ip, availOther); data.ipWidth = st::sessionInfoFont->width(data.ip); } _list.push_back(data); for (int32 i = _list.size(); i > 1;) { --i; if (_list.at(i).activeTime > _list.at(i - 1).activeTime) { qSwap(_list[i], _list[i - 1]); } } } } _inner->listUpdated(); update(); _shortPollTimer->start(SessionsShortPollTimeout); }
QDateTime TestKeePass1Reader::genDT(int year, int month, int day, int hour, int min) { QDate date(year, month, day); QTime time(hour, min, 0); return QDateTime(date, time, Qt::UTC); }
void main() { date(); }
V2Party::V2Party(const std::string& name, const std::string& ideology) : name(name), ideology(ideology) { if (ideology == "conservative") { start_date = date("1820.1.1"); end_date = date("2000.1.1"); economic_policy = "interventionism"; trade_policy = "protectionism"; religious_policy = "moralism"; citizenship_policy = "limited_citizenship"; war_policy = "pro_military"; } else if (ideology == "liberal") { start_date = date("1820.1.1"); end_date = date("2000.1.1"); economic_policy = "laissez_faire"; trade_policy = "free_trade"; religious_policy = "pluralism"; citizenship_policy = "limited_citizenship"; war_policy = "anti_military"; } else if (ideology == "reactionary") { start_date = date("1820.1.1"); end_date = date("2000.1.1"); economic_policy = "state_capitalism"; trade_policy = "protectionism"; religious_policy = "moralism"; citizenship_policy = "residency"; war_policy = "jingoism"; } else if (ideology == "socialist") { start_date = date("1849.1.1"); end_date = date("2000.1.1"); economic_policy = "state_capitalism"; trade_policy = "free_trade"; religious_policy = "secularized"; citizenship_policy = "full_citizenship"; war_policy = "anti_military"; } else if (ideology == "communist") { start_date = date("1849.1.1"); end_date = date("2000.1.1"); economic_policy = "planned_economy"; trade_policy = "protectionism"; religious_policy = "pro_atheism"; citizenship_policy = "full_citizenship"; war_policy = "pro_military"; } else if (ideology == "anarcho_liberal") { start_date = date("1830.1.1"); end_date = date("2000.1.1"); economic_policy = "laissez_faire"; trade_policy = "free_trade"; religious_policy = "pro_atheism"; citizenship_policy = "full_citizenship"; war_policy = "pro_military"; } else if (ideology == "fascist") { start_date = date("1905.1.1"); end_date = date("2000.1.1"); economic_policy = "state_capitalism"; trade_policy = "protectionism"; religious_policy = "moralism"; citizenship_policy = "residency"; war_policy = "jingoism"; } else { LOG(LogLevel::Warning) << "Unknown party ideology \"" << ideology << "\" for party \"" << name << '"'; } }
time_type operator-=(const time_duration_type& td) { time_ = (time_system::get_time_rep(date(), time_of_day() - td)); return time_type(time_); }
V2Party::V2Party(shared_ptr<Object> party_obj) { auto leaf = party_obj->getLeaf("name"); if (leaf) { name = *leaf; } else { LOG(LogLevel::Error) << "Party did not have a name"; exit(-1); } leaf = party_obj->getLeaf("ideology"); if (leaf) { ideology = *leaf; } else { LOG(LogLevel::Error) << "Party " << name << " did not have an ideology"; exit(-1); } leaf = party_obj->getLeaf("start_date"); if (leaf) { start_date = date(*leaf); } else { LOG(LogLevel::Error) << "Party " << name << " did not have a start date"; exit(-1); } leaf = party_obj->getLeaf("end_date"); if (leaf) { end_date = date(*leaf); } else { LOG(LogLevel::Error) << "Party " << name << " did not have an end date"; exit(-1); } leaf = party_obj->getLeaf("economic_policy"); if (leaf) { economic_policy = *leaf; } else { LOG(LogLevel::Error) << "Party " << name << " did not have an economic policy"; exit(-1); } leaf = party_obj->getLeaf("trade_policy"); if (leaf) { trade_policy = *leaf; } else { LOG(LogLevel::Error) << "Party " << name << " did not have a trade policy"; exit(-1); } leaf = party_obj->getLeaf("religious_policy"); if (leaf) { religious_policy = *leaf; } else { LOG(LogLevel::Error) << "Party " << name << " did not have a religious policy"; exit(-1); } leaf = party_obj->getLeaf("citizenship_policy"); if (leaf) { citizenship_policy = *leaf; } else { LOG(LogLevel::Error) << "Party " << name << " did not have a citizenship policy"; exit(-1); } leaf = party_obj->getLeaf("war_policy"); if (leaf) { war_policy = *leaf; } else { LOG(LogLevel::Error) << "Party " << name << " did not have a war policy"; exit(-1); } }
WXDLLEXPORT bool wxConvertVariantToOle(const wxVariant& variant, VARIANTARG& oleVariant) { VariantInit(&oleVariant); if (variant.IsNull()) { oleVariant.vt = VT_NULL; return true; } wxString type(variant.GetType()); if (type == wxT("long")) { oleVariant.vt = VT_I4; oleVariant.lVal = variant.GetLong() ; } else if (type == wxT("char")) { oleVariant.vt=VT_I1; // Signed Char oleVariant.cVal=variant.GetChar(); } else if (type == wxT("double")) { oleVariant.vt = VT_R8; oleVariant.dblVal = variant.GetDouble(); } else if (type == wxT("bool")) { oleVariant.vt = VT_BOOL; oleVariant.boolVal = variant.GetBool(); } else if (type == wxT("string")) { wxString str( variant.GetString() ); oleVariant.vt = VT_BSTR; oleVariant.bstrVal = wxConvertStringToOle(str); } #if wxUSE_DATETIME else if (type == wxT("datetime")) { wxDateTime date( variant.GetDateTime() ); oleVariant.vt = VT_DATE; SYSTEMTIME st; date.GetAsMSWSysTime(&st); SystemTimeToVariantTime(&st, &oleVariant.date); } #endif else if (type == wxT("void*")) { oleVariant.vt = VT_DISPATCH; oleVariant.pdispVal = (IDispatch*) variant.GetVoidPtr(); } else if (type == wxT("list") || type == wxT("stringlist")) { oleVariant.vt = VT_VARIANT | VT_ARRAY; SAFEARRAY *psa; SAFEARRAYBOUND saBound; VARIANTARG *pvargBase; VARIANTARG *pvarg; int i, j; int iCount = variant.GetCount(); saBound.lLbound = 0; saBound.cElements = iCount; psa = SafeArrayCreate(VT_VARIANT, 1, &saBound); if (psa == NULL) return false; SafeArrayAccessData(psa, (void**)&pvargBase); pvarg = pvargBase; for (i = 0; i < iCount; i++) { // copy each string in the list of strings wxVariant eachVariant(variant[i]); if (!wxConvertVariantToOle(eachVariant, * pvarg)) { // memory failure: back out and free strings alloc'ed up to // now, and then the array itself. pvarg = pvargBase; for (j = 0; j < i; j++) { SysFreeString(pvarg->bstrVal); pvarg++; } SafeArrayDestroy(psa); return false; } pvarg++; } SafeArrayUnaccessData(psa); oleVariant.parray = psa; } else { oleVariant.vt = VT_NULL; return false; } return true; }
void TimeZoneBoundaryTest::TestBoundaries() { UErrorCode status = U_ZERO_ERROR; TimeZone* pst = TimeZone::createTimeZone("PST"); Calendar* tempcal = Calendar::createInstance(pst, status); if(U_SUCCESS(status)){ verifyMapping(*tempcal, 1997, Calendar::APRIL, 3, 0, 238904.0); verifyMapping(*tempcal, 1997, Calendar::APRIL, 4, 0, 238928.0); verifyMapping(*tempcal, 1997, Calendar::APRIL, 5, 0, 238952.0); verifyMapping(*tempcal, 1997, Calendar::APRIL, 5, 23, 238975.0); verifyMapping(*tempcal, 1997, Calendar::APRIL, 6, 0, 238976.0); verifyMapping(*tempcal, 1997, Calendar::APRIL, 6, 1, 238977.0); verifyMapping(*tempcal, 1997, Calendar::APRIL, 6, 3, 238978.0); }else{ errln("Could not create calendar. Error: %s", u_errorName(status)); } TimeZone* utc = TimeZone::createTimeZone("UTC"); Calendar* utccal = Calendar::createInstance(utc, status); if(U_SUCCESS(status)){ verifyMapping(*utccal, 1997, Calendar::APRIL, 6, 0, 238968.0); }else{ errln("Could not create calendar. Error: %s", u_errorName(status)); } TimeZone* save = TimeZone::createDefault(); TimeZone::setDefault(*pst); // DST changeover for PST is 4/6/1997 at 2 hours past midnight // at 238978.0 epoch hours. tempcal->clear(); tempcal->set(1997, Calendar::APRIL, 6); UDate d = tempcal->getTime(status); // i is minutes past midnight standard time for (int i=-120; i<=180; i+=60) { UBool inDST = (i >= 120); tempcal->setTime(d + i*60*1000, status); verifyDST(tempcal->getTime(status),pst, TRUE, inDST, -8*ONE_HOUR,inDST ? -7*ONE_HOUR : -8*ONE_HOUR); } TimeZone::setDefault(*save); delete save; delete utccal; delete tempcal; #if 1 { logln("--- Test a ---"); UDate d = date(97, UCAL_APRIL, 6); TimeZone *z = TimeZone::createTimeZone("PST"); for (int32_t i = 60; i <= 180; i += 15) { UBool inDST = (i >= 120); UDate e = d + i * 60 * 1000; verifyDST(e, z, TRUE, inDST, - 8 * ONE_HOUR, inDST ? - 7 * ONE_HOUR: - 8 * ONE_HOUR); } delete z; } #endif #if 1 { logln("--- Test b ---"); TimeZone *tz; TimeZone::setDefault(*(tz = TimeZone::createTimeZone("PST"))); delete tz; logln("========================================"); findDaylightBoundaryUsingDate(date(97, 0, 1), "PST", PST_1997_BEG); logln("========================================"); findDaylightBoundaryUsingDate(date(97, 6, 1), "PDT", PST_1997_END); } #endif #if 1 { logln("--- Test c ---"); logln("========================================"); TimeZone* z = TimeZone::createTimeZone("Australia/Adelaide"); findDaylightBoundaryUsingTimeZone(date(97, 0, 1), TRUE, 859653000000.0, z); logln("========================================"); findDaylightBoundaryUsingTimeZone(date(97, 6, 1), FALSE, 877797000000.0, z); delete z; } #endif #if 1 { logln("--- Test d ---"); logln("========================================"); findDaylightBoundaryUsingTimeZone(date(97, 0, 1), FALSE, PST_1997_BEG); logln("========================================"); findDaylightBoundaryUsingTimeZone(date(97, 6, 1), TRUE, PST_1997_END); } #endif #if 0 { logln("--- Test e ---"); TimeZone *z = TimeZone::createDefault(); logln(UnicodeString("") + z->getOffset(1, 97, 3, 4, 6, 0) + " " + date(97, 3, 4)); logln(UnicodeString("") + z->getOffset(1, 97, 3, 5, 7, 0) + " " + date(97, 3, 5)); logln(UnicodeString("") + z->getOffset(1, 97, 3, 6, 1, 0) + " " + date(97, 3, 6)); logln(UnicodeString("") + z->getOffset(1, 97, 3, 7, 2, 0) + " " + date(97, 3, 7)); delete z; } #endif }
std::string GetDate() { TDatime * date(new TDatime()); return std::to_string(date->GetDate()); }