Beispiel #1
0
void Viewport::paintEvent(QPaintEvent*)
{
	vector< shared_ptr<RowItem> > row_items(view_.begin(), view_.end());
	assert(none_of(row_items.begin(), row_items.end(),
		[](const shared_ptr<RowItem> &r) { return !r; }));

	stable_sort(row_items.begin(), row_items.end(),
		[](const shared_ptr<RowItem> &a, const shared_ptr<RowItem> &b) {
			return a->visual_v_offset() < b->visual_v_offset(); });

	const vector< shared_ptr<TimeItem> > time_items(view_.time_items());
	assert(none_of(time_items.begin(), time_items.end(),
		[](const shared_ptr<TimeItem> &t) { return !t; }));

	QPainter p(this);
	p.setRenderHint(QPainter::Antialiasing);

	const ViewItemPaintParams pp(rect(), view_.scale(), view_.offset());

	for (const shared_ptr<TimeItem> t : time_items)
		t->paint_back(p, pp);
	for (const shared_ptr<RowItem> r : row_items)
		r->paint_back(p, pp);

	for (const shared_ptr<TimeItem> t : time_items)
		t->paint_mid(p, pp);
	for (const shared_ptr<RowItem> r : row_items)
		r->paint_mid(p, pp);

	p.setRenderHint(QPainter::Antialiasing, false);

	for (const shared_ptr<RowItem> r : row_items)
		r->paint_fore(p, pp);
	for (const shared_ptr<TimeItem> t : time_items)
		t->paint_fore(p, pp);

	p.end();
}
Beispiel #2
0
unsigned int DP_CalculateMaxLoopLength(
        unsigned int nLoops, const unsigned int *loops,
        double percentile, unsigned int extension, unsigned int cutoff)
{
    vector < unsigned int > loopLengths(nLoops);
    unsigned int index, max;
    for (index=0; index<nLoops; ++index)
        loopLengths[index] = loops[index];

    stable_sort(loopLengths.begin(), loopLengths.end());

    if (percentile < 1.0) {
        index = (unsigned int)(percentile * (nLoops - 1) + 0.5);
        max = loopLengths[index] + extension;
    } else {  // percentile >= 1.0
        max = ((unsigned int)(percentile * loopLengths[nLoops - 1] + 0.5)) + extension;
    }

    if (cutoff > 0 && max > cutoff)
        max = cutoff;

    return max;
}
/**
\fn	void ActivatedItemMgr::Add(ActivatedItem *lpItem)

\brief	Adds a new ActivatedItem to be managed. 

\author	dcofer
\date	3/1/2011

\param [in,out]	lpItem	The pointer to the item to add. 
**/
void ActivatedItemMgr::Add(ActivatedItem *lpItem)
{
	if(!lpItem)
		THROW_ERROR(Al_Err_lActivatedItemNull, Al_Err_strActivatedItemNull);

	//Lets make sure the ID of the item is in upper case.
	lpItem->ID(Std_CheckString(lpItem->ID()));

	//lets make sure this is a unique item key.
	try
	{
		m_aryItemsMap.Add(lpItem->ID(), lpItem);
	}
	catch(CStdErrorInfo oError)
	{
		oError.m_strError += " Duplicate activate item Key: " + lpItem->ID(); 
		THROW_ERROR(oError.m_lError, oError.m_strError);
	}
	
	m_aryItems.Add(lpItem);

	stable_sort(m_aryItems.begin(), m_aryItems.end(), LessThanActivatedItemCompare);
}
void gcta::filter_snp_max_maf(double max_maf)
{
    if(_mu.empty()) calcu_mu();

    cout<<"Pruning SNPs with MAF < "<<max_maf<<" ..."<<endl;
    map<string, int> id_map_buf(_snp_name_map);
    map<string, int>::iterator iter, end=id_map_buf.end();
    int prev_size=_include.size();
    double fbuf=0.0;
    _include.clear();
    _snp_name_map.clear();
    for(iter=id_map_buf.begin(); iter!=end; iter++){
        fbuf=_mu[iter->second]*0.5;
        if(fbuf>max_maf && 1.0-fbuf>max_maf) continue;
        _snp_name_map.insert(*iter);
        _include.push_back(iter->second);
    }
	if(_include.size()==0) throw("Error: No SNP is retained for analysis.");
	else{
		stable_sort(_include.begin(), _include.end());
		cout<<"After pruning SNPs with MAF < "<<max_maf<<", there are "<<_include.size()<<" SNPs ("<<prev_size-_include.size()<<" SNPs with MAF > "<<max_maf<<")."<<endl;
	}
}
Beispiel #5
0
void Header::paintEvent(QPaintEvent*)
{
	const QRect rect(0, 0, width(), height());

	vector< shared_ptr<ViewItem> > items(view_.list_by_type<ViewItem>());

	stable_sort(items.begin(), items.end(),
		[](const shared_ptr<ViewItem> &a, const shared_ptr<ViewItem> &b) {
			return a->drag_point(QRect()).y() < b->drag_point(QRect()).y(); });

	QPainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing);

	for (const shared_ptr<ViewItem>& r : items) {
		assert(r);

		const bool highlight = !item_dragging_ &&
			r->label_rect(rect).contains(mouse_point_);
		r->paint_label(painter, rect, highlight);
	}

	painter.end();
}
Beispiel #6
0
int Fujimap::build_(vector<pair<string, uint64_t> >& kvs,
		    FujimapBlock& fb){
  reverse(kvs.begin(), kvs.end());
  stable_sort(kvs.begin(), kvs.end(), kvsComp);
  kvs.erase(unique(kvs.begin(), kvs.end(), kvsEq), kvs.end());

  if (kvs.size() == 0){
    return 0; // not build
  }

  for (int i = 0; i < 20; ++i){
    vector<KeyEdge> keyEdges;
    for (size_t i = 0; i < kvs.size(); ++i){
      keyEdges.push_back(KeyEdge(kvs[i].first.c_str(), kvs[i].first.size(),
				 kvs[i].second, seed_));
    }
    if (fb.build(keyEdges, seed_, fpLen_, et_) == 0){
      break;
    }
    seed_ += 777;
  }
  return 0;
}
Beispiel #7
0
void
Board::saveTikZ( const char * filename, double pageWidth, double pageHeight, double margin ) const
{
  std::ofstream file( filename );
  TransformTikZ transform;
  Rect box = boundingBox();
  bool clipping = _clippingPath.size() > 2;
  if ( clipping )
    box = box && _clippingPath.boundingBox();
  transform.setBoundingBox( box, pageWidth, pageHeight, margin );

  file << "\\begin{tikzpicture}[anchor=south west,text depth=0,x={(1pt,0pt)},y={(0pt,-1pt)}]" << std::endl;

  if ( clipping  ) {
    file << "\\clip ";
    _clippingPath.flushTikZPoints( file, transform );
    file << "\n";
  }
  
  // Draw the background color if needed.
  if ( _backgroundColor != Color::None ) { 
    Rectangle r( box, Color::None, _backgroundColor, 0.0 );
    r.flushTikZ( file, transform );
  }

  // Draw the shapes.
  std::vector< Shape* > shapes = _shapes;
  stable_sort( shapes.begin(), shapes.end(), shapeGreaterDepth );
  std::vector< Shape* >::const_iterator i = shapes.begin();
  std::vector< Shape* >::const_iterator end = shapes.end();
  while ( i != end ) {
    (*i)->flushTikZ( file, transform );
    ++i;
  }  
  file << "\\end{tikzpicture}" << std::endl;
  file.close();
}
void V3LinkLevel::modSortByLevel() {
    // Sort modules by levels, root down to lowest children
    // Calculate levels again in case we added modules
    UINFO(2,"modSortByLevel()\n");

    // level() was computed for us in V3LinkCells

    typedef vector<AstNodeModule*> ModVec;

    ModVec vec;
    AstNodeModule* topp = NULL;
    for (AstNodeModule* nodep = v3Global.rootp()->modulesp(); nodep; nodep=nodep->nextp()->castNodeModule()) {
	if (nodep->level()<=2) {
	    if (topp) {
		nodep->v3warn(E_MULTITOP, "Unsupported: Multiple top level modules: "
			      <<nodep->prettyName()<<" and "<<topp->prettyName());
		nodep->v3warn(E_MULTITOP, "Fix, or use --top-module option to select which you want.");
	    }
	    topp = nodep;
	}
	vec.push_back(nodep);
    }
    stable_sort(vec.begin(), vec.end(), CmpLevel()); // Sort the vector
    UINFO(9,"modSortByLevel() sorted\n");  // Comment required for gcc4.6.3 / bug666
    for (ModVec::iterator it = vec.begin(); it != vec.end(); ++it) {
	AstNodeModule* nodep = *it;
	nodep->clearIter();  // Because we didn't iterate to find the node pointers, may have a stale m_iterp() needing cleanup
	nodep->unlinkFrBack();
    }
    if (v3Global.rootp()->modulesp()) v3Global.rootp()->v3fatalSrc("Unlink didn't work");
    for (ModVec::iterator it = vec.begin(); it != vec.end(); ++it) {
	AstNodeModule* nodep = *it;
	v3Global.rootp()->addModulep(nodep);
    }
    UINFO(9,"modSortByLevel() done\n");  // Comment required for gcc4.6.3 / bug666
    V3Global::dumpCheckGlobalTree("cells.tree", false, v3Global.opt.dumpTreeLevel(__FILE__) >= 3);
}
Beispiel #9
0
void Header::on_group()
{
	const vector< shared_ptr<TraceTreeItem> > items(
		view_.list_by_type<TraceTreeItem>());
	vector< shared_ptr<TraceTreeItem> > selected_items(
		make_filter_iterator(item_selected, items.begin(), items.end()),
		make_filter_iterator(item_selected, items.end(), items.end()));
	stable_sort(selected_items.begin(), selected_items.end(),
		[](const shared_ptr<TraceTreeItem> &a, const shared_ptr<TraceTreeItem> &b) {
			return a->visual_v_offset() < b->visual_v_offset(); });

	shared_ptr<TraceGroup> group(new TraceGroup());
	shared_ptr<TraceTreeItem> mouse_down_item(
		std::dynamic_pointer_cast<TraceTreeItem>(mouse_down_item_));
	shared_ptr<TraceTreeItem> focus_item(
		mouse_down_item ? mouse_down_item : selected_items.front());

	assert(focus_item);
	assert(focus_item->owner());
	focus_item->owner()->add_child_item(group);

	// Set the group v_offset here before reparenting
	group->force_to_v_offset(focus_item->layout_v_offset() +
		focus_item->v_extents().first);

	for (size_t i = 0; i < selected_items.size(); i++) {
		const shared_ptr<TraceTreeItem> &r = selected_items[i];
		assert(r->owner());
		r->owner()->remove_child_item(r);
		group->add_child_item(r);

		// Put the items at 1-pixel offsets, so that restack will
		// stack them in the right order
		r->set_layout_v_offset(i);
	}
}
int aggregate_duplicates( vector< struct adj >* adjstack ){

	if( adjstack == NULL ){

		printf("Error: adjstack pointer is null!\n");
		printf("Source: aggregate_duplicates\n");
		return 1;

	}


	stable_sort( adjstack->begin(), adjstack->end(), UDLess );

	for( unsigned int i = 0; i < adjstack->size(); i++ ){

		int location = locate( adjstack, adjstack->at(i).key1, adjstack->at(i).key2, i+1 );

		while( location != -1 ){

			// A duplicate exists
			// Add the value at location to the adj at i
			// Delete the entry at location
			// Check for another duplicate

			adjstack->at(i).value = adjstack->at(i).value + adjstack->at(location).value;
			adjstack->erase( adjstack->begin() + location );
			location = locate( adjstack, adjstack->at(i).key1, adjstack->at(i).key2, i+1 );


		}

	}

	return 0;

}
Beispiel #11
0
EIO_Status CConnTest::GetFWConnections(string* reason)
{
    SConnNetInfo* net_info = ConnNetInfo_Create(0, m_DebugPrintout);
    if (net_info) {
        const char* user_header;
        net_info->req_method = eReqMethod_Post;
        if (net_info->firewall) {
            user_header = "NCBI-RELAY: FALSE";
            m_Firewall = true;
        } else
            user_header = "NCBI-RELAY: TRUE";
        if (net_info->stateless)
            m_Stateless = true;
        ConnNetInfo_OverrideUserHeader(net_info, user_header);
        ConnNetInfo_SetupStandardArgs(net_info, 0/*w/o service*/);
    }

    string temp(m_Firewall ? "FIREWALL" : "RELAY (legacy)");
    temp += " connection mode has been detected for stateful services\n";
    if (m_Firewall) {
        temp += "This mode requires your firewall to be configured in such a"
            " way that it allows outbound connections to the port range ["
            STRINGIFY(CONN_FWD_PORT_MIN) ".." STRINGIFY(CONN_FWD_PORT_MAX)
            "] (inclusive) at the two fixed NCBI addresses, "
            NCBI_FWD_BEMD " and " NCBI_FWD_STVA ".\n"
            "To set that up correctly, please have your network administrator"
            " read the following (if they have not already done so):"
            " " NCBI_FWDOC_URL "\n";
    } else {
        temp += "This is an obsolescent mode that requires keeping a wide port"
            " range [4444..4544] (inclusive) open to let through connections"
            " to the entire NCBI site (130.14.xxx.xxx/165.112.xxx.xxx) -- this"
            " mode was designed for unrestricted networks when firewall port"
            " blocking had not been an issue\n";
    }
    if (m_Firewall) {
        _ASSERT(net_info);
        switch (net_info->firewall) {
        case eFWMode_Adaptive:
            temp += "Also, there are usually a few additional ports such as "
                STRINGIFY(CONN_PORT_SSH) " and " STRINGIFY(CONN_PORT_HTTPS)
                " at " NCBI_FWD_BEMD ", which can be used if connections to"
                " the ports in the range described above, have failed\n";
            break;
        case eFWMode_Firewall:
            temp += "Furthermore, your configuration explicitly forbids to use"
                " any fallback firewall ports that may exist to improve"
                " reliability of connection experience\n";
            break;
        case eFWMode_Fallback:
            temp += "There are usually a few backup connection ports such as "
                STRINGIFY(CONN_PORT_SSH) " and " STRINGIFY(CONN_PORT_HTTPS)
                " at " NCBI_FWD_BEMD ", which can be used as a failover if"
                " connections to the port range above fail.  However, your "
                " configuration explicitly requests that only those fallback"
                " firewall ports (if any exist) are to be used for"
                " connections:  this also implies that no conventional ports"
                " from the default range will be used\n";
            break;
        default:
            temp += "Internal program error, please report!\n";
            _ASSERT(0);
            break;
        }
    } else {
        temp += "This mode may not be reliable if your site has a restraining"
            " firewall imposing a fine-grained control over which hosts and"
            " ports the outbound connections are allowed to use\n";
    }
    if (m_HttpProxy) {
        temp += "Connections to the aforementioned ports will be made via an"
            " HTTP proxy at '";
        temp += net_info->http_proxy_host;
        temp += ':';
        temp += NStr::UIntToString(net_info->http_proxy_port);
        temp += "'";
        if (net_info->http_proxy_leak) {	 
            temp += ".  If that is unsuccessful, a link bypassing the proxy"
                " will then be attempted";
        }
    }
    temp += '\n';

    PreCheck(eFirewallConnPoints, 0/*main*/, temp);

    PreCheck(eFirewallConnPoints, 1/*sub*/,
             "Obtaining current NCBI " +
             string(m_Firewall ? "firewall settings" : "service entries"));

    EIO_Status status = x_GetFirewallConfiguration(net_info);

    if (status == eIO_Interrupt)
        temp = kCanceled;
    else if (status == eIO_Success) {
        if (!m_Fwd.empty()
            ||  (!m_FwdFB.empty()
                 &&  m_Firewall  &&  net_info->firewall == eFWMode_Fallback)) {
            temp = "OK: ";
            if (!m_Fwd.empty()) {
                stable_sort(m_Fwd.begin(),   m_Fwd.end());
                temp += NStr::UInt8ToString(m_Fwd.size());
            }
            size_t down = 0;
            if (!m_FwdFB.empty()) {
                stable_sort(m_FwdFB.begin(), m_FwdFB.end());
                if (!m_Fwd.empty())
                    temp += " + ";
                temp += NStr::UInt8ToString(m_FwdFB.size());
                ITERATE(vector<CConnTest::CFWConnPoint>, cp, m_FwdFB) {
                    if (cp->status != eIO_Success)
                        ++down;
                }
                if (down)
                    temp += " - " + NStr::UInt8ToString(down);
            }
            temp +=
                m_Fwd.size() + m_FwdFB.size() - down == 1 ? " port" : " ports";
        } else {
Beispiel #12
0
void
Board::saveFIG( const char * filename, double pageWidth, double pageHeight, double margin ) const
{
  std::ofstream file( filename );
  TransformFIG transform;
  Rect bbox = boundingBox();
  transform.setBoundingBox( bbox, pageWidth, pageHeight, margin  );
  transform.setDepthRange( *this );
  
  file << "#FIG 3.2  Produced by the Board library (Copyleft)2007 Sebastien Fourey\n";
  file << "Portrait\n";
  file << "Center\n";
  file << "Metric\n";
  file << "A4\n";
  file << "100.00\n";
  file << "Single\n";
  file << "-2\n";
  file << "1200 2\n";

  std::map<Color,int> colormap;
  int maxColor = 32;


  colormap[Color(0,0,0)] = 0; 
  colormap[Color(0,0,255)] = 1; 
  colormap[Color(0,255,0)] = 2; 
  colormap[Color(0,255,255)] = 0; 
  colormap[Color(255,0,0)] = 4; 
  colormap[Color(255,0,255)] = 0; 
  colormap[Color(255,255,0)] = 6; 
  colormap[Color(255,255,255)] = 7;


  std::vector< Shape* > shapes = _shapes;
  stable_sort( shapes.begin(), shapes.end(), shapeGreaterDepth );
  std::vector< Shape* >::const_iterator i = shapes.begin();
  std::vector< Shape* >::const_iterator end = shapes.end();
  while ( i != end ) { 
    if ( colormap.find( (*i)->penColor() ) == colormap.end() 
	 && (*i)->penColor().valid() )
      colormap[ (*i)->penColor() ] = maxColor++;
    if ( colormap.find( (*i)->fillColor() ) == colormap.end()
	 && (*i)->fillColor().valid() )
      colormap[ (*i)->fillColor() ] = maxColor++;
    ++i;
  }

  if ( colormap.find( _backgroundColor ) == colormap.end()
       && _backgroundColor.valid() )
    colormap[ _backgroundColor ] = maxColor++;
  
  // Write the colormap
  std::map<Color,int>::const_iterator iColormap = colormap.begin();
  std::map<Color,int>::const_iterator endColormap = colormap.end();
  char colorString[255];
  while ( iColormap != endColormap ) {
    secured_sprintf( colorString, 255,
		             "0 %d #%02x%02x%02x\n",
		             iColormap->second,
	                 iColormap->first.red(),
	                 iColormap->first.green(),
	                 iColormap->first.blue() );
    if ( iColormap->second >= 32 ) file << colorString;
    ++iColormap;
  }

  // Draw the background color if needed.
  if ( _backgroundColor != Color::None ) { 
    Rectangle r( bbox, Color::None, _backgroundColor, 0.0f );
    r.depth( std::numeric_limits<int>::max() );
    r.flushFIG( file, transform, colormap );
  }

  // Draw the shapes.
  i = shapes.begin();
  while ( i != end ) {
    // notice << (*i)->name() << " " << (*i)->depth() <<  '\n';
    (*i)->flushFIG( file, transform, colormap );
    ++i;
  }  
  file.close();
}
Beispiel #13
0
void
Board::saveSVG( const char * filename, double pageWidth, double pageHeight, double margin ) const
{
  std::ofstream file( filename );
  TransformSVG transform;
  Rect bbox = boundingBox();
  bool clipping = _clippingPath.size() > 2;
  if ( clipping )
    bbox = bbox && _clippingPath.boundingBox();
  transform.setBoundingBox( bbox, pageWidth, pageHeight, margin );

  file << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>" << std::endl;
  file << "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"" << std::endl;
  file << " \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" << std::endl;

  if ( pageWidth > 0 && pageHeight > 0 ) {
    file << "<svg width=\""
	 << pageWidth << "mm\" height=\""
	 << pageHeight << "mm\" " << std::endl;
    file << "     viewBox=\"0 0 "
 	 << pageWidth * ppmm  << " "
 	 << pageHeight * ppmm  << "\" " << std::endl;
    file << "     xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" >" << std::endl;
  } else {
    file << "<svg width=\""
	 << ( bbox.width / ppmm )  << "mm"
	 << "\" height=\""
	 << ( bbox.height / ppmm ) << "mm"
	 << "\" " << std::endl;
    file << "     viewBox=\"0 0 "
	 << bbox.width  << " "
	 << bbox.height << "\" " << std::endl;
    file << "     xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" >" << std::endl;
  }

  file << "<desc>" << filename 
       << ", created with the Board library (Copyleft) 2007 Sebastien Fourey" 
       << "</desc>" << std::endl;

  if ( clipping  ) {
    file << "<g clip-rule=\"nonzero\">\n"
	 << " <clipPath id=\"GlobalClipPath\">\n"
	 << "  <path clip-rule=\"evenodd\"  d=\"";
    _clippingPath.flushSVGCommands( file, transform );
    file << "\" />\n";
    file << " </clipPath>\n";
    file << "<g clip-path=\"url(#GlobalClipPath)\">\n";
  }
  
  // Draw the background color if needed.
  if ( _backgroundColor != Color::None ) { 
    Rectangle r( bbox, Color::None, _backgroundColor, 0.0 );
    r.flushSVG( file, transform );
  }
  
  // Draw the shapes.
  std::vector< Shape* > shapes = _shapes;
  stable_sort( shapes.begin(), shapes.end(), shapeGreaterDepth );
  std::vector< Shape* >::const_iterator i = shapes.begin();
  std::vector< Shape* >::const_iterator end = shapes.end();
  while ( i != end ) {
    (*i)->flushSVG( file, transform );
    ++i;
  }  

  if ( clipping )
    file << "</g>\n</g>";
  file << "</svg>" << std::endl;
  file.close();
}
Beispiel #14
0
void ActorUtil::SortByZPosition( vector<Actor*> &vActors )
{
	// Preserve ordering of Actors with equal Z positions.
	stable_sort( vActors.begin(), vActors.end(), CompareActorsByZPosition );
}
Beispiel #15
0
void
Board::saveEPS( const char * filename, double pageWidth, double pageHeight, double margin ) const
{
  std::ofstream file( filename );
  Rect bbox = boundingBox();
  bool clipping = _clippingPath.size() > 2;
  if ( clipping )
    bbox = bbox && _clippingPath.boundingBox();
  
  TransformEPS transform;
  transform.setBoundingBox( bbox, pageWidth, pageHeight, margin );
  
  file << "%!PS-Adobe-2.0 EPSF-2.0" << std::endl;
  file << "%%Title: " << filename << std::endl;
  file << "%%Creator: Board library (Copyleft)2007 Sebastien Fourey" << std::endl;
  {
    time_t t = time(0);
    char str_time[255];
    secured_ctime( str_time, &t, 255 );
    file << "%%CreationDate: " << str_time;
  }
  file << "%%BoundingBox: " << std::setprecision( 8 )
       << transform.mapX( bbox.left ) << " "
       << transform.mapY( bbox.top - bbox.height ) << " "
       << transform.mapX( bbox.left + bbox.width ) << " "
       << transform.mapY( bbox.top ) << std::endl;

  file << "%Magnification: 1.0000" << std::endl;
  file << "%%EndComments" << std::endl;

  file << std::endl;
  file << "/cp {closepath} bind def" << std::endl;
  file << "/ef {eofill} bind def" << std::endl;
  file << "/gr {grestore} bind def" << std::endl;
  file << "/gs {gsave} bind def" << std::endl;
  file << "/sa {save} bind def" << std::endl;
  file << "/rs {restore} bind def" << std::endl;
  file << "/l {lineto} bind def" << std::endl;
  file << "/m {moveto} bind def" << std::endl;
  file << "/rm {rmoveto} bind def" << std::endl;
  file << "/n {newpath} bind def" << std::endl;
  file << "/s {stroke} bind def" << std::endl;
  file << "/sh {show} bind def" << std::endl;
  file << "/slc {setlinecap} bind def" << std::endl;
  file << "/slj {setlinejoin} bind def" << std::endl;
  file << "/slw {setlinewidth} bind def" << std::endl;
  file << "/srgb {setrgbcolor} bind def" << std::endl;
  file << "/rot {rotate} bind def" << std::endl;
  file << "/sc {scale} bind def" << std::endl;
  file << "/sd {setdash} bind def" << std::endl;
  file << "/ff {findfont} bind def" << std::endl;
  file << "/sf {setfont} bind def" << std::endl;
  file << "/scf {scalefont} bind def" << std::endl;
  file << "/sw {stringwidth} bind def" << std::endl;
  file << "/sd {setdash} bind def" << std::endl;
  file << "/tr {translate} bind def" << std::endl;
  file << " 0.5 setlinewidth" << std::endl;

  if ( clipping ) {
    file << " newpath ";
    _clippingPath.flushPostscript( file, transform );
    file << " 0 slw clip " << std::endl;
  }
  
  // Draw the background color if needed.
  if ( _backgroundColor != Color::None ) { 
    Rectangle r( bbox, Color::None, _backgroundColor, 0.0f );
    r.flushPostscript( file, transform );
  }

  // Draw the shapes
  std::vector< Shape* > shapes = _shapes;

  stable_sort( shapes.begin(), shapes.end(), shapeGreaterDepth );
  std::vector< Shape* >::const_iterator i = shapes.begin();
  std::vector< Shape* >::const_iterator end = shapes.end();

  while ( i != end ) {
    (*i)->flushPostscript( file, transform );
    ++i;
  }
  file << "showpage" << std::endl;
  file << "%%Trailer" << std::endl;
  file << "%EOF" << std::endl;
  file.close();
}
Beispiel #16
0
void valusorts(sfvector::iterator p1, sfvector::iterator p2) {
  stable_sort(p1, p2, valult<float>);
}
Beispiel #17
0
static void
cin_chardef(char *arg, cintab_t *cintab)
{
    char cmd1[64], arg1[1024] = {'\0'}, arg2[32]= {'\0'};
    cin_char_t *cch=NULL;
    int len, ret, argc;
    unsigned int i, key, key_len;

    while ((argc=cmd_arg(True, cmd1, 64, arg1, 1024, arg2, 32, NULL)))
    {

	if ((strcasecmp("%chardef", cmd1) == 0 && strcasecmp("end", arg1) == 0) || strcasecmp("END_TABLE", cmd1) == 0)
	{
	    break;
	}

	if (argc < 2 || argc > 3)
	{
	    oxim_perr(OXIMMSG_WARNING, N_("%s(%d): arguement expected.\n"),
		cintab->fname_cin, cintab->lineno);
	    continue;
	}

	/* TODO : 字根目前限制不能超過 10 個(未來要改為不限制)*/
	key_len = strlen(cmd1);
	if (key_len > 10)
	{
	    continue;
	}

	/* 
	 * 看看字根中,是否有不合法的字元
	 * 所謂不合法,就是在 selkey、keyname、endkey 沒有定義的字元 
	 */
	int allkey_valid = True;
	for (i=0 ; i < key_len ; i++)
	{
	    cmd1[i] = tolower(cmd1[i]);
	    int kk = cmd1[i];
	    if (!validkey[kk])
	    {
		if (i || cmd1[i] != '#')
		{
		    oxim_perr(OXIMMSG_WARNING, N_("%s(%d): illegal key \"%c\" specified.\n"), cintab->fname_cin, cintab->lineno, cmd1[i]);
		}
		allkey_valid = False;
		break;
	    }
	}
	if (!allkey_valid)
	{
	    continue;
	}

	th.n_icode ++;
	if (th.n_icode == 1)
	{
	    cchar = oxim_malloc(sizeof(cin_char_t), True);
	}
	else
	{
	    cchar = oxim_realloc(cchar, (th.n_icode+1) * sizeof(cin_char_t));
	}

	cch = (cchar + th.n_icode) - 1;
 	bzero(cch, sizeof(cin_char_t));

	if ((cch->ucs4 = ccode_to_ucs4(arg1)) == 0)
	{
	    n_word ++;
	    cch->word_len = strlen(arg1);
	    cch->word = strdup(arg1);
	    table_size += cch->word_len + sizeof(cch->word_len);
	}

	if (arg2[0] != '\0')
	{
	    cch->order = atoi(arg2);
	}

	oxim_keys2codes(cch->key, 2, cmd1);
	cch->keystroke = strdup(cmd1);

	th.n_ichar ++;
	len = strlen(cmd1);
	if (th.n_max_keystroke < len)
	    th.n_max_keystroke = len;

	arg2[0] = '\0';
    }

    /*
     *  Determine the memory model.
     */
    ret = (th.n_max_keystroke <= 5) ? ICODE_MODE1 : ICODE_MODE2;
    th.icode_mode = ret;

    /*
     *  Fill in the ichar, icode_idx and icode1, icode2 arrays.
     */
    stable_sort(cchar, th.n_icode, sizeof(cin_char_t), icode_cmp);

    ichar = oxim_malloc(th.n_icode * sizeof(ichar_t), True);
    icode1 = oxim_malloc(th.n_icode*sizeof(icode_t), True);
    if (ret == ICODE_MODE2)
    {
        icode2 = oxim_malloc(th.n_icode*sizeof(icode_t), True);
    }

    if (n_word)
    {
	word_table = oxim_malloc(table_size, True);
    }

    unsigned int word_idx = 0;
    unsigned int offset = 0;
    unsigned int rec_len = 0;
    for (i=0, cch=cchar; i<th.n_icode; i++, cch++)
    {
	ichar[i] = cch->ucs4;
	/* ucs4 為 0 表示該筆紀錄是詞而不是字元 */
	if (!ichar[i])
	{
	    /* usc4 改成指向 offset_table 索引,再 or 0x80000000,讓程式可以判別這是字元或是指向 offset table */
	    /* 紀錄詞的偏移位置 */
	    ichar[i] = WORD_MASK | offset;
	    /* 計算下一個 offset */
	    rec_len = sizeof(cch->word_len) + cch->word_len;
	    memcpy(word_table + offset, &cch->word_len, sizeof(cch->word_len));
	    memcpy(word_table + offset + sizeof(cch->word_len), cch->word, cch->word_len);
	    offset += rec_len;
	    //free(cch->word);
	}
	icode1[i] = (icode_t)(cch->key[0]);
        if (ret == ICODE_MODE2)
	    icode2[i] = (icode_t)(cch->key[1]);
    }
    //free(cchar);
}
void AvFormatDecoderDVD::PostProcessTracks(void)
{
    if (!ringBuffer)
        return;
    if (!ringBuffer->IsDVD())
        return;

    if (tracks[kTrackTypeAudio].size() > 1)
    {
        stable_sort(tracks[kTrackTypeAudio].begin(),
                    tracks[kTrackTypeAudio].end());

        int trackNo = -1;
        int dvdTrack = ringBuffer->DVD()->GetTrack(kTrackTypeAudio);

        for (uint i = 0; i < GetTrackCount(kTrackTypeAudio); i++)
        {
            LOG(VB_PLAYBACK, LOG_INFO, LOC +
                QString("DVD Audio Track Map Stream id #%1, av_stream_idx %2, MPEG stream 0x%3, lang %4")
                    .arg(tracks[kTrackTypeAudio][i].stream_id)
                    .arg(tracks[kTrackTypeAudio][i].av_stream_index)
                    .arg(ic->streams[tracks[kTrackTypeAudio][i].av_stream_index]->id,0,16)
                    .arg(iso639_key_toName(tracks[kTrackTypeAudio][i].language)));

            // Find the audio track in our list that maps to the
            // selected track in the ringbuffer (the ringbuffer's
            // list should be in the same order but can have gaps,
            // so we look for the track with the same index)
            if (tracks[kTrackTypeAudio][i].stream_id == dvdTrack)
                trackNo = i;
        }

        if (trackNo < 0 && GetTrackCount(kTrackTypeAudio) > 0)
        {
            // Take the first track
            trackNo = 0;
        }

        if (trackNo >= 0)
            SetTrack(kTrackTypeAudio, trackNo);
    }

    if (tracks[kTrackTypeSubtitle].size() > 0)
    {
        map<int,uint> lang_sub_cnt;
        map<int,int>  stream2idx;

        // First, create a map containing stream id -> track index
        // of the subtitle streams that have been found so far.
        for (uint n = 0; n < GetTrackCount(kTrackTypeSubtitle); n++)
        {
            int stream_id = tracks[kTrackTypeSubtitle][n].stream_id & 0x1f;

            stream2idx[stream_id] = n;
        }

        // Get all subtitle tracks from the DVD and filter out any that
        // are not mapped in the current program chain.
        sinfo_vec_t filteredTracks;

        if (!ringBuffer->DVD()->IsInMenu())
        {
            for (uint i = 0; i < 32; ++i)
            {
                int streamid = ringBuffer->DVD()->GetSubtitleTrackNum(i);
                if (streamid >= 0)
                {
                    // This stream is mapped in the current program chain
                    int lang = ringBuffer->DVD()->GetSubtitleLanguage(i);
                    int lang_indx = lang_sub_cnt[lang]++;
                    int trackNo = -1;

                    if (stream2idx.count(streamid) != 0)
                        trackNo = stream2idx[streamid];

                    if (trackNo == -1)
                    {
                        // Create a dummy track if the physical stream has not
                        // yet been seen.
                        filteredTracks.push_back(StreamInfo(-1, lang, lang_indx,
                                                            streamid, 0, 0, false, false, false));
                    }
                    else
                    {
                        // Otherwise use the real data
                        filteredTracks.push_back(tracks[kTrackTypeSubtitle][trackNo]);
                        filteredTracks.back().stream_id &= 0x1f;
                        filteredTracks.back().language = lang;
                        filteredTracks.back().language_index = lang_indx;
                    }
                }
            }
        }
        tracks[kTrackTypeSubtitle] = filteredTracks;

        stable_sort(tracks[kTrackTypeSubtitle].begin(),
                    tracks[kTrackTypeSubtitle].end());

        int trackNo = -1;
        int selectedStream = ringBuffer->DVD()->GetTrack(kTrackTypeSubtitle);

        // Now iterate over the sorted list and try to find the index of the
        // currently selected track.
        for (uint idx = 0; idx < GetTrackCount(kTrackTypeSubtitle); idx++)
        {
            const StreamInfo& stream = tracks[kTrackTypeSubtitle][idx];
            int avidx = stream.av_stream_index;
            QString mpegstream;

            if (avidx >= 0)
                mpegstream = QString( "0x%1").arg(ic->streams[avidx]->id,0,16);
            else
                mpegstream = "n/a";

            LOG(VB_PLAYBACK, LOG_INFO, LOC +
                QString("DVD Subtitle Track Map Stream id #%1, av_stream_idx %2, MPEG #%3, lang %4")
                    .arg(stream.stream_id)
                    .arg(stream.av_stream_index)
                    .arg(mpegstream)
                    .arg(iso639_key_toName(stream.language)));

            if ((selectedStream != -1) && (stream.stream_id == selectedStream))
                trackNo = (int)idx;
        }

        uint captionmode = m_parent->GetCaptionMode();
        int trackcount = (int)GetTrackCount(kTrackTypeSubtitle);

        if (captionmode == kDisplayAVSubtitle &&
            (trackNo < 0 || trackNo >= trackcount))
        {
            m_parent->EnableSubtitles(false);
        }
        else if (trackNo >= 0 && trackNo < trackcount)
        {
            SetTrack(kTrackTypeSubtitle, trackNo);
            m_parent->EnableSubtitles(true);
        }
    }
}
Beispiel #19
0
void radix_sort(int *arr, int start, int end, int num_of_digits) {
	// inteface implementation
	for(int i=1; i<=num_of_digits; i++) {
		stable_sort(arr, start, end, i);
	}
}
Beispiel #20
0
void CombatLogic::setupCombat(MapObject * _attackerObject, MapObject * _defenderObject) {
	ViewManager::instance().isActive[CamId::COMBAT] = true;

	attackerObject = _attackerObject;
	defenderObject = _defenderObject;
	attacker = _attackerObject->hero;
	defender = _defenderObject->hero;
	attackerFaction = attacker->getFactionId();
	defenderFaction = defender->getFactionId();

	// rearrange the troops if the defender is faction 0 (map AI)
	if (defender->getFactionId() == 0) {
		defender->smartArmySetup(attacker);
	}
	// TEMP if attacker is AI rearrange the troops
	if (FactionSetup::instance().isAI[attacker->getFactionId()]) {
		attacker->smartArmySetup(defender);
	}

	// retrieve the creatures involved in combat and set their positions
	creatures.clear();
	attackerStacks = attacker->stackCount();
	int posIndex = 0;
	for (Creature* creature: attacker->creatures) {
		if (creature != nullptr && creature->count > 0) {
			creature->combatPos = COMBAT_POS[attackerStacks - 1][posIndex++];
			creatures.push_back(creature);
			defenderPotentialReward += creature->maxHealth * creature->count;
		}
	}

	// (a new loop to preserve ordering in case of speed ties)
	defenderStacks = defender->stackCount();
	posIndex = 0;
	for (Creature* creature : defender->creatures) {
		if (creature != nullptr && creature->count > 0) {
			creature->combatPos =
				vec2(COMBAT_COLS - COMBAT_POS[defenderStacks - 1][posIndex].x - 1,
					COMBAT_POS[defenderStacks - 1][posIndex].y);
			posIndex++;
			creatures.push_back(creature);
			attackerPotentialReward += creature->maxHealth * creature->count;
		}
	}

	// sort by creature speed (initiative)
	stable_sort(creatures.begin(), creatures.end(),
		[this](const Creature * a, const Creature * b) -> bool {
		return a->speed > b->speed;
	});
	for (int i = 0; i < (int)creatures.size(); i++) {
		creatures[i]->refresh();
	}

	// initialize the creatures' last active turn TODO implement waiting
	lastActive.resize(creatures.size());
	fill(lastActive.begin(), lastActive.end(), -1);

	currentCreature = 0;
	calcValidMoves();
	roundCount = 0;
	combatActive = true;

	// check if someone started the fight without any troops (autoloss)
	if (defenderStacks == 0) {
		endCombat(attackerFaction);
	}
	else if (attackerStacks == 0) {
		endCombat(defenderFaction);
	}
	else {
		std::cout << "Combat: Starting with creature (" << creatures[currentCreature]->combatPos.x << ", " <<
			creatures[currentCreature]->combatPos.y << ") faction " << creatures[currentCreature]->getFactionId() << std::endl;

		if (FactionSetup::instance().isAI[creatures[currentCreature]->getFactionId()]) {
			simpleCombatAI();
		}
		// TEMP thread sleep solution, reconsider if more threads are added
		else if (std::this_thread::get_id() == GameLogic::instance().aiThread.get_id()) {
			threadSleep();
		}
	}
}
Beispiel #21
0
static PyObject* selNSGA2(PyObject *self, PyObject *args){
    /* Args[0] : Individual list
     * Args[1] : Number of individuals wanted in output
     * Return : k selected individuals from input individual list
     */
    PyObject *lListIndv = PyTuple_GetItem(args, 0);
#ifdef PY3K
    unsigned long k = (unsigned long)PyLong_AS_LONG(PyTuple_GetItem(args, 1));
#else
    unsigned int k = (unsigned int)PyInt_AS_LONG(PyTuple_GetItem(args, 1));
#endif
    
    PyObject *lListSelect = PyList_New(0);
    
    unsigned int lLenListIndv = (unsigned int)PyList_Size(lListIndv);
    unsigned int lNbrObjectives = (unsigned int)PyTuple_Size(PyObject_GetAttrString(PyObject_GetAttrString(PyList_GetItem(lListIndv,0), "fitness"), "values"));
    
    if(k == 0)
        return lListSelect;
    
    // First : copy fitness values into an std::vector<std::vector<double> >
    // First vector index is used to identify individuals
    // Second vector index represents an objective
    std::vector<std::vector<double> > lPopFit(lLenListIndv, std::vector<double>(lNbrObjectives,0.));
    for(unsigned int i = 0; i < lLenListIndv; i++){
        for(unsigned int j = 0; j < lNbrObjectives; j++)
            lPopFit[i][j] = PyFloat_AS_DOUBLE(PyTuple_GetItem(PyObject_GetAttrString(PyObject_GetAttrString(PyList_GetItem(lListIndv,i), "fitness"), "wvalues"), j));
    }
    
    
    unsigned int lParetoSorted = 0;
    unsigned int lFrontIndex = 0;
    std::vector<std::vector<unsigned int> > lParetoFront(1, std::vector<unsigned int>(0));
    std::vector<unsigned int> lDominating(lLenListIndv, 0);
    std::vector<std::vector<unsigned int> > lDominatedInds(lLenListIndv, std::vector<unsigned int>(0));
    
    // Rank first pareto front
    for(unsigned int i = 0; i < lLenListIndv; i++){
        for(unsigned int j = i+1; j < lLenListIndv; j++){
            
            if(isDominated(lPopFit[j], lPopFit[i])){
                lDominating[j]++;
                lDominatedInds[i].push_back(j);
            }
            else if(isDominated(lPopFit[i], lPopFit[j])){
                lDominating[i]++;
                lDominatedInds[j].push_back(i);
            }
        }
        if(lDominating[i] == 0){
            lParetoFront[lFrontIndex].push_back(i);
            lParetoSorted++;
        }
    }

    // Rank other pareto fronts, until we reach the *k* limit
    while(lParetoSorted < k && lParetoSorted < lLenListIndv){
        lFrontIndex++;
        lParetoFront.push_back(std::vector<unsigned int>(0));
        for(unsigned int i = 0; i < lParetoFront[lFrontIndex-1].size(); i++){
            unsigned int lIndiceP = lParetoFront[lFrontIndex-1][i];
            for(unsigned int j = 0; j < lDominatedInds[lIndiceP].size(); j++){
                unsigned int lIndiceD = lDominatedInds[lIndiceP][j];
                if(--lDominating[lIndiceD] == 0){
                    lParetoFront[lFrontIndex].push_back(lIndiceD);
                    lParetoSorted++;
                }
            }
        }
    }
    
    // Append individuals from pareto ranking until we reach the limit
    for(unsigned int i = 0; i < lParetoFront.size(); i++){
        if(PyList_Size(lListSelect)+lParetoFront[i].size() <= k){
            for(unsigned int j = 0; j < lParetoFront[i].size(); j++)
                PyList_Append(lListSelect, PyList_GetItem(lListIndv,lParetoFront[i][j]));
        }
        else{
            break;
        }
    }

    // Crowding distance on the last front
    if(PyList_Size(lListSelect) == k)
        return lListSelect;
    
    FitComp lCmpIndvObj;
    std::vector<unsigned int> lLastParetoFront = lParetoFront.back();
    std::vector<std::pair<double, unsigned int> > lDistances(0);
    std::vector<std::pair<std::vector<double>, unsigned int> > lCrowdingList(0);
    double lInfinity = std::numeric_limits<double>::infinity();
    
    // Reserve sufficient memory for the subsequent push_back
    lDistances.reserve(lLastParetoFront.size());
    lCrowdingList.reserve(lLastParetoFront.size());
    
    for(unsigned int i = 0; i < lLastParetoFront.size(); i++){
        // Push initial distance (0.0) and individual index in lPopFit and lListIndv for each individual
        lDistances.push_back(std::pair<double, unsigned int>(0., lLastParetoFront[i]));
        
        // Push fitness and individual index in lDistances for each individual
        lCrowdingList.push_back(std::pair<std::vector<double>, unsigned int>(lPopFit[lLastParetoFront[i]],i));
    }
    
    for(unsigned int i = 0; i < lNbrObjectives; i++){
        // For each objective
        // Set the current objective in the comparison class
        lCmpIndvObj.mCompIndex = i;
        // Sort (stable, in order to keep the same order for equal fitness values)
        stable_sort(lCrowdingList.begin(), lCrowdingList.end(), lCmpIndvObj);
        
        // Set an infinite distance to the extremums
        lDistances[lCrowdingList[0].second].first = lInfinity;
        lDistances[lCrowdingList.back().second].first = lInfinity;

        for(unsigned int j = 1; j < lCrowdingList.size()-1; j++){
            if(lDistances[lCrowdingList[j].second].first < lInfinity)
                lDistances[lCrowdingList[j].second].first += lCrowdingList[j+1].first[i]-lCrowdingList[j-1].first[i];
        }
    }
    
    // Final sorting (again, must be stable)
    stable_sort(lDistances.begin(), lDistances.end(), crowdDistComp);
   
    // Pick the last individuals (with the higher crowding distance) first
    for(unsigned int i = lDistances.size()-1; i >= 0; i--){
        if(PyList_Size(lListSelect) >= k)
            break;
        // While the size of the return list is lesser than *k*, append the next individual
        PyList_Append(lListSelect, PyList_GetItem(lListIndv,lDistances[i].second));  
    }
    
    return lListSelect;
}
Beispiel #22
0
EIO_Status CConnTest::GetFWConnections(string* reason)
{
    SConnNetInfo* net_info = ConnNetInfo_Create(0);
    if (net_info) {
        const char* user_header;
        net_info->req_method = eReqMethod_Post;
        if (net_info->firewall) {
            user_header = "NCBI-RELAY: FALSE";
            m_Firewall = true;
        } else
            user_header = "NCBI-RELAY: TRUE";
        if (net_info->stateless)
            m_Stateless = true;
        ConnNetInfo_OverrideUserHeader(net_info, user_header);
        ConnNetInfo_SetupStandardArgs(net_info, 0/*w/o service*/);
    }

    string temp(m_Firewall ? "FIREWALL" : "RELAY (legacy)");
    temp += " connection mode has been detected for stateful services\n";
    if (m_Firewall) {
        temp += "This mode requires your firewall to be configured in such a"
            " way that it allows outbound connections to the port range ["
            STRINGIFY(CONN_FWD_PORT_MIN) ".." STRINGIFY(CONN_FWD_PORT_MAX)
            "] (inclusive) at the two fixed NCBI hosts, 130.14.29.112"
            " and 165.112.7.12\n"
            "To set that up correctly, please have your network administrator"
            " read the following (if they have not already done so):"
            " " NCBI_FW_URL "\n";
    } else {
        temp += "This is an obsolescent mode that requires keeping a wide port"
            " range [4444..4544] (inclusive) open to let through connections"
            " to any NCBI host (130.14.2x.xxx/165.112.xx.xxx) -- this mode was"
            " designed for unrestricted networks when firewall port blocking"
            " was not an issue\n";
    }
    if (m_Firewall) {
        _ASSERT(net_info);
        switch (net_info->firewall) {
        case eFWMode_Adaptive:
            temp += "There are also fallback connection ports such as 22 and"
                " 443 at 130.14.29.112.  They will be used if connections to"
                " the ports in the range described above have failed\n";
            break;
        case eFWMode_Firewall:
            temp += "Also, your configuration explicitly forbids to use any"
                " fallback firewall ports that may exist to improve network"
                " connectivity\n";
            break;
        case eFWMode_Fallback:
            temp += "However, your configuration explicitly requests that only"
                " fallback firewall ports (if any exist) are to be used for"
                " connections: this also implies that no conventional ports"
                " from the range above will be used\n";
            break;
        default:
            temp += "Internal program error, please report!\n";
            _ASSERT(0);
            break;
        }
    } else {
        temp += "This mode may not be reliable if your site has a restrictive"
            " firewall imposing fine-grained control over which hosts and"
            " ports the outbound connections are allowed to use\n";
    }
    if (m_HttpProxy) {
        temp += "Connections to the aforementioned ports will be made via an"
            " HTTP proxy at '";
        temp += net_info->http_proxy_host;
        temp += ':';
        temp += NStr::UIntToString(net_info->http_proxy_port);
        temp += "'";
        if (net_info  &&  net_info->http_proxy_leak) {
            temp += ".  If that is unsuccessful, a link bypassing the proxy"
                " will then be attempted";
        }
        if (m_Firewall  &&  *net_info->proxy_host)
            temp += ". In addition, your";
    }
    if (m_Firewall  &&  *net_info->proxy_host) {
        if (!m_HttpProxy)
            temp += "Your";
        temp += " configuration specifies that instead of connecting directly"
            " to NCBI addresses, a forwarding non-transparent proxy host '";
        temp += net_info->proxy_host;
        temp += "' should be used for all links";
        if (m_HttpProxy)
            temp += " (including those originating from the HTTP proxy)";
    }
    temp += '\n';

    PreCheck(eFirewallConnPoints, 0/*main*/, temp);

    PreCheck(eFirewallConnPoints, 1/*sub*/,
             "Obtaining current NCBI " +
             string(m_Firewall ? "firewall settings" : "service entries"));

    EIO_Status status = x_GetFirewallConfiguration(net_info);

    if (status == eIO_Interrupt)
        temp = kCanceled;
    else if (status == eIO_Success) {
        if (!m_Fwd.empty()
            ||  (!m_FwdFB.empty()
                 &&  m_Firewall  &&  net_info->firewall == eFWMode_Fallback)) {
            temp = "OK: ";
            if (!m_Fwd.empty()) {
                stable_sort(m_Fwd.begin(),   m_Fwd.end());
                temp += NStr::UInt8ToString(m_Fwd.size());
            }
            if (!m_FwdFB.empty()) {
                stable_sort(m_FwdFB.begin(), m_FwdFB.end());
                if (!m_Fwd.empty())
                    temp += " + ";
                temp += NStr::UInt8ToString(m_FwdFB.size());
            }
            temp += m_Fwd.size() + m_FwdFB.size() == 1 ? " port" : " ports";
        } else {
            status = eIO_Unknown;
            temp = "No connection ports found, please contact " + HELP_EMAIL;
        }
    } else if (status == eIO_Timeout) {
        temp = x_TimeoutMsg();
        if (m_Timeout > kTimeout)
            temp += "You may want to contact " + HELP_EMAIL;
    } else
        temp = "Please contact " + HELP_EMAIL;

    PostCheck(eFirewallConnPoints, 1/*sub*/, status, temp);

    ConnNetInfo_Destroy(net_info);

    if (status == eIO_Success) {
        PreCheck(eFirewallConnPoints, 2/*sub*/,
                 "Verifying configuration for consistency");

        bool firewall = true;
        // Check primary ports only
        ITERATE(vector<CConnTest::CFWConnPoint>, cp, m_Fwd) {
            if (cp->port < CONN_FWD_PORT_MIN  ||  CONN_FWD_PORT_MAX < cp->port)
                firewall = false;
            if (cp->status != eIO_Success) {
                status = cp->status;
                temp  = CSocketAPI::HostPortToString(cp->host, cp->port);
                temp += " is not operational, please contact " + HELP_EMAIL;
                break;
            }
        }
        if (status == eIO_Success) {
            if (!m_Firewall  &&  !m_FwdFB.empty()) {
                status = eIO_Unknown;
                temp = "Fallback ports found in non-firewall mode, please"
                    " contact " + HELP_EMAIL;
            } else if (m_Firewall != firewall) {
                status = eIO_Unknown;
                temp  = "Firewall ";
                temp += firewall ? "wrongly" : "not";
                temp += " acknowledged, please contact " + HELP_EMAIL;
            } else
                temp.resize(2);
        }

        PostCheck(eFirewallConnPoints, 2/*sub*/, status, temp);
    }
Beispiel #23
0
void F::m_fn1(int &p1) const {
  int *g, *h;
  stable_sort(h, g, G());
}
Beispiel #24
0
void bingQdpmRocTest(vector<string> &dirs,
					 int windowLimit = -1, double timeLimitMs = -1, float ratioThreshold = -1)
{
	size_t imageCount = 0;
	size_t personCount = 0;
	size_t matchCount = 0;
	vector<ScoreTp> pScores;
	TickMeter tm;
	vector<std::string>::const_iterator it = dirs.begin();
	char buf[512];

	for (; it != dirs.end(); it++) {
		string dir = *it;
		DataSetVOC voc(dir, true, true);
		voc.loadAnnotations();
		const size_t testNum = voc.testSet.size();
		const char *imgPath =_S(voc.imgPathW);

		// Objectness
		double base = 2;
		double intUionThr = 0.5;
		int W = 8;
		int NSS = 2;

#ifdef WINDOW_GUESS
		Objectness objNess(voc, base, intUionThr, W, NSS);

		objNess.loadTrainedModel(TRAIN_MODEL);
#endif

		// LSVM DPM
		string dpmPersonModel = "../ExtraData/latentsvmXml/person.xml";
		vector<string> models;
		models.push_back(dpmPersonModel);
		QUniLsvmDetector detector(models);
		float overlapThreshold = 0.2f;

		if (ratioThreshold > 0)
			detector.setRatioThreshold(ratioThreshold);

		printf("%d: \n", testNum);
		for (int i = 0; i < testNum; i++) {
			const vector<Vec4i> &boxesGT = voc.gtTestBoxes[i];
			const size_t gtNumCrnt = boxesGT.size();
			if (gtNumCrnt <= 0)
				continue;

			imageCount++;
			personCount += gtNumCrnt;

			Mat image = imread(format(imgPath, _S(voc.testSet[i])));
			if (image.ptr() == NULL) {
				fprintf(stderr, "No JPG Image !\n");
				exit(1);
			}

			int numPerSz = 130;
			ValStructVec<float, Vec4i> boxes;
			double preObj = tm.getTimeMilli();
			double objTime = 0.;

#ifdef WINDOW_GUESS // window guess
			tm.start();
			objNess.getObjBndBoxes(image, boxes, numPerSz);
			tm.stop();
			objTime = tm.getTimeMilli() - preObj;
#endif

			double localTimeLimitMs = timeLimitMs;
			if (timeLimitMs > 0) {
				localTimeLimitMs -= objTime;
				if (localTimeLimitMs < 0.)
					localTimeLimitMs = 0.;
			}

			vector<QRect> searchBoxes;
			if (windowLimit > 0) {
				for (int j = 0; j < (int)boxes.size() && j < windowLimit; j++) {
					const Vec4i &bb = boxes[j];
					QRect rt(bb[0], bb[1], bb[2], bb[3]);
					searchBoxes.push_back(rt);
				}
			} else {
				for (int j = 0; j < (int)boxes.size(); j++) {
					const Vec4i &bb = boxes[j];
					QRect rt(bb[0], bb[1], bb[2], bb[3]);
					searchBoxes.push_back(rt);
				}
			}

			tm.start();
			detector.setup(image, overlapThreshold, localTimeLimitMs);
			tm.stop();

			vector<FeatureMapCoord> ftrMapCoords;
#ifdef WINDOW_GUESS
			detector.cvtBox2FtrMapCoord(&searchBoxes, &ftrMapCoords);
#else
			detector.genFullFtrMapCoord(&ftrMapCoords);

			preObj = tm.getTimeMilli();
			tm.start();
#ifdef SHUFFLE_WINDOW
			random_shuffle(ftrMapCoords.begin(), ftrMapCoords.end());
#endif
			tm.stop();
			double randGenTime = tm.getTimeMilli() - preObj;

			if (localTimeLimitMs > 0 && localTimeLimitMs - preObj >= 0.)
					detector.setTimeLimit(localTimeLimitMs - preObj);
#endif

			vector<QUniLsvmDetector::ObjectDetection> detections;
			vector<vector<FeatureMapCoord> *> fmcss;
			fmcss.push_back(&ftrMapCoords);
			tm.start();
			detector.detect(detections, fmcss);
			tm.stop();

			vector<DetectedInfo> di(detections.size());
			vector<int> gtIdx(gtNumCrnt, -1);

			int detectCount = 0;
			for (size_t j = 0; j < detections.size(); j++) {
				const QUniLsvmDetector::ObjectDetection& od = detections[j];

				if (od.score < RECOMMENDABLE_THRESHOLD)
					continue;

				detectCount++;
				Vec4i bb(od.rect.x + 1, od.rect.y + 1, od.rect.x + od.rect.width, od.rect.y + od.rect.height);

				// score matchScore for the ROC curve
				double maxMatchScore = 0;
				int maxMatchId = -1;
				for (int k = 0; k < gtNumCrnt; k++) {
					double matchScore = DataSetVOC::interUnio(bb, boxesGT[k]);
					if (matchScore > maxMatchScore) {
						maxMatchScore = matchScore;
						maxMatchId = k;
					}
				}

				uchar match = maxMatchScore > 0.5 ? 1 : 0;
				if (match) {
					int preDetectedIdx = gtIdx[maxMatchId];
					if (preDetectedIdx >= 0) {
						if (maxMatchScore > di[preDetectedIdx].matchScore) {
							di[preDetectedIdx].matched = false;
							gtIdx[maxMatchId] = int(j);
							di[j].matchScore = maxMatchScore;
							di[j].matched = true;
						}
					} else {
						gtIdx[maxMatchId] = int(j);
						di[j].matchScore = maxMatchScore;
						di[j].matched = true;
					}
				}

#ifdef SAVE_IMAGE_RESULT
				// save the result image
				char buf[256];
				sprintf(buf, "%2f", od.score);
				Point pt(max((bb[2] + bb[0] - 85) / 2, 0), (bb[1] + bb[3]) / 2);
				putText(image, buf, pt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar::all(255), 3, CV_AA);
				putText(image, buf, pt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar::all(0), 1, CV_AA);
				rectangle(image, od.rect, cv::Scalar(0, 255, 0), 2);
#endif
			}

			for (size_t j = 0; j < detectCount; j++) { // detections are sorted in descending order
				const QUniLsvmDetector::ObjectDetection& od = detections[j];
				if (di[j].matched)
					matchCount++;
				pScores.push_back(ScoreTp(od.score, di[j].matched));
			}

#ifdef SAVE_IMAGE_RESULT
			imwrite((voc.testSet[i] + "_DpmResult.png").c_str(), image);
#endif
			printf("%d ", i + 1);
		}
		printf("\n");
	}
	printf("BingQdpmRocTest time = %f sec\n", tm.getTimeSec());
	printf("GT %d, Matched %d/%d \n", personCount, matchCount, pScores.size());

	// Calculate log-average miss rate
	stable_sort(begin(pScores), end(pScores),
		[](const ScoreTp &p1, const ScoreTp &p2) { return p1.first > p2.first; });

	vector<float> fp(pScores.size());
	for (size_t i = 0; i < fp.size(); i++)
		fp[i] = !pScores[i].second;

	vector<float> tp(pScores.size());
	tp[0] = pScores[0].second;
	for (size_t i = 1; i < tp.size(); i++)
		tp[i] = tp[i - 1] + pScores[i].second;
	for (size_t i = 0; i < tp.size(); i++)
		tp[i] /= personCount;

	for (size_t i = 1; i < fp.size(); i++)
		fp[i] += fp[i - 1];
	for (size_t i = 0; i < fp.size(); i++)
		fp[i] /= imageCount;

	sprintf(buf, "%s%03d_%03.fms_6137gt_%04dtp_%04ddt_%.0fs.m",
		METHOD_NAME, max(windowLimit, 0), timeLimitMs, matchCount, pScores.size(), tm.getTimeSec());
	FILE *matlabFile = fopen(buf, "w");
	printVector(matlabFile, tp, "tp");
	printVector(matlabFile, fp, "fp");

	char *matlabContent = "tp = tp'; fp = fp';\n"
		"addpath(genpath('d:/81_dataset/03_Caltech/piotr_toolbox/')); savepath;\n"
		"xs1=[-inf; fp];\n"
		"ys1=[0; tp];\n"
		"ref=10.^(-2:.25:0);\n"
		"lims=[3.1e-4 1e1 .5 1];\n"
		"m=length(ref);\n"
		"for i=1:m\n"
		"\tj=find(xs1<=ref(i));\n"
		"\tmiss(i)=ys1(j(end));\n"
		"end\n"
		"miss=exp(mean(log(max(1e-10,1-miss))));\n"
		"show=figure();\n"
		"plotRoc([fp tp],'logx',1,'logy',1,'xLbl','fppi',...\n"
		"\t'lims',lims,'color','g','smooth',1,'fpTarget',ref);\n"
		"title(sprintf('log-average miss rate = %.2f%%',miss*100));\n"
		"savefig(['MORU' 'Roc'],show,'png');\n";
	fwrite(matlabContent, strlen(matlabContent), 1, matlabFile);

	fclose(matlabFile);
}
Beispiel #25
0
DECLARE_EXPORT void SolverMRP::SolverMRPdata::commit()
{
  // Check
  SolverMRP* solver = getSolver();
  if (!demands || !solver)
    throw LogicException("Missing demands or solver.");

  // Message
  if (solver->getLogLevel()>0)
    logger << "Start solving cluster " << cluster << " at " << Date::now() << endl;

  // Solve the planning problem
  try
  {
    // TODO Propagate & solve initial shortages and overloads

    // Sort the demands of this problem.
    // We use a stable sort to get reproducible results between platforms
    // and STL implementations.
    stable_sort(demands->begin(), demands->end(), demand_comparison);

    // Solve for safety stock in buffers.
    if (solver->getPlanSafetyStockFirst())
    {
      constrainedPlanning = (solver->getPlanType() == 1);
      solveSafetyStock(solver);
    }

    // Loop through the list of all demands in this planning problem
    safety_stock_planning = false;
    constrainedPlanning = (solver->getPlanType() == 1);
    for (deque<Demand*>::const_iterator i = demands->begin();
        i != demands->end(); ++i)
    {
      try
      {
        // Plan the demand
        (*i)->solve(*solver, this);
      }
      catch (...)
      {
        // Error message
        logger << "Error: Caught an exception while solving demand '"
            << (*i)->getName() << "':" << endl;
        try {throw;}
        catch (const bad_exception&) {logger << "  bad exception" << endl;}
        catch (const exception& e) {logger << "  " << e.what() << endl;}
        catch (...) {logger << "  Unknown type" << endl;}
      }
    }

    // Clean the list of demands of this cluster
    demands->clear();

    // Solve for safety stock in buffers.
    if (!solver->getPlanSafetyStockFirst()) solveSafetyStock(solver);
  }
  catch (...)
  {
    // We come in this exception handling code only if there is a problem with
    // with this cluster that goes beyond problems with single orders.
    // If the problem is with single orders, the exception handling code above
    // will do a proper rollback.

    // Error message
    logger << "Error: Caught an exception while solving cluster "
        << cluster << ":" << endl;
    try {throw;}
    catch (const bad_exception&) {logger << "  bad exception" << endl;}
    catch (const exception& e) {logger << "  " << e.what() << endl;}
    catch (...) {logger << "  Unknown type" << endl;}

    // Clean up the operationplans of this cluster
    for (Operation::iterator f=Operation::begin(); f!=Operation::end(); ++f)
      if (f->getCluster() == cluster)
        f->deleteOperationPlans();

    // Clean the list of demands of this cluster
    demands->clear();
  }

  // Message
  if (solver->getLogLevel()>0)
    logger << "End solving cluster " << cluster << " at " << Date::now() << endl;
}
Beispiel #26
0
void indxsorts(sfvector & sfv) {
  stable_sort(sfv.begin(), sfv.end(), indxlt<float>);
}
Beispiel #27
0
FontData* CSSFontSelector::getFontData(const FontDescription& fontDescription, const AtomicString& familyName)
{
    if (m_fontFaces.isEmpty()) {
        if (familyName.startsWith("-webkit-"))
            return fontDataForGenericFamily(m_document, fontDescription, familyName);
        if (fontDescription.genericFamily() == FontDescription::StandardFamily && !fontDescription.isSpecifiedFont())
            return fontDataForGenericFamily(m_document, fontDescription, "-webkit-standard");
        return 0;
    }

    String family = familyName.string();

    Vector<RefPtr<CSSFontFace> >* familyFontFaces = m_fontFaces.get(family);
    // If no face was found, then return 0 and let the OS come up with its best match for the name.
    if (!familyFontFaces || familyFontFaces->isEmpty()) {
        // If we were handed a generic family, but there was no match, go ahead and return the correct font based off our
        // settings.
        if (fontDescription.genericFamily() == FontDescription::StandardFamily && !fontDescription.isSpecifiedFont())
            return fontDataForGenericFamily(m_document, fontDescription, "-webkit-standard");
        return fontDataForGenericFamily(m_document, fontDescription, familyName);
    }

    OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >& segmentedFontFaceCache = m_fonts.add(family, nullptr).first->second;
    if (!segmentedFontFaceCache)
        segmentedFontFaceCache = adoptPtr(new HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >);

    FontTraitsMask traitsMask = fontDescription.traitsMask();

    RefPtr<CSSSegmentedFontFace>& face = segmentedFontFaceCache->add(traitsMask, 0).first->second;
    if (!face) {
        face = CSSSegmentedFontFace::create(this);

        // Collect all matching faces and sort them in order of preference.
        Vector<CSSFontFace*, 32> candidateFontFaces;
        for (int i = familyFontFaces->size() - 1; i >= 0; --i) {
            CSSFontFace* candidate = familyFontFaces->at(i).get();
            unsigned candidateTraitsMask = candidate->traitsMask();
            if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
                continue;
            if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
                continue;
#if ENABLE(SVG_FONTS)
            // For SVG Fonts that specify that they only support the "normal" variant, we will assume they are incapable
            // of small-caps synthesis and just ignore the font face as a candidate.
            if (candidate->hasSVGFontFaceSource() && (traitsMask & FontVariantSmallCapsMask) && !(candidateTraitsMask & FontVariantSmallCapsMask))
                continue;
#endif
            candidateFontFaces.append(candidate);
        }

        if (Vector<RefPtr<CSSFontFace> >* familyLocallyInstalledFontFaces = m_locallyInstalledFontFaces.get(family)) {
            unsigned numLocallyInstalledFontFaces = familyLocallyInstalledFontFaces->size();
            for (unsigned i = 0; i < numLocallyInstalledFontFaces; ++i) {
                CSSFontFace* candidate = familyLocallyInstalledFontFaces->at(i).get();
                unsigned candidateTraitsMask = candidate->traitsMask();
                if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
                    continue;
                if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
                    continue;
                candidateFontFaces.append(candidate);
            }
        }

        desiredTraitsMaskForComparison = traitsMask;
        stable_sort(candidateFontFaces.begin(), candidateFontFaces.end(), compareFontFaces);
        unsigned numCandidates = candidateFontFaces.size();
        for (unsigned i = 0; i < numCandidates; ++i)
            face->appendFontFace(candidateFontFaces[i]);
    }

    // We have a face.  Ask it for a font data.  If it cannot produce one, it will fail, and the OS will take over.
    return face->getFontData(fontDescription);
}
Beispiel #28
0
void valusorts(sfvector & sfv) {
  stable_sort(sfv.begin(), sfv.end(), valult<float>);
}
Beispiel #29
0
Datei: host.c Projekt: Red54/axtu
struct address_list *
lookup_host (const char *host, int flags)
{
  struct address_list *al;
  int silent = flags & LH_SILENT;
  int use_cache;
  int numeric_address = 0;
  double timeout = opt.dns_timeout;

#ifndef ENABLE_IPV6
  /* If we're not using getaddrinfo, first check if HOST specifies a
     numeric IPv4 address.  Some implementations of gethostbyname
     (e.g. the Ultrix one and possibly Winsock) don't accept
     dotted-decimal IPv4 addresses.  */
  {
    uint32_t addr_ipv4 = (uint32_t)inet_addr (host);
    if (addr_ipv4 != (uint32_t) -1)
      {
	/* No need to cache host->addr relation, just return the
	   address.  */
	char *vec[2];
	vec[0] = (char *)&addr_ipv4;
	vec[1] = NULL;
	return address_list_from_ipv4_addresses (vec);
      }
  }
#else  /* ENABLE_IPV6 */
  /* If we're using getaddrinfo, at least check whether the address is
     already numeric, in which case there is no need to print the
     "Resolving..." output.  (This comes at no additional cost since
     the is_valid_ipv*_address are already required for
     url_parse.)  */
  {
    const char *end = host + strlen (host);
    if (is_valid_ipv4_address (host, end) || is_valid_ipv6_address (host, end))
      numeric_address = 1;
  }
#endif

  /* Cache is normally on, but can be turned off with --no-dns-cache.
     Don't cache passive lookups under IPv6.  */
  use_cache = opt.dns_cache;
#ifdef ENABLE_IPV6
  if ((flags & LH_BIND) || numeric_address)
    use_cache = 0;
#endif

  /* Try to find the host in the cache so we don't need to talk to the
     resolver.  If LH_REFRESH is requested, remove HOST from the cache
     instead.  */
  if (use_cache)
    {
      if (!(flags & LH_REFRESH))
	{
	  al = cache_query (host);
	  if (al)
	    return al;
	}
      else
	cache_remove (host);
    }

  /* No luck with the cache; resolve HOST. */

  if (!silent && !numeric_address)
    logprintf (LOG_VERBOSE, _("Resolving %s... "), escnonprint (host));

#ifdef ENABLE_IPV6
  {
    int err;
    struct addrinfo hints, *res;

    xzero (hints);
    hints.ai_socktype = SOCK_STREAM;
    if (opt.ipv4_only)
      hints.ai_family = AF_INET;
    else if (opt.ipv6_only)
      hints.ai_family = AF_INET6;
    else
      /* We tried using AI_ADDRCONFIG, but removed it because: it
	 misinterprets IPv6 loopbacks, it is broken on AIX 5.1, and
	 it's unneeded since we sort the addresses anyway.  */
	hints.ai_family = AF_UNSPEC;

    if (flags & LH_BIND)
      hints.ai_flags |= AI_PASSIVE;

#ifdef AI_NUMERICHOST
    if (numeric_address)
      {
	/* Where available, the AI_NUMERICHOST hint can prevent costly
	   access to DNS servers.  */
	hints.ai_flags |= AI_NUMERICHOST;
	timeout = 0;		/* no timeout needed when "resolving"
				   numeric hosts -- avoid setting up
				   signal handlers and such. */
      }
#endif

    err = getaddrinfo_with_timeout (host, NULL, &hints, &res, timeout);
    if (err != 0 || res == NULL)
      {
	if (!silent)
	  logprintf (LOG_VERBOSE, _("failed: %s.\n"),
		     err != EAI_SYSTEM ? gai_strerror (err) : strerror (errno));
	return NULL;
      }
    al = address_list_from_addrinfo (res);
    freeaddrinfo (res);
    if (!al)
      {
	logprintf (LOG_VERBOSE,
		   _("failed: No IPv4/IPv6 addresses for host.\n"));
	return NULL;
      }

    /* Reorder addresses so that IPv4 ones (or IPv6 ones, as per
       --prefer-family) come first.  Sorting is stable so the order of
       the addresses with the same family is undisturbed.  */
    if (al->count > 1 && opt.prefer_family != prefer_none)
      stable_sort (al->addresses, al->count, sizeof (ip_address),
		   opt.prefer_family == prefer_ipv4
		   ? cmp_prefer_ipv4 : cmp_prefer_ipv6);
  }
#else  /* not ENABLE_IPV6 */
  {
    struct hostent *hptr = gethostbyname_with_timeout (host, timeout);
    if (!hptr)
      {
	if (!silent)
	  {
	    if (errno != ETIMEDOUT)
	      logprintf (LOG_VERBOSE, _("failed: %s.\n"),
			 host_errstr (h_errno));
	    else
	      logputs (LOG_VERBOSE, _("failed: timed out.\n"));
	  }
	return NULL;
      }
    /* Do older systems have h_addr_list?  */
    al = address_list_from_ipv4_addresses (hptr->h_addr_list);
  }
#endif /* not ENABLE_IPV6 */

  /* Print the addresses determined by DNS lookup, but no more than
     three.  */
  if (!silent && !numeric_address)
    {
      int i;
      int printmax = al->count <= 3 ? al->count : 3;
      for (i = 0; i < printmax; i++)
	{
	  logprintf (LOG_VERBOSE, "%s",
		     pretty_print_address (al->addresses + i));
	  if (i < printmax - 1)
	    logputs (LOG_VERBOSE, ", ");
	}
      if (printmax != al->count)
	logputs (LOG_VERBOSE, ", ...");
      logputs (LOG_VERBOSE, "\n");
    }

  /* Cache the lookup information. */
  if (use_cache)
    cache_store (host, al);

  return al;
}
Beispiel #30
0
void indxsorts(sfvector::iterator p1, sfvector::iterator p2) {
  stable_sort(p1, p2, indxlt<float>);
}