void GNaiveBayes_testMath() { const char* trainFile = "@RELATION test\n" "@ATTRIBUTE a {t,f}\n" "@ATTRIBUTE b {r,g,b}\n" "@ATTRIBUTE c {y,n}\n" "@DATA\n" "t,r,y\n" "f,r,n\n" "t,g,y\n" "f,g,y\n" "f,g,n\n" "t,r,n\n" "t,r,y\n" "t,b,y\n" "f,r,y\n" "f,g,n\n" "f,b,y\n" "t,r,n\n"; GMatrix train; train.parseArff(trainFile, strlen(trainFile)); GMatrix* pFeatures = train.cloneSub(0, 0, train.rows(), 2); std::unique_ptr<GMatrix> hFeatures(pFeatures); GMatrix* pLabels = train.cloneSub(0, 2, train.rows(), 1); std::unique_ptr<GMatrix> hLabels(pLabels); GNaiveBayes nb; nb.setEquivalentSampleSize(0.0); nb.train(*pFeatures, *pLabels); GPrediction out; GVec pat(2); pat[0] = 0; pat[1] = 0; nb.predictDistribution(pat, &out); GNaiveBayes_CheckResults(7.0/12.0, 4.0/7.0*3.0/7.0, 5.0/12.0, 2.0/5.0*3.0/5.0, &out); pat[0] = 0; pat[1] = 1; nb.predictDistribution(pat, &out); GNaiveBayes_CheckResults(7.0/12.0, 4.0/7.0*2.0/7.0, 5.0/12.0, 2.0/5.0*2.0/5.0, &out); pat[0] = 0; pat[1] = 2; nb.predictDistribution(pat, &out); GNaiveBayes_CheckResults(7.0/12.0, 4.0/7.0*2.0/7.0, 5.0/12.0, 2.0/5.0*0.0/5.0, &out); pat[0] = 1; pat[1] = 0; nb.predictDistribution(pat, &out); GNaiveBayes_CheckResults(7.0/12.0, 3.0/7.0*3.0/7.0, 5.0/12.0, 3.0/5.0*3.0/5.0, &out); pat[0] = 1; pat[1] = 1; nb.predictDistribution(pat, &out); GNaiveBayes_CheckResults(7.0/12.0, 3.0/7.0*2.0/7.0, 5.0/12.0, 3.0/5.0*2.0/5.0, &out); pat[0] = 1; pat[1] = 2; nb.predictDistribution(pat, &out); GNaiveBayes_CheckResults(7.0/12.0, 3.0/7.0*2.0/7.0, 5.0/12.0, 3.0/5.0*0.0/5.0, &out); }
int main() { std::string line; boost::regex pat( "^Subject: (Re: |Aw: )*(.*)" ); while (std::cin) { std::getline(std::cin, line); boost::smatch matches; if (boost::regex_match(line, matches, pat)) std::cout << matches[2] << std::endl; } return 0; }
static JSVAL list_fields(JSARGS args) { HandleScope scope; MYSQL *handle = (MYSQL *) args[0]->IntegerValue(); const char *table = NULL; const char *wild = NULL; if (args.Length() > 1) { String::Utf8Value tbl(args[1]->ToString()); table = *tbl; } if (args.Length() > 2) { String::Utf8Value pat(args[1]->ToString()); wild = *pat; } return scope.Close(Integer::New((unsigned long)mysql_list_fields(handle, table, wild))); }
void BGDialog::initUI() { // Screens for (unsigned i = 0; i < m_numScreens; ++i) m_comboScreen->addItem(i18n("Screen %1", i + 1)); // Patterns m_comboPattern->addItem(i18n("Single Color")); m_comboPattern->addItem(i18n("Horizontal Gradient")); m_comboPattern->addItem(i18n("Vertical Gradient")); m_comboPattern->addItem(i18n("Pyramid Gradient")); m_comboPattern->addItem(i18n("Pipecross Gradient")); m_comboPattern->addItem(i18n("Elliptic Gradient")); m_patterns = KBackgroundPattern::list(); m_patterns.sort(); // Defined order QStringList::const_iterator it; for (it = m_patterns.constBegin(); it != m_patterns.constEnd(); ++it) { KBackgroundPattern pat(*it); if (pat.isAvailable()) m_comboPattern->addItem(pat.comment()); } loadWallpaperFilesList(); // Wallpaper tilings: again they must match the ones from bgrender.cc m_comboWallpaperPos->addItem(i18n("Centered")); m_comboWallpaperPos->addItem(i18n("Tiled")); m_comboWallpaperPos->addItem(i18n("Center Tiled")); m_comboWallpaperPos->addItem(i18n("Centered Maxpect")); m_comboWallpaperPos->addItem(i18n("Tiled Maxpect")); m_comboWallpaperPos->addItem(i18n("Scaled")); m_comboWallpaperPos->addItem(i18n("Centered Auto Fit")); m_comboWallpaperPos->addItem(i18n("Scale & Crop")); // Blend modes: make sure these match with kdesktop/bgrender.cc !! m_comboBlend->addItem(i18n("No Blending")); m_comboBlend->addItem(i18n("Flat")); m_comboBlend->addItem(i18n("Horizontal")); m_comboBlend->addItem(i18n("Vertical")); m_comboBlend->addItem(i18n("Pyramid")); m_comboBlend->addItem(i18n("Pipecross")); m_comboBlend->addItem(i18n("Elliptic")); m_comboBlend->addItem(i18n("Intensity")); m_comboBlend->addItem(i18n("Saturation")); m_comboBlend->addItem(i18n("Contrast")); m_comboBlend->addItem(i18n("Hue Shift")); }
void IntlTestDecimalFormatAPI::testRounding(/*char *par*/) { UErrorCode status = U_ZERO_ERROR; double Roundingnumber = 2.55; double Roundingnumber1 = -2.55; //+2.55 results -2.55 results double result[]={ 3.0, -2.0, // kRoundCeiling 0, 2.0, -3.0, // kRoundFloor 1, 2.0, -2.0, // kRoundDown 2, 3.0, -3.0, // kRoundUp 3, 3.0, -3.0, // kRoundHalfEven 4, 3.0, -3.0, // kRoundHalfDown 5, 3.0, -3.0 // kRoundHalfUp 6 }; DecimalFormat pat(status); if(U_FAILURE(status)) { errcheckln(status, "ERROR: Could not create DecimalFormat (default) - %s", u_errorName(status)); return; } uint16_t mode; uint16_t i=0; UnicodeString message; UnicodeString resultStr; for(mode=0;mode < 7;mode++){ pat.setRoundingMode((DecimalFormat::ERoundingMode)mode); if(pat.getRoundingMode() != (DecimalFormat::ERoundingMode)mode){ errln((UnicodeString)"SetRoundingMode or GetRoundingMode failed for mode=" + mode); } //for +2.55 with RoundingIncrement=1.0 pat.setRoundingIncrement(1.0); pat.format(Roundingnumber, resultStr); message= (UnicodeString)"Round() failed: round(" + (double)Roundingnumber + UnicodeString(",") + mode + UnicodeString(",FALSE) with RoundingIncrement=1.0==>"); verify(message, resultStr, result[i++]); message.remove(); resultStr.remove(); //for -2.55 with RoundingIncrement=1.0 pat.format(Roundingnumber1, resultStr); message= (UnicodeString)"Round() failed: round(" + (double)Roundingnumber1 + UnicodeString(",") + mode + UnicodeString(",FALSE) with RoundingIncrement=1.0==>"); verify(message, resultStr, result[i++]); message.remove(); resultStr.remove(); } }
void PatternMenuButton::Draw (BRect update) { extern ColorMenuButton *locolor, *hicolor; rgb_color Hi = hicolor->color(); rgb_color Lo = locolor->color(); update = Bounds(); SetHighColor (Hi); SetLowColor (Lo); FillRect (update, pat()); SetHighColor (Grey8); SetDrawingMode (B_OP_ADD); StrokeLine (update.LeftBottom(), update.LeftTop()); StrokeLine (update.RightTop()); SetDrawingMode (B_OP_SUBTRACT); StrokeLine (update.RightBottom()); StrokeLine (update.LeftBottom()); }
void IntlTestDecimalFormatAPI::TestScale() { typedef struct TestData { double inputValue; int inputScale; const char *expectedOutput; } TestData; static TestData testData[] = { { 100.0, 3, "100,000" }, { 10034.0, -2, "100.34" }, { 0.86, -3, "0.0009" }, { -0.000455, 1, "-0%" }, { -0.000555, 1, "-1%" }, { 0.000455, 1, "0%" }, { 0.000555, 1, "1%" }, }; UErrorCode status = U_ZERO_ERROR; DecimalFormat pat(status); if(U_FAILURE(status)) { errcheckln(status, "ERROR: Could not create DecimalFormat (default) - %s", u_errorName(status)); return; } UnicodeString message; UnicodeString resultStr; UnicodeString exp; UnicodeString percentPattern("#,##0%"); pat.setMaximumFractionDigits(4); for(int32_t i=0; i < UPRV_LENGTHOF(testData); i++) { if ( i > 2 ) { pat.applyPattern(percentPattern,status); } pat.setAttribute(UNUM_SCALE,testData[i].inputScale,status); pat.format(testData[i].inputValue, resultStr); message = UnicodeString("Unexpected output for ") + testData[i].inputValue + UnicodeString(" and scale ") + testData[i].inputScale + UnicodeString(". Got: "); exp = testData[i].expectedOutput; verifyString(message, resultStr, exp); message.remove(); resultStr.remove(); exp.remove(); } }
U_CAPI USet* U_EXPORT2 uset_openPattern(const UChar* pattern, int32_t patternLength, UErrorCode* ec) { UnicodeString pat(patternLength==-1, pattern, patternLength); UnicodeSet* set = new UnicodeSet(pat, *ec); /* test for NULL */ if(set == 0) { *ec = U_MEMORY_ALLOCATION_ERROR; return 0; } if (U_FAILURE(*ec)) { delete set; set = NULL; } return (USet*) set; }
std::string get_merged_file_name(int c, const char **v) { int level = 1; std::regex pat("[0-9]{8}.[0-9]{6}.cs[0-9]+.tc[0-9]+.([0-9]+).idx"); for (int i = 1; i < c; ++i) { std::string fn(v[i]); std::smatch matches; if (std::regex_search(fn , matches, pat)) { int tmp = string_utils::strtoi(matches[1]); if (tmp > level) level = tmp; } } time_t t; struct tm * ti; time(&t); ti = localtime(&t); char dt[50], fn[256]; strftime(dt, 50, "%Y%m%d.%H%M%S", ti); sprintf(fn, "%s.cs%d.tc%d.%d.idx", dt, collection_size, term_count, level+1); return fn; }
bool SyncEngine::estimateState(QString fn, csync_ftw_type_e t, SyncFileStatus* s) { Q_UNUSED(t); QString pat(fn); if( t == CSYNC_FTW_TYPE_DIR && ! fn.endsWith(QLatin1Char('/'))) { pat.append(QLatin1Char('/')); } Q_FOREACH(const SyncFileItemPtr &item, _syncedItems) { //qDebug() << Q_FUNC_INFO << fn << item._file << fn.startsWith(item._file) << item._file.startsWith(fn); if (item->_file.startsWith(pat) || item->_file == fn /* the same directory or file */) { qDebug() << Q_FUNC_INFO << "Setting" << fn << " to STATUS_EVAL"; s->set(SyncFileStatus::STATUS_EVAL); return true; } } return false; }
U_CAPI void U_EXPORT2 utrans_setFilter(UTransliterator* trans, const UChar* filterPattern, int32_t filterPatternLen, UErrorCode* status) { utrans_ENTRY(status); UnicodeFilter* filter = NULL; if (filterPattern != NULL && *filterPattern != 0) { // Create read only alias of filterPattern: UnicodeString pat(filterPatternLen < 0, filterPattern, filterPatternLen); filter = new UnicodeSet(pat, *status); /* test for NULL */ if (filter == NULL) { *status = U_MEMORY_ALLOCATION_ERROR; return; } if (U_FAILURE(*status)) { delete filter; filter = NULL; } } ((Transliterator*) trans)->adoptFilter(filter); }
void Database::PatFilter::Process(u_short Pid, u_char Tid, const u_char *Data, int Length) { //printf("PatFilter: Processing Pid %d, Tid %d\n", Pid, Tid); if (Pid==0x00 && Tid==SI::TableIdPAT) { DatabaseLock lock(database); if (!database->HasState(TuningStatePat)) { SI::PAT pat(Data); if (!pat.CheckCRCAndParse()) return; if (pat.getSectionNumber()) printf(" !!! PAT SECTION %d !!!\n", pat.getSectionNumber()); database->pat=pat; database->state=TuningStatePat; database->ts.tid=pat.getTransportStreamId(); database->stateVar.Broadcast(); //printf("Setting database's pat\n"); } SetStatus(false); } /*else if (Pid==0x10 && Tid==SI::TableIdNIT && !database->nitValid) { printf("PatFilter: Processing Pid %d, Tid %d\n", Pid, Tid); DatabaseLock lock(database); if (!database->nitValid) { SI::NIT nit(Data); if (!nit.CheckCRCAndParse()) return; database->nit=nit; database->nitValid=true; database->patVar.Broadcast(); //printf("Setting database's nit\n"); } } if (database->nitValid && database->patValid) { //printf("PatFilter: Setting status false\n"); SetStatus(false); }*/ }
void bv_elim::elim(quantifier* q, quantifier_ref& r) { svector<symbol> names, _names; sort_ref_buffer sorts(m_manager), _sorts(m_manager); expr_ref_buffer pats(m_manager); expr_ref_buffer no_pats(m_manager); expr_ref_buffer subst_map(m_manager), _subst_map(m_manager); var_subst subst(m_manager); bv_util bv(m_manager); expr_ref new_body(m_manager); expr* old_body = q->get_expr(); unsigned num_decls = q->get_num_decls(); family_id bfid = m_manager.get_family_id("bv"); // // Traverse sequence of bound variables to eliminate // bit-vecctor variables and replace them by // Booleans. // unsigned var_idx = 0; for (unsigned i = num_decls; i > 0; ) { --i; sort* s = q->get_decl_sort(i); symbol nm = q->get_decl_name(i); if (bv.is_bv_sort(s)) { // convert n-bit bit-vector variable into sequence of n-Booleans. unsigned num_bits = bv.get_bv_size(s); expr_ref_buffer args(m_manager); expr_ref bv(m_manager); for (unsigned j = 0; j < num_bits; ++j) { std::ostringstream new_name; new_name << nm.str(); new_name << "_"; new_name << j; var* v = m_manager.mk_var(var_idx++, m_manager.mk_bool_sort()); args.push_back(v); _sorts.push_back(m_manager.mk_bool_sort()); _names.push_back(symbol(new_name.str().c_str())); } bv = m_manager.mk_app(bfid, OP_MKBV, 0, 0, args.size(), args.c_ptr()); _subst_map.push_back(bv.get()); } else { _subst_map.push_back(m_manager.mk_var(var_idx++, s)); _sorts.push_back(s); _names.push_back(nm); } } // // reverse the vectors. // SASSERT(_names.size() == _sorts.size()); for (unsigned i = _names.size(); i > 0; ) { --i; names.push_back(_names[i]); sorts.push_back(_sorts[i]); } for (unsigned i = _subst_map.size(); i > 0; ) { --i; subst_map.push_back(_subst_map[i]); } expr* const* sub = subst_map.c_ptr(); unsigned sub_size = subst_map.size(); subst(old_body, sub_size, sub, new_body); for (unsigned j = 0; j < q->get_num_patterns(); j++) { expr_ref pat(m_manager); subst(q->get_pattern(j), sub_size, sub, pat); pats.push_back(pat); } for (unsigned j = 0; j < q->get_num_no_patterns(); j++) { expr_ref nopat(m_manager); subst(q->get_no_pattern(j), sub_size, sub, nopat); no_pats.push_back(nopat); } r = m_manager.mk_quantifier(true, names.size(), sorts.c_ptr(), names.c_ptr(), new_body.get(), q->get_weight(), q->get_qid(), q->get_skid(), pats.size(), pats.c_ptr(), no_pats.size(), no_pats.c_ptr()); }
SparseMatrix_ptr SystemMatrix::mergeSystemMatrix() const { const index_t n = mainBlock->numRows; if (mpi_info->size == 1) { index_t* ptr = new index_t[n]; #pragma omp parallel for for (index_t i=0; i<n; i++) ptr[i] = i; SparseMatrix_ptr out(mainBlock->getSubmatrix(n, n, ptr, ptr)); delete[] ptr; return out; } #ifdef ESYS_MPI const index_t size=mpi_info->size; const index_t rank=mpi_info->rank; // Merge main block and couple block to get the complete column entries // for each row allocated to current rank. Output (ptr, idx, val) // contains all info needed from current rank to merge a system matrix index_t *ptr, *idx; double *val; mergeMainAndCouple(&ptr, &idx, &val); std::vector<MPI_Request> mpi_requests(size*2); std::vector<MPI_Status> mpi_stati(size*2); // Now, pass all info to rank 0 and merge them into one sparse matrix if (rank == 0) { // First, copy local ptr values into ptr_global const index_t global_n = getGlobalNumRows(); index_t* ptr_global = new index_t[global_n+1]; memcpy(ptr_global, ptr, (n+1)*sizeof(index_t)); delete[] ptr; index_t iptr = n+1; index_t* temp_n = new index_t[size]; index_t* temp_len = new index_t[size]; temp_n[0] = iptr; // Second, receive ptr values from other ranks for (index_t i=1; i<size; i++) { const index_t remote_n = row_distribution->first_component[i+1] - row_distribution->first_component[i]; MPI_Irecv(&ptr_global[iptr], remote_n, MPI_INT, i, mpi_info->counter()+i, mpi_info->comm, &mpi_requests[i]); temp_n[i] = remote_n; iptr += remote_n; } mpi_info->incCounter(size); MPI_Waitall(size-1, &mpi_requests[1], &mpi_stati[0]); // Then, prepare to receive idx and val from other ranks index_t len = 0; index_t offset = -1; for (index_t i=0; i<size; i++) { if (temp_n[i] > 0) { offset += temp_n[i]; len += ptr_global[offset]; temp_len[i] = ptr_global[offset]; } else temp_len[i] = 0; } index_t* idx_global = new index_t[len]; iptr = temp_len[0]; offset = n+1; for (index_t i=1; i<size; i++) { len = temp_len[i]; MPI_Irecv(&idx_global[iptr], len, MPI_INT, i, mpi_info->counter()+i, mpi_info->comm, &mpi_requests[i]); const index_t remote_n = temp_n[i]; for (index_t j=0; j<remote_n; j++) { ptr_global[j+offset] = ptr_global[j+offset] + iptr; } offset += remote_n; iptr += len; } memcpy(idx_global, idx, temp_len[0]*sizeof(index_t)); delete[] idx; MPI_Waitall(size-1, &mpi_requests[1], &mpi_stati[0]); mpi_info->incCounter(size); delete[] temp_n; // Then generate the sparse matrix const index_t rowBlockSize = mainBlock->row_block_size; const index_t colBlockSize = mainBlock->col_block_size; Pattern_ptr pat(new Pattern(mainBlock->pattern->type, global_n, global_n, ptr_global, idx_global)); SparseMatrix_ptr out(new SparseMatrix(mainBlock->type, pat, rowBlockSize, colBlockSize, false)); // Finally, receive and copy the values iptr = temp_len[0] * block_size; for (index_t i=1; i<size; i++) { len = temp_len[i]; MPI_Irecv(&out->val[iptr], len * block_size, MPI_DOUBLE, i, mpi_info->counter()+i, mpi_info->comm, &mpi_requests[i]); iptr += len*block_size; } memcpy(out->val, val, temp_len[0] * sizeof(double) * block_size); delete[] val; mpi_info->incCounter(size); MPI_Waitall(size-1, &mpi_requests[1], &mpi_stati[0]); delete[] temp_len; return out; } else { // it's not rank 0 // First, send out the local ptr index_t tag = mpi_info->counter()+rank; MPI_Issend(&ptr[1], n, MPI_INT, 0, tag, mpi_info->comm, &mpi_requests[0]); // Next, send out the local idx index_t len = ptr[n]; tag += size; MPI_Issend(idx, len, MPI_INT, 0, tag, mpi_info->comm, &mpi_requests[1]); // At last, send out the local val len *= block_size; tag += size; MPI_Issend(val, len, MPI_DOUBLE, 0, tag, mpi_info->comm, &mpi_requests[2]); MPI_Waitall(3, &mpi_requests[0], &mpi_stati[0]); mpi_info->setCounter(tag + size - rank); delete[] ptr; delete[] idx; delete[] val; } // rank #endif return SparseMatrix_ptr(); }
void IntlTestSimpleDateFormatAPI::testAPI(/*char *par*/) { UErrorCode status = U_ZERO_ERROR; // ======= Test constructors logln("Testing SimpleDateFormat constructors"); SimpleDateFormat def(status); if(U_FAILURE(status)) { dataerrln("ERROR: Could not create SimpleDateFormat (default) - exitting"); return; } status = U_ZERO_ERROR; const UnicodeString pattern("yyyy.MM.dd G 'at' hh:mm:ss z"); const UnicodeString override("y=hebr;d=thai;s=arab"); const UnicodeString override_bogus("y=hebr;d=thai;s=bogus"); SimpleDateFormat pat(pattern, status); if(U_FAILURE(status)) { errln("ERROR: Could not create SimpleDateFormat (pattern)"); } status = U_ZERO_ERROR; SimpleDateFormat pat_fr(pattern, Locale::getFrench(), status); if(U_FAILURE(status)) { errln("ERROR: Could not create SimpleDateFormat (pattern French)"); } status = U_ZERO_ERROR; DateFormatSymbols *symbols = new DateFormatSymbols(Locale::getFrench(), status); if(U_FAILURE(status)) { errln("ERROR: Could not create DateFormatSymbols (French)"); } status = U_ZERO_ERROR; SimpleDateFormat cust1(pattern, symbols, status); if(U_FAILURE(status)) { dataerrln("ERROR: Could not create SimpleDateFormat (pattern, symbols*) - exitting"); return; } status = U_ZERO_ERROR; SimpleDateFormat cust2(pattern, *symbols, status); if(U_FAILURE(status)) { errln("ERROR: Could not create SimpleDateFormat (pattern, symbols)"); } status = U_ZERO_ERROR; SimpleDateFormat ovr1(pattern, override, status); if(U_FAILURE(status)) { errln("ERROR: Could not create SimpleDateFormat (pattern, override)"); } status = U_ZERO_ERROR; SimpleDateFormat ovr2(pattern, override, Locale::getGerman(), status); if(U_FAILURE(status)) { errln("ERROR: Could not create SimpleDateFormat (pattern, override, locale)"); } status = U_ZERO_ERROR; SimpleDateFormat ovr3(pattern, override_bogus, Locale::getGerman(), status); if(U_SUCCESS(status)) { errln("ERROR: Should not have been able to create SimpleDateFormat (pattern, override, locale) with a bogus override"); } SimpleDateFormat copy(pat); // ======= Test clone(), assignment, and equality logln("Testing clone(), assignment and equality operators"); if( ! (copy == pat) || copy != pat) { errln("ERROR: Copy constructor (or ==) failed"); } copy = cust1; if(copy != cust1) { errln("ERROR: Assignment (or !=) failed"); } Format *clone = def.clone(); if( ! (*clone == def) ) { errln("ERROR: Clone() (or ==) failed"); } delete clone; // ======= Test various format() methods logln("Testing various format() methods"); UDate d = 837039928046.0; Formattable fD(d, Formattable::kIsDate); UnicodeString res1, res2; FieldPosition pos1(0), pos2(0); res1 = def.format(d, res1, pos1); logln( (UnicodeString) "" + d + " formatted to " + res1); status = U_ZERO_ERROR; res2 = cust1.format(fD, res2, pos2, status); if(U_FAILURE(status)) { errln("ERROR: format(Formattable [Date]) failed"); } logln((UnicodeString) "" + fD.getDate() + " formatted to " + res2); // ======= Test parse() logln("Testing parse()"); UnicodeString text("02/03/76 2:50 AM, CST"); UDate result1, result2; ParsePosition pos(0); result1 = def.parse(text, pos); logln(text + " parsed into " + result1); status = U_ZERO_ERROR; result2 = def.parse(text, status); if(U_FAILURE(status)) { errln("ERROR: parse() failed"); } logln(text + " parsed into " + result2); // ======= Test getters and setters logln("Testing getters and setters"); const DateFormatSymbols *syms = pat.getDateFormatSymbols(); if(!syms) { errln("Couldn't obtain DateFormatSymbols. Quitting test!"); return; } if(syms->getDynamicClassID() != DateFormatSymbols::getStaticClassID()) { errln("ERROR: format->getDateFormatSymbols()->getDynamicClassID() != DateFormatSymbols::getStaticClassID()"); } DateFormatSymbols *newSyms = new DateFormatSymbols(*syms); def.adoptDateFormatSymbols(newSyms); pat_fr.setDateFormatSymbols(*newSyms); if( *(pat.getDateFormatSymbols()) != *(def.getDateFormatSymbols())) { errln("ERROR: adopt or set DateFormatSymbols() failed"); } status = U_ZERO_ERROR; UDate startDate = pat.get2DigitYearStart(status); if(U_FAILURE(status)) { errln("ERROR: getTwoDigitStartDate() failed"); } status = U_ZERO_ERROR; pat_fr.set2DigitYearStart(startDate, status); if(U_FAILURE(status)) { errln("ERROR: setTwoDigitStartDate() failed"); } // ======= Test DateFormatSymbols constructor newSyms =new DateFormatSymbols("gregorian", status); if(U_FAILURE(status)) { errln("ERROR: new DateFormatSymbols() failed"); } def.adoptDateFormatSymbols(newSyms); // ======= Test applyPattern() logln("Testing applyPattern()"); UnicodeString p1("yyyy.MM.dd G 'at' hh:mm:ss z"); logln("Applying pattern " + p1); status = U_ZERO_ERROR; pat.applyPattern(p1); UnicodeString s2; s2 = pat.toPattern(s2); logln("Extracted pattern is " + s2); if(s2 != p1) { errln("ERROR: toPattern() result did not match pattern applied"); } logln("Applying pattern " + p1); status = U_ZERO_ERROR; pat.applyLocalizedPattern(p1, status); if(U_FAILURE(status)) { errln("ERROR: applyPattern() failed with " + (int32_t) status); } UnicodeString s3; status = U_ZERO_ERROR; s3 = pat.toLocalizedPattern(s3, status); if(U_FAILURE(status)) { errln("ERROR: toLocalizedPattern() failed"); } logln("Extracted pattern is " + s3); if(s3 != p1) { errln("ERROR: toLocalizedPattern() result did not match pattern applied"); } // ======= Test getStaticClassID() logln("Testing getStaticClassID()"); status = U_ZERO_ERROR; DateFormat *test = new SimpleDateFormat(status); if(U_FAILURE(status)) { errln("ERROR: Couldn't create a SimpleDateFormat"); } if(test->getDynamicClassID() != SimpleDateFormat::getStaticClassID()) { errln("ERROR: getDynamicClassID() didn't return the expected value"); } delete test; // ======= Test Ticket 5684 (Parsing with 'e' and 'Y') SimpleDateFormat object(UNICODE_STRING_SIMPLE("YYYY'W'wwe"), status); if(U_FAILURE(status)) { errln("ERROR: Couldn't create a SimpleDateFormat"); } object.setLenient(false); ParsePosition pp(0); UDate udDate = object.parse("2007W014", pp); if ((double)udDate == 0.0) { errln("ERROR: Parsing failed using 'Y' and 'e'"); } }
nsresult nsThebesImage::ThebesDrawTile(gfxContext *thebesContext, nsIDeviceContext* dx, const gfxPoint& offset, const gfxRect& targetRect, const nsIntRect& aSubimageRect, const PRInt32 xPadding, const PRInt32 yPadding) { NS_ASSERTION(xPadding >= 0 && yPadding >= 0, "negative padding"); if (targetRect.size.width <= 0.0 || targetRect.size.height <= 0.0) return NS_OK; // don't do anything if we have a transparent pixel source if (mSinglePixel && mSinglePixelColor.a == 0.0) return NS_OK; PRBool doSnap = !(thebesContext->CurrentMatrix().HasNonTranslation()); PRBool hasPadding = ((xPadding != 0) || (yPadding != 0)); gfxImageSurface::gfxImageFormat format = mFormat; gfxPoint tmpOffset = offset; if (mSinglePixel && !hasPadding) { thebesContext->SetDeviceColor(mSinglePixelColor); } else { nsRefPtr<gfxASurface> surface; PRInt32 width, height; if (hasPadding) { /* Ugh we have padding; create a temporary surface that's the size of the surface + pad area, * and render the image into it first. Then we'll tile that surface. */ width = mWidth + xPadding; height = mHeight + yPadding; // Reject over-wide or over-tall images. if (!AllowedImageSize(width, height)) return NS_ERROR_FAILURE; format = gfxASurface::ImageFormatARGB32; surface = gfxPlatform::GetPlatform()->CreateOffscreenSurface( gfxIntSize(width, height), format); if (!surface || surface->CairoStatus()) { return NS_ERROR_OUT_OF_MEMORY; } gfxContext tmpContext(surface); if (mSinglePixel) { tmpContext.SetDeviceColor(mSinglePixelColor); } else { tmpContext.SetSource(ThebesSurface()); } tmpContext.SetOperator(gfxContext::OPERATOR_SOURCE); tmpContext.Rectangle(gfxRect(0, 0, mWidth, mHeight)); tmpContext.Fill(); } else { width = mWidth; height = mHeight; surface = ThebesSurface(); } // Scale factor to account for CSS pixels; note that the offset (and // therefore p0) is in device pixels, while the width and height are in // CSS pixels. gfxFloat scale = gfxFloat(dx->AppUnitsPerDevPixel()) / gfxFloat(nsIDeviceContext::AppUnitsPerCSSPixel()); if ((aSubimageRect.width < width || aSubimageRect.height < height) && (thebesContext->CurrentMatrix().HasNonTranslation() || scale != 1.0)) { // Some of the source image should not be drawn, and we're going // to be doing more than just translation, so we might accidentally // sample the non-drawn pixels. Avoid that by creating a // temporary image representing the portion that will be drawn, // with built-in padding since we can't use EXTEND_PAD and // EXTEND_REPEAT at the same time for different axes. PRInt32 padX = aSubimageRect.width < width ? 1 : 0; PRInt32 padY = aSubimageRect.height < height ? 1 : 0; PRInt32 tileWidth = PR_MIN(aSubimageRect.width, width); PRInt32 tileHeight = PR_MIN(aSubimageRect.height, height); // This tmpSurface will contain a snapshot of the repeated // tile image at (aSubimageRect.x, aSubimageRect.y, // tileWidth, tileHeight), with padX padding added to the left // and right sides and padY padding added to the top and bottom // sides. nsRefPtr<gfxASurface> tmpSurface; tmpSurface = gfxPlatform::GetPlatform()->CreateOffscreenSurface( gfxIntSize(tileWidth + 2*padX, tileHeight + 2*padY), format); if (!tmpSurface || tmpSurface->CairoStatus()) { return NS_ERROR_OUT_OF_MEMORY; } gfxContext tmpContext(tmpSurface); tmpContext.SetOperator(gfxContext::OPERATOR_SOURCE); gfxPattern pat(surface); pat.SetExtend(gfxPattern::EXTEND_REPEAT); // Copy the needed portion of the source image to the temporary // surface. We also copy over horizontal and/or vertical padding // strips one pixel wide, plus the corner pixels if necessary. // So in the most general case the temporary surface ends up // looking like // P P P ... P P P // P X X ... X X P // P X X ... X X P // ............... // P X X ... X X P // P X X ... X X P // P P P ... P P P // Where each P pixel has the color of its nearest source X // pixel. We implement this as a loop over all nine possible // areas, [padding, body, padding] x [padding, body, padding]. // Note that we will not need padding on both axes unless // we are painting just a single tile, in which case this // will hardly ever get called since nsCSSRendering converts // the single-tile case to nsLayoutUtils::DrawImage. But this // could be called on other paths (XUL trees?) and it's simpler // and clearer to do it the general way. PRInt32 destY = 0; for (PRInt32 y = -1; y <= 1; ++y) { PRInt32 stripHeight = y == 0 ? tileHeight : padY; if (stripHeight == 0) continue; PRInt32 srcY = y == 1 ? aSubimageRect.YMost() - padY : aSubimageRect.y; PRInt32 destX = 0; for (PRInt32 x = -1; x <= 1; ++x) { PRInt32 stripWidth = x == 0 ? tileWidth : padX; if (stripWidth == 0) continue; PRInt32 srcX = x == 1 ? aSubimageRect.XMost() - padX : aSubimageRect.x; gfxMatrix patMat; patMat.Translate(gfxPoint(srcX - destX, srcY - destY)); pat.SetMatrix(patMat); tmpContext.SetPattern(&pat); tmpContext.Rectangle(gfxRect(destX, destY, stripWidth, stripHeight)); tmpContext.Fill(); tmpContext.NewPath(); destX += stripWidth; } destY += stripHeight; } // tmpOffset was the top-left of the old tile image. Make it // the top-left of the new tile image. Note that tmpOffset is // in destination coordinate space so we have to scale our // CSS pixels. tmpOffset += gfxPoint(aSubimageRect.x - padX, aSubimageRect.y - padY)/scale; surface = tmpSurface; } gfxMatrix patMat; gfxPoint p0; p0.x = - floor(tmpOffset.x + 0.5); p0.y = - floor(tmpOffset.y + 0.5); patMat.Scale(scale, scale); patMat.Translate(p0); gfxPattern pat(surface); pat.SetExtend(gfxPattern::EXTEND_REPEAT); pat.SetMatrix(patMat); #ifndef XP_MACOSX if (scale < 1.0) { // See bug 324698. This is a workaround. See comments // by the earlier SetFilter call. pat.SetFilter(0); } #endif thebesContext->SetPattern(&pat); } gfxContext::GraphicsOperator op = thebesContext->CurrentOperator(); if (op == gfxContext::OPERATOR_OVER && format == gfxASurface::ImageFormatRGB24) thebesContext->SetOperator(gfxContext::OPERATOR_SOURCE); thebesContext->NewPath(); thebesContext->Rectangle(targetRect, doSnap); thebesContext->Fill(); thebesContext->SetOperator(op); thebesContext->SetDeviceColor(gfxRGBA(0,0,0,0)); return NS_OK; }
void DiveProfileItem::modelDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { bool eventAdded = false; if (!shouldCalculateStuff(topLeft, bottomRight)) return; AbstractProfilePolygonItem::modelDataChanged(topLeft, bottomRight); if (polygon().isEmpty()) return; show_reported_ceiling = prefs.dcceiling; reported_ceiling_in_red = prefs.redceiling; profileColor = getColor(DEPTH_BOTTOM); int currState = qobject_cast<ProfileWidget2 *>(scene()->views().first())->currentState; if (currState == ProfileWidget2::PLAN) { plot_data *entry = dataModel->data().entry; for (int i = 0; i < dataModel->rowCount(); i++, entry++) { int max = maxCeiling(i); // Don't scream if we violate the ceiling by a few cm if (entry->depth < max - 100) { profileColor = QColor(Qt::red); if (!eventAdded) { add_event(&displayed_dive.dc, entry->sec, SAMPLE_EVENT_CEILING, -1, max / 1000, "planned waypoint above ceiling"); eventAdded = true; } } } } /* Show any ceiling we may have encountered */ if (prefs.dcceiling && !prefs.redceiling) { QPolygonF p = polygon(); plot_data *entry = dataModel->data().entry + dataModel->rowCount() - 1; for (int i = dataModel->rowCount() - 1; i >= 0; i--, entry--) { if (!entry->in_deco) { /* not in deco implies this is a safety stop, no ceiling */ p.append(QPointF(hAxis->posAtValue(entry->sec), vAxis->posAtValue(0))); } else { p.append(QPointF(hAxis->posAtValue(entry->sec), vAxis->posAtValue(qMin(entry->stopdepth, entry->depth)))); } } setPolygon(p); } // This is the blueish gradient that the Depth Profile should have. // It's a simple QLinearGradient with 2 stops, starting from top to bottom. QLinearGradient pat(0, polygon().boundingRect().top(), 0, polygon().boundingRect().bottom()); pat.setColorAt(1, profileColor); pat.setColorAt(0, getColor(DEPTH_TOP)); setBrush(QBrush(pat)); int last = -1; for (int i = 0, count = dataModel->rowCount(); i < count; i++) { struct plot_data *entry = dataModel->data().entry + i; if (entry->depth < 2000) continue; if ((entry == entry->max[2]) && entry->depth / 100 != last) { plot_depth_sample(entry, Qt::AlignHCenter | Qt::AlignBottom, getColor(SAMPLE_DEEP)); last = entry->depth / 100; } if ((entry == entry->min[2]) && entry->depth / 100 != last) { plot_depth_sample(entry, Qt::AlignHCenter | Qt::AlignTop, getColor(SAMPLE_SHALLOW)); last = entry->depth / 100; } if (entry->depth != last) last = -1; } }
void cLivePatFilter::Process(u_short Pid, u_char Tid, const u_char *Data, int Length) { if (Pid == 0x00) { if (Tid == 0x00) { SI::PAT pat(Data, false); if (!pat.CheckCRCAndParse()) return; SI::PAT::Association assoc; for (SI::Loop::Iterator it; pat.associationLoop.getNext(assoc, it); ) { if (!assoc.isNITPid()) { const cChannel *Channel = Channels.GetByServiceID(Source(), Transponder(), assoc.getServiceId()); if (Channel && (Channel == m_Channel)) { int prevPmtPid = m_pmtPid; if (0 != (m_pmtPid = assoc.getPid())) { m_pmtSid = assoc.getServiceId(); if (m_pmtPid != prevPmtPid) { Add(m_pmtPid, 0x02); m_pmtVersion = -1; } return; } } } } } } else if (Pid == m_pmtPid && Tid == SI::TableIdPMT && Source() && Transponder()) { SI::PMT pmt(Data, false); if (!pmt.CheckCRCAndParse()) return; if (pmt.getServiceId() != m_pmtSid) return; // skip broken PMT records if (m_pmtVersion != -1) { if (m_pmtVersion != pmt.getVersionNumber()) { // printf("cStreamdevPatFilter: PMT version changed, detaching all pids\n"); cFilter::Del(m_pmtPid, 0x02); m_pmtPid = 0; // this triggers PAT scan } return; } m_pmtVersion = pmt.getVersionNumber(); SI::PMT::Stream stream; int pids[MAXRECEIVEPIDS + 1]; eStreamType types[MAXRECEIVEPIDS + 1]; char langs[MAXRECEIVEPIDS + 1][MAXLANGCODE2]; int subtitlingType[MAXRECEIVEPIDS + 1]; int compositionPageId[MAXRECEIVEPIDS + 1]; int ancillaryPageId[MAXRECEIVEPIDS + 1]; int streams = 0; for (SI::Loop::Iterator it; pmt.streamLoop.getNext(stream, it); ) { eStreamType type; int pid = GetPid(stream, &type, langs[streams], &subtitlingType[streams], &compositionPageId[streams], &ancillaryPageId[streams]); if (0 != pid && streams < MAXRECEIVEPIDS) { pids[streams] = pid; types[streams] = type; streams++; } } pids[streams] = 0; int newstreams = 0; for (int i = 0; i < streams; i++) { if (m_Streamer->HaveStreamDemuxer(pids[i], types[i]) == -1) newstreams++; } if (newstreams > 0) { m_Streamer->m_FilterMutex.Lock(); if (m_Streamer->m_Receiver) { DEBUGLOG("Detaching Live Receiver"); m_Streamer->m_Device->Detach(m_Streamer->m_Receiver); DELETENULL(m_Streamer->m_Receiver); } for (int idx = 0; idx < MAXRECEIVEPIDS; ++idx) { if (m_Streamer->m_Streams[idx]) { DELETENULL(m_Streamer->m_Streams[idx]); m_Streamer->m_Pids[idx] = 0; } } m_Streamer->m_NumStreams = 0; m_Streamer->m_streamReady = false; m_Streamer->m_IFrameSeen = false; for (int i = 0; i < streams; i++) { switch (types[i]) { case stMPEG2AUDIO: { m_Streamer->m_Streams[m_Streamer->m_NumStreams] = new cTSDemuxer(m_Streamer, stMPEG2AUDIO, pids[i]); m_Streamer->m_Streams[m_Streamer->m_NumStreams]->SetLanguage(langs[i]); m_Streamer->m_Pids[m_Streamer->m_NumStreams] = pids[i]; m_Streamer->m_NumStreams++; break; } case stMPEG2VIDEO: { m_Streamer->m_Streams[m_Streamer->m_NumStreams] = new cTSDemuxer(m_Streamer, stMPEG2VIDEO, pids[i]); m_Streamer->m_Pids[m_Streamer->m_NumStreams] = pids[i]; m_Streamer->m_NumStreams++; break; } case stH264: { m_Streamer->m_Streams[m_Streamer->m_NumStreams] = new cTSDemuxer(m_Streamer, stH264, pids[i]); m_Streamer->m_Pids[m_Streamer->m_NumStreams] = pids[i]; m_Streamer->m_NumStreams++; break; } case stAC3: { m_Streamer->m_Streams[m_Streamer->m_NumStreams] = new cTSDemuxer(m_Streamer, stAC3, pids[i]); m_Streamer->m_Streams[m_Streamer->m_NumStreams]->SetLanguage(langs[i]); m_Streamer->m_Pids[m_Streamer->m_NumStreams] = pids[i]; m_Streamer->m_NumStreams++; break; } case stEAC3: { m_Streamer->m_Streams[m_Streamer->m_NumStreams] = new cTSDemuxer(m_Streamer, stEAC3, pids[i]); m_Streamer->m_Streams[m_Streamer->m_NumStreams]->SetLanguage(langs[i]); m_Streamer->m_Pids[m_Streamer->m_NumStreams] = pids[i]; m_Streamer->m_NumStreams++; break; } case stDTS: { m_Streamer->m_Streams[m_Streamer->m_NumStreams] = new cTSDemuxer(m_Streamer, stDTS, pids[i]); m_Streamer->m_Streams[m_Streamer->m_NumStreams]->SetLanguage(langs[i]); m_Streamer->m_Pids[m_Streamer->m_NumStreams] = pids[i]; m_Streamer->m_NumStreams++; break; } case stAAC: { m_Streamer->m_Streams[m_Streamer->m_NumStreams] = new cTSDemuxer(m_Streamer, stAAC, pids[i]); m_Streamer->m_Streams[m_Streamer->m_NumStreams]->SetLanguage(langs[i]); m_Streamer->m_Pids[m_Streamer->m_NumStreams] = pids[i]; m_Streamer->m_NumStreams++; break; } case stLATM: { m_Streamer->m_Streams[m_Streamer->m_NumStreams] = new cTSDemuxer(m_Streamer, stLATM, pids[i]); m_Streamer->m_Streams[m_Streamer->m_NumStreams]->SetLanguage(langs[i]); m_Streamer->m_Pids[m_Streamer->m_NumStreams] = pids[i]; m_Streamer->m_NumStreams++; break; } case stDVBSUB: { m_Streamer->m_Streams[m_Streamer->m_NumStreams] = new cTSDemuxer(m_Streamer, stDVBSUB, pids[i]); m_Streamer->m_Streams[m_Streamer->m_NumStreams]->SetLanguage(langs[i]); m_Streamer->m_Streams[m_Streamer->m_NumStreams]->SetSubtitlingDescriptor(subtitlingType[i], compositionPageId[i], ancillaryPageId[i]); m_Streamer->m_Pids[m_Streamer->m_NumStreams] = pids[i]; m_Streamer->m_NumStreams++; break; } case stTELETEXT: { m_Streamer->m_Streams[m_Streamer->m_NumStreams] = new cTSDemuxer(m_Streamer, stTELETEXT, pids[i]); m_Streamer->m_Pids[m_Streamer->m_NumStreams] = pids[i]; m_Streamer->m_NumStreams++; break; } default: break; } } m_Streamer->m_Receiver = new cLiveReceiver(m_Streamer, m_Channel->GetChannelID(), m_Streamer->m_Priority, m_Streamer->m_Pids); m_Streamer->m_Device->AttachReceiver(m_Streamer->m_Receiver); INFOLOG("Currently unknown new streams found, requesting stream change"); m_Streamer->RequestStreamChange(); m_Streamer->m_FilterMutex.Unlock(); } } }
void FileMgr::operate(const char* pattern, bool dirs, OperateCB cb, InternalOperateCB cb2) { // exactly one of these should be set WTON_ASSERT(cb == NULL || cb2 == NULL); WTON_ASSERT(cb || cb2); String pat(pattern); if (pat.endsWith("\\")) { pat = pat.substr(0, pat.len() - 1); } String ipath; // we'll be gentle, promise! char* sz = const_cast<char*>(pat.cStr()); bool wild = false; char* dir = NULL; while (*sz) { if (*sz == '/' || *sz == '\\') { if (wild) { *sz = 0; gSzs.push_back(sz); gCBs.push_back(cb); gCB2s.push_back(cb2); // recurse wildcard dirs to expand them operate(pat.cStr(), true, NULL, internalOperateCB); gSzs.pop_back(); gCBs.pop_back(); gCB2s.pop_back(); *sz = '\\'; return; } *sz = '\\'; dir = sz; } else if (*sz == '*') wild = true; ++sz; } #ifdef WTON_PC const char* qpat = pat.cStr(); WIN32_FIND_DATA data; // FindFirstFileEx ? HANDLE hResult = FindFirstFile(qpat, &data); if (hResult == INVALID_HANDLE_VALUE) return; if (dir) { *dir = 0; ipath = pat; *dir = '\\'; } do { // TODO: support .dotfiles if (startsWith(data.cFileName, ".")) continue; if (dirs == ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)) { String fullname(dir ? strCat(ipath, "\\", data.cFileName) : data.cFileName); if (dirs) { fullname += "\\"; } operateFile(fullname, cb, cb2); } } while (FindNextFile(hResult, &data)); FindClose(hResult); #else unused(dir); DIR* pdir; dirent* dent; pat.replace("\\", "/"); int pos = pat.find_last_of('/'); String patternn(pat.substr(pos + 1)); int pos2 = patternn.find('*'); String startPat, endPat; if (pos2 != String::npos) { startPat = patternn.substr(0, pos2); endPat = patternn.substr(pos2+1); } else { startPat = endPat = patternn; } pat = pat.substr(0, pos+1); WTON_ASSERT(pat[0] != '.' || pat[1] != '/', pat); pdir = opendir (strCat("./", pat.cStr())); if (pdir != NULL) { while ((dent = readdir (pdir))) { String name(dent->d_name); // TODO: support .dotfiles if (name.startsWith(".")) continue; String fullpath(strCat(pat, name)); bool entDir; { struct stat foo; int ret = stat(fullpath.cStr(), &foo); WTON_ASSERT(ret == 0); entDir = S_ISDIR(foo.st_mode); } if (dirs == entDir) { if (dirs) { fullpath += "/"; } if (name.startsWith(startPat.cStr()) && name.endsWith(endPat.cStr())) { operateFile(fullpath, cb, cb2); } } } (void) closedir (pdir); } else { // this just means the fixed path doesn't exist } #endif }
int main(int argc, char* argv[]) { unsigned int frequency = 0, adapter = 0; boost::filesystem::path directory; bool dvbv5 = false; { boost::program_options::options_description descriptions("Allowed options"); descriptions.add_options() ("help", "produce this help message") ("directory", boost::program_options::value<std::string>(), "Directory to download DSMCC to") ("frequency", boost::program_options::value<unsigned int>(), "Frequency of channel") ("adapter", boost::program_options::value<unsigned int>(), "Adapter number") ("dvbv5", boost::program_options::value<bool>(), "If should use DVBv5 for frontend (default: use dvbv3)") ; boost::program_options::variables_map vm; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, descriptions), vm); boost::program_options::notify(vm); if(vm.count("help") > 0) { std::cout << descriptions << std::endl; return 1; } if(!vm.count("frequency")) { std::cout << "You must specify the frequency (e.g. 599142857)" << std::endl; return 1; } if(!vm.count("directory")) { std::cout << "You must specify a directory to download the DSMCC to" << std::endl; return 1; } directory = vm["directory"].as<std::string>(); if(!boost::filesystem::exists(directory)) { std::cout << "Path " << directory << " doesn't exist" << std::endl; return 1; } frequency = vm["frequency"].as<unsigned int>(); if(vm.count("adapter")) { adapter = vm["adapter"].as<unsigned int>(); } if(vm.count("dvbv5") && vm["dvbv5"].as<bool>()) dvbv5 = true; } std::cout << "Opening /dev/dvb/adapter" << adapter << "/frontend0" << std::endl; std::string adapter_devname; { std::stringstream s; s << "/dev/dvb/adapter" << adapter; adapter_devname = s.str(); } int frontend_fd = 0; { const std::string frontend_devname = adapter_devname + "/frontend0"; frontend_fd = open(frontend_devname.c_str(), O_RDWR); if(frontend_fd < 0) { std::cout << "Couldn't open frontend device " << frontend_devname << " for reading and writing" << std::endl; return -1; } } try { dfd::frontend frontend (frontend_fd); if(dvbv5) frontend.tune_dvb5(frequency); else frontend.tune_dvb3(frequency); dfd::programs programs; dfd::carousels carousels; dfd::filters filters(adapter_devname + "/demux0"); { dfd::filters::table_filter pat(0); filters.add_table_filter(pat, boost::bind(&dfd::parsers::pat, _1, _2, _3, boost::ref(filters) , boost::ref(programs), boost::ref(carousels)) , DMX_IMMEDIATE_START|DMX_ONESHOT|DMX_CHECK_CRC); } filters.run(); std::cout << "Finished. Carousels: " << carousels.carousels_.size() << std::endl; unsigned int files = 0, directories = 0; for(std::map<unsigned int, dfd::carousel>::const_iterator first = carousels.carousels_.begin() , last = carousels.carousels_.end() ; first != last;++first) { files += first->second.file_objects.size(); directories += first->second.directory_objects.size(); } std::cout << "Files: " << files << " directories: " << directories << std::endl; directories = 0; for(std::map<unsigned int, dfd::carousel>::const_iterator first = carousels.carousels_.begin() , last = carousels.carousels_.end() ;first != last;++first) { std::stringstream s; s << "directory" << directories; boost::filesystem::path child_directory = directory / s.str(); boost::filesystem::create_directory(child_directory); dfd::directory_object const& gateway = first->second.gateway; save_directory(child_directory, gateway, carousels); } } catch(std::exception const& e) { std::cout << "Exception caught " << e.what() << std::endl; } }
void cLivePatFilter::Process(u_short Pid, u_char Tid, const u_char *Data, int Length) { if (Pid == 0x00 && Tid == 0x00) { SI::PAT pat(Data, false); if (!pat.CheckCRCAndParse()) return; SI::PAT::Association assoc; for (SI::Loop::Iterator it; pat.associationLoop.getNext(assoc, it); ) { if (!assoc.isNITPid()) { XVDRChannels.Lock(false); const cChannel *Channel = XVDRChannels.Get()->GetByServiceID(Source(), Transponder(), assoc.getServiceId()); if (Channel && (Channel == m_Channel)) { int prevPmtPid = m_pmtPid; if (0 != (m_pmtPid = assoc.getPid())) { m_pmtSid = assoc.getServiceId(); if (m_pmtPid != prevPmtPid) { Add(m_pmtPid, 0x02); m_pmtVersion = -1; } XVDRChannels.Unlock(); return; } } XVDRChannels.Unlock(); } } } else if (Pid == m_pmtPid && Tid == SI::TableIdPMT && Source() && Transponder()) { SI::PMT pmt(Data, false); if (!pmt.CheckCRCAndParse() || pmt.getServiceId() != m_pmtSid) return; if (m_pmtVersion != -1) { if (m_pmtVersion != pmt.getVersionNumber()) { cFilter::Del(m_pmtPid, 0x02); m_pmtPid = 0; // this triggers PAT scan } return; } m_pmtVersion = pmt.getVersionNumber(); // get cached channel data if(m_ChannelCache.size() == 0) m_ChannelCache = cChannelCache::GetFromCache(CreateChannelUID(m_Channel)); // get all streams and check if there are new (currently unknown) streams SI::PMT::Stream stream; cChannelCache cache; for (SI::Loop::Iterator it; pmt.streamLoop.getNext(stream, it); ) { cStreamInfo info; if (GetStreamInfo(stream, info) && cache.size() < MAXRECEIVEPIDS) { info.SetContent(); cache.AddStream(info); } } // no new streams found -> exit if (m_ChannelCache.ismetaof(cache)) return; m_Streamer->m_FilterMutex.Lock(); // create new stream demuxers m_Streamer->Detach(); cache.CreateDemuxers(m_Streamer); m_Streamer->m_ready = false; INFOLOG("Currently unknown new streams found, requesting stream change"); m_Streamer->RequestStreamChange(); // write changed data back to the cache m_ChannelCache = cache; cChannelCache::AddToCache(CreateChannelUID(m_Channel), m_ChannelCache); // try to attach receiver int c = 0; for(; c < 3 && !m_Streamer->Attach(); c++) { INFOLOG("Unable to attach receiver, retrying ..."); usleep(100 * 1000); } // unable to attach receiver if(c == 3) { ERRORLOG("failed to attach receiver, sending detach ..."); m_Streamer->sendDetach(); } m_Streamer->m_FilterMutex.Unlock(); } }
void cLivePatFilter::Process(u_short Pid, u_char Tid, const u_char *Data, int Length) { if (Pid == 0x00 && Tid == 0x00) { SI::PAT pat(Data, false); if (!pat.CheckCRCAndParse()) return; SI::PAT::Association assoc; for (SI::Loop::Iterator it; pat.associationLoop.getNext(assoc, it); ) { if (!assoc.isNITPid()) { const cChannel *Channel = Channels.GetByServiceID(Source(), Transponder(), assoc.getServiceId()); if (Channel && (Channel == m_Channel)) { int prevPmtPid = m_pmtPid; if (0 != (m_pmtPid = assoc.getPid())) { m_pmtSid = assoc.getServiceId(); if (m_pmtPid != prevPmtPid) { Add(m_pmtPid, 0x02); m_pmtVersion = -1; } return; } } } } } else if (Pid == m_pmtPid && Tid == SI::TableIdPMT && Source() && Transponder()) { SI::PMT pmt(Data, false); if (!pmt.CheckCRCAndParse() || pmt.getServiceId() != m_pmtSid) return; if (m_pmtVersion != -1) { if (m_pmtVersion != pmt.getVersionNumber()) { cFilter::Del(m_pmtPid, 0x02); m_pmtPid = 0; // this triggers PAT scan } return; } m_pmtVersion = pmt.getVersionNumber(); // get cached channel data if(m_ChannelCache.size() == 0) m_ChannelCache = cChannelCache::GetFromCache(CreateChannelUID(m_Channel)); // get all streams and check if there are new (currently unknown) streams SI::PMT::Stream stream; cChannelCache cache; for (SI::Loop::Iterator it; pmt.streamLoop.getNext(stream, it); ) { struct StreamInfo info; if (GetStreamInfo(stream, info) && cache.size() < MAXRECEIVEPIDS) cache.AddStream(info); } // no new streams found -> exit if (cache == m_ChannelCache) return; m_Streamer->m_FilterMutex.Lock(); // create new stream demuxers cache.CreateDemuxers(m_Streamer); INFOLOG("Currently unknown new streams found, requesting stream change"); // write changed data back to the cache m_ChannelCache = cache; cChannelCache::AddToCache(CreateChannelUID(m_Channel), m_ChannelCache); m_Streamer->RequestStreamChange(); m_Streamer->m_FilterMutex.Unlock(); } }
void _Cairo_graphics_surfaces <_Graphics_math_float_impl>::surfaces::_Render_to_native_surface < _Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>::surfaces::_Output_surface_data*, basic_output_surface <_Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>> > ( _Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>::surfaces::_Output_surface_data * & osdp, basic_output_surface <_Cairo::_Cairo_graphics_surfaces <_Graphics_math_float_impl>> & sfc ) { auto& osd = *osdp; const cairo_filter_t cairoFilter = CAIRO_FILTER_GOOD; auto& data = osd.data; double displayWidth = static_cast<double>(data.display_dimensions.x()); double displayHeight = static_cast<double>(data.display_dimensions.y()); double backBufferWidth = static_cast<double>(data.back_buffer.dimensions.x()); double backBufferHeight = static_cast<double>(data.back_buffer.dimensions.y()); auto backBufferSfc = data.back_buffer.surface.get(); auto displaySfc = data.display_surface.get(); auto displayContext = data.display_context.get(); cairo_surface_flush(backBufferSfc); cairo_set_operator(displayContext, CAIRO_OPERATOR_SOURCE); if (osd.user_scaling_callback != nullptr) { bool letterbox = false; auto userRect = osd.user_scaling_callback(sfc, letterbox); if (letterbox) { if (data._Letterbox_brush == nullopt) { cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); cairo_paint(displayContext); } else { auto pttn = data._Letterbox_brush.value().data().brush.get(); if (data._Letterbox_brush_props == nullopt) { cairo_pattern_set_extend(pttn, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(pttn, CAIRO_FILTER_GOOD); cairo_matrix_t cPttnMatrix; cairo_matrix_init_identity(&cPttnMatrix); cairo_pattern_set_matrix(pttn, &cPttnMatrix); cairo_set_source(displayContext, pttn); cairo_paint(displayContext); } else { const basic_brush_props<_Cairo_graphics_surfaces<std::experimental::io2d::v1::_Graphics_math_float_impl>>& props = data._Letterbox_brush_props.value(); cairo_pattern_set_extend(pttn, _Extend_to_cairo_extend_t(props.wrap_mode())); cairo_pattern_set_filter(pttn, _Filter_to_cairo_filter_t(props.filter())); cairo_matrix_t cPttnMatrix; const auto& m = props.brush_matrix(); cairo_matrix_init(&cPttnMatrix, m.m00(), m.m01(), m.m10(), m.m11(), m.m20(), m.m21()); cairo_pattern_set_matrix(pttn, &cPttnMatrix); cairo_set_source(displayContext, pttn); cairo_paint(displayContext); } } } cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / displayWidth / static_cast<double>(userRect.width()), 1.0 / displayHeight / static_cast<double>(userRect.height())); cairo_matrix_translate(&ctm, -static_cast<double>(userRect.x()), -static_cast<double>(userRect.y())); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } else { // Calculate the destRect values. switch (data.scl) { case std::experimental::io2d::scaling::letterbox: { _Render_for_scaling_uniform_or_letterbox(osd); } break; case std::experimental::io2d::scaling::uniform: { _Render_for_scaling_uniform_or_letterbox(osd); } break; case std::experimental::io2d::scaling::fill_uniform: { // Maintain aspect ratio and center, but overflow if needed rather than letterboxing. if (backBufferWidth == displayWidth && backBufferHeight == displayHeight) { cairo_set_source_surface(displayContext, backBufferSfc, 0.0, 0.0); cairo_paint(displayContext); } else { auto widthRatio = displayWidth / backBufferWidth; auto heightRatio = displayHeight / backBufferHeight; if (widthRatio < heightRatio) { cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); cairo_paint(displayContext); cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / heightRatio, 1.0 / heightRatio); cairo_matrix_translate(&ctm, trunc(abs((displayWidth - (backBufferWidth * heightRatio)) / 2.0)), 0.0); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } else { cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); cairo_paint(displayContext); cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / widthRatio, 1.0 / widthRatio); cairo_matrix_translate(&ctm, 0.0, trunc(abs((displayHeight - (backBufferHeight * widthRatio)) / 2.0))); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } } } break; case std::experimental::io2d::scaling::fill_exact: { // Maintain aspect ratio and center, but overflow if needed rather than letterboxing. if (backBufferWidth == displayWidth && backBufferHeight == displayHeight) { cairo_set_source_surface(displayContext, backBufferSfc, 0.0, 0.0); cairo_paint(displayContext); } else { auto widthRatio = displayWidth / backBufferWidth; auto heightRatio = displayHeight / backBufferHeight; cairo_matrix_t ctm; cairo_matrix_init_scale(&ctm, 1.0 / widthRatio, 1.0 / heightRatio); unique_ptr<cairo_pattern_t, decltype(&cairo_pattern_destroy)> pat(cairo_pattern_create_for_surface(backBufferSfc), &cairo_pattern_destroy); auto patPtr = pat.get(); cairo_pattern_set_matrix(patPtr, &ctm); cairo_pattern_set_extend(patPtr, CAIRO_EXTEND_NONE); cairo_pattern_set_filter(patPtr, cairoFilter); cairo_set_source(displayContext, patPtr); cairo_paint(displayContext); } } break; case std::experimental::io2d::scaling::none: { cairo_set_source_surface(displayContext, backBufferSfc, 0.0, 0.0); cairo_paint(displayContext); } break; default: { assert("Unexpected _Scaling value." && false); } break; } } // cairo_restore(_Native_context.get()); // This call to cairo_surface_flush is needed for Win32 surfaces to update. cairo_surface_flush(displaySfc); cairo_set_source_rgb(displayContext, 0.0, 0.0, 0.0); SDL_SetRenderDrawColor(data.renderer, 0, 0, 0, 255); if (SDL_RenderClear(data.renderer) != 0) { throw ::std::system_error(::std::make_error_code(::std::errc::io_error), SDL_GetError()); } // Copy Cairo canvas to SDL2 texture unsigned char * src = cairo_image_surface_get_data(displaySfc); // TODO([email protected]): compute the pitch, given const int pitch = (int)backBufferWidth * 4; // '4' == 4 bytes per pixel if (SDL_UpdateTexture(data.texture, nullptr, src, pitch) != 0) { throw ::std::system_error(::std::make_error_code(::std::errc::io_error), SDL_GetError()); } if (SDL_RenderCopy(data.renderer, data.texture, nullptr, nullptr) != 0) { throw ::std::system_error(::std::make_error_code(::std::errc::io_error), SDL_GetError()); } // Present latest image SDL_RenderPresent(data.renderer); }
void cLivePatFilter::Process(u_short Pid, u_char Tid, const u_char *Data, int Length) { if (Pid == 0x00) { if (Tid == 0x00) { SI::PAT pat(Data, false); if (!pat.CheckCRCAndParse()) return; SI::PAT::Association assoc; for (SI::Loop::Iterator it; pat.associationLoop.getNext(assoc, it); ) { if (!assoc.isNITPid()) { const cChannel *Channel = Channels.GetByServiceID(Source(), Transponder(), assoc.getServiceId()); if (Channel && (Channel == m_Channel)) { int prevPmtPid = m_pmtPid; if (0 != (m_pmtPid = assoc.getPid())) { if (m_pmtPid != prevPmtPid) { m_pmtSid = assoc.getServiceId(); Add(m_pmtPid, 0x02); m_pmtVersion = -1; break; } return; } } } } } } else if (Pid == m_pmtPid && Tid == SI::TableIdPMT && Source() && Transponder()) { SI::PMT pmt(Data, false); if (!pmt.CheckCRCAndParse()) return; if (pmt.getServiceId() != m_pmtSid) return; // skip broken PMT records if (m_pmtVersion != -1) { if (m_pmtVersion != pmt.getVersionNumber()) { cFilter::Del(m_pmtPid, 0x02); m_pmtPid = 0; // this triggers PAT scan } return; } m_pmtVersion = pmt.getVersionNumber(); cChannel *Channel = Channels.GetByServiceID(Source(), Transponder(), pmt.getServiceId()); if (Channel) { // Scan the stream-specific loop: SI::PMT::Stream stream; int Vpid = 0; int Ppid = 0; int Vtype = 0; int Apids[MAXAPIDS + 1] = { 0 }; // these lists are zero-terminated int Atypes[MAXAPIDS + 1] = { 0 }; int Dpids[MAXDPIDS + 1] = { 0 }; int Dtypes[MAXDPIDS + 1] = { 0 }; int Spids[MAXSPIDS + 1] = { 0 }; uchar SubtitlingTypes[MAXSPIDS + 1] = { 0 }; uint16_t CompositionPageIds[MAXSPIDS + 1] = { 0 }; uint16_t AncillaryPageIds[MAXSPIDS + 1] = { 0 }; char ALangs[MAXAPIDS][MAXLANGCODE2] = { "" }; char DLangs[MAXDPIDS][MAXLANGCODE2] = { "" }; char SLangs[MAXSPIDS][MAXLANGCODE2] = { "" }; int Tpid = 0; int NumApids = 0; int NumDpids = 0; int NumSpids = 0; for (SI::Loop::Iterator it; pmt.streamLoop.getNext(stream, it); ) { bool ProcessCaDescriptors = false; int esPid = stream.getPid(); switch (stream.getStreamType()) { case 1: // STREAMTYPE_11172_VIDEO case 2: // STREAMTYPE_13818_VIDEO case 0x1B: // MPEG4 Vpid = esPid; Ppid = pmt.getPCRPid(); Vtype = stream.getStreamType(); ProcessCaDescriptors = true; break; case 3: // STREAMTYPE_11172_AUDIO case 4: // STREAMTYPE_13818_AUDIO case 0x0F: // ISO/IEC 13818-7 Audio with ADTS transport syntax case 0x11: // ISO/IEC 14496-3 Audio with LATM transport syntax { if (NumApids < MAXAPIDS) { Apids[NumApids] = esPid; Atypes[NumApids] = stream.getStreamType(); SI::Descriptor *d; for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) { switch (d->getDescriptorTag()) { case SI::ISO639LanguageDescriptorTag: { SI::ISO639LanguageDescriptor *ld = (SI::ISO639LanguageDescriptor *)d; SI::ISO639LanguageDescriptor::Language l; char *s = ALangs[NumApids]; int n = 0; for (SI::Loop::Iterator it; ld->languageLoop.getNext(l, it); ) { if (*ld->languageCode != '-') { // some use "---" to indicate "none" if (n > 0) *s++ = '+'; strn0cpy(s, I18nNormalizeLanguageCode(l.languageCode), MAXLANGCODE1); s += strlen(s); if (n++ > 1) break; } } } break; default: ; } delete d; } NumApids++; } ProcessCaDescriptors = true; } break; case 5: // STREAMTYPE_13818_PRIVATE case 6: // STREAMTYPE_13818_PES_PRIVATE //XXX case 8: // STREAMTYPE_13818_DSMCC { int dpid = 0; int dtype = 0; char lang[MAXLANGCODE1] = { 0 }; SI::Descriptor *d; for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) { switch (d->getDescriptorTag()) { case SI::AC3DescriptorTag: case SI::EnhancedAC3DescriptorTag: dpid = esPid; dtype = d->getDescriptorTag(); ProcessCaDescriptors = true; break; case SI::SubtitlingDescriptorTag: if (NumSpids < MAXSPIDS) { Spids[NumSpids] = esPid; SI::SubtitlingDescriptor *sd = (SI::SubtitlingDescriptor *)d; SI::SubtitlingDescriptor::Subtitling sub; char *s = SLangs[NumSpids]; int n = 0; for (SI::Loop::Iterator it; sd->subtitlingLoop.getNext(sub, it); ) { if (sub.languageCode[0]) { SubtitlingTypes[NumSpids] = sub.getSubtitlingType(); CompositionPageIds[NumSpids] = sub.getCompositionPageId(); AncillaryPageIds[NumSpids] = sub.getAncillaryPageId(); if (n > 0) *s++ = '+'; strn0cpy(s, I18nNormalizeLanguageCode(sub.languageCode), MAXLANGCODE1); s += strlen(s); if (n++ > 1) break; } } NumSpids++; } break; case SI::TeletextDescriptorTag: Tpid = esPid; break; case SI::ISO639LanguageDescriptorTag: { SI::ISO639LanguageDescriptor *ld = (SI::ISO639LanguageDescriptor *)d; strn0cpy(lang, I18nNormalizeLanguageCode(ld->languageCode), MAXLANGCODE1); } break; default: ; } delete d; } if (dpid) { if (NumDpids < MAXDPIDS) { Dpids[NumDpids] = dpid; Dtypes[NumDpids] = dtype; strn0cpy(DLangs[NumDpids], lang, MAXLANGCODE1); NumDpids++; } } } break; case 0x80: // STREAMTYPE_USER_PRIVATE #if APIVERSNUM >= 10728 if (Setup.StandardCompliance == STANDARD_ANSISCTE) #endif { // DigiCipher II VIDEO (ANSI/SCTE 57) Vpid = esPid; Ppid = pmt.getPCRPid(); Vtype = 0x02; // compression based upon MPEG-2 ProcessCaDescriptors = true; break; } // fall through case 0x81: // STREAMTYPE_USER_PRIVATE #if APIVERSNUM >= 10728 if (Setup.StandardCompliance == STANDARD_ANSISCTE) #endif { // ATSC A/53 AUDIO (ANSI/SCTE 57) char lang[MAXLANGCODE1] = { 0 }; SI::Descriptor *d; for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) { switch (d->getDescriptorTag()) { case SI::ISO639LanguageDescriptorTag: { SI::ISO639LanguageDescriptor *ld = (SI::ISO639LanguageDescriptor *)d; strn0cpy(lang, I18nNormalizeLanguageCode(ld->languageCode), MAXLANGCODE1); } break; default: ; } delete d; } if (NumDpids < MAXDPIDS) { Dpids[NumDpids] = esPid; Dtypes[NumDpids] = SI::AC3DescriptorTag; strn0cpy(DLangs[NumDpids], lang, MAXLANGCODE1); NumDpids++; } ProcessCaDescriptors = true; break; } // fall through case 0x82: // STREAMTYPE_USER_PRIVATE #if APIVERSNUM >= 10728 if (Setup.StandardCompliance == STANDARD_ANSISCTE) #endif { // STANDARD SUBTITLE (ANSI/SCTE 27) //TODO break; } // fall through case 0x83 ... 0xFF: // STREAMTYPE_USER_PRIVATE { char lang[MAXLANGCODE1] = { 0 }; bool IsAc3 = false; SI::Descriptor *d; for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) { switch (d->getDescriptorTag()) { case SI::RegistrationDescriptorTag: { SI::RegistrationDescriptor *rd = (SI::RegistrationDescriptor *)d; // http://www.smpte-ra.org/mpegreg/mpegreg.html switch (rd->getFormatIdentifier()) { case 0x41432D33: // 'AC-3' IsAc3 = true; break; default: //printf("Format identifier: 0x%08X (pid: %d)\n", rd->getFormatIdentifier(), esPid); break; } } break; case SI::ISO639LanguageDescriptorTag: { SI::ISO639LanguageDescriptor *ld = (SI::ISO639LanguageDescriptor *)d; strn0cpy(lang, I18nNormalizeLanguageCode(ld->languageCode), MAXLANGCODE1); } break; default: ; } delete d; } if (IsAc3) { if (NumDpids < MAXDPIDS) { Dpids[NumDpids] = esPid; Dtypes[NumDpids] = SI::AC3DescriptorTag; strn0cpy(DLangs[NumDpids], lang, MAXLANGCODE1); NumDpids++; } ProcessCaDescriptors = true; } } break; default: ;//printf("PID: %5d %5d %2d %3d %3d\n", pmt.getServiceId(), stream.getPid(), stream.getStreamType(), pmt.getVersionNumber(), Channel->Number()); } } cChannel pmtChannel(*Channel); pmtChannel.SetPids(Vpid, Ppid, Vtype, Apids, Atypes, ALangs, Dpids, Dtypes, DLangs, Spids, SLangs, Tpid); pmtChannel.SetSubtitlingDescriptors(SubtitlingTypes, CompositionPageIds, AncillaryPageIds); m_Streamer->SetTpid(Tpid); cPatPmtGenerator patPmtGenerator(&pmtChannel); m_Streamer->m_bufferLock.Lock(); m_Streamer->Put(patPmtGenerator.GetPat(), TS_SIZE); int Index = 0; while (uchar *pmt = patPmtGenerator.GetPmt(Index)) m_Streamer->Put(pmt, TS_SIZE); m_Streamer->m_bufferLock.Unlock(); } }
int main(int argc, char** argv){ int c; bool has_edit_option = false; bool has_pattern_file_option = false; bool silent = false; int count_option_num = 0;//count number of arguments int max_error = 0;//maximum edit distance allowed string pat_file; vector<string> patterns; vector<string> textfiles; while (1){ static struct option long_options[] = { {"silent", no_argument, 0, 's'}, {"help", no_argument, 0, 'h'}, {"edit", required_argument, 0, 'e'}, {"pattern", required_argument, 0, 'p'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "she:p:",long_options, &option_index); if (c == -1)//end break; switch (c){ case 'e': has_edit_option = true; max_error = atoi(optarg); count_option_num += 2; break; case 'p': has_pattern_file_option = true; pat_file = optarg; count_option_num += 2; break; case 's': silent = true; break; case 'h': case '?': default: help(); break; } } if(!has_pattern_file_option){//read pattern from command line arg count_option_num++; string pat(argv[count_option_num]); patterns.push_back(pat); }else{//read patterns from file ifstream infile(pat_file); if (!infile.good()){ cout << "Arquivo de padrão << " << pat_file << " >> não existe" << endl; } string pat; while (infile >> pat){ patterns.push_back(pat); } } if(argc - 1 <= count_option_num){ cout << "Insira 1 ou mais arquivos de texto" << endl; } for (int i = count_option_num+1; i < argc; i++){ string str = argv[i]; vector<string> files = getTextFiles(str); for(string &file : files){ textfiles.push_back(file); } } if(!has_edit_option || max_error == 0){//exact search if(patterns.size() == 1){//kmp string pat = patterns[0]; for(string &txt : textfiles){ run_kmp(txt, pat, silent); } }else if(patterns.size() > 1){//aho for(string &txt : textfiles){ run_aho(txt, patterns, silent); } }else{ //error } }else if(has_edit_option){//approximate search for(string &txt : textfiles){ for(string &pat : patterns){ if(pat.length() < 64){ run_wu_manber(txt, pat, max_error, silent); }else{ run_sellers(txt, pat, max_error, silent); } } } } return 0; }
/** * This test checks various generic API methods in DecimalFormat to achieve 100% * API coverage. */ void IntlTestDecimalFormatAPI::testAPI(/*char *par*/) { UErrorCode status = U_ZERO_ERROR; // ======= Test constructors logln((UnicodeString)"Testing DecimalFormat constructors"); DecimalFormat def(status); if(U_FAILURE(status)) { errcheckln(status, "ERROR: Could not create DecimalFormat (default) - %s", u_errorName(status)); return; } // bug 10864 status = U_ZERO_ERROR; DecimalFormat noGrouping("###0.##", status); if (noGrouping.getGroupingSize() != 0) { errln("Grouping size should be 0 for no grouping."); } // end bug 10864 status = U_ZERO_ERROR; const UnicodeString pattern("#,##0.# FF"); DecimalFormat pat(pattern, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern)"); return; } status = U_ZERO_ERROR; DecimalFormatSymbols *symbols = new DecimalFormatSymbols(Locale::getFrench(), status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Could not create DecimalFormatSymbols (French)"); return; } status = U_ZERO_ERROR; DecimalFormat cust1(pattern, symbols, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols*)"); } status = U_ZERO_ERROR; DecimalFormat cust2(pattern, *symbols, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols)"); } DecimalFormat copy(pat); // ======= Test clone(), assignment, and equality logln((UnicodeString)"Testing clone(), assignment and equality operators"); if( ! (copy == pat) || copy != pat) { errln((UnicodeString)"ERROR: Copy constructor or == failed"); } copy = cust1; if(copy != cust1) { errln((UnicodeString)"ERROR: Assignment (or !=) failed"); } Format *clone = def.clone(); if( ! (*clone == def) ) { errln((UnicodeString)"ERROR: Clone() failed"); } delete clone; // ======= Test various format() methods logln((UnicodeString)"Testing various format() methods"); double d = -10456.0037; int32_t l = 100000000; Formattable fD(d); Formattable fL(l); UnicodeString res1, res2, res3, res4; FieldPosition pos1(0), pos2(0), pos3(0), pos4(0); res1 = def.format(d, res1, pos1); logln( (UnicodeString) "" + (int32_t) d + " formatted to " + res1); res2 = pat.format(l, res2, pos2); logln((UnicodeString) "" + (int32_t) l + " formatted to " + res2); status = U_ZERO_ERROR; res3 = cust1.format(fD, res3, pos3, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: format(Formattable [double]) failed"); } logln((UnicodeString) "" + (int32_t) fD.getDouble() + " formatted to " + res3); status = U_ZERO_ERROR; res4 = cust2.format(fL, res4, pos4, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: format(Formattable [long]) failed"); } logln((UnicodeString) "" + fL.getLong() + " formatted to " + res4); // ======= Test parse() logln((UnicodeString)"Testing parse()"); UnicodeString text("-10,456.0037"); Formattable result1, result2; ParsePosition pos(0); UnicodeString patt("#,##0.#"); status = U_ZERO_ERROR; pat.applyPattern(patt, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: applyPattern() failed"); } pat.parse(text, result1, pos); if(result1.getType() != Formattable::kDouble && result1.getDouble() != d) { errln((UnicodeString)"ERROR: Roundtrip failed (via parse()) for " + text); } logln(text + " parsed into " + (int32_t) result1.getDouble()); status = U_ZERO_ERROR; pat.parse(text, result2, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: parse() failed"); } if(result2.getType() != Formattable::kDouble && result2.getDouble() != d) { errln((UnicodeString)"ERROR: Roundtrip failed (via parse()) for " + text); } logln(text + " parsed into " + (int32_t) result2.getDouble()); // ======= Test getters and setters logln((UnicodeString)"Testing getters and setters"); const DecimalFormatSymbols *syms = pat.getDecimalFormatSymbols(); DecimalFormatSymbols *newSyms = new DecimalFormatSymbols(*syms); def.setDecimalFormatSymbols(*newSyms); def.adoptDecimalFormatSymbols(newSyms); // don't use newSyms after this if( *(pat.getDecimalFormatSymbols()) != *(def.getDecimalFormatSymbols())) { errln((UnicodeString)"ERROR: adopt or set DecimalFormatSymbols() failed"); } UnicodeString posPrefix; pat.setPositivePrefix("+"); posPrefix = pat.getPositivePrefix(posPrefix); logln((UnicodeString)"Positive prefix (should be +): " + posPrefix); if(posPrefix != "+") { errln((UnicodeString)"ERROR: setPositivePrefix() failed"); } UnicodeString negPrefix; pat.setNegativePrefix("-"); negPrefix = pat.getNegativePrefix(negPrefix); logln((UnicodeString)"Negative prefix (should be -): " + negPrefix); if(negPrefix != "-") { errln((UnicodeString)"ERROR: setNegativePrefix() failed"); } UnicodeString posSuffix; pat.setPositiveSuffix("_"); posSuffix = pat.getPositiveSuffix(posSuffix); logln((UnicodeString)"Positive suffix (should be _): " + posSuffix); if(posSuffix != "_") { errln((UnicodeString)"ERROR: setPositiveSuffix() failed"); } UnicodeString negSuffix; pat.setNegativeSuffix("~"); negSuffix = pat.getNegativeSuffix(negSuffix); logln((UnicodeString)"Negative suffix (should be ~): " + negSuffix); if(negSuffix != "~") { errln((UnicodeString)"ERROR: setNegativeSuffix() failed"); } int32_t multiplier = 0; pat.setMultiplier(8); multiplier = pat.getMultiplier(); logln((UnicodeString)"Multiplier (should be 8): " + multiplier); if(multiplier != 8) { errln((UnicodeString)"ERROR: setMultiplier() failed"); } int32_t groupingSize = 0; pat.setGroupingSize(2); groupingSize = pat.getGroupingSize(); logln((UnicodeString)"Grouping size (should be 2): " + (int32_t) groupingSize); if(groupingSize != 2) { errln((UnicodeString)"ERROR: setGroupingSize() failed"); } pat.setDecimalSeparatorAlwaysShown(TRUE); UBool tf = pat.isDecimalSeparatorAlwaysShown(); logln((UnicodeString)"DecimalSeparatorIsAlwaysShown (should be TRUE) is " + (UnicodeString) (tf ? "TRUE" : "FALSE")); if(tf != TRUE) { errln((UnicodeString)"ERROR: setDecimalSeparatorAlwaysShown() failed"); } // Added by Ken Liu testing set/isExponentSignAlwaysShown pat.setExponentSignAlwaysShown(TRUE); UBool esas = pat.isExponentSignAlwaysShown(); logln((UnicodeString)"ExponentSignAlwaysShown (should be TRUE) is " + (UnicodeString) (esas ? "TRUE" : "FALSE")); if(esas != TRUE) { errln((UnicodeString)"ERROR: ExponentSignAlwaysShown() failed"); } // Added by Ken Liu testing set/isScientificNotation pat.setScientificNotation(TRUE); UBool sn = pat.isScientificNotation(); logln((UnicodeString)"isScientificNotation (should be TRUE) is " + (UnicodeString) (sn ? "TRUE" : "FALSE")); if(sn != TRUE) { errln((UnicodeString)"ERROR: setScientificNotation() failed"); } // Added by Ken Liu testing set/getMinimumExponentDigits int8_t MinimumExponentDigits = 0; pat.setMinimumExponentDigits(2); MinimumExponentDigits = pat.getMinimumExponentDigits(); logln((UnicodeString)"MinimumExponentDigits (should be 2) is " + (int8_t) MinimumExponentDigits); if(MinimumExponentDigits != 2) { errln((UnicodeString)"ERROR: setMinimumExponentDigits() failed"); } // Added by Ken Liu testing set/getRoundingIncrement double RoundingIncrement = 0.0; pat.setRoundingIncrement(2.0); RoundingIncrement = pat.getRoundingIncrement(); logln((UnicodeString)"RoundingIncrement (should be 2.0) is " + (double) RoundingIncrement); if(RoundingIncrement != 2.0) { errln((UnicodeString)"ERROR: setRoundingIncrement() failed"); } //end of Ken's Adding UnicodeString funkyPat; funkyPat = pat.toPattern(funkyPat); logln((UnicodeString)"Pattern is " + funkyPat); UnicodeString locPat; locPat = pat.toLocalizedPattern(locPat); logln((UnicodeString)"Localized pattern is " + locPat); // ======= Test applyPattern() logln((UnicodeString)"Testing applyPattern()"); UnicodeString p1("#,##0.0#;(#,##0.0#)"); logln((UnicodeString)"Applying pattern " + p1); status = U_ZERO_ERROR; pat.applyPattern(p1, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: applyPattern() failed with " + (int32_t) status); } UnicodeString s2; s2 = pat.toPattern(s2); logln((UnicodeString)"Extracted pattern is " + s2); if(s2 != p1) { errln((UnicodeString)"ERROR: toPattern() result did not match pattern applied"); } if(pat.getSecondaryGroupingSize() != 0) { errln("FAIL: Secondary Grouping Size should be 0, not %d\n", pat.getSecondaryGroupingSize()); } if(pat.getGroupingSize() != 3) { errln("FAIL: Primary Grouping Size should be 3, not %d\n", pat.getGroupingSize()); } UnicodeString p2("#,##,##0.0# FF;(#,##,##0.0# FF)"); logln((UnicodeString)"Applying pattern " + p2); status = U_ZERO_ERROR; pat.applyLocalizedPattern(p2, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: applyPattern() failed with " + (int32_t) status); } UnicodeString s3; s3 = pat.toLocalizedPattern(s3); logln((UnicodeString)"Extracted pattern is " + s3); if(s3 != p2) { errln((UnicodeString)"ERROR: toLocalizedPattern() result did not match pattern applied"); } status = U_ZERO_ERROR; UParseError pe; pat.applyLocalizedPattern(p2, pe, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: applyPattern((with ParseError)) failed with " + (int32_t) status); } UnicodeString s4; s4 = pat.toLocalizedPattern(s3); logln((UnicodeString)"Extracted pattern is " + s4); if(s4 != p2) { errln((UnicodeString)"ERROR: toLocalizedPattern(with ParseErr) result did not match pattern applied"); } if(pat.getSecondaryGroupingSize() != 2) { errln("FAIL: Secondary Grouping Size should be 2, not %d\n", pat.getSecondaryGroupingSize()); } if(pat.getGroupingSize() != 3) { errln("FAIL: Primary Grouping Size should be 3, not %d\n", pat.getGroupingSize()); } // ======= Test getStaticClassID() logln((UnicodeString)"Testing getStaticClassID()"); status = U_ZERO_ERROR; NumberFormat *test = new DecimalFormat(status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Couldn't create a DecimalFormat"); } if(test->getDynamicClassID() != DecimalFormat::getStaticClassID()) { errln((UnicodeString)"ERROR: getDynamicClassID() didn't return the expected value"); } delete test; }
ToServerChatEvent() { hooking::Pattern pat("55 8B EC 6A FF 68 ? ? ? ? 64 A1 ? ? ? ? 50 83 EC 08 56 A1 ? ? ? ? 33 C5 50 8D 45 F4 64 A3 ? ? ? ? 8B F1 89 75 F0 89 75 EC C7 45 ? ? ? ? ? C6 46 04 05"); ((dio::ToServerChatEvent*(__thiscall *) (ToServerChatEvent*, int, int, int, int, int, unsigned int))(pat.Get(0).Address()))(this, 0, 0, 0, 0, 0, 0); }
ToServerPlayerStateEvent() { hooking::Pattern pat("55 8B EC F3 0F 7E 45 ? 8B 45 10 66 0F D6 41 ?"); ((dio::ToServerPlayerStateEvent*(__thiscall *) (ToServerPlayerStateEvent*, __int64, int, __int64, int, __int64, int, char, char, int, char))(pat.Get(0).Address()))(this, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); }
bool project3::Parser::parseRawHtml(std::vector<unsigned char> &raw_html, std::vector<std::tuple<std::string, std::string, std::string, std::string>> &proc_html) { bool ret = false; if(raw_html.empty()) { #if DEBUG == 1 Logger::instance().log("Raw html vector is empty.", project3::Logger::m_logLevelError); #endif return ret; } // Remove MIME header first. if(!delMimeHeader(raw_html)) { return ret; } // Convert unsigned char vector to string. std::string str_html(raw_html.begin(), raw_html.end()); // String can now be processed... // Create a regex for tags. std::regex re("<(\\w+)((?:\\s+\\w+(?:\\s*=\\s*(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>\\s]+))?)*)\\s*(\\/?)>"); //std::regex re("(.*)<(\\/?)(\\w+)[^>]*(\\/?)>(.*)"); std::smatch match; std::sregex_iterator pos(str_html.cbegin(), str_html.cend(), re); std::sregex_iterator end; std::string html_tag; std::string html_val; std::string html_suffix; unsigned found; bool ol = false, ul = false, li = false; for(; pos!=end; ++pos) { // Test for html tag presence. html_tag = pos->str(1); html_val = pos->str(2); html_suffix = pos->suffix().str(); // Remove leading CRLF. if(html_suffix.at(0) == '\r') { html_suffix.erase(html_suffix.begin()); } if(html_suffix.at(0) == '\n') { html_suffix.erase(html_suffix.begin()); } if(html_val[0] == ' ') { html_val.erase(0, 1); } if(html_val[html_val.size()-1] == ' ') { html_val.pop_back(); } if(html_tag == "html" || html_tag == "head") { // Ignore <htm* and <head> tags. continue; } else if(html_tag.compare("title") == 0) { if(!html_suffix.empty()) { // Find and erase character beginning at end of value. found = html_suffix.find_first_of("<"); html_suffix.erase(html_suffix.begin()+found, html_suffix.end()); if(html_val[0] == ' ') { html_val.erase(0, 1); } if(html_val[html_val.size()-1] == ' ') { html_val.pop_back(); } // Store to vector. proc_html.push_back(std::make_tuple(html_tag, html_suffix, "", "")); } } else if(html_tag.compare("body") == 0) { if(!html_suffix.empty()) { // Find and erase character beginning end of value. found = html_suffix.find_first_of("<"); html_suffix.erase(html_suffix.begin()+found, html_suffix.end()); std::size_t len = html_suffix.size(); html_suffix[len] = '\0'; std::replace(html_suffix.begin(), html_suffix.end(), '\n', ' '); // Store to vector. proc_html.push_back(std::make_tuple("no_tag", html_suffix, "", "")); } } else if(html_tag.compare("b") == 0) { if(!html_suffix.empty()) { // Find and erase character beginning end of value. found = html_suffix.find_first_of("<"); html_suffix.erase(html_suffix.begin()+found, html_suffix.end()); std::size_t len = html_suffix.size(); html_suffix[len] = '\0'; std::replace(html_suffix.begin(), html_suffix.end(), '\n', ' '); proc_html.push_back(std::make_tuple(html_tag, html_suffix, "", "")); } } else if(html_tag.compare("br") == 0) { if(!html_suffix.empty()) { // Find and erase character beginning end of value. found = html_suffix.find_first_of("<"); html_suffix.erase(html_suffix.begin()+found, html_suffix.end()); std::size_t len = html_suffix.size(); html_suffix[len] = '\0'; std::replace(html_suffix.begin(), html_suffix.end(), '\n', ' '); proc_html.push_back(std::make_tuple(html_tag, html_suffix, "", "")); } } else if(html_tag.compare("p") == 0) { if(!html_suffix.empty()) { // Find and erase character beginning end of value. found = html_suffix.find_first_of("<"); html_suffix.erase(html_suffix.begin()+found, html_suffix.end()); std::size_t len = html_suffix.size(); html_suffix[len] = '\0'; std::replace(html_suffix.begin(), html_suffix.end(), '\n', ' '); proc_html.push_back(std::make_tuple(html_tag, html_suffix, "", "")); } } else if(html_tag.compare("img") == 0) { if(!html_suffix.empty()) { // Search for keyword "ALT" or "alt". std::regex pat("alt", std::regex_constants::icase); std::smatch m; if(std::regex_search(html_val, m, pat)) { // Extract string associated with "alt". std::size_t end = html_val.size(); html_suffix = html_val.substr(m.position()+5, end-(m.position()+6)); } std::size_t len = html_suffix.size(); html_suffix[len] = '\0'; std::replace(html_suffix.begin(), html_suffix.end(), '\n', ' '); proc_html.push_back(std::make_tuple(html_tag, html_suffix, "", "")); } } else if(html_tag.compare("a") == 0) { if(!html_suffix.empty()) { // Search for link. std::regex pat("href", std::regex_constants::icase); std::smatch m; if(std::regex_search(html_val, m, pat)) { std::size_t end = html_val.size(); html_val = html_val.substr(m.position()+6, end-(m.position()+7)); } // Find and erase character beginning end of value. found = html_suffix.find_first_of("<"); html_suffix.erase(html_suffix.begin()+found, html_suffix.end()); if(ul && li) { std::size_t len = html_suffix.size(); html_suffix[len] = '\0'; std::replace(html_suffix.begin(), html_suffix.end(), '\n', ' '); proc_html.push_back(std::make_tuple(html_tag, html_suffix, html_val, "ul")); li = false; } else if(ol && li) { std::size_t len = html_suffix.size(); html_suffix[len] = '\0'; std::replace(html_suffix.begin(), html_suffix.end(), '\n', ' '); proc_html.push_back(std::make_tuple(html_tag, html_suffix, html_val, "ol")); li = false; } else if(!(ul && li)) { std::size_t len = html_suffix.size(); html_suffix[len] = '\0'; std::replace(html_suffix.begin(), html_suffix.end(), '\n', ' '); proc_html.push_back(std::make_tuple(html_tag, html_suffix, html_val, "")); } else if(!(ol && li)) { std::size_t len = html_suffix.size(); html_suffix[len] = '\0'; std::replace(html_suffix.begin(), html_suffix.end(), '\n', ' '); proc_html.push_back(std::make_tuple(html_tag, html_suffix, html_val, "")); } } } else if(html_tag.compare("ol") == 0) { ol = true; } else if(html_tag.compare("ul") == 0) { ul = true; } else if(html_tag.compare("li") == 0) { li = true; } html_tag.clear(); html_val.clear(); html_suffix.clear(); } return true; }
void ProfileGraphicsView::plot_depth_profile() { int i, incr; int sec, depth; struct plot_data *entry; int maxtime, maxdepth, marker, maxline; int increments[8] = { 10, 20, 30, 60, 5*60, 10*60, 15*60, 30*60 }; /* Get plot scaling limits */ maxtime = get_maxtime(&gc.pi); maxdepth = get_maxdepth(&gc.pi); gc.maxtime = maxtime; /* Time markers: at most every 10 seconds, but no more than 12 markers. * We start out with 10 seconds and increment up to 30 minutes, * depending on the dive time. * This allows for 6h dives - enough (I hope) for even the craziest * divers - but just in case, for those 8h depth-record-breaking dives, * we double the interval if this still doesn't get us to 12 or fewer * time markers */ i = 0; while (maxtime / increments[i] > 12 && i < 7) i++; incr = increments[i]; while (maxtime / incr > 12) incr *= 2; gc.leftx = 0; gc.rightx = maxtime; gc.topy = 0; gc.bottomy = 1.0; last_gc = gc; QColor c = getColor(TIME_GRID); for (i = incr; i < maxtime; i += incr) { QGraphicsLineItem *item = new QGraphicsLineItem(SCALEGC(i, 0), SCALEGC(i, 1)); QPen pen(defaultPen); pen.setColor(c); item->setPen(pen); scene()->addItem(item); } timeMarkers = new QGraphicsRectItem(); /* now the text on the time markers */ struct text_render_options tro = {DEPTH_TEXT_SIZE, TIME_TEXT, CENTER, LINE_DOWN}; if (maxtime < 600) { /* Be a bit more verbose with shorter dives */ for (i = incr; i < maxtime; i += incr) plot_text(&tro, QPointF(i, 0), QString("%1:%2").arg(i/60).arg(i%60, 2, 10, QChar('0')), timeMarkers); } else { /* Only render the time on every second marker for normal dives */ for (i = incr; i < maxtime; i += 2 * incr) plot_text(&tro, QPointF(i, 0), QString("%1").arg(QString::number(i/60)), timeMarkers); } timeMarkers->setPos(0,0); scene()->addItem(timeMarkers); /* Depth markers: every 30 ft or 10 m*/ gc.leftx = 0; gc.rightx = 1.0; gc.topy = 0; gc.bottomy = maxdepth; switch (prefs.units.length) { case units::METERS: marker = 10000; break; case units::FEET: marker = 9144; break; /* 30 ft */ } maxline = qMax(gc.pi.maxdepth + marker, maxdepth * 2 / 3); c = getColor(DEPTH_GRID); for (i = marker; i < maxline; i += marker) { QGraphicsLineItem *item = new QGraphicsLineItem(SCALEGC(0, i), SCALEGC(1, i)); QPen pen(defaultPen); pen.setColor(c); item->setPen(pen); scene()->addItem(item); } gc.leftx = 0; gc.rightx = maxtime; c = getColor(MEAN_DEPTH); /* Show mean depth */ if (! gc.printer) { QGraphicsLineItem *item = new QGraphicsLineItem(SCALEGC(0, gc.pi.meandepth), SCALEGC(gc.pi.entry[gc.pi.nr - 1].sec, gc.pi.meandepth)); QPen pen(defaultPen); pen.setColor(c); item->setPen(pen); scene()->addItem(item); } #if 0 /* * These are good for debugging text placement etc, * but not for actual display.. */ if (0) { plot_smoothed_profile(gc, pi); plot_minmax_profile(gc, pi); } #endif /* Do the depth profile for the neat fill */ gc.topy = 0; gc.bottomy = maxdepth; entry = gc.pi.entry; QPolygonF p; QLinearGradient pat(0.0,0.0,0.0,scene()->height()); QGraphicsPolygonItem *neatFill = NULL; p.append(QPointF(SCALEGC(0, 0))); for (i = 0; i < gc.pi.nr; i++, entry++) p.append(QPointF(SCALEGC(entry->sec, entry->depth))); /* Show any ceiling we may have encountered */ if (prefs.profile_dc_ceiling) { for (i = gc.pi.nr - 1; i >= 0; i--, entry--) { if (!entry->in_deco) { /* not in deco implies this is a safety stop, no ceiling */ p.append(QPointF(SCALEGC(entry->sec, 0))); } else if (entry->stopdepth < entry->depth) { p.append(QPointF(SCALEGC(entry->sec, entry->stopdepth))); } else { p.append(QPointF(SCALEGC(entry->sec, entry->depth))); } } } pat.setColorAt(1, getColor(DEPTH_BOTTOM)); pat.setColorAt(0, getColor(DEPTH_TOP)); neatFill = new QGraphicsPolygonItem(); neatFill->setPolygon(p); neatFill->setBrush(QBrush(pat)); neatFill->setPen(QPen(QBrush(Qt::transparent),0)); scene()->addItem(neatFill); /* if the user wants the deco ceiling more visible, do that here (this * basically draws over the background that we had allowed to shine * through so far) */ if (prefs.profile_dc_ceiling && prefs.profile_red_ceiling) { p.clear(); pat.setColorAt(0, getColor(CEILING_SHALLOW)); pat.setColorAt(1, getColor(CEILING_DEEP)); entry = gc.pi.entry; p.append(QPointF(SCALEGC(0, 0))); for (i = 0; i < gc.pi.nr; i++, entry++) { if (entry->in_deco && entry->stopdepth) { if (entry->stopdepth < entry->depth) { p.append(QPointF(SCALEGC(entry->sec, entry->stopdepth))); } else { p.append(QPointF(SCALEGC(entry->sec, entry->depth))); } } else { p.append(QPointF(SCALEGC(entry->sec, 0))); } } neatFill = new QGraphicsPolygonItem(); neatFill->setBrush(QBrush(pat)); neatFill->setPolygon(p); neatFill->setPen(QPen(QBrush(Qt::NoBrush),0)); scene()->addItem(neatFill); } /* finally, plot the calculated ceiling over all this */ if (prefs.profile_calc_ceiling) { pat.setColorAt(0, getColor(CALC_CEILING_SHALLOW)); pat.setColorAt(1, getColor(CALC_CEILING_DEEP)); entry = gc.pi.entry; p.clear(); p.append(QPointF(SCALEGC(0, 0))); for (i = 0; i < gc.pi.nr; i++, entry++) { if (entry->ceiling) p.append(QPointF(SCALEGC(entry->sec, entry->ceiling))); else p.append(QPointF(SCALEGC(entry->sec, 0))); } p.append(QPointF(SCALEGC((entry-1)->sec, 0))); neatFill = new QGraphicsPolygonItem(); neatFill->setPolygon(p); neatFill->setPen(QPen(QBrush(Qt::NoBrush),0)); neatFill->setBrush(pat); scene()->addItem(neatFill); } /* plot the calculated ceiling for all tissues */ if (prefs.profile_calc_ceiling && prefs.calc_all_tissues) { int k; for (k=0; k<16; k++) { pat.setColorAt(0, getColor(CALC_CEILING_SHALLOW)); pat.setColorAt(1, QColor(100, 100, 100, 50)); entry = gc.pi.entry; p.clear(); p.append(QPointF(SCALEGC(0, 0))); for (i = 0; i < gc.pi.nr; i++, entry++) { if ((entry->ceilings)[k]) p.append(QPointF(SCALEGC(entry->sec, (entry->ceilings)[k]))); else p.append(QPointF(SCALEGC(entry->sec, 0))); } p.append(QPointF(SCALEGC((entry-1)->sec, 0))); neatFill = new QGraphicsPolygonItem(); neatFill->setPolygon(p); neatFill->setBrush(pat); scene()->addItem(neatFill); } } /* next show where we have been bad and crossed the dc's ceiling */ if (prefs.profile_dc_ceiling) { pat.setColorAt(0, getColor(CEILING_SHALLOW)); pat.setColorAt(1, getColor(CEILING_DEEP)); entry = gc.pi.entry; p.clear(); p.append(QPointF(SCALEGC(0, 0))); for (i = 0; i < gc.pi.nr; i++, entry++) p.append(QPointF(SCALEGC(entry->sec, entry->depth))); for (i-- , entry--; i >= 0; i--, entry--) { if (entry->in_deco && entry->stopdepth > entry->depth) { p.append(QPointF(SCALEGC(entry->sec, entry->stopdepth))); } else { p.append(QPointF(SCALEGC(entry->sec, entry->depth))); } } } neatFill = new QGraphicsPolygonItem(); neatFill->setPolygon(p); neatFill->setPen(QPen(QBrush(Qt::NoBrush),0)); neatFill->setBrush(QBrush(pat)); scene()->addItem(neatFill); /* Now do it again for the velocity colors */ entry = gc.pi.entry; for (i = 1; i < gc.pi.nr; i++) { entry++; sec = entry->sec; /* we want to draw the segments in different colors * representing the vertical velocity, so we need to * chop this into short segments */ depth = entry->depth; QGraphicsLineItem *item = new QGraphicsLineItem(SCALEGC(entry[-1].sec, entry[-1].depth), SCALEGC(sec, depth)); QPen pen(defaultPen); pen.setColor(getColor((color_indice_t)(VELOCITY_COLORS_START_IDX + entry->velocity))); item->setPen(pen); scene()->addItem(item); } }