Example #1
0
void Viewer::on_bt_intrinsic()
{


	tvStatus->get_buffer()->set_text("Getting intrinsics ...");

	Size boardSize, imageSize;
	Mat cameraMatrix, distCoeffs;
	vector<vector<Point2f> > imagePoints;


	// TODO: get this data from user by GUI
	boardSize.width = 9;
	boardSize.height= 6;

	//flag
	int flag = 0;
	flag |= CV_CALIB_FIX_PRINCIPAL_POINT;
	flag |= CV_CALIB_ZERO_TANGENT_DIST;
	flag |= CV_CALIB_FIX_ASPECT_RATIO;


	if ( !boost::filesystem::exists(pathImage))
	{
		std::cerr << "[E] Images calibration directory doesn't exist: " << pathImage << std::endl;
		return;
	}

	// List of images
	boost::filesystem::directory_iterator end_itr;
	for ( boost::filesystem::directory_iterator itr( pathImage ); itr != end_itr; ++itr )
	{

		if ( itr->path().generic_string().find("jpg") == std::string::npos )
			continue;

		std::cout << itr->path().generic_string() << std::endl;
		Mat view;
		view = imread(itr->path().c_str(), CV_LOAD_IMAGE_COLOR);

		imageSize = view.size();

		vector<Point2f> pointBuf;
		bool found = findChessboardCorners( view, boardSize, pointBuf,
				CV_CALIB_CB_ADAPTIVE_THRESH |
				CV_CALIB_CB_FAST_CHECK |
				CV_CALIB_CB_NORMALIZE_IMAGE);

		if (found)
		{

			Mat viewGray;
			cvtColor(view, viewGray, CV_BGR2GRAY);
			cornerSubPix( viewGray, pointBuf, Size(11,11),
					Size(-1,-1), TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 30, 0.1 ));

			imagePoints.push_back(pointBuf);

			// Draw the corners.
			drawChessboardCorners( view, boardSize, Mat(pointBuf), found );
			//imshow("Image View", view);

		}
	}


	mCalibration->runCalibrationAndSave(boardSize, 20.0, flag, imageSize,
			cameraMatrix, distCoeffs, imagePoints);

	std::cout << std::endl << cameraMatrix << std::endl;

	std::stringstream matrixStr;

	matrixStr << "Intrinsic Matrix" << std::endl;
	matrixStr << "================" << std::endl << std::endl;

	for (int i=0; i<cameraMatrix.cols ; i++)
	{
		for (int j=0; j<cameraMatrix.rows; j++)
		{
			matrixStr << cameraMatrix.at<double>(i,j) << "\t\t";
			if (i==2 && j==0)
				matrixStr << "\t";
		}
		matrixStr<<std::endl;

		tvStatus->get_buffer()->set_text(matrixStr.str().c_str());
	}


}
Example #2
0
void ADFun<Base,RecBase>::ForSparseHesCase(
    bool              set_type         ,
    const SetVector&  r                ,
    const SetVector&  s                ,
    SetVector&        h                )
{
    // used to identify the RecBase type in calls to sweeps
    RecBase not_used_rec_base;
    //
    size_t n = Domain();
    size_t m = Range();
    //
    // check Vector is Simple SetVector class with bool elements
    CheckSimpleVector<bool, SetVector>();
    //
    CPPAD_ASSERT_KNOWN(
        size_t(r.size()) == n,
        "ForSparseHes: size of r is not equal to\n"
        "domain dimension for ADFun object."
    );
    CPPAD_ASSERT_KNOWN(
        size_t(s.size()) == m,
        "ForSparseHes: size of s is not equal to\n"
        "range dimension for ADFun object."
    );
    //
    // sparsity pattern corresponding to r
    local::sparse_pack for_jac_pattern;
    for_jac_pattern.resize(num_var_tape_, n + 1);
    for(size_t i = 0; i < n; i++)
    {   CPPAD_ASSERT_UNKNOWN( ind_taddr_[i] < n + 1 );
        // ind_taddr_[i] is operator taddr for i-th independent variable
        CPPAD_ASSERT_UNKNOWN( play_.GetOp( ind_taddr_[i] ) == local::InvOp );
        //
        // Use add_element when only adding one element per set is added.
        if( r[i] )
            for_jac_pattern.add_element( ind_taddr_[i], ind_taddr_[i] );
    }
    // compute forward Jacobiain sparsity pattern
    bool dependency = false;
    local::sweep::for_jac<addr_t>(
        &play_,
        dependency,
        n,
        num_var_tape_,
        for_jac_pattern,
        not_used_rec_base

    );
    // sparsity pattern correspnding to s
    local::sparse_pack rev_jac_pattern;
    rev_jac_pattern.resize(num_var_tape_, 1);
    for(size_t i = 0; i < m; i++)
    {   CPPAD_ASSERT_UNKNOWN( dep_taddr_[i] < num_var_tape_ );
        //
        // Use add_element when only adding one element per set is added.
        if( s[i] )
            rev_jac_pattern.add_element( dep_taddr_[i], 0);
    }
    // compute reverse sparsity pattern for dependency analysis
    // (note that we are only want non-zero derivatives not true dependency)
    local::sweep::rev_jac<addr_t>(
        &play_,
        dependency,
        n,
        num_var_tape_,
        rev_jac_pattern,
        not_used_rec_base

    );
    // vector of sets that will hold the forward Hessain values
    local::sparse_pack for_hes_pattern;
    for_hes_pattern.resize(n+1, n+1);
    //
    // compute the Hessian sparsity patterns
    local::sweep::for_hes<addr_t>(
        &play_,
        n,
        num_var_tape_,
        for_jac_pattern,
        rev_jac_pattern,
        for_hes_pattern,
        not_used_rec_base

    );
    // initialize return values corresponding to independent variables
    h.resize(n * n);
    for(size_t i = 0; i < n; i++)
    {   for(size_t j = 0; j < n; j++)
            h[ i * n + j ] = false;
    }
    // copy to result pattern
    CPPAD_ASSERT_UNKNOWN( for_hes_pattern.end() == n+1 );
    for(size_t i = 0; i < n; i++)
    {   // ind_taddr_[i] is operator taddr for i-th independent variable
        CPPAD_ASSERT_UNKNOWN( ind_taddr_[i] == i + 1 );
        CPPAD_ASSERT_UNKNOWN( play_.GetOp( ind_taddr_[i] ) == local::InvOp );

        // extract the result from for_hes_pattern
        local::sparse_pack::const_iterator itr(for_hes_pattern, ind_taddr_[i] );
        size_t j = *itr;
        while( j < for_hes_pattern.end() )
        {   CPPAD_ASSERT_UNKNOWN( 0 < j )
            h[ i * n + (j-1) ] = true;
            j = *(++itr);
        }
    }
}
Example #3
0
void diff_set(s,t)
{register int i,v ;
  itr(t,i,v,del_set(s,v));
}
Example #4
0
void SettingsDialog::outputSettings() {
    QSettings settings;

    QListIterator<QString> itr(settings.allKeys());
    QString output;

    output += "QOwnNotes Debug Information\n";
    output += "===========================\n";

    QDateTime dateTime = QDateTime::currentDateTime();

    // add information about QOwnNotes
    output += "\n## General Info\n\n";
    output += prepareDebugInformationLine("Current Date", dateTime.toString());
    output += prepareDebugInformationLine("Version", QString(VERSION));
    output += prepareDebugInformationLine("Build date", QString(__DATE__));
    output += prepareDebugInformationLine("Build number",
                                          QString::number(BUILD));
    output += prepareDebugInformationLine("Platform", QString(PLATFORM));

#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
    output += prepareDebugInformationLine("Operating System",
                                          QSysInfo::prettyProductName());
    output += prepareDebugInformationLine("Build architecture",
                                          QSysInfo::buildCpuArchitecture());
    output += prepareDebugInformationLine("Current architecture",
                                          QSysInfo::currentCpuArchitecture());
#endif
    output += prepareDebugInformationLine("Release", QString(RELEASE));
    output += prepareDebugInformationLine("Qt Version", QT_VERSION_STR);

    // add information about the server
    output += "\n## Server Info\n\n";
    output += prepareDebugInformationLine("serverUrl",
                                          ui->serverUrlEdit->text());
    output += prepareDebugInformationLine("appIsValid",
                                          QString(appIsValid ? "yes" : "no"));
    if (appIsValid) {
        output += prepareDebugInformationLine("serverVersion", serverVersion);
        output += prepareDebugInformationLine("appVersion", appVersion);
    } else {
        output += prepareDebugInformationLine("connectionErrorMessage",
                                              connectionErrorMessage);
    }

    // add information about the settings
    output += "\n## Settings\n\n";

    // hide values of these keys
    QStringList keyHiddenList = (QStringList() <<
            "cryptoKey" <<
            "ownCloud/password" <<
            "GAnalytics-cid");

    while (itr.hasNext()) {
        QString key = itr.next();
        QVariant value = settings.value(key);

        // hide values of certain keys
        if (keyHiddenList.contains(key)) {
            output += prepareDebugInformationLine(key, "<hidden>");
        } else {
            switch (value.type()) {
                case QVariant::StringList:
                    output += prepareDebugInformationLine(
                            key,
                            value.toStringList().join(", "));
                    break;
                case QVariant::ByteArray:
                    output += prepareDebugInformationLine(key, "<binary data>");
                    break;
                default:
                    output += prepareDebugInformationLine(key,
                                                          value.toString());
            }
        }
    }

    ui->debugInfoTextEdit->setPlainText(output);
}
Example #5
0
	//! Generate code for an event-actions set
	void Compiler::CodeGenerator::visit(const EventActionsSet& eventActionsSet, bool debugLog)
	{
		// action and event name
		const QString& eventName(eventActionsSet.getEventBlock()->getName());
		QString lookupEventName;
		if (eventName == "proxground")
			lookupEventName = "prox";
		else
			lookupEventName = eventName;
		
		// the first mode of the acc event is just a tap
		if ((eventName == "acc") && (eventActionsSet.getEventBlock()->getValue(0) == AccEventBlock::MODE_TAP))
			lookupEventName = "tap";
		
		// lookup corresponding block
		int block = eventToCodePosMap[lookupEventName].first;
		int size = eventToCodePosMap[lookupEventName].second;
		unsigned currentBlock(0);
		
		// if block does not exist, create it for the corresponding event and set the usage flag
		if (block < 0)
		{
			block = generatedCode.size();
			
			if (lookupEventName == "button")
			{
				generatedCode.push_back(L"\nonevent buttons\n");
				size++;
			}
			else if (lookupEventName == "prox")
			{
				generatedCode.push_back(L"\nonevent prox\n");
				size++;
			}
			else if (lookupEventName == "tap")
			{
				generatedCode.push_back(L"\nonevent tap\n");
				size++;
			}
			else if (lookupEventName == "acc")
			{
				useAccAngle = true;
				generatedCode.push_back(L"\nonevent acc\n");
				size++;
			}
			else if (lookupEventName == "clap")
			{
				useMicrophone = true;
				generatedCode.push_back(L"\nonevent mic\n");
				size++;
			}
			else if (lookupEventName == "timeout")
			{
				useTimer = true;
				generatedCode.push_back(
					L"\nonevent timer0"
					L"\n\ttimer.period[0] = 0\n"
				);
				size++;
			}
			else
			{
				// internal compiler error, invalid event found
				abort();
			}
			
			// FIXME: do this in a second pass, once we have written all the code for this event, and only if the state is actually assigned
			// if in advanced mode, copy setting of state
			if (eventActionsSet.isAdvanced())
			{
				generatedCode.push_back(
					L"\n\tcall math.copy(state, new_state)"
					L"\n\tcallsub display_state\n"
				);
				eventToCodePosMap[lookupEventName] = qMakePair(block, size+1);
			}
			else
				eventToCodePosMap[lookupEventName] = qMakePair(block, size);

			// prepare to add the new code block
			currentBlock = block + size;
		}
		else
		{
			// get current block, insert and update map
			currentBlock = (eventActionsSet.isAdvanced() ? block + size : block + size + 1);
			eventToCodePosMap[lookupEventName].second++;
			for (EventToCodePosMap::iterator itr(eventToCodePosMap.begin()); itr != eventToCodePosMap.end(); ++itr)
				if (itr->first > block)
					itr->first++;
			
			// if non-conditional code
			if (!eventActionsSet.isAnyAdvancedFeature() && !eventActionsSet.getEventBlock()->isAnyValueSet())
			{
				// find where "if" block starts for the current event
				for (unsigned int i=0; i<setToCodeIdMap.size(); i++)
					if (setToCodeIdMap[i] >= block && setToCodeIdMap[i] < (int)currentBlock &&
						generatedCode[setToCodeIdMap[i]].find(L"if ") != wstring::npos)
						currentBlock = setToCodeIdMap[i];
			}
			
			// make "space" for this block
			for (unsigned int i=0; i<setToCodeIdMap.size(); i++)
				if(setToCodeIdMap[i] >= (int)currentBlock)
					setToCodeIdMap[i]++;
		}
		
		// add the code block
		Q_ASSERT(currentBlock <= generatedCode.size());
		generatedCode.insert(generatedCode.begin() + currentBlock, L"");
		setToCodeIdMap.push_back(currentBlock);
		
		// add event and actions details
		visitEventAndStateFilter(eventActionsSet.getEventBlock(), eventActionsSet.getStateFilterBlock(), currentBlock);
		for (int i=0; i<eventActionsSet.actionBlocksCount(); ++i)
			visitAction(eventActionsSet.getActionBlock(i), currentBlock);
		
		// possibly add the debug event
		if (debugLog)
			visitDebugLog(eventActionsSet, currentBlock);
		
		// possibly close condition and add code
		visitEndOfLine(currentBlock);
	}
Example #6
0
	/*! Find an xml entity by tag in the supplied map.
	  \param tag the tag to find
	  \param from the map to search
	  \return the found entity or 0 if not found */
	const XmlElement *find_element(const std::string& tag, const ConfigMap& from) const
		{ ConfigMap::const_iterator itr(from.find(tag)); return itr != from.end() ? itr->second : 0; }
Example #7
0
ofstream & operator << (ofstream & ofs, const basic_string<T>& s) {
  ostreambuf_iterator<T> itr (ofs);
  copy(s.begin(), s.end(), itr);
  return ofs;
}
Example #8
0
CRef<CSeq_loc>
CBlastFastaInputSource::x_FastaToSeqLoc(CRef<objects::CSeq_loc>& lcase_mask,
                                        CScope& scope)
{
    static const TSeqRange kEmptyRange(TSeqRange::GetEmpty());
    CRef<CBlastScopeSource> query_scope_source;

    if (m_Config.GetLowercaseMask())
        lcase_mask = m_InputReader->SaveMask();

    CRef<CSeq_entry> seq_entry(m_InputReader->ReadOneSeq());
    if (lcase_mask) {
        if (lcase_mask->Which() != CSeq_loc::e_not_set) {
            lcase_mask->SetStrand(eNa_strand_plus);
        }
        _ASSERT(lcase_mask->GetStrand() == eNa_strand_plus ||
                lcase_mask->GetStrand() == eNa_strand_unknown);
    }
    _ASSERT(seq_entry.NotEmpty());
    scope.AddTopLevelSeqEntry(*seq_entry);

    CTypeConstIterator<CBioseq> itr(ConstBegin(*seq_entry));

    CRef<CSeq_loc> retval(new CSeq_loc());

    if ( !blast::HasRawSequenceData(*itr) ) {
        CBlastInputReader* blast_reader = 
            dynamic_cast<CBlastInputReader*>(m_InputReader.get());
        _ASSERT(blast_reader);
        CRef<CBlastScopeSource> query_scope_source =
            blast_reader->GetQueryScopeSource();
        query_scope_source->AddDataLoaders(CRef<CScope>(&scope));
    }

    if (m_ReadProteins && itr->IsNa()) {
        NCBI_THROW(CInputException, eSequenceMismatch,
                   "Nucleotide FASTA provided for protein sequence");
    } else if ( !m_ReadProteins && itr->IsAa() ) {
        NCBI_THROW(CInputException, eSequenceMismatch,
                   "Protein FASTA provided for nucleotide sequence");
    }

    // set strand
    if (m_Config.GetStrand() == eNa_strand_other ||
        m_Config.GetStrand() == eNa_strand_unknown) {
        if (m_ReadProteins)
            retval->SetInt().SetStrand(eNa_strand_unknown);
        else
            retval->SetInt().SetStrand(eNa_strand_both);
    } else {
        if (m_ReadProteins) {
            NCBI_THROW(CInputException, eInvalidStrand,
                       "Cannot assign nucleotide strand to protein sequence");
        }
        retval->SetInt().SetStrand(m_Config.GetStrand());
    }

    // sanity checks for the range
    const TSeqPos from = m_Config.GetRange().GetFrom() == kEmptyRange.GetFrom()
        ? 0 : m_Config.GetRange().GetFrom();
    const TSeqPos to = m_Config.GetRange().GetTo() == kEmptyRange.GetTo()
        ? 0 : m_Config.GetRange().GetTo();

    // Get the sequence length
    const TSeqPos seqlen = seq_entry->GetSeq().GetInst().GetLength();
    //if (seqlen == 0) {
    //    NCBI_THROW(CInputException, eEmptyUserInput,
    //               "Query contains no sequence data");
    //}
    _ASSERT(seqlen != numeric_limits<TSeqPos>::max());
    if (to > 0 && to < from) {
        NCBI_THROW(CInputException, eInvalidRange, 
                   "Invalid sequence range");
    }
    if (from > seqlen) {
        NCBI_THROW(CInputException, eInvalidRange, 
                   "Invalid from coordinate (greater than sequence length)");
    }
    // N.B.: if the to coordinate is greater than or equal to the sequence
    // length, we fix that silently


    // set sequence range
    retval->SetInt().SetFrom(from);
    retval->SetInt().SetTo((to > 0 && to < seqlen) ? to : (seqlen-1));

    // set ID
    retval->SetInt().SetId().Assign(*FindBestChoice(itr->GetId(), CSeq_id::BestRank));

    return retval;
}
void PatternScanner::shutdown(const scanner_params&) {
  for (vector<const Handler*>::iterator itr(Handlers.begin()); itr != Handlers.end(); ++itr) {
    delete *itr;
  }
}
Example #10
0
  path& path::m_normalize()
  {
    if (m_pathname.empty()) return *this;
      
    path temp;
    iterator start(begin());
    iterator last(end());
    iterator stop(last--);
    for (iterator itr(start); itr != stop; ++itr)
    {
      // ignore "." except at start and last
      if (itr->native().size() == 1
        && (itr->native())[0] == dot
        && itr != start
        && itr != last) continue;

      // ignore a name and following ".."
      if (!temp.empty()
        && itr->native().size() == 2
        && (itr->native())[0] == dot
        && (itr->native())[1] == dot) // dot dot
      {
        string_type lf(temp.filename().native());  
        if (lf.size() > 0  
          && (lf.size() != 1
            || (lf[0] != dot
              && lf[0] != separator))
          && (lf.size() != 2 
            || (lf[0] != dot
              && lf[1] != dot
#             ifdef BOOST_WINDOWS_API
              && lf[1] != colon
#             endif
               )
             )
          )
        {
          temp.remove_filename();
          // if not root directory, must also remove "/" if any
          if (temp.m_pathname.size() > 0
            && temp.m_pathname[temp.m_pathname.size()-1]
              == separator)
          {
            string_type::size_type rds(
              root_directory_start(temp.m_pathname, temp.m_pathname.size()));
            if (rds == string_type::npos
              || rds != temp.m_pathname.size()-1) 
              { temp.m_pathname.erase(temp.m_pathname.size()-1); }
          }

          iterator next(itr);
          if (temp.empty() && ++next != stop
            && next == last && *last == dot_path) temp /= dot_path;
          continue;
        }
      }

      temp /= *itr;
    };

    if (temp.empty()) temp /= dot_path;
    m_pathname = temp.m_pathname;
    return *this;
  }
Example #11
0
         void rotate_files( bool initializing = false )
         {
             FC_ASSERT( cfg.rotate );
             fc::time_point now = time_point::now();
             fc::time_point_sec start_time = get_file_start_time( now, cfg.rotation_interval );
             string timestamp_string = start_time.to_non_delimited_iso_string();
             fc::path link_filename = cfg.filename;
             fc::path log_filename = link_filename.parent_path() / (link_filename.filename().string() + "." + timestamp_string);

             {
               fc::scoped_lock<boost::mutex> lock( slock );

               if( !initializing )
               {
                   if( start_time <= _current_file_start_time )
                   {
                       _rotation_task = schedule( [this]() { rotate_files(); },
                                                  _current_file_start_time + cfg.rotation_interval.to_seconds(),
                                                  "rotate_files(2)" );
                       return;
                   }

                   out.flush();
                   out.close();
               }
               remove_all(link_filename);  // on windows, you can't delete the link while the underlying file is opened for writing
               if( fc::exists( log_filename ) )
                  out.open( log_filename, std::ios_base::out | std::ios_base::app );
               else
                  out.open( log_filename, std::ios_base::out | std::ios_base::app);

               create_hard_link(log_filename, link_filename);
             }

             /* Delete old log files */
             fc::time_point limit_time = now - cfg.rotation_limit;
             string link_filename_string = link_filename.filename().string();
             directory_iterator itr(link_filename.parent_path());
             for( ; itr != directory_iterator(); itr++ )
             {
                 try
                 {
                     string current_filename = itr->filename().string();
                     if (current_filename.compare(0, link_filename_string.size(), link_filename_string) != 0 ||
                         current_filename.size() <= link_filename_string.size() + 1)
                       continue;
                     string current_timestamp_str = current_filename.substr(link_filename_string.size() + 1,
                                                                            timestamp_string.size());
                     fc::time_point_sec current_timestamp = fc::time_point_sec::from_iso_string( current_timestamp_str );
                     if( current_timestamp < start_time )
                     {
                         if( current_timestamp < limit_time || file_size( current_filename ) <= 0 )
                         {
                             remove_all( *itr );
                             continue;
                         }
                     }
                 }
                 catch (const fc::canceled_exception&)
                 {
                     throw;
                 }
                 catch( ... )
                 {
                 }
             }

             _current_file_start_time = start_time;
             _rotation_task = schedule( [this]() { rotate_files(); },
                                        _current_file_start_time + cfg.rotation_interval.to_seconds(),
                                        "rotate_files(3)" );
         }
Example #12
0
void
TransferQueueManager::notifyAboutTransfersTakingTooLong()
{
	SimpleListIterator<TransferQueueRequest *> itr(m_xfer_queue);
	TransferQueueRequest *client = NULL;

	FILE *email = NULL;

	while( itr.Next(client) ) {
		if( client->m_gave_go_ahead && !client->m_notified_about_taking_too_long ) {
			int age = time(NULL) - client->m_time_go_ahead;
			int max_queue_age = client->m_max_queue_age;
			if( max_queue_age > 0 && max_queue_age < age ) {
				client->m_notified_about_taking_too_long = true;
				if( !email ) {
					email = email_admin_open("file transfer took too long");
					if( !email ) {
							// Error sending the message
						dprintf( D_ALWAYS, 
								 "ERROR: Can't send email to the Condor "
								 "Administrator\n" );
						return;
					}
					fprintf( email,
							 "Below is a list of file transfers that took longer than\n"
							 "MAX_TRANSFER_QUEUE_AGE=%ds.  When other transfers are waiting\n"
							 "to start, these old transfer attempts will be aborted.\n"
							 "To avoid this timeout, MAX_TRANSFER_QUEUE_AGE may be increased,\n"
							 "but be aware that transfers which take a long time will delay other\n"
							 "transfers from starting if the maximum number of concurrent transfers\n"
							 "is exceeded.  Therefore, it is advisable to also review the settings\n"
							 "of MAX_CONCURRENT_UPLOADS, MAX_CONCURRENT_DOWNLOADS, and/or\n"
							 "FILE_TRANSFER_DISK_LOAD_THROTTLE.\n\n"
							 "The transfer queue currently has %d/%d uploads,\n"
							 "%d/%d downloads, %d transfers waiting %ds to upload,\n"
							 "and %d transfers waiting %ds to download.\n",
							 max_queue_age,
							 m_uploading,
							 m_max_uploads,
							 m_downloading,
							 m_max_downloads,
							 m_waiting_to_upload,
							 m_upload_wait_time,
							 m_waiting_to_download,
							 m_download_wait_time);

					char const *ema_horizon = m_iostats.bytes_sent.ShortestHorizonEMAName();
					if( ema_horizon ) {
						fprintf(email,
								"Upload %s I/O load: %.0f bytes/s  %.3f disk load  %.3f net load\n",
								ema_horizon,
								m_iostats.bytes_sent.EMAValue(ema_horizon),
								m_iostats.file_read.EMAValue(ema_horizon),
								m_iostats.net_write.EMAValue(ema_horizon));

						fprintf(email,
								"Download %s I/O load: %.0f bytes/s  %.3f disk load  %.3f net load\n",
								ema_horizon,
								m_iostats.bytes_received.EMAValue(ema_horizon),
								m_iostats.file_write.EMAValue(ema_horizon),
								m_iostats.net_read.EMAValue(ema_horizon));
					}
					fprintf(email,"\n\nTransfers older than MAX_TRANSFER_QUEUE_AGE=%ds:\n\n",max_queue_age);
				}

				fprintf( email, "%s\n", client->SinlessDescription() );
			}
		}
	}
	if( email ) {
		email_close ( email );
	}
}
Example #13
0
void
ReliableSession::send_naks()
{
  // Could get data samples before syn control message.
  // No use nak'ing until syn control message is received and session is acked.
  if (!this->acked()) return;

  if (DCPS_debug_level > 5) {
    ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) ReliableSession::send_naks local %d ")
                         ACE_TEXT("remote %d nak request size %d \n"),
      this->link_->local_peer(), this->remote_peer_, this->nak_requests_.size()));
  }

  if (!this->nak_sequence_.disjoint()) return;  // nothing to send

  ACE_Time_Value now(ACE_OS::gettimeofday());

  // Record high-water mark for this interval; this value will
  // be used to reset the low-water mark in the event the remote
  // peer becomes unresponsive:
  this->nak_requests_[now] = this->nak_sequence_.high();

  typedef std::vector<SequenceRange> RangeVector;
  RangeVector ignored;

  /// The range first - second will be skiped (no naks sent for it).
  SequenceNumber first;
  SequenceNumber second;

  NakRequestMap::reverse_iterator itr(this->nak_requests_.rbegin());

  if (this->nak_requests_.size() > 1) {
    // The sequences between rbegin - 1 and rbegin will not be ignored for naking.
    ++itr;

    size_t nak_delay_intervals = this->link()->config()->nak_delay_intervals_;
    size_t nak_max = this->link()->config()->nak_max_;
    size_t sz = this->nak_requests_.size();

    // Image i is the index of element in nak_requests_ in reverse order.
    // index 0 sequence is most recent high water mark.
    // e.g index , 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
    //  0 (rbegin) is always skipped because missing sample between 1 and 0 interval
    //  should always be naked.,
    //  if nak_delay_intervals=4, nak_max=3, any sequence between 5 - 1, 10 - 6, 15 - 11
    //  are skipped for naking due to nak_delay_intervals and 20 - 16 are skipped for
    //  naking due to nak_max.
    for (size_t i = 1; i < sz; ++i) {
      if ((i * 1.0) / (nak_delay_intervals + 1) > nak_max) {
        if (first != SequenceNumber()) {
          first = this->nak_requests_.begin()->second;
        }
        else {
          ignored.push_back(std::make_pair(this->nak_requests_.begin()->second, itr->second));
        }
        break;
      }

      if (i % (nak_delay_intervals + 1) == 1) {
        second = itr->second;
      }
      if (second != SequenceNumber()) {
        first = itr->second;
      }

      if (i % (nak_delay_intervals + 1) == 0) {
        first = itr->second;

        if (first != SequenceNumber() && second != SequenceNumber()) {
          ignored.push_back(std::make_pair(first, second));
          first = SequenceNumber();
          second = SequenceNumber();
        }
      }

      ++itr;
    }

    if (first != SequenceNumber() && second != SequenceNumber() && first != second) {
      ignored.push_back(std::make_pair(first, second));
    }
  }

  // Take a copy to facilitate temporary suppression:
  DisjointSequence received(this->nak_sequence_);
  if (DCPS_debug_level > 0) {
    received.dump();
  }

  size_t sz = ignored.size();
  for (size_t i = 0; i < sz; ++i) {

    if (ignored[i].second > received.cumulative_ack()) {
      SequenceNumber high = ignored[i].second;
      SequenceNumber low = ignored[i].first;
      if (low < received.cumulative_ack()) {
        low = received.cumulative_ack();
      }

      if (DCPS_debug_level > 0) {
        ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) ReliableSession::send_naks local %d ")
          ACE_TEXT("remote %d ignore missing [%q - %q]\n"),
          this->link_->local_peer(), this->remote_peer_, low.getValue(), high.getValue()));
      }

      // Make contiguous between ignored sequences.
      received.insert(SequenceRange(low, high));
    }
  }

  for (NakPeerSet::iterator it(this->nak_peers_.begin());
       it != this->nak_peers_.end(); ++it) {
    // Update sequence to temporarily suppress repair requests for
    // ranges already requested by other peers for this interval:
    received.insert(*it);
  }

  if (received.disjoint()) {
    send_naks(received);
  }

  // Clear peer repair requests:
  this->nak_peers_.clear();
}
Example #14
0
int main(int argc, char** argv)
{
    /**********
    bfs::create_directory(input_dir / "prova");
    std::ofstream file(input_dir / "prova/testo.txt");
    file << "ciao!";
    file.close();
    if (!bfs::exists(input_dir / "prova/testo.txt"))
        std::cout << "Something went wrong." << std::endl;
    else std::cout << "apposto" << std::endl;
    **************/
    static const char *faceCascadeFilename = "/usr/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml";
    CvHaarClassifierCascade* faceCascade = (CvHaarClassifierCascade*)cvLoad(faceCascadeFilename, 0, 0, 0 );
     if( !faceCascade ) 
     {
       printf("Could not load Haar cascade Face detection classifier in '%s'.", faceCascadeFilename);
       exit(1);
     }   

    if (!bfs::exists(input_dir))
    { 
        std::cout << "Directory does not exist!" << std::endl;
        return -1; // check existence of input_dir
    }

    bfs::directory_iterator end_itr;
    //int pictures=0;
    std::vector<int> compression_params; //params for imwrite function
    compression_params.push_back(CV_IMWRITE_PXM_BINARY);
    compression_params.push_back(1);
    std::string filename;
    IplImage* img;
    //CvMat* mat;
    
    for (bfs::directory_iterator itr(input_dir); itr!=end_itr; itr++)
    {
        try
        { 
            filename = itr->path().string();
            img = cvLoadImage( filename.c_str(),1);
        }
        catch(int e)
        {
            std::cout << "An exception occured: exception n: " << e << std::endl;
        }
       CvRect rect = detectFaceInImage(img, faceCascade);
       std::cout << "3 cvrect ok" << std::endl;
       if (rect.x > 0 && rect.y > 0 && rect.height > 0 && rect.width > 0)
            img = crop(img,rect);
       
       //mat = cvCreateMat(img->height, img->width,CV_32FC3);
       //std::cout << "5 createMat ok" << std::endl;
       //cvConvert(img,mat);
       //std::cout << "6 convert ok" << std::endl;
       //cvNamedWindow( "check2", 1 );
       //cvShowImage( "check2", mat );
       //cv::waitKey(30);
       //std::string tmp;
       // std::cin>>tmp;
       if(cvSaveImage(filename.c_str(), img))
      // if (cv::imwrite(filename,(cv::InputArray)mat,compression_params))
           std::cout<<"image " << filename << " written" << std::endl;
       else
            std::cout<<"can't write image"<<std::endl;
      // std::cout << filename << std::endl;
        
    }
    

    
    return 0;
}
Example #15
0
int
putDirUtil( rcComm_t **myConn, char *srcDir, char *targColl,
            rodsEnv *myRodsEnv, rodsArguments_t *rodsArgs, dataObjInp_t *dataObjOprInp,
            bulkOprInp_t *bulkOprInp, rodsRestart_t *rodsRestart,
            bulkOprInfo_t *bulkOprInfo ) {
    char srcChildPath[MAX_NAME_LEN], targChildPath[MAX_NAME_LEN];

    if ( srcDir == NULL || targColl == NULL ) {
        rodsLog( LOG_ERROR,
                 "putDirUtil: NULL srcDir or targColl input" );
        return USER__NULL_INPUT_ERR;
    }

    if ( isPathSymlink( rodsArgs, srcDir ) > 0 ) {
        return 0;
    }

    if ( rodsArgs->recursive != True ) {
        rodsLog( LOG_ERROR,
                 "putDirUtil: -r option must be used for putting %s directory",
                 srcDir );
        return USER_INPUT_OPTION_ERR;
    }

    if ( rodsArgs->redirectConn == True && rodsArgs->force != True ) {
        int reconnFlag;
        if ( rodsArgs->reconnect == True ) {
            reconnFlag = RECONN_TIMEOUT;
        }
        else {
            reconnFlag = NO_RECONN;
        }
        /* reconnect to the resource server */
        rstrcpy( dataObjOprInp->objPath, targColl, MAX_NAME_LEN );
        redirectConnToRescSvr( myConn, dataObjOprInp, myRodsEnv, reconnFlag );
        rodsArgs->redirectConn = 0;    /* only do it once */
    }

    rcComm_t *conn = *myConn;
    boost::filesystem::path srcDirPath( srcDir );
    if ( !exists( srcDirPath ) || !is_directory( srcDirPath ) ) {
        rodsLog( LOG_ERROR,
                 "putDirUtil: opendir local dir error for %s, errno = %d\n",
                 srcDir, errno );
        return USER_INPUT_PATH_ERR;
    }

    if ( rodsArgs->verbose == True ) {
        fprintf( stdout, "C- %s:\n", targColl );
    }

    int bulkFlag = NON_BULK_OPR;
    if ( bulkOprInfo != NULL ) {
        bulkFlag = bulkOprInfo->flags;
    }

    int savedStatus = 0;
    boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
    for ( boost::filesystem::directory_iterator itr( srcDirPath ); itr != end_itr; ++itr ) {
        boost::filesystem::path p = itr->path();
        snprintf( srcChildPath, MAX_NAME_LEN, "%s",
                  p.c_str() );

        if ( isPathSymlink( rodsArgs, srcChildPath ) > 0 ) {
            continue;
        }
        if ( !exists( p ) ) {
            rodsLog( LOG_ERROR,
                     "putDirUtil: stat error for %s, errno = %d\n",
                     srcChildPath, errno );
            return USER_INPUT_PATH_ERR;
        }

        if ( is_symlink( p ) ) {
            boost::filesystem::path cp = read_symlink( p );
            snprintf( srcChildPath, MAX_NAME_LEN, "%s/%s",
                      srcDir, cp.c_str() );
            p = boost::filesystem::path( srcChildPath );
        }
        rodsLong_t dataSize = 0;
        dataObjOprInp->createMode = getPathStMode( p.c_str() );
        objType_t childObjType;
        if ( is_regular_file( p ) ) {
            childObjType = DATA_OBJ_T;
            dataSize = file_size( p );
        }
        else if ( is_directory( p ) ) {
            childObjType = COLL_OBJ_T;
        }
        else {
            rodsLog( LOG_ERROR,
                     "putDirUtil: unknown local path type for %s",
                     srcChildPath );
            savedStatus = USER_INPUT_PATH_ERR;
            continue;
        }
        boost::filesystem::path childPath = p.filename();
        snprintf( targChildPath, MAX_NAME_LEN, "%s/%s",
                  targColl, childPath.c_str() );
        if ( childObjType == DATA_OBJ_T ) {
            if ( bulkFlag == BULK_OPR_SMALL_FILES &&
                    file_size( p ) > MAX_BULK_OPR_FILE_SIZE ) {
                continue;
            }
            else if ( bulkFlag == BULK_OPR_LARGE_FILES &&
                      file_size( p ) <= MAX_BULK_OPR_FILE_SIZE ) {
                continue;
            }
        }

        int status = chkStateForResume( conn, rodsRestart, targChildPath,
                                        rodsArgs, childObjType, &dataObjOprInp->condInput, 1 );

        if ( status < 0 ) {
            /* restart failed */
            return status;
        }
        else if ( status == 0 ) {
            if ( bulkFlag == BULK_OPR_SMALL_FILES &&
                    ( rodsRestart->restartState & LAST_PATH_MATCHED ) != 0 ) {
                /* enable foreFlag one time */
                setForceFlagForRestart( bulkOprInp, bulkOprInfo );
            }
            continue;
        }

        if ( childObjType == DATA_OBJ_T ) {   /* a file */
            if ( bulkFlag == BULK_OPR_SMALL_FILES ) {
                status = bulkPutFileUtil( conn, srcChildPath, targChildPath,
                                          dataSize,  dataObjOprInp->createMode, rodsArgs,
                                          bulkOprInp, bulkOprInfo );
            }
            else {
                /* normal put */
                status = putFileUtil( conn, srcChildPath, targChildPath,
                                      dataSize, rodsArgs, dataObjOprInp );
            }
            if ( rodsRestart->fd > 0 ) {
                if ( status >= 0 ) {
                    if ( bulkFlag == BULK_OPR_SMALL_FILES ) {
                        if ( status > 0 ) {
                            /* status is the number of files bulk loaded */
                            rodsRestart->curCnt += status;
                            status = writeRestartFile( rodsRestart,
                                                       targChildPath );
                        }
                    }
                    else {
                        /* write the restart file */
                        rodsRestart->curCnt ++;
                        status = writeRestartFile( rodsRestart, targChildPath );
                    }
                }
            }
        }
        else {        /* a directory */
            status = mkColl( conn, targChildPath );
            if ( status < 0 ) {
                rodsLogError( LOG_ERROR, status,
                              "putDirUtil: mkColl error for %s", targChildPath );
            }
            status = putDirUtil( myConn, srcChildPath, targChildPath,
                                 myRodsEnv, rodsArgs, dataObjOprInp, bulkOprInp,
                                 rodsRestart, bulkOprInfo );

        }

        if ( status < 0 &&
                status != CAT_NO_ROWS_FOUND ) {
            rodsLogError( LOG_ERROR, status,
                          "putDirUtil: put %s failed. status = %d",
                          srcChildPath, status );
            savedStatus = status;
            if ( rodsRestart->fd > 0 ) {
                break;
            }
        }
    }
    return savedStatus;
}
bool LightgrepController::addUserPatterns(PatternScanner& scanner, CallbackFnType* callbackPtr, const FindOptsStruct& user) {
  unsigned int patBegin = lg_pattern_map_size(PatternInfo),
               patEnd = 0;

  LG_KeyOptions opts;
  opts.FixedString = 0;
  opts.CaseInsensitive = 0;

  LG_Error *err = 0;

  for (vector<string>::const_iterator itr(user.Files.begin()); itr != user.Files.end(); ++itr) {
    ifstream file(itr->c_str(), ios::in);
    if (!file.is_open()) {
      cerr << "Could not open pattern file '" << *itr << "'." << endl;
      return false;
    }
    string contents = string(istreambuf_iterator<char>(file), istreambuf_iterator<char>());

    const char* contentsCStr = contents.c_str();
    if (lg_add_pattern_list(Fsm, PatternInfo, contentsCStr, DefaultEncodingsCStrings, 2, &opts, &err) < 0) {

      vector<string> lines;
      istringstream input(contents);
      string line;
      while (input) {
        getline(input, line);
        lines.push_back(line);
      }
      LG_Error* cur(err);
      while (cur) {
        cerr << "Error in " << *itr << ", line " << cur->Index+1 << ", pattern '" << lines[cur->Index]
          << "': " << cur->Message << endl;
        cur = cur->Next;
      }
      lg_free_error(err);
      return false;
    }
  }
  for (vector<string>::const_iterator itr(user.Patterns.begin()); itr != user.Patterns.end(); ++itr) {
    bool good = false;
    if (lg_parse_pattern(ParsedPattern, itr->c_str(), &opts, &err)) {
      for (unsigned int i = 0; i < NumDefaultEncodings; ++i) {
        if (lg_add_pattern(Fsm, PatternInfo, ParsedPattern, DefaultEncodingsCStrings[i], &err) >= 0) {
          good = true;
        }
      }
    }
    if (!good) {
      cerr << "Error on '" << *itr << "': " << err->Message << endl;
      lg_free_error(err);
      return false;
    }
  }
  patEnd = lg_pattern_map_size(PatternInfo);
  for (unsigned int i = patBegin; i < patEnd; ++i) {
    lg_pattern_info(PatternInfo, i)->UserData = const_cast<void*>(static_cast<const void*>(callbackPtr));
  }
  scanner.patternRange() = make_pair(patBegin, patEnd);
  Scanners.push_back(&scanner);
  return true;
}
void
GContactClient::receiveItemProcessed (Sync::TransferType aModificationType,
                                      Sync::TransferDatabase transferDb,
                                      QString database,
                                      int aCommittedItems)
{

    FUNCTION_CALL_TRACE;

    LOG_DEBUG("Modification Type " << aModificationType);
    LOG_DEBUG("Committed items" << aCommittedItems);

    ++mCommittedItems;
    if(!receivedItems.contains(database))
    {
        ReceivedItemDetails details;
        details.added = details.modified = details.deleted = details.error = 0;
        //details.mime = aMimeType;
        receivedItems[database] = details;
    }

    switch (aModificationType) {
    case Sync::ITEM_ADDED: {
        ++receivedItems[database].added;
        break;
    }
    case Sync::ITEM_MODIFIED: {
        ++receivedItems[database].modified;
        break;
    }
    case Sync::ITEM_DELETED: {
        ++receivedItems[database].deleted;
        break;
    }
    case Sync::ITEM_ERROR: {
        ++receivedItems[database].error;
        break;
    }
    default: {
        Q_ASSERT(0);
        break;

    }
    }

    if( mCommittedItems == aCommittedItems )
    {
        QMapIterator<QString,ReceivedItemDetails> itr(receivedItems);
        while( itr.hasNext() )
        {
            itr.next();
            if( itr.value().added )
                emit transferProgress(getProfileName(), transferDb, Sync::ITEM_ADDED, itr.value().mime, itr.value().added);

            if( itr.value().modified )
                emit transferProgress(getProfileName(), transferDb, Sync::ITEM_MODIFIED, itr.value().mime, itr.value().modified);

            if( itr.value().deleted )
                emit transferProgress(getProfileName(), transferDb, Sync::ITEM_DELETED, itr.value().mime, itr.value().deleted);

            if( itr.value().error )
                emit transferProgress(getProfileName(), transferDb, Sync::ITEM_ERROR, itr.value().mime, itr.value().error);
        }
        mCommittedItems = 0;
        receivedItems.clear();
    }
}
Example #18
0
/**
 *  Imports the files in a directory and returns a directory object.
 */
cafs::directory cafs::import_directory( const fc::path& p ) {
   directory dir;

   fc::directory_iterator itr(p);
   fc::directory_iterator end;

   chunk_header            cur_chunk;
   fc::vector<char>        cur_chunk_data(MAX_CHUNK_SIZE);
   fc::datastream<char*>   cur_chunk_ds(cur_chunk_data.data(),cur_chunk_data.size());

   while( itr != end ) {
       fc::path    cur_path = *itr;
       slog( "%s", cur_path.generic_string().c_str() );
       fc::string  name = cur_path.filename().string();
       file_type   cur_file_type = unknown;

       fc::vector<char> cur_file;

       if( fc::is_directory( cur_path ) && name[0] != '.' ) {
           directory d = fc::async( [=]() { return import_directory( cur_path ); } );
           cur_file = fc::raw::pack( d );
           cur_file_type = directory_type;
       } else if( fc::is_regular_file( cur_path ) ) {
           if( fc::file_size(cur_path) > IMBED_THRESHOLD ) {
              cur_file = fc::raw::pack( import_file(cur_path) );
              cur_file_type = file_header_type;
           } else {
              cur_file.resize( fc::file_size(cur_path) ); 
              fc::ifstream inf( cur_path, fc::ifstream::binary );
              inf.read(cur_file.data(), cur_file.size() );
              cur_file_type = file_data_type;
           }
       }
       ++itr;

       fc::sha1 h = fc::sha1::hash(cur_file.data(),cur_file.size());
       fc::optional<file_ref> ofr = my->file_db.fetch(h);
       //slog( "                                               %s", fc::string(h).c_str() );
       if( ofr ) {
       //  wlog( "We already have a file ref for this..." );
         dir.entries.push_back( directory::entry(name) );
         dir.entries.back().ref = *ofr;
       }
      
       if( !ofr && !add_to_chunk( cur_chunk_ds, cur_file, name, dir, cur_file_type ) ) {
          // save cur chunk... 
        //  wlog( "                           save chunk size %llu", cur_chunk_ds.tellp() );
          cur_chunk_data.resize(cur_chunk_ds.tellp());
          save_chunk( *this, dir, cur_chunk_data );
          cur_chunk_data.resize(MAX_CHUNK_SIZE);
          cur_chunk_ds = fc::datastream<char*>(cur_chunk_data.data(),
                                               cur_chunk_data.size());
          add_to_chunk( cur_chunk_ds, cur_file, name, dir, cur_file_type );
       } 
       if( itr == end && cur_chunk_ds.tellp() > 0 ) {
        //  wlog( "                            save chunk size %llu", cur_chunk_ds.tellp() );
          cur_chunk_data.resize(cur_chunk_ds.tellp());
          save_chunk( *this, dir, cur_chunk_data );
       }
   }
   for( auto itr = dir.entries.begin(); itr != dir.entries.end(); ++itr ) {
     my->file_db.store( itr->ref );
   }
   return dir;
}
Example #19
0
int main(int argc, char** argv) {
  unsigned int uint_opt;
  double double_opt;
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help", "produce help message")
    ("img", po::value<std::string>(), "Label only this image")
    ("dir", po::value<std::string>(), "Label all images in directory")
    ("load", po::value<std::string>(), "clicks to load")
    ("save", po::value<std::string>(), "file to save the clicks in")

    ;
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc),vm);
  po::notify(vm);
  if (vm.count("help")) {
    std::cout <<desc<<"\n";
    return 1;
  }
  FILE* save_fp = NULL;
  if (vm.count("save")) {
    save_fp = fopen(vm["save"].as<std::string>().c_str(), "a");
    
  }
  std::vector< CvRect> pos;
  std::vector< CvRect> neg;
  cvNamedWindow("Input",1);
  cvSetMouseCallback("Input", on_mouse);
  if (vm.count("dir")) {
    std::string thepath = vm["dir"].as<std::string>();
    if (!boost::filesystem::is_directory(thepath))  {
      printf("Give me a better path, not %s\n",vm["dir"].as<std::string>().c_str());
      return 1;
    }
    unsigned int key = -1;
    for (boost::filesystem::directory_iterator itr(thepath);
	 itr != boost::filesystem::directory_iterator();
	 ++itr) {
      if (!boost::filesystem::is_regular_file(itr->status())){
	continue;
      }
      std::string full_name =  thepath + itr->path().filename();
      printf ("Loading %s\n",
	      full_name.c_str());
      IplImage* img_in = cvLoadImage(full_name.c_str());
      IplImage* img_bw = TrainPrepImage(img_in);
      cvShowImage("Input", img_in);
      do {
	IplImage* img = cvCloneImage(img_in);
	DrawCurrentRects(img, pos,neg);
	if (pp.num_pts != 0) {
	  if (pp.neg) cvRectangle(img, pp.p1, pp.p2, CV_RGB(255,0,0), 1);
	  else cvRectangle(img, pp.p1, pp.p2, CV_RGB(0,255,0), 1);
	}
	if (pp.num_pts == 2) {
	  pp.num_pts = 0;
	  CvPoint UL = cvPoint(MIN(pp.p1.x, pp.p2.x),
			       MIN(pp.p1.y, pp.p2.y));
	  CvSize signsize = cvSize(abs(pp.p2.x-pp.p1.x),
				   abs(pp.p2.y-pp.p1.y));
	  if (!signsize.width  || 
	      !signsize.height) {
	    printf("too small!\n");
	    continue;
	  }
	  CvRect newrect = cvRect(UL.x,UL.y,signsize.width,signsize.height);
	  if (pp.neg) neg.push_back(newrect);
	  else pos.push_back(newrect);
	}
	cvShowImage("Input", img);
	key = cvWaitKey(30);
	cvReleaseImage(&img);
	if ((char)key == 'u') {
	  pos.clear();
	  neg.clear();
	}

      }while ((char) key != ' ' &&
	      (char) key != 'd');
      //next image?
      Save(save_fp ,full_name,
	   pos,neg);
      pos.clear();
      neg.clear();

      cvReleaseImage(&img_in);
      cvReleaseImage(&img_bw);   
    }
  }
  return -1;
}
Example #20
0
// Evaluates all conditional lines and regex mods the loaded masterlist.
// This exists so that Load() doesn't need to be called whenever the mods
// installed are changed. Evaluation does not take place unless this function
// is called. Repeated calls re-evaluate the masterlist from scratch each time,
// ignoring the results of any previous evaluations. Paths are case-sensitive
// if the underlying filesystem is case-sensitive.
LOOT_API unsigned int loot_eval_lists (loot_db db, const unsigned int language) {
    if (db == NULL)
        return c_error(loot_error_invalid_args, "Null pointer passed.");

    std::list<loot::Plugin> temp = db->rawMetadata;
    try {
        db->game.RefreshActivePluginsList();
        for (std::list<loot::Plugin>::iterator it=temp.begin(); it != temp.end();) {
            it->EvalAllConditions(db->game, language);
            if (it->IsRegexPlugin()) {
                boost::regex regex;
                try {
                    regex = boost::regex(it->Name(), boost::regex::perl|boost::regex::icase);
                } catch (boost::regex_error& e) {
                    return c_error(loot_error_regex_eval_fail, e.what());
                }

                for (boost::filesystem::directory_iterator itr(db->game.DataPath()); itr != boost::filesystem::directory_iterator(); ++itr) {
                    const std::string filename = itr->path().filename().string();
                    if (boost::regex_match(filename, regex)) {
                        loot::Plugin p = *it;
                        p.Name(filename);
                        temp.push_back(p);
                    }
                }
                it = temp.erase(it);
            } else {
                ++it;
            }
        }
    } catch (loot::error& e) {
        return c_error(e);
    }
    db->metadata = temp;

    temp = db->rawUserMetadata;
    try {
        for (std::list<loot::Plugin>::iterator it=temp.begin(); it != temp.end();) {
            it->EvalAllConditions(db->game, language);
            if (it->IsRegexPlugin()) {
                boost::regex regex;
                try {
                    regex = boost::regex(it->Name(), boost::regex::perl|boost::regex::icase);
                } catch (boost::regex_error& e) {
                    return c_error(loot_error_regex_eval_fail, e.what());
                }

                for (boost::filesystem::directory_iterator itr(db->game.DataPath()); itr != boost::filesystem::directory_iterator(); ++itr) {
                    const std::string filename = itr->path().filename().string();
                    if (boost::regex_match(filename, regex)) {
                        loot::Plugin p = *it;
                        p.Name(filename);
                        temp.push_back(p);
                    }
                }
                it = temp.erase(it);
            } else {
                ++it;
            }
        }
    } catch (loot::error& e) {
        return c_error(e);
    }
    db->userMetadata = temp;

    return loot_ok;
}
Example #21
0
/**
 * Reloads the task list from the SQLite database
 */
void TodoDialog::reloadTodoListItems() {
    QList<CalendarItem> calendarItemList = CalendarItem::fetchAllByCalendar(
            ui->todoListSelector->currentText());

    int itemCount = calendarItemList.count();
    MetricsService::instance()->sendEventIfEnabled(
            "todo/list/loaded",
            "todo",
            "todo list loaded",
            QString::number(itemCount) + " todo items",
            itemCount);

    {
        const QSignalBlocker blocker(ui->todoList);
        Q_UNUSED(blocker);

        ui->todoList->clear();

        QListIterator<CalendarItem> itr(calendarItemList);
        while (itr.hasNext()) {
            CalendarItem calItem = itr.next();

            // skip completed items if the "show completed items" checkbox
            // is not checked
            if (!ui->showCompletedItemsCheckBox->checkState()) {
                if (calItem.isCompleted()) {
                    continue;
                }
            }

            QString uid = calItem.getUid();

            // skip items that were not fully loaded yet
            if (uid == "") {
                continue;
            }

            QListWidgetItem *item = new QListWidgetItem(calItem.getSummary());
            item->setData(Qt::UserRole, uid);
            item->setCheckState(
                    calItem.isCompleted() ? Qt::Checked : Qt::Unchecked);
            item->setFlags(
                    Qt::ItemIsDragEnabled |
                    Qt::ItemIsDropEnabled |
                    Qt::ItemIsEnabled |
                    Qt::ItemIsUserCheckable |
                    Qt::ItemIsSelectable);

            ui->todoList->addItem(item);
        }
    }

    // set the current row of the task list to the first row
    jumpToTodoListItem();

    // set the focus to the description edit if we wanted to
    if (_setFocusToDescriptionEdit) {
        ui->descriptionEdit->setFocus();
        _setFocusToDescriptionEdit = false;
    }
}
Example #22
0
amyCubeLing::ItrType amyCubeLing::ComputeIteratorFromView()
{
	amyCube::tCube ::SizeType size = m_InputRegion.GetSize();
	amyCube::tCube::IndexType index= m_InputRegion.GetIndex();
	
	amyCube::tCube::RegionType region;
	if(this->GetInputView()==amyUtil::AXIAL)
	{
		if(this->GetView()==amyUtil::AXIAL)
		{
			size[2]=1;
			index[2]=GetSlice();
			region.SetSize(size);
			region.SetIndex(index);
			ItrType itr(this->GetInput()->obj,region);
			itr.SetFirstDirection(0);
			itr.SetSecondDirection(1);
			return itr;
		}
		if(this->GetView()==amyUtil::CORONAL)
		{
			size[1]=1;
			index[1]=GetSlice();
			region.SetSize(size);
			region.SetIndex(index);
			ItrType itr(this->GetInput()->obj,region);
			itr.SetFirstDirection(0);
			itr.SetSecondDirection(2);
			return itr;
		}
		if(this->GetView()==amyUtil::SAGITTAL)
		{
			size[0]=1;
			index[0]=GetSlice();
			region.SetSize(size);
			region.SetIndex(index);
			ItrType itr(this->GetInput()->obj,region);
			itr.SetFirstDirection(1);
			itr.SetSecondDirection(2);
			return itr;
		}
	}
	if(this->GetInputView()==amyUtil::CORONAL)
	{
		if(this->GetView()==amyUtil::AXIAL)
		{
			size[1]=1;
			index[1]=GetSlice();
			region.SetSize(size);
			region.SetIndex(index);
			ItrType itr(this->GetInput()->obj,region);
			itr.SetFirstDirection(0);
			itr.SetSecondDirection(2);
			return itr;
		}
		if(this->GetView()==amyUtil::CORONAL)
		{
			size[2]=1;
			index[2]=GetSlice();
			region.SetSize(size);
			region.SetIndex(index);
			ItrType itr(this->GetInput()->obj,region);
			itr.SetFirstDirection(0);
			itr.SetSecondDirection(1);
			return itr;
		}
		if(this->GetView()==amyUtil::SAGITTAL)
		{
			size[0]=1;
			index[0]=GetSlice();
			region.SetSize(size);
			region.SetIndex(index);
			ItrType itr(this->GetInput()->obj,region);
			itr.SetFirstDirection(2);
			itr.SetSecondDirection(1);
			return itr;
		}
	}
	if(this->GetInputView()==amyUtil::SAGITTAL)
	{
		if(this->GetView()==amyUtil::AXIAL)
		{
			size[1]=1;
			index[1]=GetSlice();
			region.SetSize(size);
			region.SetIndex(index);
			amyCube::tCube::Pointer p=this->GetInput()->obj;
			ItrType itr(p,region);
			itr.SetFirstDirection(2);
			itr.SetSecondDirection(0);
			return itr;
		}
		if(this->GetView()==amyUtil::CORONAL)
		{
			size[0]=1;
			index[0]=GetSlice();
			region.SetSize(size);
			region.SetIndex(index);
			ItrType itr(this->GetInput()->obj,region);
			itr.SetFirstDirection(2);
			itr.SetSecondDirection(1);
			return itr;
		}
		if(this->GetView()==amyUtil::SAGITTAL)
		{
			size[2]=1;
			index[2]=GetSlice();
			region.SetSize(size);
			region.SetIndex(index);
			ItrType itr(this->GetInput()->obj,region);
			itr.SetFirstDirection(0);
			itr.SetSecondDirection(1);
			return itr;
		}
	}
}
Example #23
0
void SettingsDialog::refreshTodoCalendarList(QStringList items,
                                             bool forceReadCheckedState) {
    // we want to read the checked state from the settings if the
    // todo calendar list was not empty
    bool readCheckedState = forceReadCheckedState ? true :
                            ui->todoCalendarListWidget->count() > 0;

    // clear the todo calendar list
    ui->todoCalendarListWidget->clear();

    QSettings settings;
    QStringList todoCalendarEnabledList = settings.value(
            "ownCloud/todoCalendarEnabledList").toStringList();

    QListIterator<QString> itr(items);
    while (itr.hasNext()) {
        QString url = itr.next();

        QUrl serverUrl(ui->serverUrlEdit->text());

        // continue if server url isn't valid
        if (!serverUrl.isValid()) {
            continue;
        }

        QString serverUrlText(serverUrl.toString());
        QString serverUrlPath = serverUrl.path();
        if (serverUrlPath != "") {
            // remove the path from the end because we already got it in the url
            serverUrlText.replace(QRegularExpression(
                    QRegularExpression::escape(serverUrlPath) + "$"), "");
        }

        // only add the server url if it wasn't already added
        if (!url.startsWith(serverUrlText)) {
            url = serverUrlText + url;
        }

        // get the name out of the url part
        QRegularExpression regex("\\/([^\\/]*)\\/$");
        QRegularExpressionMatch match = regex.match(url);
        QString name = match.captured(1);

        // remove percent encoding
        name = QUrl::fromPercentEncoding(name.toLatin1());

        // skip the contact birthdays calendar
        if (name == "contact_birthdays") {
            continue;
        }

        // skip the Calendar Plus birthday calendar
        if (name.startsWith("bdaycpltocal_")) {
            continue;
        }

        // create the list widget item and add it to the
        // todo calendar list widget
        QListWidgetItem *item = new QListWidgetItem(name);

        // eventually check if item was checked
        Qt::CheckState checkedState = readCheckedState
                                      ? (todoCalendarEnabledList.contains(name)
                                         ? Qt::Checked : Qt::Unchecked)
                                      : Qt::Checked;
        item->setCheckState(checkedState);

        item->setFlags(Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled |
                       Qt::ItemIsEnabled | Qt::ItemIsUserCheckable);
        item->setToolTip(url);
        ui->todoCalendarListWidget->addItem(item);
    }
}
Example #24
0
   void _sptInvoker::_reportError( JSContext *cx,
                                   INT32 rc,
                                   const bson::BSONObj &detail )
   {
      sdbSetErrno( rc ) ;

      if ( SDB_OK != rc )
      {
         stringstream ss ;
         BSONObjIterator itr( detail) ;
         INT32 fieldNum = detail.nFields() ;
         INT32 count = 0 ;
         while ( itr.more() )
         {
            if ( count > 0 )
            {
               ss << ", " ;
            }
            BSONElement e = itr.next() ;
            if ( fieldNum > 1 ||
                 0 != ossStrcmp( SPT_ERR, e.fieldName() ) )
            {
               ss << e.fieldName() << ": " ;
            }

            if ( String == e.type() )
            {
               ss << e.valuestr() ;
            }
            else if ( NumberInt == e.type() )
            {
               ss << e.numberInt() ;
            }
            else if ( NumberLong == e.type() )
            {
               ss << e.numberLong() ;
            }
            else if ( NumberDouble == e.type() )
            {
               ss << e.numberDouble() ;
            }
            else if ( Bool == e.type() )
            {
               ss << ( e.boolean() ? "true" : "false" ) ;
            }
            else
            {
               ss << e.toString( false, false ) ;
            }
            ++count ;
         }
         sdbSetErrMsg( ss.str().c_str() ) ;

         if ( sdbIsErrMsgEmpty() )
         {
            sdbSetErrMsg( getErrDesp( rc ) ) ;
         }

         JS_SetPendingException( cx , INT_TO_JSVAL( rc ) ) ;
      }
      else
      {
         sdbSetErrMsg( NULL ) ;
      }

      return ;
   }
Example #25
0
void DatabaseImportForm::filterObjects(QTreeWidget *tree_wgt, const QString &pattern, int search_column, bool sel_single_leaf)
{
    if(!tree_wgt)
        throw Exception(ERR_OPR_NOT_ALOC_OBJECT ,__PRETTY_FUNCTION__,__FILE__,__LINE__);

    QList<QTreeWidgetItem*> items=tree_wgt->findItems(pattern, Qt::MatchStartsWith | Qt::MatchRecursive, search_column);
    QTreeWidgetItemIterator itr(tree_wgt);

    tree_wgt->blockSignals(true);
    tree_wgt->collapseAll();
    tree_wgt->clearSelection();

    while(*itr)
    {
        (*itr)->setHidden(!pattern.isEmpty());
        ++itr;
    }

    if(pattern.isEmpty())
    {
        tree_wgt->topLevelItem(0)->setExpanded(true);
    }
    else
    {
        QTreeWidgetItem *parent=nullptr, *item=nullptr, *leaf=nullptr;
        int leaf_count=0;

        while(!items.isEmpty())
        {
            item=items.front();
            item->setExpanded(true);
            item->setHidden(false);
            parent=item->parent();

            while(parent)
            {
                parent->setHidden(false);
                parent->setExpanded(true);
                parent=parent->parent();
            }

            items.pop_front();

            //Counting the leaf items found so far
            if(sel_single_leaf && item->childCount()==0 && item->parent())
            {
                leaf_count++;
                leaf=item;
            }
        }

        //Selecting the single leaf item
        if(sel_single_leaf && leaf_count == 1 && leaf)
        {
            leaf->setSelected(true);
            tree_wgt->setCurrentItem(leaf);
        }
    }

    tree_wgt->blockSignals(false);
}
Example #26
0
//------------------------------------------------------------------------------
AsciiBoard::AsciiBoard (BitBoard const& b) {
   negativeSpaceIsDark = true;

   // Draw board itself
   std::ostringstream out;
   bool light = true;
   Square s = 56;
   out << "|----------+----------+----------+----------+----------+----------+----------+----------|   \n";
   for (int r = 7; r >= 0; --r) {
      s = 8 * r;
      // each rank needs many lines
      for (int i=0; i<4; ++i) {
         s = (r << 3) + i;
         for (int file = 0; file < 8; ++file) {
            out << '|';
            if (light == negativeSpaceIsDark) {
               out << "..........";
            } else {
               out << "          ";
            }
            ++s;
            light = !light;
         }
         out << '|';

         if (i == 2) {
            out << "  " << r + 1;
         } else {
            out << "   ";
         }

         out << '\n';
         ++s;
      }

      // draw bottom ruler
      out << "|----------+----------+----------+----------+----------+----------+----------+----------|   \n";

      // next row starts with other color
      light = !light;
   }
   out << "     A          B          C          D          E          F          G          H\n";

   // Superimpose Pieces
   str = out.str();
   for (PieceItr itr(b, PieceItr::all_pieces); itr.valid(); ++itr) {
      int x = file(itr.square()) * 11 + 1;
      int y = (7 - rank(itr.square())) * 5 + 1;
      int i = y*rowL + x;
      switch (itr.piece()) {
      case PC::p0:
         negativeSpaceIsDark ? drawFilledPawn(i) : drawEmptyPawn(i); break;
      case PC::n0:
         negativeSpaceIsDark ? drawFilledKnight(i) : drawEmptyKnight(i); break;
      case PC::b0:
         negativeSpaceIsDark ? drawFilledBishop(i) : drawEmptyBishop(i); break;
      case PC::r0:
         negativeSpaceIsDark ? drawFilledRook(i) : drawEmptyRook(i); break;
      case PC::q0:
         negativeSpaceIsDark ? drawFilledQueen(i) : drawEmptyQueen(i); break;
      case PC::k0:
         negativeSpaceIsDark ? drawFilledKing(i) : drawEmptyKing(i); break;
      case PC::p1:
         negativeSpaceIsDark ? drawEmptyPawn(i) : drawFilledPawn(i); break;
      case PC::n1:
         negativeSpaceIsDark ? drawEmptyKnight(i) : drawFilledKnight(i); break;
      case PC::b1:
         negativeSpaceIsDark ? drawEmptyBishop(i) : drawFilledBishop(i); break;
      case PC::r1:
         negativeSpaceIsDark ? drawEmptyRook(i) : drawFilledRook(i); break;
      case PC::q1:
         negativeSpaceIsDark ? drawEmptyQueen(i) : drawFilledQueen(i); break;
      case PC::k1:
         negativeSpaceIsDark ? drawEmptyKing(i) : drawFilledKing(i); break;
      }
   }
}
Example #27
0
void union_set(s,t)
{register int i,v ;
  itr(t,i,v,add_set(s,v));
}
Example #28
0
   void crlf_check::inspect(
      const string & library_name,
      const path & full_path,   // example: c:/foo/boost/filesystem/path.hpp
      const string & contents )     // contents of file to be inspected
    {
      if (contents.find( "boostinspect:" "nocrlf" ) != string::npos) return;

      // this file deliberately contains errors
      const char test_file_name[] = "wrong_line_ends_test.cpp";

      bool failed = false;
      // The understanding on line endings, as I remember it, was that
      // either "\n" or "\r\n" is OK, and they can be mixed, but "\r" alone
      // is not acceptable. Mixed line endings are allowed because Boost files
      // are commonly edited in both Windows and UNIX environments, and editors
      // in those environments generally accept either ending. Even Mac people
      // agreed with this policy. --Beman

      // Joerg's original implementation is saved below,
      // in case we change our minds!

      for ( std::string::const_iterator itr ( contents.begin() );
        itr != contents.end(); ++itr )
      {
        if ( *itr == '\r' && ((itr+1) == contents.end() || *(itr+1) != '\n') )
        {
          failed = true;
          break;
        }
      }

      if (failed && full_path.leaf() != test_file_name)
      {
        ++m_files_with_errors;
        error( library_name, full_path, name() );
      }

      if (!failed && full_path.leaf() == test_file_name)
      {
        ++m_files_with_errors;
        error( library_name, full_path, string(name()) + " should have cr-only line endings" );
      }

/*
      size_t cr_count = 0;
      size_t lf_count = 0;
      size_t crlf_count = 0;
      bool had_cr = false;
      for ( size_t i = 0; i < contents.length(); ++i )
      {
        switch ( contents[i] )
        {
          case '\r':
            had_cr = true;
            ++cr_count;
            break;
          case '\n':
            ++lf_count;
            if ( had_cr )
              ++crlf_count;
            // fallthrough
          default:
            had_cr = false;
            break;
        }
      }
      if ( cr_count > 0 && lf_count != crlf_count )
      {
        ++m_files_with_errors;
        error( library_name, full_path, desc() );
      }
*/
    }
Example #29
0
void UcUseCaseCanvas::send(ToolCom * com, Q3CanvasItemList & all)
{
  Q3PtrList<UcUseCaseCanvas> lu;
  Q3PtrList<UcClassCanvas> la;
  Q3CanvasItemList::Iterator cit;

  for (cit = all.begin(); cit != all.end(); ++cit) {
    DiagramItem *di = QCanvasItemToDiagramItem(*cit);
    
    if ((di != 0) && (*cit)->visible()) {
      switch (di->type()) {
      case UmlUseCase:
	lu.append((UcUseCaseCanvas *) di);
	break;
      case UmlClass:
	la.append((UcClassCanvas *) di);
	break;
      default:
	break;
      }
    }
  }
  
  // send UC
  
  com->write_unsigned(lu.count());
  
  Q3PtrListIterator<UcUseCaseCanvas> itu(lu);
  
  for (; itu.current(); ++itu) {
    com->write_unsigned((unsigned) itu.current()->get_ident());
    itu.current()->get_bn()->write_id(com);
    com->write(itu.current()->rect());
  }
  
  // send Actors
  
  com->write_unsigned(la.count());
  
  Q3PtrListIterator<UcClassCanvas> ita(la);
  
  for (; ita.current(); ++ita)
    ita.current()->get_bn()->write_id(com);
  
  // send rels
  
  Q3PtrList<ArrowCanvas> lr;
  
  for (itu.toFirst(); itu.current(); ++itu) {
    Q3PtrListIterator<ArrowCanvas> itl(itu.current()->lines);
    
    for (; itl.current(); ++itl) {
      ArrowCanvas * r = itl.current();
      DiagramItem * from = r->get_start();
      DiagramItem * to = r->get_end();
      
      if ((from->type() == UmlUseCase)
	  ? (to->type() == UmlClass)
	  : (from->type() == UmlClass))
	lr.append(r);
    }
  }
  
  com->write_unsigned(lr.count());
  
  Q3PtrListIterator<ArrowCanvas> itr(lr);
  
  for (; itr.current(); ++itr)
    itr.current()->write_uc_rel(com);
}
void DicomSelectorDialog::exec() {
	typedef itk::ImageFileReader< CTImageType >  ReaderType;
	int index = 0; bool canceled = false;
	
	QProgressDialog indexProgress(tr("Indexing Files..."), tr("Abort"), 0, m_fileNames.size(), this);
	indexProgress.setMinimumDuration(1000);
	indexProgress.setWindowModality(Qt::ApplicationModal);
	while( index < m_fileNames.size() ) {
		indexProgress.setValue(index + 1);
		if (indexProgress.wasCanceled()) break;
		if ( boost::filesystem::is_directory( m_fileNames[index].toAscii().data() ) ) 
		{
			boost::filesystem::path fpath( m_fileNames.takeAt(index).toAscii().data() );
			QList< boost::filesystem::path > pathList;
			boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
			pathList.push_back( fpath );
			indexProgress.setMaximum(m_fileNames.size() + pathList.size());
			while( !pathList.isEmpty() ) {
				if (indexProgress.wasCanceled()) break;
				boost::filesystem::path currentPath = pathList.takeFirst();
				for ( boost::filesystem::directory_iterator itr( currentPath ); itr != end_itr; ++itr ) 
				{
					if (indexProgress.wasCanceled()) break;
					if ( boost::filesystem::is_directory(itr->status()) ) 
					{
						pathList.push_back( itr->path() );
						indexProgress.setMaximum(m_fileNames.size() + pathList.size());
						indexProgress.setValue(index);
					}
					else if ( boost::filesystem::is_regular_file( itr->status() )) 
					{
						m_fileNames.push_back( itr->path().directory_string().c_str() );
					}
				}
			}
		} else {
			index++;
		}
	}
	canceled = indexProgress.wasCanceled();
	
	m_fileNames.removeDuplicates();
	if (!canceled ) {
		QProgressDialog metaReadProgress(tr("Reading MetaData..."), tr("Abort"), 0, m_fileNames.size(), this);
		metaReadProgress.setMinimumDuration(1000);
		metaReadProgress.setWindowModality(Qt::ApplicationModal);
		for(int i = 0; i < m_fileNames.size(); i++) {
			metaReadProgress.setValue(i);
			if (metaReadProgress.wasCanceled()) 
				break;
			boost::filesystem::path fpath( m_fileNames[i].toAscii().data() );
			if ( boost::filesystem::is_regular_file( fpath ) ) {
				try {
					ReaderType::Pointer reader = ReaderType::New();
					reader->SetFileName( fpath.string() );
					reader->GenerateOutputInformation();
					m_ctImageModel.appendFilename( reader->GetMetaDataDictionary(), fpath.string() );
				} catch (itk::ImageFileReaderException &ifrExep) {
					std::cerr << "Exception caught !" << std::endl;
					std::cerr << ifrExep << std::endl;
				} catch (itk::ExceptionObject & excep) {
					std::cerr << "Exception caught !" << std::endl;
					std::cerr << excep << std::endl;
				}
			}
		}
	}
	if (m_ctImageModel.rowCount(QModelIndex())==0) return;

	treeView->setModel( &m_ctImageModel );
	treeView->selectAll();
	for(unsigned int t=0; t < m_HeaderFields.size(); t++) treeView->resizeColumnToContents(t);
	
	treeView->setSortingEnabled(true);
	treeView->sortByColumn(2,Qt::AscendingOrder);
	
	QDialog::exec();
}