void main(int n) { int i,j,k,l; // tmpl("(le(n,l,i,j,k),le(n,l,i,j,k))") tmpl("(le(n,l,i,j,k))"); assume(l>1); for (i=n;i>=1;i--) { // Accumulation of right-hand transformations. if (i < n) { if ( NONDET ) { for (j=l;j<=n;j++) { // Double division to avoid possible underflow. tmpl("(le(n,l,i,j,k),le(n,l,i,j,k))"); assert(1<=j); //assert(j<=n); // assert(1<=i);assert(i<=n); // assert(1<=i);assert(i<=m); // TODO feasible counterexample found, hm //assert(1<=l);assert(l<=n); } for (j=l;j<=n;j++) { for (k=l;k<=n;k++) { //assert(1<=i);assert(i<=m); // TODO feasible counterexample found, hm //assert(1<=k);assert(k<=n); //assert(1<=j);assert(j<=n); } /* for (k=l;k<=n;k++) { //assert(1<=k);assert(k<=n); //assert(1<=j); //assert(j<=n); //assert(1<=i);assert(i<=n); }*/ } } for (j=l;j<=n;j++) { //assert(1<=j); //assert(j<=n); //assert(1<=i); //assert(i<=n); } } //assert(1<=i); //assert(i<=n); //assert(1<=i); //assert(i<=n); l=i; } }
long perform_edit(MTextAddOn *addon) { long result = B_NO_ERROR; try { long s, e, l; addon->GetSelection(&s, &e); sSelectionOnly = (s != e); BMemoryIO tmpl(kDLOG1, kDLOG1Size); CCutContainingDialog *p = DialogCreator<CCutContainingDialog>::CreateDialog(addon->Window(), tmpl); p->Show(); wait_for_thread(p->Thread(), &l); if (sOK) result = CutContaining(addon); if (sText) free(sText); } catch (HErr& e) { e.DoError(); result = B_ERROR; } return result; } /* perform_edit */
int main(int argc, char** argv) { if(argc!=5) { printHelp(argv[0]); return -1; } if(strcmp(argv[4], "g") !=0 && strcmp(argv[4], "l") !=0 ) { printHelp(argv[0]); return -2; } bool globalTrain = false; if(strcmp(argv[4], "g") == 0) { globalTrain = true; } int nRound=-1; sscanf(argv[3], "%d", &nRound); if(nRound<1) { printf("Error: nRound(%d) is illegal.\n", nRound); return -3; } seqInput input; input.loadFile(argv[1]); percFeatureTmpl tmpl(input.C); percFeature feature(tmpl, input); percTraining tr(feature); if(globalTrain) tr.setGMode(); tr.Train(nRound); tr.WriteToFile(argv[2]); return 0; }
int main(int n0, int n1) { int i0 = 0; int k = 0; tmpl("2"); while( i0 < n0 ) { i0++; k++; } int i1 = 0; while( i1 < n1 ) { i1++; k++; } int j1 = 0; while( j1 < n1 ) { if(k <= 0) ERROR:; j1++; k--; } int j0 = 0; while( j0 < n0 ) { if(k <= 0) ERROR:; j0++; k--; } return 0; }
void SettingsDialog::updateColorToolButtonColor(QToolButton* but) { QString tmpl("QToolButton { background-color: %1; color: %2; }"); QColor fg(SETTINGS->get("Color", but->text()).toString()); QColor bg(255 - fg.red(), 255 - fg.green(), 255 - fg.blue(), 25); but->setStyleSheet(tmpl.arg(fg.name()).arg(bg.name())); }
void InsetFormulaMacro::draw(PainterInfo & p, int x, int y) const { // label Font font = p.base.font; font.setColor(Color_math); PainterInfo pi(p.base.bv, p.pain); pi.base.style = LM_ST_TEXT; pi.base.font = font; int const a = y - dim_.asc + 1; int const w = dim_.wid - 2; int const h = dim_.height() - 2; // Color_mathbg used to be "AntiqueWhite" but is "linen" now, too pi.pain.fillRectangle(x, a, w, h, Color_mathmacrobg); pi.pain.rectangle(x, a, w, h, Color_mathframe); // FIXME #if 0 Cursor & cur = p.base.bv->cursor(); if (cur.isInside(this)) cur.drawSelection(pi); #endif pi.pain.text(x + 2, y, prefix(), font); // body tmpl()->draw(pi, x + theFontMetrics(p.base.font).width(prefix()) + 5, y); setPosCache(pi, x, y); }
void InsetFormulaMacro::metrics(MetricsInfo & mi, Dimension & dim) const { //lyxerr << "InsetFormulaMacro: " << this << " -- " << &tmpl() << endl; tmpl()->metrics(mi, dim); dim.asc += 5; dim.des += 5; dim.wid += 10 + theFontMetrics(mi.base.font).width(prefix()); dim_ = dim; }
int InsetFormulaMacro::plaintext(odocstream & os, OutputParams const & runparams) const { odocstringstream oss; WriteStream wi(oss, false, true, WriteStream::wsDefault, runparams.encoding); tmpl()->write(wi); docstring const str = oss.str(); os << str; return str.size(); }
SparseMatrix::SparseMatrix(std::string env, std::string stif) { // std::string filename("/home/popka/kursach/simple1_out_model/ENV.bin"); std::ifstream env_stream; env_stream.open(env.c_str(), std::ios::binary); if (env_stream.bad()) std::cout << "wrong file name " << env; env_stream.seekg(0, std::ios_base::end); const size_t count_of_elements(env_stream.tellg() / sizeof(int)); env_stream.seekg(0, std::ios_base::beg); std::vector<size_t> sizes(count_of_elements); int* buf(new int[count_of_elements]); env_stream.read(static_cast<char*>(static_cast<void*>(buf)), count_of_elements * sizeof(int)); env_stream.close(); for (size_t i(0); i != sizes.size(); ++i) { sizes[i] = buf[i]; } delete[] buf; table.resize(sizes.size()); size = sizes.size(); std::ifstream stif_stream; stif_stream.open(stif.c_str(), std::ios::binary); size_t fullSize(0); stif_stream.seekg(0, std::ios_base::end); fullSize = stif_stream.tellg(); stif_stream.seekg(0, std::ios_base::beg); real* buf_m(new real[fullSize]); stif_stream.read(static_cast<char*>(static_cast<void*>(buf_m)), fullSize); stif_stream.close(); size_t sum(0); for (size_t i=0 ;i<sizes.size(); ++i) { std::vector<real> tmpl(sizes[i]); for (size_t j=0; j<sizes[i]; ++j) { tmpl[sizes[i]-j-1] = buf_m[sum+j]; if (abs(buf_m[sum+j]) >1e+40) std::cout << "BIG MATRIX "; } /* size_t k = i- (sizes[i] - 1); std::cout << "\n sizes[i] = " << sizes[i] << " i=" << i <<" первый ненулевой" << k << std::endl; std::cout << "\n SparseArray \n ============= \n "; for (size_t m=0; m<tmpl.size(); m++) { std::cout << tmpl[m] << " "; } std::cout << "\n Buf \n ============= \n "; for (size_t m=0; m<tmpl.size(); m++) { std::cout << buf_m[sum+m] << " "; } int as; std::cin >> as;*/ table[i] = new SparseArray(tmpl, i - (sizes[i] - 1)); sum+=sizes[i]; } delete[] buf_m; }
void InsetFormulaMacro::latex(otexstream & os, OutputParams const & runparams) const { //lyxerr << "InsetFormulaMacro::latex" << endl; WriteStream wi(os.os(), runparams.moving_arg, true, runparams.dryrun ? WriteStream::wsDryrun: WriteStream::wsDefault, runparams.encoding); wi.canBreakLine(os.canBreakLine()); tmpl()->write(wi); os.canBreakLine(wi.canBreakLine()); os.texrow().newlines(wi.line()); }
void main() { int i,j,k,n; tmpl("(le(n,i,j,k),le(n,i,j,k))"); for (i=0;i<n;i++) for (j=i;j<n;j++) for (k=j;k<n;k++) if(NONDET){ assert(k>=j); assert(j>=i); // assert(i>=0); } }
void Dialog::addFileTemplates() { DialogFileTemplate prefdialog; if(prefdialog.exec() == QDialog::Accepted) { QString tmpl(prefdialog.getTemplate()); qDebug() << "tmpl = " << tmpl; opts.filetemplatelist.append(tmpl); opts.startdatetemplatelist.append(QString::number(prefdialog.getStartDateTemplate())); showFileTemplateList(); } }
::std::string make_tmp_file(::std::string name) { name += "XXXXXX"; ::std::vector<char> tmpl(name.begin(), name.end()); tmpl.push_back('\0'); int fd = ::mkstemp(&tmpl[0]); if (fd != -1) { name.assign(tmpl.begin(), tmpl.end()-1); ::close(fd); } return name; }
void main() { int i,k,n; // tmpl("(le(n,i,k,l),le(n,i,k,l))"); tmpl("(le(n,i,k),le(n,i,k))"); // assume(l>0); for (k=1;k<n;k++){ for (i=1;i<n;i++) assert(1<=k); if(i<n) for (i=1;i<n;i++); } }
void main() { int i,k,n,l; tmpl("(le(n,i,k),le(n,i,k))"); for (k=1;k<n;k++){ // assert(k<=n); // assert(1<=k); for (i=1;i<n;i++) { //assert(1<=k); // assert(1<=i); // assert(i<=n); } } assert(1<=k); }
void main() { int n,m; int i = 1; tmpl("(le(i,j,k,n),le(i,j,k,n))"); // tmpl("(le(i,j,k,n),le(i,j,k,n),le(i,j,k,n))"); while( i < n ) { if( m > 0 ) { i = 2*i; } else { i = 3*i; } } assert (i > 0 ); }
::std::string make_tmp_file(::std::string name, ::std::ofstream& of) { name += "XXXXXX"; ::std::vector<char> tmpl(name.begin(), name.end()); tmpl.push_back('\0'); int fd = ::mkstemp(&tmpl[0]); if (fd != -1) { name.assign(tmpl.begin(), tmpl.end()-1); of.open(name.c_str(), ::std::ios_base::trunc | ::std::ios_base::out); ::close(fd); } return name; }
void TemplateChooserPage::initializePage() // ---------------------------------------------------------------------------- // Fill the template list with the templates we find on the disk // ---------------------------------------------------------------------------- { NewDocumentWizard * wiz = (NewDocumentWizard *)wizard(); QDir appPath(TaoApp->applicationDirPath() + "/templates"); QDir userPath(TaoApp->defaultTaoPreferencesFolderPath() + "/templates"); QList<QDir> dirs; dirs << appPath << userPath; wiz->templates = Templates(dirs); // Insert entries from the settings (remote menus) QSharedPointer<TextureCache> tc = TextureCache::instance(); QString docPath = TaoApp->window()->currentProjectFolderPath(); QSettings settings; int size = settings.beginReadArray("examples"); for (int i = 0; i < size; i++) { settings.setArrayIndex(i); QString caption = settings.value("caption").toString(); QString url = settings.value("url").toString(); QString tip = settings.value("description").toString(); Template tmpl(userPath); tmpl.name = caption; tmpl.description = tip; tmpl.type = "url"; tmpl.mainFile = url; QString thumbPath = exampleThumbnail(caption); CachedTexture *tex = tc->load(thumbPath, docPath); tmpl.thumbnail = QPixmap::fromImage(tex->loadedImage()); if (tmpl.thumbnail.isNull()) { connect(tex, SIGNAL(textureUpdated(CachedTexture *)), this, SLOT(thumbnailChanged(CachedTexture *))); } wiz->templates.append(tmpl); }
void main() { int i,k,n,l; tmpl("(le(n,i,k,l),le(n,i,k,l))"); assume(l>0); for (k=1;k<n;k++){ //assert(k<=n); //assert(1<=k)assert(1<=j);; for (i=l;i<n;i++) { //assert(1<=i); //assert(i<=n); } for (i=l;i<n;i++) { assert(1<=k); } } }
int main( int argc, char *argv[]){ int n,l,r,i,j; //tmpl("(le(n,l,r,i,j),le(n,l,r,i,j),le(n,l,r,i,j))"); tmpl("(le(n,l,r,i,j),le(n,l,r,i,j))"); assume(1 <= n); l = n/2 + 1; r = n; if(l>1) { l--; } else { r--; } while(r > 1) { i = l; j = 2*l; while(j <= r) { if( j < r) { if( NONDET ) j = j + 1; } if( NONDET ) { break; } i = j; j = 2*j; } if(l > 1) { l--; } else { assert(r <= n); r--; } } return 0; }
std::string DBSearch::build_where(const std::string& col, const std::string& data) const { static const std::vector<std::string> select_modes = boost::assign::list_of(std::string("LIKE"))("=")("LIKE")("REGEXP"); static const std::vector<std::string> inverted_select_modes = boost::assign::list_of(std::string("LIKE"))("<>")("NOT LIKE")("NOT REGEXP"); std::string where_condition; if (_cast_to.empty()) where_condition.append(base::sqlstring("!", base::QuoteOnlyIfNeeded) << col); else { std::string tmpl("CAST(! AS "); tmpl += _cast_to; tmpl += ") "; where_condition.append(base::sqlstring(tmpl.c_str(), base::QuoteOnlyIfNeeded) << col); } where_condition.append(" "); where_condition.append(_invert ? inverted_select_modes[_search_mode].c_str() : select_modes[_search_mode].c_str()); if (_search_mode == Contains) where_condition.append(std::string(base::sqlstring(" ? ", 0) << "%" + data + "%")); else where_condition.append(std::string(base::sqlstring(" ? ", 0) << data)); return where_condition; }
void mustache_spec_parse_partials(yaml_document_t * document, yaml_node_t * node, mustache::Node::Partials * partials) { if( node->type != YAML_MAPPING_NODE ) { return; } mustache::Mustache mustache; std::string ckey; yaml_node_pair_t * pair; for( pair = node->data.mapping.pairs.start; pair < node->data.mapping.pairs.top; pair++ ) { yaml_node_t * keyNode = yaml_document_get_node(document, pair->key); yaml_node_t * valueNode = yaml_document_get_node(document, pair->value); char * keyValue = reinterpret_cast<char *>(keyNode->data.scalar.value); char * valueValue = reinterpret_cast<char *>(valueNode->data.scalar.value); std::string ckey(keyValue); std::string tmpl(valueValue); mustache::Node node; partials->insert(std::make_pair(ckey, node)); mustache.tokenize(&tmpl, &(*partials)[ckey]); } }
void ReportGenerator::slotAddresseeSearchFinished( int ) { qDebug() << "** Reached slotAddresseeSearchFinished!"; // now the addressee search through the address provider is finished. // Rendering can be started. QString tmplFile = findTemplate( mArchDoc->docType() ); if ( tmplFile.isEmpty() ) { // qDebug () << "tmplFile is empty!"; return; } else { // qDebug () << "Reading this template: " << tmplFile; } // create a text template TextTemplate tmpl( tmplFile ); if( !tmpl.open() ) { // qDebug () << "ERROR: Unable to open document template " << tmplFile; QMessageBox msgBox; msgBox.setText(i18n("The template file could not be opened: %1\n ", tmplFile)); msgBox.setInformativeText(i18n("Please check the setup and the doc type configuration.")); msgBox.setWindowTitle(i18n("Template Error")); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.exec(); return; } /* replace the placeholders */ /* A placeholder has the format <!-- %VALUE --> */ const ArchDocPositionList posList = mArchDoc->positions(); QString h; ArchDocPositionList::const_iterator it; int specialPosCnt = 0; int taxFreeCnt = 0; int reducedTaxCnt = 0; int fullTaxCnt = 0; bool individualTax = false; /* Check for the tax settings: If the taxType is not the same for all items, * we have individual Tax setting and show the tax marker etc. */ DocPositionBase::TaxType ttype = DocPositionBase::TaxInvalid; for ( it = posList.begin(); it != posList.end(); ++it ) { ArchDocPosition pos (*it); if( ttype == DocPositionBase::TaxInvalid ) { ttype = pos.taxType(); } else { if( ttype != pos.taxType() ) { // different from previous one? individualTax = true; break; } } } /* now loop over the items to fill the template structures */ for ( it = posList.begin(); it != posList.end(); ++it ) { ArchDocPosition pos (*it); tmpl.createDictionary( "POSITIONS" ); tmpl.setValue( "POSITIONS", TAG( "POS_NUMBER" ) , pos.posNumber() ); tmpl.setValue( "POSITIONS", "POS_TEXT", rmlString( pos.text(), QString( "%1text" ).arg( pos.kind().toLower() ) ) ); // format the amount value of the item, do not show the precision if there is no fraction double amount = pos.amount(); QString num; num.setNum( amount ); // no locale awareness. int prec = 0; if( num.contains( QChar('.') ) ) { // there is a decimal point // calculate the precision prec = num.length() - (1+num.lastIndexOf( QChar('.') ) ); } // qDebug() << "**** " << num << " has precision " << prec; h = mArchDoc->locale()->toString( amount, 'f', prec ); tmpl.setValue( "POSITIONS", "POS_AMOUNT", h ); tmpl.setValue( "POSITIONS", "POS_UNIT", escapeTrml2pdfXML( pos.unit() ) ); tmpl.setValue( "POSITIONS", "POS_UNITPRICE", pos.unitPrice().toString( mArchDoc->locale() ) ); tmpl.setValue( "POSITIONS", "POS_TOTAL", pos.nettoPrice().toString( mArchDoc->locale() ) ); tmpl.setValue( "POSITIONS", "POS_KIND", pos.kind().toLower() ); QString taxType; if( individualTax ) { if( pos.taxType() == 1 ) { taxFreeCnt++; taxType = "TAX_FREE"; } else if( pos.taxType() == 2 ) { reducedTaxCnt++; taxType = "REDUCED_TAX"; } else { // ATTENTION: Default for all non known tax types is full tax. fullTaxCnt++; taxType = "FULL_TAX"; } tmpl.createSubDictionary( "POSITIONS", taxType ); } /* item kind: Normal, alternative or demand item. For normal items, the kind is empty. */ if ( !pos.kind().isEmpty() ) { specialPosCnt++; } } if ( specialPosCnt ) { tmpl.createDictionary( "SPECIAL_POS" ); tmpl.setValue( "SPECIAL_POS", "COUNT", QString::number( specialPosCnt ) ); } /* * Just show the tax index if we have multiple tax settings */ if( individualTax ) { tmpl.createDictionary( "TAX_FREE_ITEMS" ); tmpl.setValue( "TAX_FREE_ITEMS", "COUNT", QString::number( taxFreeCnt )); tmpl.createDictionary( "REDUCED_TAX_ITEMS" ); tmpl.setValue( "REDUCED_TAX_ITEMS", "COUNT", QString::number( reducedTaxCnt )); tmpl.setValue( "REDUCED_TAX_ITEMS", "TAX", mArchDoc->locale()->toString( mArchDoc->reducedTax()) ); tmpl.createDictionary( "FULL_TAX_ITEMS" ); tmpl.setValue( "FULL_TAX_ITEMS", "COUNT", QString::number( fullTaxCnt )); tmpl.setValue( "FULL_TAX_ITEMS", "TAX", mArchDoc->locale()->toString( mArchDoc->tax()) ); } /* now replace stuff in the whole document */ tmpl.setValue( TAG( "DATE" ), mArchDoc->locale()->toString(mArchDoc->date(), QLocale::NarrowFormat) ); tmpl.setValue( TAG( "DOCTYPE" ), escapeTrml2pdfXML( mArchDoc->docType() ) ); tmpl.setValue( TAG( "ADDRESS" ), escapeTrml2pdfXML( mArchDoc->address() ) ); contactToTemplate( &tmpl, "CLIENT", mCustomerContact ); contactToTemplate( &tmpl, "MY", myContact ); tmpl.setValue( TAG( "DOCID" ), escapeTrml2pdfXML( mArchDoc->ident() ) ); tmpl.setValue( TAG( "PROJECTLABEL" ), escapeTrml2pdfXML( mArchDoc->projectLabel() ) ); tmpl.setValue( TAG( "SALUT" ), escapeTrml2pdfXML( mArchDoc->salut() ) ); tmpl.setValue( TAG( "GOODBYE" ), escapeTrml2pdfXML( mArchDoc->goodbye() ) ); tmpl.setValue( TAG( "PRETEXT" ), rmlString( mArchDoc->preText() ) ); tmpl.setValue( TAG( "POSTTEXT" ), rmlString( mArchDoc->postText() ) ); tmpl.setValue( TAG( "BRUTTOSUM" ), mArchDoc->bruttoSum().toString( mArchDoc->locale() ) ); tmpl.setValue( TAG( "NETTOSUM" ), mArchDoc->nettoSum().toString( mArchDoc->locale() ) ); h = mArchDoc->locale()->toString( mArchDoc->tax() ); // qDebug () << "Tax in archive document: " << h; if ( mArchDoc->reducedTaxSum().toLong() > 0 ) { tmpl.createDictionary( DICT( "SECTION_REDUCED_TAX" ) ); tmpl.setValue( "SECTION_REDUCED_TAX", TAG( "REDUCED_TAX_SUM" ), mArchDoc->reducedTaxSum().toString( mArchDoc->locale() ) ); h = mArchDoc->locale()->toString( mArchDoc->reducedTax() ); tmpl.setValue( "SECTION_REDUCED_TAX", TAG( "REDUCED_TAX" ), h ); tmpl.setValue( "SECTION_REDUCED_TAX", TAG( "REDUCED_TAX_LABEL" ), i18n( "reduced VAT" ) ); } if ( mArchDoc->fullTaxSum().toLong() > 0 ) { tmpl.createDictionary( DICT( "SECTION_FULL_TAX" ) ); tmpl.setValue( "SECTION_FULL_TAX", TAG( "FULL_TAX_SUM" ), mArchDoc->fullTaxSum().toString( mArchDoc->locale() ) ); h = mArchDoc->locale()->toString( mArchDoc->tax() ); tmpl.setValue( "SECTION_FULL_TAX", TAG( "FULL_TAX" ), h ); tmpl.setValue( "SECTION_FULL_TAX", TAG( "FULL_TAX_LABEL" ), i18n( "VAT" ) ); } h = mArchDoc->locale()->toString( mArchDoc->tax() ); tmpl.setValue( TAG( "VAT" ), h ); tmpl.setValue( TAG( "VATSUM" ), mArchDoc->taxSum().toString( mArchDoc->locale() ) ); // My own contact data const QString output = tmpl.expand(); convertTemplate(output); }
void InsetFormulaMacro::write(ostream & os) const { os << "FormulaMacro\n"; WriteStream wi(os, false, false, WriteStream::wsDefault); tmpl()->write(wi); }
void TabletServer::mainScreen(QTcpSocket *socket, const QStringList &path, const QStringMap &query) { Document * doc = mw->currentDocument(); if(!doc) { generic404(socket,path,query); return; } QStringList pathCopy = path; pathCopy.takeFirst(); // should be "tablet", but could be anything - /tablet/ is canonized for use in the tablet cache manifest for sfari QString control = pathCopy.isEmpty() ? "" : pathCopy.takeFirst().toLower(); //bool flag = pathCopy.isEmpty() ? 0 : pathCopy.takeFirst().toInt(); //qDebug() << "TabletServer::mainScreen(): control: "<<control; HttpUser *user = HttpUserUtil::instance()->currentUser(); if(control != "login") { if(!user) { QString from = QUrl::toPercentEncoding(toPathString(path,query).toAscii()).replace(" ", "+"); redirect(socket, "/tablet/login?from=" + from); return; } // I've decided to allow guests "view-only" access // else // if(user->level() == HttpUser::Guest) // { // Http_Send_Ok(socket) << "<html><head><title>Not Allowed</title></head><body><h1>Not Allowed</h1>Sorry, you're not allowed to access this site. (<a href='/tablet/login'>Login again</a>)</body></html"; // return; // } } if(control.isEmpty()) { SimpleTemplate tmpl("data/http/tablet.tmpl"); tmpl.param("user_name", user->user()); tmpl.param("user_level", (int)user->level()); tmpl.param("is_admin", user->level() == HttpUser::Admin); tmpl.param("is_user", user->level() == HttpUser::User); tmpl.param("is_guest", user->level() == HttpUser::Guest); // tmpl.param("list",outputGroupList); // // OutputControl * outputControl = mw->outputControl(liveId); // tmpl.param("black_toggled", outputControl->isBlackToggled()); // tmpl.param("clear_toggled", outputControl->isClearToggled()); // // SlideGroupViewControl *viewControl = mw->viewControl(liveId); // tmpl.param("qslide_toggled", viewControl->isQuickSlideToggled()); // // if(doc->filename().isEmpty()) // tmpl.param("docfile",tr("New File")); // else // tmpl.param("docfile",QFileInfo(doc->filename()).baseName()); // Http_Send_Ok(socket) << // "Content-Type: text/html\n\n" << // tmpl.toString(); QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "text/html"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << tmpl.toString(); } else if(control == "login") { loginPage(socket, path, query, "/tablet/login"); } else if(control == "list") { QString filter = query["filter"]; // Can be empty // Don't allow non-admins to search because it would interfere with the main UI if(!filter.isEmpty() && user->level() < HttpUser::Admin) { Http_Send_500txt(socket, "Not Authorized"); return; } QString mode = query["mode"]; // Either "db" or "file" bool pollingFlag = query["poll"] == "true"; QString clientMD5 = query["md5"]; // the md5 of the list contents to use to check for changes if pollingFlag == true // Compile list of results matching mode (from db or from current sched) and the filter, and return as json string // TODO add button to search online //qDebug() << "TabletServer::mainScreen(): list: mode: "<<mode<<", filter: "<<filter; QVariantMap result; QVariantList resultList; bool moreResults = false; int listCutoffLimit = 10; // included in results even though only relevant to 'db' mode // Buffer for compiling MD5 hash QStringList md5sigList; if(mode == "db") { bool isChanged = true; if(pollingFlag) { int currentChangeSequence = m_songListModel->currentChangeSequence(); QString seqString = QString::number(currentChangeSequence); // md5sigList is used to generate the md5 to send back to the client md5sigList << seqString; QString seqMd5 = MD5::md5sum(md5sigList.join("")); isChanged = false; if(seqMd5 != clientMD5) isChanged = true; } // Only regen list if 'isChanged' - and isChanged is only set to 'false' if: // - Client is in polling mode // - Client MD5 matches the MD5 of current sequence number // We do this because generating the list makes a call to filter() // which can cause trouble if the filter string is empty and the user // in the DViz main UI is trying to search for something (which would NOT change // the sequence number above, but would change the filter) if(isChanged) { // List cutoff limit only relevant when searching/quering database. // Cutoff not honored or implemented for file schedule QString maxResults = query["max"]; if(!maxResults.isEmpty()) listCutoffLimit = maxResults.toInt(); if(listCutoffLimit < 1) listCutoffLimit = 1; m_songListModel->filter(filter); moreResults = m_songListModel->rowCount() > listCutoffLimit; int resultCount = qMin(listCutoffLimit, m_songListModel->rowCount()); for(int i=0; i<resultCount; i++) { SongRecord *song = m_songListModel->songAt(i); if(!song) { qDebug() << "TabletServer::mainScreen(): list: db: No song at index: "<<i; continue; } QVariantMap line; line["id"] = song->songId(); line["title"] = song->title(); line["text"] = song->text(); line["arr"] = song->defaultArrangement()->arrangement().join(", "); resultList << line; // We use the sequence md5 (above) for the md5 sig instead of the list contents now // md5sigList.append(QString::number(song->songId())); // md5sigList.append(song->title()); // md5sigList.append(song->text()); } } } else { // int liveId = AppSettings::taggedOutput("live")->id(); // SlideGroup *liveGroup = mw->outputInst(liveId)->slideGroup(); DocumentListModel * model = mw->documentListModel(); //uint secs = QDateTime::currentDateTime().toTime_t(); QString lowerFilter = filter.toLower(); for(int idx = 0; idx < model->rowCount(); idx++) { SlideGroup * group = model->groupAt(idx); SongSlideGroup *songGroup = dynamic_cast<SongSlideGroup*>(group); if(songGroup && ( songGroup->groupTitle().toLower().contains(lowerFilter) || songGroup->text().toLower().contains(lowerFilter))) { QVariantMap row; QVariant tooltip = model->data(model->index(group->groupNumber(),0), Qt::ToolTipRole); QString viewText = group->assumedName(); if(tooltip.isValid()) viewText = tooltip.toString(); row["id"] = idx; //songGroup->groupId(); row["title"] = viewText; row["text"] = songGroup->text(); row["arr"] = songGroup->arrangement().join(", "); row["mapping"] = genArrMapping(songGroup->text(), songGroup->arrangement()); resultList << row; md5sigList.append(QString::number(songGroup->groupId())); md5sigList.append(viewText); md5sigList.append(songGroup->text()); } // We don't limit the number of results in the document results moreResults = false; } } QString currentMD5 = MD5::md5sum(md5sigList.join("")); bool isChanged = true; if(pollingFlag && currentMD5 == clientMD5) isChanged = false; if(isChanged) { result["num"] = resultList.size(); result["list"] = QVariant(resultList); result["more"] = moreResults; result["cutoff"] = listCutoffLimit; } else result["nochange"] = true; result["md5"] = currentMD5; QString jsonString = m_toJson.serialize(result); //qDebug() << "TabletServer::mainScreen(): list: result: "<<result; //qDebug() << "TabletServer::mainScreen(): list: json: "<<jsonString; // Http_Send_Ok(socket) << // "Content-Type: application/json\n\n" << // jsonString; QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "application/json"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << jsonString; } else if(control == "save_song") { if(user->level() < HttpUser::Admin) { Http_Send_500txt(socket, "Not Authorized"); return; } QString mode = query["mode"]; // Either "db" or "file" int itemid = query["itemid"].toInt(); // If mode is db, itemid is a songid, otherwise, it's a group index QString title = query["title"]; QString text = query["text"]; QString arrTxt = query["arr"]; QStringList newArrList = arrTxt.split(QRegExp("\\s*,\\s*")); SongRecord *song; if(mode == "file") { DocumentListModel * model = mw->documentListModel(); SlideGroup * group = model->groupAt(itemid); SongSlideGroup *songGroup = dynamic_cast<SongSlideGroup*>(group); // Update the document model songGroup->setArrangement(newArrList); songGroup->setGroupTitle(title); songGroup->setText(text); // automatically regenerates slides in document song = songGroup->song(); } else { song = SongRecord::retrieve(itemid); } if(!song) { Http_Send_404(socket) << "Invalid songid"; } song->setTitle(title); song->setText(text); SongArrangement *arr = song->defaultArrangement(); arr->setArrangement(newArrList); // Changes automatically committed to database QVariantMap result; result["mapping"] = genArrMapping(song->text(), arr->arrangement()); QString jsonString = m_toJson.serialize(result); QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "application/json"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << jsonString; } else if(control == "add_song") { if(user->level() < HttpUser::Admin) { Http_Send_500txt(socket, "Not Authorized"); return; } int songid = query["songid"].toInt(); QVariantMap result; SongRecord *song = SongRecord::retrieve(songid); if(!song) { Http_Send_404(socket) << "Invalid songid"; } else { SlideGroup *group = mw->songBrowser()->createSlideGroup(song); group->setGroupNumber(mw->currentDocument()->numGroups()); mw->currentDocument()->addGroup(group); result["groupnum"] = group->groupNumber(); } QString jsonString = m_toJson.serialize(result); QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "application/json"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << jsonString; } else if(control == "del_song") { if(user->level() < HttpUser::Admin) { Http_Send_500txt(socket, "Not Authorized"); return; } QString mode = query["mode"]; // Either "db" or "file" int itemid = query["itemid"].toInt(); if(mode == "file") { DocumentListModel * model = mw->documentListModel(); SlideGroup * group = model->groupAt(itemid); SongSlideGroup *songGroup = dynamic_cast<SongSlideGroup*>(group); if(!songGroup) { Http_Send_404(socket) << "Invalid songid"; } mw->currentDocument()->removeGroup(songGroup); } else { SongRecord *song = SongRecord::retrieve(itemid); if(!song) { Http_Send_404(socket) << "Invalid songid"; } SongRecord::deleteSong(song); } QVariantMap result; // Nothing to see here, move along. QString jsonString = m_toJson.serialize(result); QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "application/json"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << jsonString; } else if(control == "show_slide") { if(user->level() < HttpUser::User) { Http_Send_500txt(socket, "Not Authorized"); return; } int groupIdx = query["group"].toInt(); Document * doc = mw->currentDocument(); if(!doc) { generic404(socket,path,query); return; } if(groupIdx < 0 || groupIdx >= doc->numGroups()) { generic404(socket,path,query); return; } DocumentListModel * docModel = mw->documentListModel(); SlideGroup *group = docModel->groupAt(groupIdx); if(!group) { generic404(socket,path,query); return; } int liveId = AppSettings::taggedOutput("live")->id(); SlideGroup *liveGroup = mw->outputInst(liveId)->slideGroup(); Slide * liveSlide = mw->outputInst(liveId)->slide(); //SlideGroupViewControl *viewControl = mw->viewControl(liveId); //Slide * liveSlide = viewControl->selectedSlide(); int idx = query.value("slide").toInt(); if(idx < 0 || idx > group->numSlides()) { generic404(socket,path,query); return; } Slide *slide = group->at(idx); if(liveGroup != group || liveSlide != slide) mw->setLiveGroup(group, ! slide ? liveSlide : slide); // prevent changing slides when loading the group page if group already live on different slide if(liveGroup == group && liveSlide != slide/* && nextPathElement != "icon"*/) { // this is JUST a change slide request mw->setLiveGroup(liveGroup,slide); // 204 = HTTP No Content, ("...[the browser] SHOULD NOT change its document view...") Http_Send_Response(socket,"HTTP/1.0 204 Changed Slide") << ""; // BlackBerry Internet Browser doesnt honor HTTP 204, so we have to use javascript to make it not change the current document return; } else Http_Send_Response(socket,"HTTP/1.0 204 No Change") << ""; } else if(control == "poll_live_slide") { if(user->level() < HttpUser::Guest) { Http_Send_500txt(socket, "Not Authorized"); return; } DocumentListModel * docModel = mw->documentListModel(); QVariantMap result; bool ok = true; int liveId = AppSettings::taggedOutput("live")->id(); SlideGroup *liveGroup = mw->outputInst(liveId)->slideGroup(); Slide *liveSlide = mw->outputInst(liveId)->slide(); if(!liveGroup) { ok = false; result["error"] = "NLG"; } // SlideGroupViewControl *viewControl = mw->viewControl(liveId); // Slide * liveSlide = viewControl->selectedSlide(); if(!liveSlide && ok) { ok = false; result["error"] = "NLS"; } if(ok) { int groupIdx = docModel->indexForGroup(liveGroup).row(); int slideIdx = liveGroup->indexOf(liveSlide); result["groupIdx"] = groupIdx; result["slideIdx"] = slideIdx; } QString jsonString = m_toJson.serialize(result); QHttpResponseHeader header(QString("HTTP/1.0 200 OK")); header.setValue("Content-Type", "application/json"); respond(socket, header); QTextStream output(socket); output.setAutoDetectUnicode(true); output << jsonString; } else { generic404(socket,path,query); } }
void KraftViewRO::setup( DocGuardedPtr doc ) { KraftViewBase::setup( doc ); if ( !doc ) return; KLocale *locale = doc->locale(); if ( !locale ) locale = KGlobal::locale(); // do stuff like open a template and render values into it. KStandardDirs stdDirs; QString templFileName = QString( "kraftdoc_ro.trml" ); QString findFile = "kraft/reports/" + templFileName; QString tmplFile = stdDirs.findResource( "data", findFile ); QByteArray kraftHome = qgetenv("KRAFT_HOME"); if( !kraftHome.isEmpty() ) { QString file = QString( "%1/reports/kraftdoc_ro.trml").arg(QString::fromLocal8Bit(kraftHome)); QFileInfo fi(file); if( fi.exists() && fi.isReadable() ) { tmplFile = file; } } if( tmplFile.isEmpty() ) { kDebug() << "Could not find template to render ro view of document."; return; } TextTemplate tmpl( tmplFile ); if( !tmpl.open() ) { return; } tmpl.setValue( DOC_RO_TAG( "HEADLINE" ), doc->docType() + " " + doc->ident() ); tmpl.setValue( DOC_RO_TAG( "DATE" ), locale->formatDate( doc->date(), KLocale::ShortDate ) ); tmpl.setValue( DOC_RO_TAG( "DOC_TYPE" ), doc->docType() ); QString address = doc->address(); address.replace( '\n', "<br/>" ); tmpl.setValue( DOC_RO_TAG( "ADDRESS" ), address ); tmpl.setValue( DOC_RO_TAG( "DOCNO" ), doc->ident() ); tmpl.setValue( DOC_RO_TAG( "PRETEXT" ), doc->preText() ); tmpl.setValue( DOC_RO_TAG( "POSTTEXT" ), doc->postText() ); tmpl.setValue( DOC_RO_TAG( "SALUT" ), doc->salut() ); tmpl.setValue( DOC_RO_TAG( "GOODBYE" ), doc->goodbye() ); DocPositionList positions = doc->positions(); // check the tax settings: If all items have the same settings, its not individual. bool individualTax = false; int ttype = -1; foreach( DocPositionBase *dp, positions ) { if( ttype == -1 ) { ttype = dp->taxType(); } else { if( ttype != dp->taxType() ) { // different from previous one? individualTax = true; break; } } } int pos = 1; int taxFreeCnt = 0; int reducedTaxCnt = 0; int fullTaxCnt = 0; QString docType = doc->docType(); DocType dt(docType); foreach( DocPositionBase *dpb, positions ) { DocPosition *dp = static_cast<DocPosition*>(dpb); tmpl.createDictionary( "ITEMS" ); tmpl.setValue( "ITEMS", "NUMBER", QString::number( pos++ ) ); tmpl.setValue( "ITEMS", "TEXT", dp->text() ); tmpl.setValue( "ITEMS", "AMOUNT", locale->formatNumber( dp->amount() ) ); tmpl.setValue( "ITEMS", "UNIT", dp->unit().einheit( dp->amount() ) ); double singlePrice = dp->unitPrice().toDouble(); if( dt.pricesVisible() ) { tmpl.createSubDictionary("ITEMS", "PRICE_DISPLAY"); tmpl.setValue( "PRICE_DISPLAY", "SINGLE_PRICE", locale->formatMoney( singlePrice ) ); QString style( "positive" ); if ( singlePrice < 0 ) { style = "negative"; } tmpl.setValue( "PRICE_DISPLAY", "PRICE_STYLE", style ); tmpl.setValue( "PRICE_DISPLAY", "PRICE", locale->formatMoney( dp->overallPrice().toDouble() ) ); } #if 0 QString taxType; if( individualTax ) { if( dp->taxType() == 1 ) { taxFreeCnt++; taxType = "TAX_FREE"; } else if( dp->taxType() == 2 ) { taxType = "REDUCED_TAX"; reducedTaxCnt++; } else { // ATTENTION: Default for all non known tax types is full tax. fullTaxCnt++; taxType = "FULL_TAX"; } } #endif }