void save_distribution_separate(complex *h, const int M, const int N) { { geometry::HeightMap heights(M, N, matrix3x1(0, 0, 0)); for (int row = 0; row < M; row++) { for (int col = 0; col < N; col++) { heights.set(row, col, h[row * N + col].r); } } util::Image image; heights.toImage(image, true); std::ofstream file("P_real.bmp"); image.write(file, util::Image::F_BMP); } { geometry::HeightMap heights(M, N, matrix3x1(0, 0, 0)); for (int row = 0; row < M; row++) { for (int col = 0; col < N; col++) { heights.set(row, col, h[row * N + col].i); } } util::Image image; heights.toImage(image, true); std::ofstream file("P_imag.bmp"); image.write(file, util::Image::F_BMP); } }
int HashEquivalence<T>::max_height () const{ int mh = 0; for (auto h : heights()) if (h.second > mh) mh = h.second; return mh; }
int maximalRectangle(vector<vector<char> > &matrix) { if(matrix.empty() || matrix[0].empty()) return 0; int m = matrix.size(); int n = matrix[0].size(); int i, j; vector<vector<int> > heights(m, vector<int>(n, 0)); // fill first row for(j = 0; j < n; j++){ heights[0][j] = matrix[0][j] == '1' ? 1 : 0; } for(j = 0; j < n; j++){ for(i = 1; i < m; i++){ heights[i][j] = matrix[i][j] == '0' ? 0 : 1 + heights[i-1][j]; } } // find max rectangle whose bottom lies in current row int global_max = 0; for(i = m-1; i >= 0; i--){ global_max = max(global_max, helper(heights[i])); } return global_max; }
void SCXferFnDirector::BuildWindow ( SCCircuitDocument* doc ) { JArray<JCoordinate> heights(2); heights.AppendElement(kInitExprHeight); heights.AppendElement(kInitExprHeight); JArray<JCoordinate> minHeights(2); minHeights.AppendElement(kMinExprHeight); minHeights.AppendElement(kMinExprHeight); // begin JXLayout JXWindow* window = new JXWindow(this, 500,230, ""); assert( window != NULL ); JXMenuBar* menuBar = new JXMenuBar(window, JXWidget::kHElastic, JXWidget::kFixedTop, 0,0, 430,30); assert( menuBar != NULL ); itsPartition = new JXVertPartition(heights, 0, minHeights, window, JXWidget::kHElastic, JXWidget::kVElastic, 0,30, 500,205); assert( itsPartition != NULL ); itsEvalButton = new JXTextButton(JGetString("itsEvalButton::SCXferFnDirector::JXLayout"), window, JXWidget::kFixedRight, JXWidget::kFixedTop, 430,0, 70,30); assert( itsEvalButton != NULL ); // end JXLayout window->SetTitle("Transfer function"); const JRect frame = itsPartition->GetFrame(); window->SetMinSize(150, frame.top + itsPartition->GetMinTotalSize()); ListenTo(itsEvalButton); SCExprEditorSet* exprSet = new SCExprEditorSet(doc, menuBar, &itsXferFn, itsPartition->GetCompartment(1), JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 100,100); assert( exprSet != NULL ); exprSet->FitToEnclosure(); exprSet = new SCExprEditorSet(doc, itsXferFn, &itsResult, itsPartition->GetCompartment(2), JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 100,100); assert( exprSet != NULL ); exprSet->FitToEnclosure(); }
void compute() { const int M = 256; const int N = 256; cmatrix h_naught(M, N, true, complex(0.0f, 0.0f)); for (int row = 0; row < M; row++) { for (int col = 0; col < N; col++) { int n = col; int m = row; matrix3x1 K = Pi_2 * matrix3x1((float)n / N, 0, (float)m / M); complex h_0 = height_naught(K); h_naught.set(row, col, h_0); } } cmatrix h_tilde(M, N, true, complex(0, 0)); cmatrix c_heights(M, N, true, complex(0, 0)); fftwf_plan plan = fftwf_plan_dft_2d(M, N, (fftwf_complex *)h_tilde.getData(), (fftwf_complex *)c_heights.getData(), FFTW_BACKWARD, FFTW_ESTIMATE); matrix heights(M, N, true, 0.0f); const int Frames = 1; for (int p = 0; p < Frames; p++) { float t = (float)p / Frames; for (int row = 0; row < M; row++) { for (int col = 0; col < N; col++) { h_tilde.set(row, col, Htilde(h_naught, row, col, t)); } } // complex2complex FFT2D fftwf_execute(plan); // extract the real component for (int row = 0; row < M; row++) { for (int col = 0; col < N; col++) { heights.set(row, col, c_heights.get(row, col).r / 20.0f); } } // save the results { std::stringstream ss; ss << "ocean_" << std::setw(2) << std::setfill('0') << p << ".mat"; std::ofstream file(ss.str().c_str()); file << std::setprecision(10); math::matrix_writeAsText(file, heights); } } fftwf_destroy_plan(plan); }
TEST(largestRectangleAreaTest, Positive01){ Solution s; int arr[] = {1, 2, 2, 3, 2}; vector<int> heights(arr, arr + sizeof(arr)/sizeof(int)); int expected = 8; EXPECT_EQ(expected, s.largestRectangleArea(heights)); }
// This method returns the computed mode-height of blobs in the pix. // It also prunes very small blobs from calculation. int ShiroRekhaSplitter::GetModeHeight(Pix* pix) { Boxa* boxa = pixConnComp(pix, NULL, 8); STATS heights(0, pixGetHeight(pix)); heights.clear(); for (int i = 0; i < boxaGetCount(boxa); ++i) { Box* box = boxaGetBox(boxa, i, L_CLONE); if (box->h >= 3 || box->w >= 3) { heights.add(box->h, 1); } boxDestroy(&box); } boxaDestroy(&boxa); return heights.mode(); }
int maximalRectangle(vector<vector<char> > &matrix) { if (matrix.size()<=0 || matrix[0].size()<=0) return 0; int row = matrix.size(); int col = matrix[0].size(); vector< vector<int> > heights(row, vector<int>(col)); int maxArea = 0; for(int i=0; i<row; i++){ for(int j=0; j<col; j++) { if (matrix[i][j]=='1'){ heights[i][j] = (i==0 ? 1 : heights[i-1][j] + 1); } } int area = largestRectangleArea(heights[i]); if (area > maxArea) maxArea = area; } return maxArea; }
QwtArray<long> LegendMarker::itemsHeight(int y, int symbolLineLength, int &width, int &height) const { int maxL=0; width = 0; height = 0; QString text=d_text->text(); QStringList titles=QStringList::split ("\n",text,FALSE); int n=(int)titles.count(); QwtArray<long> heights(n); int h = top_margin; for (int i=0; i<n; i++) { QString str=titles[i]; int textL=0; if (str.contains("\\c{",TRUE)>0 || str.contains("\\p{",TRUE)>0) { textL = symbolLineLength + hspace; int pos=str.find("}",0); str = str.right(str.length()-pos-1); } QwtText aux(str); QSize size = aux.textSize(d_text->font()); textL += size.width(); if (textL>maxL) maxL = textL; int textH = size.height(); height += textH; heights[i] = y + h + textH/2; h += textH; } height += 2*top_margin; width = 2*left_margin + maxL; return heights; }
void CmIllustr::Imgs(const ImgsOptions &opts, int maxImgNum) { vecS names; CmFile::MkDir(opts._outDir); int imgNum = CmFile::GetNamesNE(opts._inDir + "*" + opts._exts[0], names); FILE *f = fopen(_S(opts._texName), "w"); CV_Assert(f != NULL); //* Sort image names in order vector<pair<int, string>> costIdx(imgNum); for (int i = 0; i < imgNum; i++) costIdx[i] = make_pair(atoi(_S(names[i])), names[i]); sort(costIdx.begin(), costIdx.end()); for (int i = 0; i < imgNum; i++) names[i] = costIdx[i].second; //*/ imgNum = min(imgNum, maxImgNum); vecI heights(imgNum); for (int i = 0; i < imgNum; i++){ Mat img = imread(opts._inDir + names[i] + opts._exts[0]); heights[i] = (img.rows * opts._w + img.cols/2) / img.cols; } vecS subNames; vecI subHeights; int height = -space; for (int i = 0; i < imgNum; i++) { height += heights[i] + space; subNames.push_back(names[i]); subHeights.push_back(heights[i]); if (height > opts._H){ height = 0; WriteFigure(subNames, f, subHeights, opts); subNames.clear(); subHeights.clear(); } } WriteFigure(subNames, f, subHeights, opts); fclose(f); printf("%70s\r", ""); }
int main() { int num_players = 0; int selection = 0; scanf("%d%d", &num_players, &selection); std::vector<int> heights(num_players); for (int i = 0; i < num_players; ++i) { scanf("%d", &heights[i]); } std::swap(heights[selection - 1], heights[0]); int itr = 1, jtr = num_players - 1, ktr = 1; while (itr <= jtr) { if (heights[itr] > heights[0]) { while (heights[jtr] > heights[0]) { --jtr; } if (itr < jtr) { std::swap(heights[itr], heights[jtr]); } else { break; } } if (heights[itr] == heights[0]) { std::swap(heights[itr], heights[ktr++]); } ++itr; } for (int i = 0, s = std::min(ktr, itr - ktr); i < s; ++i) { std::swap(heights[i], heights[itr - s + i]); } for (int i = 0; i < heights.size(); ++i) { printf("%d ", heights[i]); } return 0; }
int maximalRectangle(vector<vector<char>>& matrix) { int m=matrix.size(); if(m==0) return 0; int n=matrix.front().size(); int mmax=0; vector<int> heights(n,0); for(int i=0;i<m;++i) { for(int j=0;j<n;++j) { if(matrix[i][j]=='1') { heights[j]++; } else heights[j]=0; } mmax=max(mmax,maxRect(heights)); } return mmax; }
QwtArray<long> LegendMarker::itemsHeight(int y, int symbolLineLength, int &width, int &height) const { int maxL=0; width = 0; height = 0; QString text = d_text->text().trimmed(); QStringList titles = text.split("\n", QString::KeepEmptyParts); int n=(int)titles.count(); QwtArray<long> heights(n); int h = top_margin; for (int i=0; i<n; i++) { QString str=titles[i]; int textL=0; if (str.contains("\\c{") || str.contains("\\p{") || str.contains("\\l(")) textL = symbolLineLength + hspace; QwtText aux(parse(str)); QSize size = aux.textSize(d_text->font()); textL += size.width(); if (textL > maxL) maxL = textL; int textH = size.height(); height += textH; heights[i] = y + h + textH/2; h += textH; } height += 2*top_margin; width = 2*left_margin + maxL; return heights; }
vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) { // sort by x-coord multimap<int, int> endpoints; for(auto b : buildings) { endpoints.emplace(b[0], b[2]); endpoints.emplace(b[1], -b[2]); } multiset<int> heights({0}); vector<pair<int, int>> res; for(auto it = endpoints.begin(); it != endpoints.end();) { int x = it->first; // handle all points in the same x-coord do { int h = it->second; if (h > 0) heights.insert(h); else heights.erase(heights.find(-h)); it++; } while(it != endpoints.end() && it->first == x); // check current max height int mh = *(heights.rbegin()); if (res.empty() || mh != res.back().second) res.emplace_back(x, mh); } return res; }
void Tfm::Read () { if (! dviChars.empty() || dviInfo.notLoadable) { return; } trace_tfm->WriteFormattedLine ("libdvi", T_("going to load TFM file %s"), dviInfo.name.c_str()); PathName fileName; bool tfmFileExists = SessionWrapper(true)->FindTfmFile(dviInfo.name.c_str(), fileName, false); if (! tfmFileExists) { if (Make(dviInfo.name)) { tfmFileExists = SessionWrapper(true)->FindTfmFile(dviInfo.name.c_str(), fileName, false); if (! tfmFileExists) { // this shouldn't happen; but it does (#521481) } } if (! tfmFileExists) { dviInfo.transcript += "\r\n"; dviInfo.transcript += T_("Loading 'cmr10' instead.\r\n"); trace_error->WriteFormattedLine ("libdvi", T_("'%s' not loadable - loading 'cmr10' instead!"), dviInfo.name.c_str()); if (! (SessionWrapper(true)->FindTfmFile("cmr10", fileName, false) || (Make("cmr10") && SessionWrapper(true)->FindTfmFile("cmr10", fileName, false)))) { dviInfo.transcript += T_("'cmr10' not loadable either!"); trace_error->WriteLine ("libdvi", T_("'cmr10' not loadable - will display blank chars!")); return; } } } dviInfo.fileName = fileName.ToString(); trace_tfm->WriteFormattedLine ("libdvi", T_("opening TFM file %s"), fileName.Get()); InputStream inputStream (fileName.Get()); long lf = inputStream.ReadSignedPair(); if (lf == 0) { FATAL_DVI_ERROR ("Tfm::Read", T_("Invalid TFM file."), 0); } long lh = inputStream.ReadSignedPair(); long bc = inputStream.ReadSignedPair(); long ec = inputStream.ReadSignedPair(); long nw = inputStream.ReadSignedPair(); long nh = inputStream.ReadSignedPair(); long nd = inputStream.ReadSignedPair(); long ni = inputStream.ReadSignedPair(); long nl = inputStream.ReadSignedPair(); long nk = inputStream.ReadSignedPair(); long ne = inputStream.ReadSignedPair(); long np = inputStream.ReadSignedPair(); trace_tfm->WriteFormattedLine ("libdvi", T_("header size: %ld"), lh); trace_tfm->WriteFormattedLine ("libdvi", T_("smallest character code: %ld"), bc); trace_tfm->WriteFormattedLine ("libdvi", T_("largest character code: %ld"), ec); trace_tfm->WriteFormattedLine ("libdvi", T_("width table size: %ld"), nw); trace_tfm->WriteFormattedLine ("libdvi", T_("height table size: %ld"), nh); trace_tfm->WriteFormattedLine ("libdvi", T_("depth table size: %ld"), nd); trace_tfm->WriteFormattedLine ("libdvi", T_("italic correction table size: %ld"), ni); trace_tfm->WriteFormattedLine ("libdvi", T_("lig/kern table size: %ld"), nl); trace_tfm->WriteFormattedLine ("libdvi", T_("kern table size: %ld"), nk); trace_tfm->WriteFormattedLine ("libdvi", T_("extensible character table size: %ld"), ne); trace_tfm->WriteFormattedLine ("libdvi", T_("font parameter size: %ld"), np); int my_checkSum = inputStream.ReadSignedQuad(); trace_tfm->WriteFormattedLine ("libdvi", "checkSum: 0%lo", my_checkSum); int my_designSize = inputStream.ReadSignedQuad(); trace_tfm->WriteFormattedLine ("libdvi", "designSize: %ld", my_designSize); if (my_checkSum != checkSum) { trace_error->WriteFormattedLine ("libdvi", T_("%s: checkSum mismatch"), dviInfo.name.c_str()); } if (my_designSize * tfmConv != designSize) { trace_error->WriteFormattedLine ("libdvi", T_("%s: designSize mismatch"), dviInfo.name.c_str()); } inputStream.SkipBytes ((lh - 2) * 4); struct TfmIndex { int widthIndex; int heightIndex; int depthIndex; }; vector<TfmIndex> infoTable (ec); for (int charCode = bc; charCode < ec; ++ charCode) { DviChar * pDviChar = new DviChar (this); dviChars[charCode] = pDviChar; pDviChar->SetCharacterCode (charCode); TfmIndex tfmIndex; tfmIndex.widthIndex = inputStream.ReadSignedByte(); int heightDepth = inputStream.ReadSignedByte(); tfmIndex.heightIndex = ((heightDepth >> 4) & 15); tfmIndex.depthIndex = (heightDepth & 15); inputStream.SkipBytes (2); infoTable[charCode] = tfmIndex; } vector<int> widths (nw); for (int idx = 0; idx < nw; ++ idx) { widths[idx] = inputStream.ReadSignedQuad(); } vector<int> heights (nh); for (int idx = 0; idx < nh; ++ idx) { heights[idx] = inputStream.ReadSignedQuad(); } vector<int> depths (nd); for (int idx = 0; idx < nd; ++ idx) { depths[idx] = inputStream.ReadSignedQuad(); } // inputStream.Close (); for (int charCode = bc; charCode < ec; ++ charCode) { int tfmWidth = ScaleFix(widths[infoTable[charCode].widthIndex], GetScaledAt()); dviChars[charCode]->SetDviWidth (tfmWidth); int pixelWidth; if (tfmWidth >= 0) { pixelWidth = static_cast<int>(conv * tfmWidth + 0.5); } else { pixelWidth = - static_cast<int>(conv * -tfmWidth + 0.5); } dviChars[charCode]->SetWidth (pixelWidth); } }
static UniValue getpeerinfo(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() != 0) throw std::runtime_error( "getpeerinfo\n" "\nReturns data about each connected network node as a json array of objects.\n" "\nResult:\n" "[\n" " {\n" " \"id\": n, (numeric) Peer index\n" " \"addr\":\"host:port\", (string) The IP address and port of the peer\n" " \"addrbind\":\"ip:port\", (string) Bind address of the connection to the peer\n" " \"addrlocal\":\"ip:port\", (string) Local address as reported by the peer\n" " \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n" " \"relaytxes\":true|false, (boolean) Whether peer has asked us to relay transactions to it\n" " \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n" " \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n" " \"bytessent\": n, (numeric) The total bytes sent\n" " \"bytesrecv\": n, (numeric) The total bytes received\n" " \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n" " \"timeoffset\": ttt, (numeric) The time offset in seconds\n" " \"pingtime\": n, (numeric) ping time (if available)\n" " \"minping\": n, (numeric) minimum observed ping time (if any at all)\n" " \"pingwait\": n, (numeric) ping wait (if non-zero)\n" " \"version\": v, (numeric) The peer version, such as 70001\n" " \"subver\": \"/Satoshi:0.8.5/\", (string) The string version\n" " \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n" " \"addnode\": true|false, (boolean) Whether connection was due to addnode/-connect or if it was an automatic/inbound connection\n" " \"startingheight\": n, (numeric) The starting height (block) of the peer\n" " \"banscore\": n, (numeric) The ban score\n" " \"synced_headers\": n, (numeric) The last header we have in common with this peer\n" " \"synced_blocks\": n, (numeric) The last block we have in common with this peer\n" " \"inflight\": [\n" " n, (numeric) The heights of blocks we're currently asking from this peer\n" " ...\n" " ],\n" " \"whitelisted\": true|false, (boolean) Whether the peer is whitelisted\n" " \"bytessent_per_msg\": {\n" " \"addr\": n, (numeric) The total bytes sent aggregated by message type\n" " ...\n" " },\n" " \"bytesrecv_per_msg\": {\n" " \"addr\": n, (numeric) The total bytes received aggregated by message type\n" " ...\n" " }\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getpeerinfo", "") + HelpExampleRpc("getpeerinfo", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); std::vector<CNodeStats> vstats; g_connman->GetNodeStats(vstats); UniValue ret(UniValue::VARR); for (const CNodeStats& stats : vstats) { UniValue obj(UniValue::VOBJ); CNodeStateStats statestats; bool fStateStats = GetNodeStateStats(stats.nodeid, statestats); obj.pushKV("id", stats.nodeid); obj.pushKV("addr", stats.addrName); if (!(stats.addrLocal.empty())) obj.pushKV("addrlocal", stats.addrLocal); if (stats.addrBind.IsValid()) obj.pushKV("addrbind", stats.addrBind.ToString()); obj.pushKV("services", strprintf("%016x", stats.nServices)); obj.pushKV("relaytxes", stats.fRelayTxes); obj.pushKV("lastsend", stats.nLastSend); obj.pushKV("lastrecv", stats.nLastRecv); obj.pushKV("bytessent", stats.nSendBytes); obj.pushKV("bytesrecv", stats.nRecvBytes); obj.pushKV("conntime", stats.nTimeConnected); obj.pushKV("timeoffset", stats.nTimeOffset); if (stats.dPingTime > 0.0) obj.pushKV("pingtime", stats.dPingTime); if (stats.dMinPing < static_cast<double>(std::numeric_limits<int64_t>::max())/1e6) obj.pushKV("minping", stats.dMinPing); if (stats.dPingWait > 0.0) obj.pushKV("pingwait", stats.dPingWait); obj.pushKV("version", stats.nVersion); // Use the sanitized form of subver here, to avoid tricksy remote peers from // corrupting or modifying the JSON output by putting special characters in // their ver message. obj.pushKV("subver", stats.cleanSubVer); obj.pushKV("inbound", stats.fInbound); obj.pushKV("addnode", stats.m_manual_connection); obj.pushKV("startingheight", stats.nStartingHeight); if (fStateStats) { obj.pushKV("banscore", statestats.nMisbehavior); obj.pushKV("synced_headers", statestats.nSyncHeight); obj.pushKV("synced_blocks", statestats.nCommonHeight); UniValue heights(UniValue::VARR); for (int height : statestats.vHeightInFlight) { heights.push_back(height); } obj.pushKV("inflight", heights); } obj.pushKV("whitelisted", stats.fWhitelisted); UniValue sendPerMsgCmd(UniValue::VOBJ); for (const mapMsgCmdSize::value_type &i : stats.mapSendBytesPerMsgCmd) { if (i.second > 0) sendPerMsgCmd.pushKV(i.first, i.second); } obj.pushKV("bytessent_per_msg", sendPerMsgCmd); UniValue recvPerMsgCmd(UniValue::VOBJ); for (const mapMsgCmdSize::value_type &i : stats.mapRecvBytesPerMsgCmd) { if (i.second > 0) recvPerMsgCmd.pushKV(i.first, i.second); } obj.pushKV("bytesrecv_per_msg", recvPerMsgCmd); ret.push_back(obj); } return ret; }
std::vector<cv::Rect> SoftPPWordSplitter::split(const CCGroup &grp) { cv::Rect bb = grp.get_rect(); // generate the projection profile sums cv::Mat sums(1, bb.width, CV_32FC1, cv::Scalar(0)); ProjectionProfileComputer pp_computer(cv::Size(bb.width, 1), bb.x); for (int i = 0; i < grp.ccs.size(); i++) { sums = pp_computer.compute(grp.ccs[i].pixels, sums); } int threshold = pp_computer.compute_threshold(sums); if (_verbose) { std::cout << "Projection Profile Threshold: " << threshold << std::endl; } cv::Mat gaps = sums < threshold; // now shrink each bounding rect on the border with the gaps matrix std::vector<cv::Rect> original_rects(grp.ccs.size()); std::transform( grp.ccs.begin(), grp.ccs.end(), original_rects.begin(), [](const CC &cc) -> cv::Rect { return cc.rect; }); std::sort( original_rects.begin(), original_rects.end(), [](const cv::Rect &a, const cv::Rect &b) -> bool { return a.x < b.x; }); RectShrinker shrinker(0.10, bb.x); std::vector<cv::Rect> shrinked_rects(shrinker.shrink(original_rects, gaps)); //cv::Mat img(grp.get_image()); //cv::imshow("RECTS-wo-rects", img); //cv::waitKey(0); //for (cv::Rect r : shrinked_rects) { // cv::rectangle(img, r.tl(), r.br(), cv::Scalar(128)); //} //cv::imshow("RECTS", img); //cv::waitKey(0); std::vector<bool> collide(bb.width, false); for (int i = 0; i < shrinked_rects.size(); i++) { for (int j = shrinked_rects[i].x; j < shrinked_rects[i].x + shrinked_rects[i].width; j++) { collide[j-bb.x] = true; } } //std::vector<bool> collide(bb.width, false); //for (int i = 0; i < ccs.size(); i++) { // for (int j = ccs[i].rect.x; j < ccs[i].rect.x + ccs[i].rect.width; j++) { // collide[j-bb.x] = true; // } //} std::vector<float> heights(grp.ccs.size(), 0.0); std::transform( grp.ccs.begin(), grp.ccs.end(), heights.begin(), [] (const CC &c) -> float { return c.rect.height; }); float mean_height = cv::sum(heights)[0] / heights.size(); // Now find the rects from this binary mask. // This merges overlapping/touching CCs into a single component std::vector<cv::Rect> rects; cv::Rect last_rect(bb.x, bb.y, 1, bb.height); for (int i = 0; i < collide.size(); i++) { if (collide[i]) { last_rect.width += 1; } else { if (last_rect.width > 0) { rects.push_back(last_rect); } last_rect = cv::Rect(bb.x + i, bb.y, 0, bb.height); } } if (last_rect.width > 0) { rects.push_back(last_rect); } if (_verbose) std::cout << "#Rects: " << rects.size() << std::endl; if (rects.size() <= 2) { std::vector<cv::Rect> result; result.push_back(bb); return result; } // find the dists std::vector<float> dists; for (int i = 1; i < rects.size(); i++) { dists.push_back(rects[i].tl().x - rects[i-1].br().x); } // kmeans cv::Mat dist_mat(dists.size(), 1, CV_32FC1); for (size_t i = 0; i < dists.size(); i++) { dist_mat.at<float>(i,0) = dists[i]; } cv::Mat centers; cv::Mat labels;//(dists.size(),1, CV_32SC1, cv::Scalar(0)); /* float min = *std::min_element(dists.begin(), dists.end()); float max = *std::max_element(dists.begin(), dists.end()); for (size_t i = 0; i < dists.size(); i++) { labels.at<int>(i,0) = std::abs(dists[i] - min) < std::abs(dists[i] - max) ? 0 : 1; } */ if (_verbose) std::cout << dist_mat << std::endl; kmeans(dist_mat, 2, labels, cv::TermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 100, .01), 5, cv::KMEANS_PP_CENTERS, centers); if (_verbose) std::cout << centers << std::endl; std::vector<float> cpy(dists); std::sort(cpy.begin(), cpy.end()); float median = cpy[cpy.size() / 2]; if (cpy.size() % 2 == 0) { median = cpy[cpy.size() / 2] + cpy[cpy.size() / 2 - 1]; median = median / 2.0f; } float medval = median; float height = std::abs(centers.at<float>(0,0) - centers.at<float>(1,0)) / mean_height; median = std::abs(centers.at<float>(0,0) - centers.at<float>(1,0)) / (median + 1e-10); if (_verbose) { std::cout << dists.size() << " " << medval << " " << median << " " << height << std::endl; } // liblinear: 92% ACC: (10-F) // ./train -v 10 -B 1 -w1 2 -c 100 dists_cleaned.dat // do we have a single cluster?! //if (dists.size() > 3 && median * 0.84320891 + height * 0.3127415 < 1.23270849 || // dists.size() <= 3 && height < 0.43413942) { if (median * 0.33974138 + height * 0.47850904 < 0.56307525) { std::vector<cv::Rect> result; result.push_back(bb); return result; } // get the index of the smallest center int small_center = centers.at<float>(0,0) < centers.at<float>(1,0) ? 0 : 1; // count the distance to cluster assignments int cnt[2] = {0,0}; for (int i = 0; i < labels.rows; i++) { cnt[labels.at<int>(i,0)]++; } // we have more word gaps than letter gaps -> don't split! if (cnt[small_center] < cnt[1-small_center]) { std::vector<cv::Rect> result; result.push_back(bb); return result; } // start from left to right and iteratively merge rects if the // distance between them is clustered into the smaller center last_rect = rects[0]; std::vector<cv::Rect> word_candidates; for (int i = 1; i < rects.size(); i++) { if (_allow_single_letters) { if (labels.at<int>(i-1,0) == small_center) { // extend the last rect last_rect = last_rect | rects[i]; } else { // do not extend it! word_candidates.push_back(last_rect); last_rect = rects[i]; } } else { if (labels.at<int>(i-1,0) == small_center) { // extend the last rect last_rect = last_rect | rects[i]; } else if (i < labels.rows && labels.at<int>(i,0) == small_center) { // do not extend it! word_candidates.push_back(last_rect); last_rect = rects[i]; } else { last_rect = last_rect | rects[i]; } } } word_candidates.push_back(last_rect); // for each rect, find the original connected component rects std::vector<cv::Rect> words; for (cv::Rect candidate : word_candidates) { std::vector<cv::Rect> word; for (size_t i = 0; i < grp.ccs.size(); i++) { cv::Rect intersect(grp.ccs[i].rect & candidate); if (float (intersect.width * intersect.height) / float (grp.ccs[i].rect.width * grp.ccs[i].rect.height) >= 0.8f) { cv::Rect r = grp.ccs[i].rect; // set the text height correctly r.y = bb.y; r.height = bb.height; word.push_back(r); } } if (_verbose) { std::cout << "Accumulated: " << word.size() << " rects!" << std::endl; } if (word.empty()) continue; assert(!word.empty()); cv::Rect r = word[0]; for (size_t i = 1; i < word.size(); i++) { r = r | word[i]; } words.push_back(r); } return words; }
void FlexGrid::Layout() { std::vector<double> heights(rows.size(), 0.0); std::vector<double> widths(defaultCols.size(), 0.0); Vec2 totalSize(0, 0); Vec2 padding2x = padding; padding2x *= 2; // First, measure each of the cells to determine the height of each row // and width of each column. auto heightIter = heights.begin(); auto widthIter = widths.begin(); for (auto &cols : rows) { for (auto &cell : cols) { if (cell) { Vec3 size = cell->Measure(); size += padding2x; if (size.x > *widthIter) { *widthIter = size.x; } if (size.y > *heightIter) { *heightIter = size.y; } } ++widthIter; } ++heightIter; widthIter = widths.begin(); } // If a fixed size is set, then scale the dimensions. if (IsFixedWidth()) { ScaleDimension(widths, fixedSize.x, padding.x, margin.x); } if (IsFixedHeight()) { ScaleDimension(heights, fixedSize.y, padding.y, margin.y); } // Move each cell contents into position. heightIter = heights.begin(); widthIter = widths.begin(); double x = 0; double y = 0; for (auto &cols : rows) { for (auto &cell : cols) { if (cell) { cell->SetExtents(x, y, *widthIter, *heightIter, padding.x, padding.y); } x += *widthIter + padding2x.x; if (x > totalSize.x) { totalSize.x = x; } x += margin.x; ++widthIter; } y += *heightIter + padding2x.y; totalSize.y = y; y += margin.y; ++heightIter; x = 0; widthIter = widths.begin(); } // Update the calculated size of the grid. size = totalSize; SUPER::SetSize(totalSize); }
void GLFitDirector::BuildWindow() { JCoordinate w = 600; JCoordinate h = 420; JXWindow* window = new JXWindow(this, w,h, "Fit"); assert( window != NULL ); window->SetCloseAction(JXWindow::kDeactivateDirector); JXMenuBar* menuBar = new JXMenuBar(window, JXWidget::kHElastic, JXWidget::kFixedTop, 0,0, w,kJXDefaultMenuBarHeight); assert( menuBar != NULL ); itsToolBar = new JXToolBar(GetPrefsMgr(), kFitToolBarID, menuBar, w, h, window, JXWidget::kHElastic, JXWidget::kVElastic, 0,kJXDefaultMenuBarHeight, w,h - kJXDefaultMenuBarHeight); assert( itsToolBar != NULL ); JSize newHeight = itsToolBar->GetWidgetEnclosure()->GetBoundsHeight(); const JCoordinate kPartitionHandleWidth = 5; const JCoordinate kFitListWidth = 155; JArray<JCoordinate> widths(2); widths.AppendElement(kFitListWidth); widths.AppendElement(w - kFitListWidth - kPartitionHandleWidth); JIndex elasticIndex = 2; JArray<JCoordinate> minWidths(2); minWidths.AppendElement(100); minWidths.AppendElement(300); itsMainPartition = new JXHorizPartition(widths, elasticIndex, minWidths, itsToolBar->GetWidgetEnclosure(), JXWidget::kHElastic,JXWidget::kVElastic, 0, 0, w, newHeight); assert( itsMainPartition != NULL ); // This is the first column the contains the curve and fit lists. JXContainer* container = itsMainPartition->GetCompartment(1); const JCoordinate kCurveListHeight = 100; const JCoordinate kColHeaderHeight = 20; const JCoordinate kExprHeight = 50; const JCoordinate kFitListHeight = newHeight - kCurveListHeight - 2 * kPartitionHandleWidth - kExprHeight; JArray<JCoordinate> heights(3); heights.AppendElement(kCurveListHeight); heights.AppendElement(kFitListHeight); heights.AppendElement(kExprHeight); elasticIndex = 2; JArray<JCoordinate> minHeights(3); minHeights.AppendElement(50); minHeights.AppendElement(100); minHeights.AppendElement(40); itsListPartition = new JXVertPartition(heights, elasticIndex, minHeights, container, JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, kFitListWidth, newHeight); assert( itsListPartition != NULL ); container = itsListPartition->GetCompartment(1); JXScrollbarSet* scrollbarSet = new JXScrollbarSet(container, JXWidget::kHElastic,JXWidget::kVElastic, 0, kColHeaderHeight, kFitListWidth, kCurveListHeight - kColHeaderHeight); assert( scrollbarSet != NULL ); // This will be the curve list itsCurveList = new GLCurveNameList(itsDir, itsPlot, scrollbarSet, scrollbarSet->GetScrollEnclosure(), JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, kFitListWidth, kCurveListHeight - kColHeaderHeight); assert(itsCurveList != NULL); ListenTo(itsCurveList); JXColHeaderWidget* header = new JXColHeaderWidget(itsCurveList, scrollbarSet, container, JXWidget::kHElastic, JXWidget::kFixedTop, 0, 0, kFitListWidth, kColHeaderHeight); assert(header != NULL); header->SetColTitle(1, "Curves"); container = itsListPartition->GetCompartment(2); scrollbarSet = new JXScrollbarSet(container, JXWidget::kHElastic,JXWidget::kVElastic, 0, kColHeaderHeight, kFitListWidth, kFitListHeight - kColHeaderHeight); assert( scrollbarSet != NULL ); // This will be the fit list itsFitList = new GLFitDescriptionList(scrollbarSet, scrollbarSet->GetScrollEnclosure(), JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, kFitListWidth, kFitListHeight - kColHeaderHeight); assert(itsFitList != NULL); ListenTo(itsFitList); header = new JXColHeaderWidget(itsFitList, scrollbarSet, container, JXWidget::kHElastic, JXWidget::kFixedTop, 0, 0, kFitListWidth, kColHeaderHeight); assert(header != NULL); header->SetColTitle(1, "Fits"); // this is the expression widget that displays the current JFunction container = itsListPartition->GetCompartment(3); scrollbarSet = new JXScrollbarSet(container, JXWidget::kHElastic,JXWidget::kVElastic, 0, 0, kFitListWidth, kExprHeight); assert( scrollbarSet != NULL ); itsExprVarList = new GVarList(); assert(itsExprVarList != NULL); itsExprWidget = new JXExprWidget(itsExprVarList, scrollbarSet, scrollbarSet->GetScrollEnclosure(), JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, kFitListWidth, kExprHeight); assert(itsExprWidget != NULL); itsExprWidget->Hide(); // This is the second column that will contain the parameter table // and the plots container = itsMainPartition->GetCompartment(2); const JCoordinate kParmsTableHeight = 50; const JCoordinate kChiSqHeight = 20; const JCoordinate kTotalParmsHeight = kParmsTableHeight + kColHeaderHeight + kChiSqHeight; const JCoordinate kFirstPlotHeight = 120; const JCoordinate kMinPlotHeight = 100; heights.RemoveAll(); heights.AppendElement(kTotalParmsHeight); heights.AppendElement(kFirstPlotHeight); heights.AppendElement(newHeight - kFirstPlotHeight - kTotalParmsHeight - 2 * kPartitionHandleWidth); elasticIndex = 2; minHeights.RemoveAll(); minHeights.AppendElement(kTotalParmsHeight - 20); minHeights.AppendElement(kMinPlotHeight); minHeights.AppendElement(kMinPlotHeight); itsPlotPartition = new JXVertPartition(heights, elasticIndex, minHeights, container, JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, w - kFitListWidth - kPartitionHandleWidth, newHeight); assert( itsPlotPartition != NULL ); container = itsPlotPartition->GetCompartment(1); scrollbarSet = new JXScrollbarSet(container, JXWidget::kHElastic,JXWidget::kVElastic, 0, kColHeaderHeight, w - kFitListWidth - kPartitionHandleWidth, kParmsTableHeight); assert( scrollbarSet != NULL ); // this will be the parameter table itsParameterTable = new GLFitParameterTable(scrollbarSet, scrollbarSet->GetScrollEnclosure(), JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, w - kFitListWidth - kPartitionHandleWidth, kParmsTableHeight); assert(itsParameterTable != NULL); ListenTo(itsParameterTable); itsParameterColHeader = new GLParmColHeaderWidget(itsParameterTable, scrollbarSet, container, JXWidget::kHElastic, JXWidget::kFixedTop, 0, 0, w - kFitListWidth - kPartitionHandleWidth, kColHeaderHeight); assert(itsParameterColHeader != NULL); itsParameterTable->SetColHeaderWidget(itsParameterColHeader); itsFitMenu = menuBar->AppendTextMenu(kFitMenuTitleStr); itsFitMenu->SetMenuItems(kFitMenuStr); itsFitMenu->SetUpdateAction(JXMenu::kDisableAll); ListenTo(itsFitMenu); const JCoordinate kChiSqLabelWidth = 170; GLChiSqLabel* label = new GLChiSqLabel(container, JXWidget::kFixedLeft, JXWidget::kFixedBottom, 0, kParmsTableHeight + kColHeaderHeight, kChiSqLabelWidth, kChiSqHeight); assert(label != NULL); JXDownRect* downRect = new JXDownRect(container, JXWidget::kHElastic, JXWidget::kFixedBottom, kChiSqLabelWidth, kParmsTableHeight + kColHeaderHeight, w - kFitListWidth - kPartitionHandleWidth, kChiSqHeight); assert(downRect != NULL); itsChiSq = new JXStaticText("", container, JXWidget::kHElastic, JXWidget::kFixedBottom, kChiSqLabelWidth + kJXDefaultBorderWidth, kParmsTableHeight + kColHeaderHeight + kJXDefaultBorderWidth, w - kFitListWidth - kPartitionHandleWidth - 2 * kJXDefaultBorderWidth, kChiSqHeight - 2 * kJXDefaultBorderWidth); assert(itsChiSq != NULL); itsChiSq->SetBackColor(GetColormap()->GetWhiteColor()); // now add the 2 plots container = itsPlotPartition->GetCompartment(2); itsFitPlot = new JX2DPlotWidget(menuBar, container, JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, w - kFitListWidth - kPartitionHandleWidth, container->GetApertureHeight()); assert(itsFitPlot != NULL); itsFitPlot->SetTitle(kFitPlotTitle); itsFitPlot->SetXLabel(itsPlot->GetXLabel()); itsFitPlot->SetYLabel(itsPlot->GetYLabel()); container = itsPlotPartition->GetCompartment(3); itsDiffPlot = new JX2DPlotWidget(itsFitPlot, container, JXWidget::kHElastic, JXWidget::kVElastic, 0, 0, w - kFitListWidth - kPartitionHandleWidth, newHeight - kFirstPlotHeight - kTotalParmsHeight - 2 * kPartitionHandleWidth); assert(itsDiffPlot != NULL); itsDiffPlot->SetTitle(kDiffPlotTitle); itsDiffPlot->SetXLabel(itsPlot->GetXLabel()); itsDiffPlot->SetYLabel(itsPlot->GetYLabel()); itsDiffPlot->ShowFrame(kJFalse); itsPrefsMenu = menuBar->AppendTextMenu(kPrefsMenuTitleStr); itsPrefsMenu->SetMenuItems(kPrefsMenuStr); itsPrefsMenu->SetUpdateAction(JXMenu::kDisableNone); ListenTo(itsPrefsMenu); itsHelpMenu = menuBar->AppendTextMenu(kHelpMenuTitleStr); itsHelpMenu->SetMenuItems(kHelpMenuStr); itsHelpMenu->SetUpdateAction(JXMenu::kDisableNone); ListenTo(itsHelpMenu); itsHelpMenu->SetItemImage(kTOCCmd, jx_help_toc); itsHelpMenu->SetItemImage(kThisWindowCmd, JXPM(jx_help_specific)); itsCurveList->SetCurrentCurveIndex(1); GetPrefsMgr()->ReadFitDirectorSetup(this); }
WinHelpIcon::WinHelpIcon(QFile &file, qint64 off) : images() { PRINT_DBG("Loading icon"); seekFile(file, off); quint16 magicIn = readUnsignedWord(file); if (magicIn != 0) { throw std::runtime_error("Not an icon resource header"); } PRINT_DBG(" Icon resource header magic: %d", magicIn); quint16 resourceTypeIn = readUnsignedWord(file); if (resourceTypeIn != 1) { throw std::runtime_error("Resource is not an icon"); } PRINT_DBG(" Icon resource header resource type: %d", resourceTypeIn); quint16 imagesCountIn = readUnsignedWord(file); PRINT_DBG(" Icon resource header images count: %d", imagesCountIn); QScopedArrayPointer<quint8> widths(new quint8[imagesCountIn]); QScopedArrayPointer<quint8> heights(new quint8[imagesCountIn]); QScopedArrayPointer<quint32> colorCounts(new quint32[imagesCountIn]); QScopedArrayPointer<quint16> colorPlanes(new quint16[imagesCountIn]); QScopedArrayPointer<quint16> bitsPerPixelCount(new quint16[imagesCountIn]); QScopedArrayPointer<qint64> bitmapSizes(new qint64[imagesCountIn]); QScopedArrayPointer<qint64> bitmapOffsets(new qint64[imagesCountIn]); for (int index = 0; index < imagesCountIn; index++) { widths[index] = readUnsignedByte(file); PRINT_DBG(" Icon image directory image header width: %d", widths[index]); heights[index] = readUnsignedByte(file); PRINT_DBG(" Icon image directory image header height: %d", heights[index]); colorCounts[index] = static_cast<quint32> (readUnsignedByte(file)); PRINT_DBG(" Icon image directory image header color count: %d", colorCounts[index]); quint8 reservedIn = readUnsignedByte(file); if (reservedIn != 0) { qDebug() << "Icon image directory image header reserved value is non-zero"; } PRINT_DBG(" Icon image directory image header reserved: %d", reservedIn); colorPlanes[index] = readUnsignedWord(file); PRINT_DBG(" Icon image directory image header color planes: %d", colorPlanes[index]); bitsPerPixelCount[index] = readUnsignedWord(file); PRINT_DBG( " Icon image directory image header bits per pixel count: %d", bitsPerPixelCount[index]); bitmapSizes[index] = static_cast<qint64> (readUnsignedDWord(file)); PRINT_DBG(" Icon image directory image header bitmap size: %lld", bitmapSizes[index]); bitmapOffsets[index] = static_cast<qint64> (readUnsignedDWord(file)); PRINT_DBG( " Icon image directory image header bitmap offset: %lld", bitmapOffsets[index]); } for (int index = 0; index < imagesCountIn; index++) { seekFile(file, off + bitmapOffsets[index]); quint32 headerSizeIn = readUnsignedDWord(file); PRINT_DBG(" Icon image header size: %d", headerSizeIn); if (headerSizeIn == 40) { qint32 widthIn = readSignedDWord(file); PRINT_DBG(" Icon image width: %d", widthIn); qint64 realWidth = static_cast<qint64> (widths[index]); if (realWidth == 0) { realWidth = static_cast<qint64> (widthIn); } qint32 heightIn = readSignedDWord(file); PRINT_DBG(" Icon image height: %d", heightIn); qint64 realHeight = static_cast<qint64> (heights[index]); if (realHeight == 0) { realHeight = (static_cast<qint64> (heightIn)) / (Q_INT64_C(2)); } quint16 colorPlanesIn = readUnsignedWord(file); PRINT_DBG(" Icon image color planes: %d", colorPlanesIn); quint16 bitsPerPixelCountIn = readUnsignedWord(file); PRINT_DBG(" Icon image bits per pixel count: %d", bitsPerPixelCountIn); if (colorCounts[index] == 0) { if (colorPlanesIn == 1) { if (bitsPerPixelCountIn == 1) { colorCounts[index] = 2; } else { if (bitsPerPixelCountIn == 4) { colorCounts[index] = 16; } else { if (bitsPerPixelCountIn == 8) { colorCounts[index] = 256; } else { if (bitsPerPixelCountIn != 32) { colorCounts[index] = 1 << bitsPerPixelCountIn; } } } } } else { colorCounts[index] = 1 << (bitsPerPixelCountIn * colorPlanesIn); } } quint32 compressionMethodIn = readUnsignedDWord(file); PRINT_DBG(" Icon image compression method: %d", compressionMethodIn); quint32 imageSizeIn = readUnsignedDWord(file); PRINT_DBG(" Icon image size: %d", imageSizeIn); qint32 horizontalResolutionIn = readSignedDWord(file); PRINT_DBG(" Icon image horizontal resolution: %d", horizontalResolutionIn); qint32 verticalResolutionIn = readSignedDWord(file); PRINT_DBG(" Icon image vertical resolution: %d", verticalResolutionIn); quint32 colorsInPaletteIn = readUnsignedDWord(file); PRINT_DBG(" Icon image colors in palette: %d", colorsInPaletteIn); quint32 importantColorsUsedIn = readUnsignedDWord(file); PRINT_DBG(" Icon image imporatnt colors used: %d", importantColorsUsedIn); if ((realWidth != 0) && (realHeight != 0) && ((colorCounts[index] == 0) || (colorCounts[index] == 2) || (colorCounts[index] == 16) || (colorCounts[index] == 256))) { QImage image(static_cast<int> (realWidth), static_cast<int> (realHeight), QImage::Format_ARGB32); if (colorCounts[index] == 2) { QScopedArrayPointer<QRgb> palette(new QRgb[2]); for (int i = 0; i < 2; i++) { palette[i] = readBGRDword(file); } qint64 scanlineBytes = ((realWidth + Q_INT64_C(31)) / (Q_INT64_C(32))) * Q_INT64_C(4); QScopedArrayPointer<quint8> xorImage( new quint8[scanlineBytes * realHeight]); QScopedArrayPointer<quint8> andImage( new quint8[scanlineBytes * realHeight]); if (file.read(reinterpret_cast<char *> (xorImage.data()), (scanlineBytes * realHeight)) != (scanlineBytes * realHeight)) { throw std::runtime_error("Unable to read icon image"); } if (file.read(reinterpret_cast<char *> (andImage.data()), (scanlineBytes * realHeight)) != (scanlineBytes * realHeight)) { throw std::runtime_error("Unable to read icon image"); } quint8 masks[] = { 128, 64, 32, 16, 8, 4, 2, 1 }; for (qint64 row = 0; row < realHeight; row++) { for (qint64 col = 0; col < realWidth; col++) { int colorIndex = 0; if ((xorImage[row * scanlineBytes + col / (Q_INT64_C(8))] & masks[col % (Q_INT64_C(8))]) != 0) { colorIndex = 1; } else { colorIndex = 0; } if ((andImage[row * scanlineBytes + col / (Q_INT64_C(8))] & masks[col % (Q_INT64_C(8))]) != 0) { image.setPixel(col, realHeight - Q_INT64_C(1) - row, qRgba(qRed(palette[colorIndex]), qGreen(palette[colorIndex]), qBlue( palette[colorIndex]), 0)); } else { image.setPixel(col, realHeight - Q_INT64_C(1) - row, qRgba(qRed(palette[colorIndex]), qGreen(palette[colorIndex]), qBlue( palette[colorIndex]), 0xFF)); } } } } else { if (colorCounts[index] == 16) { QScopedArrayPointer<QRgb> palette(new QRgb[16]); for (int i = 0; i < 16; i++) { palette[i] = readBGRDword(file); } qint64 scanlineBytesXor = ((realWidth * Q_INT64_C(4) + Q_INT64_C(31)) / (Q_INT64_C(32))) * Q_INT64_C(4); qint64 scanlineBytesAnd = ((realWidth + Q_INT64_C(31)) / (Q_INT64_C(32))) * Q_INT64_C(4); QScopedArrayPointer<quint8> xorImage( new quint8[scanlineBytesXor * realHeight]); QScopedArrayPointer<quint8> andImage( new quint8[scanlineBytesAnd * realHeight]); if (file.read( reinterpret_cast<char *> (xorImage.data()), (scanlineBytesXor * realHeight)) != (scanlineBytesXor * realHeight)) { throw std::runtime_error( "Unable to read icon image"); } if (file.read( reinterpret_cast<char *> (andImage.data()), (scanlineBytesAnd * realHeight)) != (scanlineBytesAnd * realHeight)) { throw std::runtime_error( "Unable to read icon image"); } quint8 masks[] = { 128, 64, 32, 16, 8, 4, 2, 1 }; for (qint64 row = 0; row < realHeight; row++) { for (qint64 col = 0; col < realWidth; col++) { quint8 colorIndex = 0; if ((col & Q_INT64_C(1)) == Q_INT64_C(0)) { colorIndex = xorImage[row * scanlineBytesXor + col / Q_INT64_C(2)]; colorIndex = colorIndex >> 4; } else { colorIndex = xorImage[row * scanlineBytesXor + col / Q_INT64_C(2)] & 15; } if ((andImage[row * scanlineBytesAnd + col / (Q_INT64_C(8))] & masks[col % (Q_INT64_C(8))]) != 0) { image.setPixel( col, realHeight - Q_INT64_C(1) - row, qRgba( qRed( palette[static_cast<int> ( colorIndex)]), qGreen( palette[static_cast<int> ( colorIndex)]), qBlue( palette[static_cast<int> ( colorIndex)]), 0)); } else { image.setPixel( col, realHeight - Q_INT64_C(1) - row, qRgba( qRed( palette[static_cast<int> ( colorIndex)]), qGreen( static_cast<int> (palette[ colorIndex])), qBlue( palette[static_cast<int> ( colorIndex)]), 0xFF)); } } } }
bool forward_ocl(InputArrayOfArrays inps, OutputArrayOfArrays outs, OutputArrayOfArrays internals) { std::vector<UMat> inputs; std::vector<UMat> outputs; bool use_half = (inps.depth() == CV_16S); inps.getUMatVector(inputs); outs.getUMatVector(outputs); int _layerWidth = inputs[0].size[3]; int _layerHeight = inputs[0].size[2]; int _imageWidth = inputs[1].size[3]; int _imageHeight = inputs[1].size[2]; if (umat_offsetsX.empty()) { Mat offsetsX(1, _offsetsX.size(), CV_32FC1, &_offsetsX[0]); Mat offsetsY(1, _offsetsY.size(), CV_32FC1, &_offsetsY[0]); Mat variance(1, _variance.size(), CV_32FC1, &_variance[0]); Mat widths(1, _boxWidths.size(), CV_32FC1, &_boxWidths[0]); Mat heights(1, _boxHeights.size(), CV_32FC1, &_boxHeights[0]); offsetsX.copyTo(umat_offsetsX); offsetsY.copyTo(umat_offsetsY); variance.copyTo(umat_variance); widths.copyTo(umat_widths); heights.copyTo(umat_heights); } String opts; if (use_half) opts = "-DDtype=half -DDtype4=half4 -Dconvert_T=convert_half4"; else opts = "-DDtype=float -DDtype4=float4 -Dconvert_T=convert_float4"; size_t nthreads = _layerHeight * _layerWidth; ocl::Kernel kernel("prior_box", ocl::dnn::prior_box_oclsrc, opts); kernel.set(0, (int)nthreads); kernel.set(1, (float)_stepX); kernel.set(2, (float)_stepY); kernel.set(3, ocl::KernelArg::PtrReadOnly(umat_offsetsX)); kernel.set(4, ocl::KernelArg::PtrReadOnly(umat_offsetsY)); kernel.set(5, (int)_offsetsX.size()); kernel.set(6, ocl::KernelArg::PtrReadOnly(umat_widths)); kernel.set(7, ocl::KernelArg::PtrReadOnly(umat_heights)); kernel.set(8, (int)_boxWidths.size()); kernel.set(9, ocl::KernelArg::PtrWriteOnly(outputs[0])); kernel.set(10, (int)_layerHeight); kernel.set(11, (int)_layerWidth); kernel.set(12, (int)_imageHeight); kernel.set(13, (int)_imageWidth); kernel.run(1, &nthreads, NULL, false); // clip the prior's coordidate such that it is within [0, 1] if (_clip) { Mat mat = outputs[0].getMat(ACCESS_READ); int aspect_count = (_maxSize > 0) ? 1 : 0; int offset = nthreads * 4 * _offsetsX.size() * (1 + aspect_count + _aspectRatios.size()); float* outputPtr = mat.ptr<float>() + offset; int _outChannelSize = _layerHeight * _layerWidth * _numPriors * 4; for (size_t d = 0; d < _outChannelSize; ++d) { outputPtr[d] = std::min<float>(std::max<float>(outputPtr[d], 0.), 1.); } } // set the variance. { ocl::Kernel kernel("set_variance", ocl::dnn::prior_box_oclsrc, opts); int offset = total(shape(outputs[0]), 2); size_t nthreads = _layerHeight * _layerWidth * _numPriors; kernel.set(0, (int)nthreads); kernel.set(1, (int)offset); kernel.set(2, (int)_variance.size()); kernel.set(3, ocl::KernelArg::PtrReadOnly(umat_variance)); kernel.set(4, ocl::KernelArg::PtrWriteOnly(outputs[0])); if (!kernel.run(1, &nthreads, NULL, false)) return false; } return true; }
void Foam::IH_Waves_InletVelocityFvPatchVectorField::updateCoeffs() { if (updated()) { return; } // PHC // Info << "Velocity BC on patch " << this->patch().name() << endl; // Auxiliar variables scalar auxiliar = 0; scalar auxiliarTotal = 0; scalar auxiliarSolit = 0; scalar auxiliarSO = 0; // Variables solitary scalar Csolitary = 0; scalar etaSolit = 0; scalar ts = 0; scalar Xa = 0; scalar X0 = 0; scalarField patchXsolit; // Variables stream function scalar celerity = 0; scalar faseTot; // Variables tveta scalar etaInterp = 0; scalar UInterp = 0; label indexF = 0; // 3D Variables const vector cMin = gMin(patch().patch().localPoints()); const vector cMax = gMax(patch().patch().localPoints()); const vector cSpan = cMax - cMin; const scalar zSpan = cSpan[2]; scalar dMin = 0.0; scalar dSpan = 0.0; const scalarField patchD = patchDirection( cSpan, &dMin, &dSpan ); // Variables & constants const fvMesh& mesh = dimensionedInternalField().mesh(); const word& patchName = this->patch().name(); const label patchID = mesh.boundaryMesh().findPatchID(patchName); const label nF = patch().faceCells().size(); labelList cellGroup = Foam::labelList(nF, 1); const volScalarField& alpha = db().lookupObject<volScalarField>(alphaName()); const volVectorField& U = db().lookupObject<volVectorField>("U"); const scalarField alphaCell = alpha.boundaryField()[patchID].patchInternalField(); const vectorField UCell = U.boundaryField()[patchID].patchInternalField(); const vectorField nVecCell = patch().nf(); scalarField patchU = Foam::scalarField(nF, 0.0); scalarField patchUABS = Foam::scalarField(nF, 0.0); scalarField patchV = Foam::scalarField(nF, 0.0); scalarField patchVABS = Foam::scalarField(nF, 0.0); scalarField patchW = Foam::scalarField(nF, 0.0); const labelList celdas = patch().faceCells(); const scalarField patchHeight = patch().Cf().component(2)-cMin[2]; const scalar g = 9.81; // Calculate Z bounds of the faces scalarField zSup, zInf; faceBoundsZ( &zSup, &zInf ); // Change in reference level (-= zMin) zSup -= cMin[2]; zInf -= cMin[2]; // Waves variables scalar waveOmega; scalarList waveOmegas; scalar waveK; scalarList waveKs; scalar waveAngle; scalarList waveAngles; scalar waveKx; scalarList waveKxs; scalar waveKy; scalarList waveKys; // Define dictionary IOdictionary IHWavesDict ( IOobject ( waveDictName_, this->db().time().constant(), this->db(), IOobject::MUST_READ, IOobject::AUTO_WRITE ) ); // Check for errors - Just the first time if (!allCheck_) { waveType_ = (IHWavesDict.lookupOrDefault<word>("waveType", "aaa")); tSmooth_ = (IHWavesDict.lookupOrDefault<scalar>("tSmooth", -1.0 )); tuningFactor_ = (IHWavesDict.lookupOrDefault<scalar>("tuningFactor", 1.0 )); uCurrent_ = (IHWavesDict.lookupOrDefault<vector>("uCurrent", vector(0,0,0) )); if ( waveType_ == "aaa" ) // No target specified { FatalError << "Wave type not specified. Use:\n" << "regular, solitary, irregular, wavemaker." << exit(FatalError); } if ( waveType_ == "regular" ) { #include "checkInputErrorsRegular.H" } else if ( waveType_ == "solitary" ) { #include "checkInputErrorsSolitary.H" } else if ( waveType_ == "irregular" ) { #include "checkInputErrorsIrregular.H" } else if ( waveType_ == "wavemaker" ) { #include "checkInputErrorsWavemaker.H" } else if ( waveType_ == "current" ) { #include "checkInputErrorsCurrent.H" } else { FatalError << "Wave type not supported, use:\n" << "regular, solitary, irregular, wavemaker." << exit(FatalError); } allCheck_ = true; } // End of allCheck scalar currTime = this->db().time().value(); scalar timeMult = tuningFactor_; // Setting the rest of the wave variables if ( tSmooth_ > 0.0 && currTime < tSmooth_ ) { timeMult = timeMult*currTime/tSmooth_; } if ( waveType_ == "regular" ) { waveOmega = (2.0*PI())/wavePeriod_; waveK = 2.0*PI()/waveLength_; celerity = waveLength_/wavePeriod_; waveAngle = waveDir_*PI()/180.0; waveKx = waveK*cos(waveAngle); waveKy = waveK*sin(waveAngle); // Add lag to correct the phase if ( waveTheory_ == "StokesII" || waveTheory_ == "StokesV" || waveTheory_ == "cnoidal" ) { currTime += timeLag_; } } else if ( waveType_ == "solitary" ) { waveAngle = waveDir_*PI()/180.0; patchXsolit = patch().Cf().component(0)*cos(waveAngle) + patch().Cf().component(1)*sin(waveAngle); X0 = gMin(patchXsolit); } else if ( waveType_ == "irregular" ) { waveOmegas = (2.0*PI())/wavePeriods_; waveKs = 2.0*PI()/waveLengths_; waveAngles = waveDirs_*PI()/180.0; waveKxs = waveKs*cos(waveAngles); waveKys = waveKs*sin(waveAngles); } // Grouping part scalarList dBreakPoints = Foam::scalarList(nPaddles_+1, dMin); scalarList xGroup = Foam::scalarList(nPaddles_, 0.0); scalarList yGroup = Foam::scalarList(nPaddles_, 0.0); for (label i=0; i<nPaddles_; i++) { // Breakpoints, X & Y centre of the paddles dBreakPoints[i+1] = dMin + dSpan/(nPaddles_)*(i+1); xGroup[i] = cMin[0] + cSpan[0]/(2.0*nPaddles_) + cSpan[0]/(nPaddles_)*i; yGroup[i] = cMin[1] + cSpan[1]/(2.0*nPaddles_) + cSpan[1]/(nPaddles_)*i; } forAll(patchD, patchCells) { for (label i=0; i<nPaddles_; i++) { if ( (patchD[patchCells]>=dBreakPoints[i]) && (patchD[patchCells]<dBreakPoints[i+1]) ) { cellGroup[patchCells] = i+1; // Group of each face continue; } } } // Absorption direction part scalarList meanAngle (nPaddles_, 0.0); bool absDireccional = false; // Check if absorption is directional if ( absDir_ > 360.0 ) // Automatic { absDireccional = true; meanAngle = meanPatchDirs( cellGroup ); } else // Fixed { meanAngle = absDir_*PI()/180.0; } // Info << "Paddle angle " << meanAngle << endl; scalarList calculatedLevel (nPaddles_,0.0); if ( waveType_ == "regular" ) { #include "calculatedLevelRegular.H" } else if ( waveType_ == "solitary" ) { #include "calculatedLevelSolitary.H" } else if ( waveType_ == "irregular" ) { #include "calculatedLevelIrregular.H" } else if ( waveType_ == "wavemaker" ) { #include "calculatedLevelEta.H" } else if ( waveType_ == "current" ) { #include "calculatedLevelCurrent.H" } // Calculate water measured levels scalarList measuredLevels = calcWL( alphaCell, cellGroup, zSpan ); // Auxiliar variables auxiliarTotal = 0.0; auxiliar = 0.0; // Define heights as minimum of calculatedLevel and measuredLevels scalarList heights (nPaddles_,0.0); forAll(heights, iterMin) { heights[iterMin] = min(calculatedLevel[iterMin],measuredLevels[iterMin]); }
QwtArray<int> LegendWidget::itemsHeight(int y, int symbolLineLength, int &width, int &height) { // RJT (22/09/09): For most of method, copied in code from current // QtiPlot (rev. 1373) to fix infinite loop if closing bracket missing QString text = d_text->text(); QStringList titles = text.split("\n", QString::KeepEmptyParts); int n = (int)titles.count(); QwtArray<int> heights(n); width = 0; height = 0; int maxL = 0; int h = top_margin; // In QtiPlot rev 1373: + d_frame_pen.width(); for (int i=0; i<n; i++){ QString s = titles[i]; int textL = 0; //bool curveSymbol = false; while (s.contains("\\l(",Qt::CaseInsensitive) || s.contains("\\p{",Qt::CaseInsensitive)){ int pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive); int pos2 = s.indexOf(",",pos); // two arguments in case if pie chart int pos3 = s.indexOf(")",pos); //curveSymbol = true; if (pos >= 0 && (pos2==-1 || pos2>pos3)){ QwtText aux(parse(s.left(pos))); //not a pie chart aux.setFont(d_text->font()); QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux); textL += size.width(); int pos1 = s.indexOf("(", pos); int pos2 = s.indexOf(")", pos1); if (pos2 == -1){ s = s.right(s.length() - pos1 - 1); continue; } int point = -1; PlotCurve *curve = getCurve(s.mid(pos1+1, pos2-pos1-1), point); if (!curve){ s = s.right(s.length() - pos2 - 1); continue; } textL += symbolLineLength + h_space; s = s.right(s.length() - s.indexOf(")", pos) - 1); } else { //Pie chart? pos = s.indexOf("\\p{", 0,Qt::CaseInsensitive); //look for old syntax if (pos >= 0){ QwtText aux(parse(s.left(pos))); aux.setFont(d_text->font()); QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux); textL += size.width(); textL += symbolLineLength; int pos2=s.indexOf("}", pos); if (pos2==-1) pos2=pos+3; s = s.right(s.length() - pos2 - 1); } else { pos = s.indexOf("\\l(", 0,Qt::CaseInsensitive); // new syntax if (pos >= 0){ QwtText aux(parse(s.left(pos))); aux.setFont(d_text->font()); QSize size = aux.textSize(); // In QtiPlot rev 1373: textSize(p, aux); textL += size.width(); textL += symbolLineLength; int pos2=s.indexOf(")", pos); if (pos2==-1) pos2=pos+3; s = s.right(s.length() - pos2 - 1); } } } } // RJT (22/09/09): End copied in code from rev. 1373 QwtText aux(parse(s)); aux.setFont(d_text->font()); QSize size = aux.textSize(); textL += size.width(); if (textL > maxL) maxL = textL; int textH = size.height(); height += textH; heights[i] = y + h + textH/2; h += textH; } height += 2*top_margin; width = 2*left_margin + maxL + h_space; return heights; }
void SCFeedbackDirector::BuildWindow ( SCCircuitDocument* doc ) { const SCCircuit* circuit = doc->GetCircuit(); JArray<JCoordinate> heights(4); heights.AppendElement(kInitExprHeight); heights.AppendElement(kInitExprHeight); heights.AppendElement(kInitExprHeight); heights.AppendElement(kInitExprHeight); JArray<JCoordinate> minHeights(4); minHeights.AppendElement(kMinExprHeight); minHeights.AppendElement(kMinExprHeight); minHeights.AppendElement(kMinExprHeight); minHeights.AppendElement(kMinExprHeight); // begin JXLayout JXWindow* window = new JXWindow(this, 360,520, ""); assert( window != NULL ); itsMainPartition = new JXVertPartition(heights, 0, minHeights, window, JXWidget::kHElastic, JXWidget::kVElastic, 0,110, 365,415); assert( itsMainPartition != NULL ); itsInputSource = new SCComponentMenu(circuit, SCACSourceFilter, "Input source:", window, JXWidget::kFixedLeft, JXWidget::kFixedTop, 20,20, 150,30); assert( itsInputSource != NULL ); itsDepSource = new SCComponentMenu(circuit, SCDepSourceFilter, "Dependent source:", window, JXWidget::kFixedLeft, JXWidget::kFixedTop, 20,60, 150,30); assert( itsDepSource != NULL ); itsEvalButton = new JXTextButton(JGetString("itsEvalButton::SCFeedbackDirector::JXLayout"), window, JXWidget::kFixedRight, JXWidget::kFixedTop, 230,20, 80,20); assert( itsEvalButton != NULL ); JXStaticText* layoutMessage = new JXStaticText(JGetString("layoutMessage::SCFeedbackDirector::JXLayout"), window, JXWidget::kFixedRight, JXWidget::kFixedTop, 240,50, 110,60); assert( layoutMessage != NULL ); // end JXLayout const JCoordinate kMinWindowWidth = window->GetBoundsWidth(); window->SetTitle("Feedback Theorem"); window->SetMinSize(kMinWindowWidth, window->GetBoundsHeight()); layoutMessage->SetText( "Output fn\nH0 | Hinf\n T | Tn\nScratch area"); itsInputSource->SetToPopupChoice(kJTrue); itsDepSource->SetToPopupChoice(kJTrue); ListenTo(itsEvalButton); // create sub-partitions const JCoordinate w = (itsMainPartition->GetBoundsWidth() - JPartition::kDragRegionSize)/2; JArray<JCoordinate> widths(2); widths.AppendElement(w); widths.AppendElement(w); const JCoordinate wMin = (kMinWindowWidth - JPartition::kDragRegionSize)/2; JArray<JCoordinate> minWidths(2); minWidths.AppendElement(wMin); minWidths.AppendElement(wMin); JXContainer* encl = itsMainPartition->GetCompartment(2); itsHPartition = new JXHorizPartition(widths, 0, minWidths, encl, JXWidget::kHElastic, JXWidget::kVElastic, 0,0, encl->GetBoundsWidth(), encl->GetBoundsHeight()); assert( itsHPartition != NULL ); encl = itsMainPartition->GetCompartment(3); itsTPartition = new JXHorizPartition(widths, 0, minWidths, encl, JXWidget::kHElastic, JXWidget::kVElastic, 0,0, encl->GetBoundsWidth(), encl->GetBoundsHeight()); assert( itsTPartition != NULL ); // create expressions SCExprEditorSet* exprSet = new SCExprEditorSet(doc, &itsOutputFn, itsMainPartition->GetCompartment(1), JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 100,100); assert( exprSet != NULL ); exprSet->FitToEnclosure(); exprSet = new SCExprEditorSet(doc, itsOutputFn, &itsH0, itsHPartition->GetCompartment(1), JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 100,100); assert( exprSet != NULL ); exprSet->FitToEnclosure(); exprSet = new SCExprEditorSet(doc, itsOutputFn, &itsHinf, itsHPartition->GetCompartment(2), JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 100,100); assert( exprSet != NULL ); exprSet->FitToEnclosure(); exprSet = new SCExprEditorSet(doc, itsOutputFn, &itsT, itsTPartition->GetCompartment(1), JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 100,100); assert( exprSet != NULL ); exprSet->FitToEnclosure(); exprSet = new SCExprEditorSet(doc, itsOutputFn, &itsTn, itsTPartition->GetCompartment(2), JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 100,100); assert( exprSet != NULL ); exprSet->FitToEnclosure(); exprSet = new SCExprEditorSet(doc, itsOutputFn, &itsScratchFn, itsMainPartition->GetCompartment(4), JXWidget::kHElastic, JXWidget::kVElastic, 0,0, 100,100); assert( exprSet != NULL ); exprSet->FitToEnclosure(); // add our menu items JXTextMenu* menu = itsOutputFn->GetExtraMenu(); menu->AppendItem(kBuildH0FormItemStr); itsBuildH0Index = menu->GetItemCount(); menu->AppendItem(kBuildHinfFormItemStr); itsBuildHinfIndex = menu->GetItemCount(); menu->ShowSeparatorAfter(itsBuildH0Index-1); ListenTo(menu); }
QwtArray<long> LegendWidget::itemsHeight(int symbolLineLength, int &width, int &height, int &textWidth, int &textHeight) { QString text = d_text->text(); QStringList titles = text.split("\n", QString::KeepEmptyParts); int n = (int)titles.count(); QwtArray<long> heights(n); width = 0; height = 0; int maxL = 0; int h = top_margin + d_frame_pen.width(); for (int i=0; i<n; i++){ QString s = titles[i]; int textL = 0; bool curveSymbol = false; while (s.contains("\\l(") || s.contains("\\p{")){ int pos = s.indexOf("\\l(", 0); curveSymbol = true; if (pos >= 0){ QwtText aux(parse(s.left(pos))); aux.setFont(d_text->font()); QSize size = aux.textSize(); textL += size.width(); int pos1 = s.indexOf("(", pos); int pos2 = s.indexOf(")", pos1); int point = -1; PlotCurve *curve = getCurve(s.mid(pos1+1, pos2-pos1-1), point); if (!curve){ s = s.right(s.length() - pos2 - 1); continue; } textL += symbolLineLength + h_space; s = s.right(s.length() - s.indexOf(")", pos) - 1); } else { pos = s.indexOf("\\p{", 0); if (pos >= 0){ QwtText aux(parse(s.left(pos))); aux.setFont(d_text->font()); QSize size = aux.textSize(); textL += size.width(); textL += symbolLineLength; s = s.right(s.length() - s.indexOf("}", pos) - 1); } } } QwtText aux(parse(s)); aux.setFont(d_text->font()); QSize size = aux.textSize(); textL += size.width(); if (curveSymbol) textL += h_space; if (textL > maxL) maxL = textL; int textH = size.height(); height += textH; heights[i] = h + textH/2; h += textH; } height += 2*top_margin; width = 2*left_margin + maxL; int fw = 2*d_frame_pen.width(); height += fw; width += fw; textHeight = height; textWidth = width; int aux_a = d_angle; if (aux_a > 270) aux_a -= 270; if (aux_a >= 180) aux_a -= 180; if (aux_a > 90) aux_a -= 90; double angle = aux_a*M_PI/180.0; if ((d_angle >= 0 && d_angle <= 90) || (d_angle >= 180 && d_angle <= 270)){ height = int(textWidth*sin(angle) + textHeight*cos(angle)); width = int(textWidth*cos(angle) + textHeight*sin(angle)); } else { height = int(textWidth*cos(angle) + textHeight*sin(angle)); width = int(textWidth*sin(angle) + textHeight*cos(angle)); } if (d_frame == Shadow){ width += d_shadow_width; height += d_shadow_width; } return heights; }