Esempio n. 1
1
status_t
POP3Protocol::SyncMessages()
{
	bool leaveOnServer;
	if (fSettings.FindBool("leave_mail_on_server", &leaveOnServer) != B_OK)
		leaveOnServer = true;

	// create directory if not exist
	create_directory(fDestinationDir, 0777);

	printf("POP3Protocol::SyncMessages()\n");
	_ReadManifest();

	SetTotalItems(2);
	ReportProgress(0, 1, "Connect to server...");
	status_t error = Connect();
	if (error < B_OK) {
		ResetProgress();
		return error;
	}

	ReportProgress(0, 1, MDR_DIALECT_CHOICE("Getting UniqueIDs...",
		"固有のIDを取得中..."));
	error = _UniqueIDs();
	if (error < B_OK) {
		ResetProgress();
		return error;
	}

	BStringList toDownload;
	fManifest.NotHere(fUniqueIDs, &toDownload);

	int32 numMessages = toDownload.CountItems();
	if (numMessages == 0) {
		CheckForDeletedMessages();
		ResetProgress();
		return B_OK;
	}

	ResetProgress();
	SetTotalItems(toDownload.CountItems());

	printf("POP3: Messages to download: %i\n", (int)toDownload.CountItems());
	for (int32 i = 0; i < toDownload.CountItems(); i++) {
		const char* uid = toDownload.ItemAt(i);
		int32 toRetrieve = fUniqueIDs.IndexOf(uid);

		if (toRetrieve < 0) {
			// should not happen!
			error = B_NAME_NOT_FOUND;
			printf("POP3: uid %s index %i not found in fUniqueIDs!\n", uid,
				(int)toRetrieve);
			continue;
		}

		BPath path(fDestinationDir);
		BString fileName = "Downloading file... uid: ";
		fileName += uid;
		fileName.ReplaceAll("/", "_SLASH_");
		path.Append(fileName);
		BEntry entry(path.Path());
		BFile file(&entry, B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE);
		error = file.InitCheck();
		if (error != B_OK) {
			printf("POP3: Can't create file %s\n ", path.Path());
			break;
		}
		BMailMessageIO mailIO(this, &file, toRetrieve);

		entry_ref ref;
		entry.GetRef(&ref);

		// the ref becomes invalid after renaming the file thus we already
		// write the status here
		MarkMessageAsRead(ref, B_UNREAD);

		int32 size = MessageSize(toRetrieve);
		if (fFetchBodyLimit < 0 || size <= fFetchBodyLimit) {
			error = mailIO.Seek(0, SEEK_END);
			if (error < 0) {
				printf("POP3: Failed to download body %s\n ", uid);
				break;
			}
			NotifyHeaderFetched(ref, &file);
			NotifyBodyFetched(ref, &file);

			if (!leaveOnServer)
				Delete(toRetrieve);
		} else {
			int32 dummy;
			error = mailIO.ReadAt(0, &dummy, 1);
			if (error < 0) {
				printf("POP3: Failed to download header %s\n ", uid);
				break;
			}
			NotifyHeaderFetched(ref, &file);
		}
		ReportProgress(0, 1);

		if (file.WriteAttr("MAIL:unique_id", B_STRING_TYPE, 0, uid,
			strlen(uid)) < 0) {
			error = B_ERROR;
		}

		file.WriteAttr("MAIL:size", B_INT32_TYPE, 0, &size, sizeof(int32));

		// save manifest in case we get disturbed
		fManifest += uid;
		_WriteManifest();
	}

	ResetProgress();

	CheckForDeletedMessages();
	Disconnect();
	return error;
}
void ManchesterAnalyzer::SaveBit( U64 location, U32 value )
{
	if( mIgnoreBitCount == 0 )
		mBitsForNextByte.push_back( std::pair< U64, U64 >( value, location ) );
	else
		--mIgnoreBitCount;
	if( value == 1 )
		mResults->AddMarker( location, AnalyzerResults::One, mSettings->mInputChannel );
	else if( value == 0 )
		mResults->AddMarker( location, AnalyzerResults::Zero, mSettings->mInputChannel );

	U32 bit_count = mSettings->mBitsPerTransfer;
	if( mBitsForNextByte.size() == bit_count )
	{
		U64 byte = 0;
		if( mSettings->mShiftOrder == AnalyzerEnums::MsbFirst )
		{
			for( U32 i = 0; i < bit_count; ++i )
				byte |= ( mBitsForNextByte[i].first << ( bit_count - i - 1 ) );
		}
		else if( mSettings->mShiftOrder == AnalyzerEnums::LsbFirst )
		{
			for( U32 i = 0; i < bit_count; ++i )
				byte |= ( mBitsForNextByte[i].first << i );
		}
		Frame frame;
		frame.mStartingSampleInclusive = mBitsForNextByte[0].second - ( mT / 2 );
		frame.mEndingSampleInclusive = location + ( mT / 2 );
		frame.mData1 = byte;
		mResults->AddFrame( frame );
		mBitsForNextByte.clear();
		mResults->CommitResults();
		ReportProgress( mManchester->GetSampleNumber() );
	}
}
Esempio n. 3
0
U64 IRAnalyzer::DecodeAddr(U64 sample, U8 j, IRAnalyzerResults::TypeFrame type)
{
	U8 addr = 0xFF;
	U64 ntick, mtick, first, tt;

	first = sample;
	tt = sample;

	for( U8 i=0; i<j; i++ )
	{
		mSerial->AdvanceToNextEdge();
		ntick = mSerial->GetSampleNumber();
		mtick = U64((ntick - tt)*1000000/mSampleRateHz);
		if (mtick > 400 && mtick < 700)
		{
			addr ^= (1 << (7-i));
		}
		mSerial->AdvanceToNextEdge();
		tt = mSerial->GetSampleNumber();
	}
	Frame frame;
	frame.mData1 = j | type;
	frame.mData2 = reverse(addr);
	frame.mFlags = 0;
	frame.mStartingSampleInclusive = first;
	frame.mEndingSampleInclusive = tt;
	mResults->AddFrame( frame );
	mResults->CommitResults();
	ReportProgress( frame.mEndingSampleInclusive );

	return tt;
}
Esempio n. 4
0
void I2sAnalyzer::WorkerThread()
{
	//UpArrow, DownArrow
	if( mSettings->mDataValidEdge == AnalyzerEnums::NegEdge )
		mArrowMarker = AnalyzerResults::DownArrow;
	else
		mArrowMarker = AnalyzerResults::UpArrow;

	mClock = GetAnalyzerChannelData( mSettings->mClockChannel );
	mFrame = GetAnalyzerChannelData( mSettings->mFrameChannel );
	mData = GetAnalyzerChannelData( mSettings->mDataChannel );

	SetupForGettingFirstBit();
	SetupForGettingFirstFrame();

	for( ; ; )
	{
		GetFrame();
		AnalyzeFrame();

		mResults->CommitResults();
		ReportProgress( mClock->GetSampleNumber() );
		CheckIfThreadShouldExit();
	}

}
Esempio n. 5
0
status_t
POP3Protocol::FetchBody(const entry_ref& ref)
{
	ResetProgress("Fetch body");
	SetTotalItems(1);

	status_t error = Connect();
	if (error < B_OK)
		return error;

	error = _UniqueIDs();
	if (error < B_OK) {
		Disconnect();
		return error;
	}

	BFile file(&ref, B_READ_WRITE);
	status_t status = file.InitCheck();
	if (status != B_OK) {
		Disconnect();
		return status;
	}

	char uidString[256];
	BNode node(&ref);
	if (node.ReadAttr("MAIL:unique_id", B_STRING_TYPE, 0, uidString, 256) < 0) {
		Disconnect();
		return B_ERROR;
	}

	int32 toRetrieve = fUniqueIDs.IndexOf(uidString);
	if (toRetrieve < 0) {
		Disconnect();
		return B_NAME_NOT_FOUND;
	}

	bool leaveOnServer;
	if (fSettings.FindBool("leave_mail_on_server", &leaveOnServer) != B_OK)
		leaveOnServer = true;

	// TODO: get rid of this BMailMessageIO!
	BMailMessageIO io(this, &file, toRetrieve);
	// read body
	status = io.Seek(0, SEEK_END);
	if (status < 0) {
		Disconnect();
		return status;
	}

	NotifyBodyFetched(ref, &file);

	if (!leaveOnServer)
		Delete(toRetrieve);

	ReportProgress(0, 1);
	ResetProgress();

	Disconnect();
	return B_OK;
}
Esempio n. 6
0
HRESULT CAssemblyDownload::PrepNextDownload(LPWSTR pwzNextCodebase)
{
    HRESULT                                  hr = S_OK;
    CCriticalSection                         cs(&_cs);


    // Set the new URL
    
    SetUrl((LPCWSTR)pwzNextCodebase);

    // Notify all clients that we are trying the next codebase

    ReportProgress(0, 0, 0, ASM_NOTIFICATION_ATTEMPT_NEXT_CODEBASE,
                   (LPCWSTR)_pwzUrl, _hrResult);

    // Re-initialize our state
    
    hr = cs.Lock();
    if (FAILED(hr)) {
        goto Exit;
    }

    _state = ADLSTATE_INITIALIZE;

    cs.Unlock();

Exit:
    return hr;
}
Esempio n. 7
0
status_t
POP3Protocol::Open(const char* server, int port, int)
{
	ReportProgress(0, 0, B_TRANSLATE("Connecting to POP3 server"
		B_UTF8_ELLIPSIS));

	if (port <= 0)
		port = fUseSSL ? 995 : 110;

	fLog = "";

	// Prime the error message
	BString errorMessage(B_TRANSLATE("Error while connecting to server %serv"));
	errorMessage.ReplaceFirst("%serv", server);
	if (port != 110)
		errorMessage << ":" << port;

	delete fServerConnection;
	fServerConnection = NULL;

	BNetworkAddress address(server, port);
	if (fUseSSL)
		fServerConnection = new(std::nothrow) BSecureSocket(address);
	else
		fServerConnection = new(std::nothrow) BSocket(address);

	status_t status = B_NO_MEMORY;
	if (fServerConnection != NULL)
		status = fServerConnection->InitCheck();

	BString line;
	if (status == B_OK) {
		ssize_t length = ReceiveLine(line);
		if (length < 0)
			status = length;
	}

	if (status != B_OK) {
		fServerConnection->Disconnect();
		errorMessage << ": " << strerror(status);
		ShowError(errorMessage.String());
		return status;
	}

	if (strncmp(line.String(), "+OK", 3) != 0) {
		if (line.Length() > 0) {
			errorMessage << B_TRANSLATE(". The server said:\n")
				<< line.String();
		} else
			errorMessage << B_TRANSLATE(": No reply.\n");

		ShowError(errorMessage.String());
		fServerConnection->Disconnect();
		return B_ERROR;
	}

	fLog = line;
	return B_OK;
}
Esempio n. 8
0
//------------------------------------------------------------------------------
void SequentialEstimator::RunComplete()
{
   ReportProgress();
   measManager.ProcessingComplete();
   esm.MapVectorToObjects();

//   WriteToTextFile();
}
void main(int argc,char **argv)
{
	InitCommandLineProgram( argc, argv );
	if (argc != 2)
	{
		printf("format is 'normal2ssbump filename.tga\n");
	}
	else
	{
		ReportProgress( "reading src texture",0,0 );
		FloatBitMap_t src_texture(argv[1]);
		for(int y=0;y<src_texture.Height;y++)
		{
			ReportProgress( "Converting to ssbump format",src_texture.Height,y );
			for(int x=0;x<src_texture.Width;x++)
			{
				Vector n( RangeAdjust( src_texture.Pixel( x,y,0 ) ),
						  RangeAdjust( src_texture.Pixel( x,y,1 ) ),
						  RangeAdjust( src_texture.Pixel( x,y,2 ) ) );
				Vector dp( saturate_and_square( DotProduct( n, bumpBasis[0] ) ),
						   saturate_and_square( DotProduct( n, bumpBasis[1] ) ),
						   saturate_and_square( DotProduct( n, bumpBasis[2] ) ) );
				float sum = DotProduct(dp, Vector(1,1,1));
				dp *= 1.0/sum;
				src_texture.Pixel(x,y,0) = dp.x;
				src_texture.Pixel(x,y,1) = dp.y;
				src_texture.Pixel(x,y,2) = dp.z;
			}
		}
		char oname[1024];
		strcpy(oname,argv[1]);
		char *dot=Q_stristr(oname,"_normal");
		if (! dot)
			dot=strchr(oname,'.');
		if (! dot)
			dot=oname+strlen(oname);
		strcpy(dot,"_ssbump.tga");
		printf( "\nWriting %s\n",oname );
		src_texture.WriteTGAFile( oname );
	}

}
Esempio n. 10
0
void ptFilter_SpotTuning::startInteraction() {
  if (!ViewWindow)
    return;

  FGui->SpotList->setEditMode(true);
  ViewWindow->ShowStatus(QObject::tr("Prepare"));
  ReportProgress(QObject::tr("Prepare for local adjust"));
  TheProcessor->RunLocalEdit(ptProcessorStopBefore::SpotTuning);
  this->updatePreview();

  // Allow to be selected in the view window. And deactivate main.
  ViewWindow->ShowStatus(QObject::tr("Local adjust"));
  ReportProgress(QObject::tr("Local adjust"));
  BlockTools(btmBlockForSpotTuning, QStringList(this->uniqueName()));

  ViewWindow->StartLocalAdjust(std::bind(&ptFilter_SpotTuning::cleanupAfterInteraction, this));
  QObject::connect(ViewWindow->spotTuning(), SIGNAL(clicked(QPoint)),
                   FGui->SpotList, SLOT(processCoordinates(QPoint)));
  ViewWindow->setFocus();
}
Esempio n. 11
0
//------------------------------------------------------------------------------
void BatchEstimator::RunComplete()
{
   #ifdef WALK_STATE_MACHINE
      MessageInterface::ShowMessage("BatchEstimator state is FINALIZING\n");
   #endif

   measManager.ProcessingComplete();

   // Report the results
   WriteToTextFile();
   ReportProgress();

   if (showAllResiduals)
      PlotResiduals();
}
Esempio n. 12
0
bool CMassiveGitTaskBase::ExecuteCommands(volatile BOOL& cancel)
{
	m_bUnused = false;

	int maxLength = 0;
	int firstCombine = 0;
	for (int i = 0; i < GetListCount(); ++i)
	{
		if (maxLength + GetListItem(i).GetLength() > MAX_COMMANDLINE_LENGTH || i == GetListCount() - 1 || cancel)
		{
			CString add;
			for (int j = firstCombine; j <= i; ++j)
			{
				add += L" \"";
				add += GetListItem(j);
				add += L'"';
			}

			CString cmd, out;
			cmd.Format(L"git.exe %s %s%s", (LPCTSTR)m_sParams, m_bIsPath ? L"--" : L"", (LPCTSTR)add);
			int exitCode = g_Git.Run(cmd, &out, CP_UTF8);
			if (exitCode && !m_bIgnoreErrors)
			{
				ReportError(out, exitCode);
				return false;
			}

			if (m_bIsPath)
			{
				for (int j = firstCombine; j <= i; ++j)
					ReportProgress(m_pathList[j], j);
			}

			maxLength = 0;
			firstCombine = i+1;

			if (cancel)
			{
				ReportUserCanceled();
				return false;
			}
		}
		else
			maxLength += 3 + GetListItem(i).GetLength();
	}
	return true;
}
Esempio n. 13
0
status_t
POP3Protocol::Stat()
{
	ReportProgress(0, 0, B_TRANSLATE("Getting mailbox size" B_UTF8_ELLIPSIS));

	if (SendCommand("STAT" CRLF) < B_OK)
		return B_ERROR;

	int32 messages,dropSize;
	if (sscanf(fLog.String(), "+OK %ld %ld", &messages, &dropSize) < 2)
		return B_ERROR;

	fNumMessages = messages;
	fMailDropSize = dropSize;

	return B_OK;
}
Esempio n. 14
0
status_t
POP3Protocol::Stat()
{
	ReportProgress(0, 0, MDR_DIALECT_CHOICE("Getting mailbox size...",
		"メールボックスのサイズを取得しています..."));

	if (SendCommand("STAT" CRLF) < B_OK)
		return B_ERROR;

	int32 messages,dropSize;
	if (sscanf(fLog.String(), "+OK %ld %ld", &messages, &dropSize) < 2)
		return B_ERROR;

	fNumMessages = messages;
	fMailDropSize = dropSize;

	return B_OK;
}
bool CMassiveGitTaskBase::ExecuteCommands(volatile BOOL& cancel)
{
	m_bUnused = false;

	int maxLength = 0;
	int firstCombine = 0;
	for (int i = 0; i < GetListCount(); ++i)
	{
		if (maxLength + GetListItem(i).GetLength() > MAX_COMMANDLINE_LENGTH || i == GetListCount() - 1 || cancel)
		{
			CString add;
			for (int j = firstCombine; j <= i; ++j)
				add += _T(" \"") + GetListItem(j) + _T("\"");

			CString cmd, out;
			cmd.Format(_T("git.exe %s %s%s"), m_sParams, m_bIsPath ? _T("--") : _T(""), add);
			if (g_Git.Run(cmd, &out, CP_UTF8) && !m_bIgnoreErrors)
			{
				ReportError(out);
				return false;
			}

			if (m_bIsPath)
			{
				for (int j = firstCombine; j <= i; ++j)
					ReportProgress(m_pathList[j], j);
			}

			maxLength = 0;
			firstCombine = i+1;

			if (cancel)
			{
				ReportUserCanceled();
				return false;
			}
		}
		else
		{
			maxLength += 3 + GetListItem(i).GetLength();
		}
	}
	return true;
}
Esempio n. 16
0
//------------------------------------------------------------------------------
Solver::SolverState Solver::AdvanceState()
{
   switch (currentState) {
      case INITIALIZING:
         CompleteInitialization();
         break;
        
      case NOMINAL:
         RunNominal();
         break;
        
      case PERTURBING:
         RunPerturbation();
         break;
        
      case ITERATING:
         RunIteration();
         break;
        
      case CALCULATING:
         CalculateParameters();
         break;
        
      case CHECKINGRUN:
         CheckCompletion();
         break;
        
      case RUNEXTERNAL:
         RunExternal();
         break;
        
      case FINISHED:
         RunComplete();
         break;
        
      default:
         throw SolverException(wxT("Undefined Solver state"));
    };
    
    ReportProgress();
    return currentState; 
}
Esempio n. 17
0
// ==============================================================================
// Results and Screen Markers
// ==============================================================================
void RFFEAnalyzer::FillInFrame(RFFEAnalyzerResults::RffeFrameType type, U64 frame_data, U64 extra_data, U32 idx_start, U32 idx_end, U8 flags) {
  Frame frame;

  frame.mType = (U8)type;
  frame.mData1 = frame_data;
  frame.mData2 = extra_data; // Additional Data (could be used for AnalyzerResults if required)
  frame.mStartingSampleInclusive = mSampleClkOffsets[idx_start];
  frame.mEndingSampleInclusive = mSampleClkOffsets[idx_end];
  frame.mFlags = flags;

  // Add Markers to the SDATA stream while we are creating the Frame
  // That is if the Frame is non-zero length and also merits a marker.
  for (U32 i = idx_start; i < idx_end; i += 1) {
    mResults->AddMarker(mSampleDataOffsets[i], mSampleMarker[i], mSettings->mSdataChannel);
  }

  mResults->AddFrame(frame);
  mResults->CommitResults();
  ReportProgress(frame.mEndingSampleInclusive);
}
Esempio n. 18
0
void PWMAnalyzer::WorkerThread()
{
    mSampleRateHz = GetSampleRate();
    mPWM = GetAnalyzerChannelData(mSettings->mInputChannel);

    // Find the next full pulse for a clean start.
    mPWM->AdvanceToNextEdge();
    if (mPWM->GetBitState() == BIT_LOW) {
        mPWM->AdvanceToNextEdge();
    }

    int type = mSettings->mAnalysisType;

    double prevval(0);
    for (;;) {
        U64 start = mPWM->GetSampleNumber(); // Rising
        mPWM->AdvanceToNextEdge();
        U64 mid = mPWM->GetSampleNumber(); // Falling
        mPWM->AdvanceToNextEdge();
        U64 end = mPWM->GetSampleNumber(); // Rising

        double val = Value(start, mid, end);
        if (std::abs(val - prevval) >= mSettings->mMinChange) {
            mResults->AddMarker(end - ((end - start) / 2),
                                val > prevval ? AnalyzerResults::UpArrow : AnalyzerResults::DownArrow,
                                mSettings->mInputChannel);

            Frame frame;
            frame.mData1 = mid;
            frame.mStartingSampleInclusive = start;
            frame.mEndingSampleInclusive = end;
            mResults->AddFrame(frame);
            mResults->CommitResults();
            ReportProgress(frame.mEndingSampleInclusive);

            prevval = val;
        }
    }
}
Esempio n. 19
0
status_t
POP3Protocol::Retrieve(int32 message, BPositionIO* to)
{
	BString cmd;
	cmd << "RETR " << message + 1 << CRLF;
	status_t status = RetrieveInternal(cmd.String(), message, to, true);
	ReportProgress(1, 0);

	if (status == B_OK) {
		// Check if the actual message size matches the expected one
		int32 size = MessageSize(message);
 		to->Seek(0, SEEK_END);
		if (to->Position() != size) {
			printf("POP3Protocol::Retrieve Note: message size is %" B_PRIdOFF
				", was expecting %" B_PRId32 ", for message #%" B_PRId32
				".  Could be a transmission error or a bad POP server "
				"implementation (does it remove escape codes when it counts "
				"size?).\n", to->Position(), size, message);
		}
	}

	return status;
}
Esempio n. 20
0
status_t
POP3Protocol::Retrieve(int32 message, BPositionIO *write_to)
{
	status_t returnCode;
	BString cmd;
	cmd << "RETR " << message + 1 << CRLF;
	returnCode = RetrieveInternal(cmd.String(), message, write_to, true);
	ReportProgress(0 /* bytes */, 1 /* messages */);

	if (returnCode == B_OK) { // Some debug code.
		int32 message_len = MessageSize(message);
 		write_to->Seek (0, SEEK_END);
		if (write_to->Position() != message_len) {
			printf ("POP3Protocol::Retrieve Note: message size is %d, was "
			"expecting %ld, for message #%ld.  Could be a transmission error "
			"or a bad POP server implementation (does it remove escape codes "
			"when it counts size?).\n",
			(int) write_to->Position(), message_len, message);
		}
	}

	return returnCode;
}
Esempio n. 21
0
//------------------------------------------------------------------------------
void BatchEstimator::CompleteInitialization()
{
   #ifdef WALK_STATE_MACHINE
      MessageInterface::ShowMessage("BatchEstimator state is INITIALIZING\n");
   #endif

   if (showAllResiduals)
   {
      StringArray plotMeasurements;
      for (UnsignedInt i = 0; i < measurementNames.size(); ++i)
      {
         plotMeasurements.clear();
         plotMeasurements.push_back(measurementNames[i]);
         std::string plotName = instanceName + "_" + measurementNames[i] +
               "_Residuals";
         BuildResidualPlot(plotName, plotMeasurements);
      }
   }

   if (advanceToEstimationEpoch == false)
   {
      PropagationStateManager *psm = propagator->GetPropStateManager();
      GmatState               *gs  = psm->GetState();
      estimationState              = esm.GetState();
      stateSize = estimationState->GetSize();

      Estimator::CompleteInitialization();

      // If estimation epoch not set, use the epoch from the prop state
      if ((estEpochFormat == "FromParticipants") || (estimationEpoch <= 0.0))
      {
         ObjectArray participants;
         esm.GetStateObjects(participants, Gmat::SPACEOBJECT);
         for (UnsignedInt i = 0; i < participants.size(); ++i)
            estimationEpoch   = ((SpaceObject *)(participants[i]))->GetEpoch();
      }
      currentEpoch         = gs->GetEpoch();

      // Tell the measManager to complete its initialization
      bool measOK = measManager.Initialize();
      if (!measOK)
         throw SolverException(
               "BatchEstimator::CompleteInitialization - error initializing "
               "MeasurementManager.\n");

      // Now load up the observations
      measManager.PrepareForProcessing();
      measManager.LoadObservations();

      if (!GmatMathUtil::IsEqual(currentEpoch, estimationEpoch))
      {
         advanceToEstimationEpoch = true;
         nextMeasurementEpoch = estimationEpoch;
         currentState = PROPAGATING;
         return;
      }
   }

   advanceToEstimationEpoch = false;

   // First measurement epoch is the epoch of the first measurement.  Duh.
   nextMeasurementEpoch = measManager.GetEpoch();

   #ifdef DEBUG_INITIALIZATION
      MessageInterface::ShowMessage(
            "Init complete!\n   STM = %s\n   Covariance = %s\n",
            stm->ToString().c_str(), covariance->ToString().c_str());
   #endif

   hAccum.clear();
   if (useApriori)
   {
      information = stateCovariance->GetCovariance()->Inverse();
   }
   else
   {
      information.SetSize(stateSize, stateSize);
      for (UnsignedInt i = 0; i <  stateSize; ++i)
         for (UnsignedInt j = 0; j <  stateSize; ++j)
            information(i,j) = 0.0;
   }

   residuals.SetSize(stateSize);
   x0bar.SetSize(stateSize);

   measurementResiduals.clear();
   measurementEpochs.clear();

   for (Integer i = 0; i < information.GetNumRows(); ++i)
   {
      residuals[i] = 0.0;
      if (useApriori)
         x0bar[i] = (*estimationState)[i];
      else
         x0bar[i] = 0.0;
   }

   if (useApriori)
      for (Integer i = 0; i < information.GetNumRows(); ++i)
      {
         for (UnsignedInt j = 0; j < stateSize; ++j)
            residuals[i] += information(i,j) * x0bar[j];
      }

   esm.BufferObjects(&outerLoopBuffer);
   esm.MapObjectsToVector();

   converged   = false;
   isInitialized = true;

   WriteToTextFile();
   ReportProgress();

   if (GmatMathUtil::IsEqual(currentEpoch, nextMeasurementEpoch))
      currentState = CALCULATING;
   else
   {
      timeStep = (nextMeasurementEpoch - currentEpoch) *
            GmatTimeConstants::SECS_PER_DAY;
      currentState = PROPAGATING;
   }

   #ifdef DEBUG_INITIALIZATION
      MessageInterface::ShowMessage("BatchEstimator::CompleteInitialization "
            "process complete\n");
      MessageInterface::ShowMessage("   Estimation state = [");
      for (UnsignedInt i = 0; i < stateSize; ++i)
         MessageInterface::ShowMessage(" %.12lf ", (*estimationState)[i]);
      MessageInterface::ShowMessage("]\n");
      MessageInterface::ShowMessage("   Information Matrix = \n");
      for (Integer i = 0; i < information.GetNumRows(); ++i)
      {
         MessageInterface::ShowMessage("      [");
         for (Integer j = 0; j < information.GetNumColumns(); ++j)
         {
            MessageInterface::ShowMessage(" %.12lf ", information(i, j));
         }
         MessageInterface::ShowMessage("]\n");
      }
      MessageInterface::ShowMessage("   Residuals = [");
      for (Integer i = 0; i < residuals.GetSize(); ++i)
         MessageInterface::ShowMessage(" %.12lf ", residuals[i]);
      MessageInterface::ShowMessage("]\n");
   #endif
}
Esempio n. 22
0
void IRAnalyzer::WorkerThread()
{
	U64 tick, ntick, mtick, sample;
	mResults.reset( new IRAnalyzerResults( this, mSettings.get() ) );
	SetAnalyzerResults( mResults.get() );
	mResults->AddChannelBubblesWillAppearOn( mSettings->mInputChannel );

	mSampleRateHz = GetSampleRate();

	mSerial = GetAnalyzerChannelData( mSettings->mInputChannel );

	U32 samples_per_bit = mSampleRateHz / mSettings->mFrequency; // 562.5
	U32 samples_to_first_center_of_first_data_bit = U32( 1.5 * double( mSampleRateHz ) / double( mSettings->mFrequency ) );  // 843.75

	for ( ; ; )
	{
	if( mSerial->GetBitState() == BIT_HIGH )
	{
		mSerial->AdvanceToNextEdge();
	}
	tick = mSerial->GetSampleNumber();
	mSerial->AdvanceToNextEdge();
	ntick = mSerial->GetSampleNumber();

	mtick = U32((ntick - tick)*1000000/mSampleRateHz);


	if (mtick > 8700 && mtick < 9300)
	{
		// Found 9ms leading burst
		Frame frame;
		frame.mData1 = 0x1;
		frame.mFlags = 0;
		frame.mStartingSampleInclusive = tick;
		frame.mEndingSampleInclusive = ntick;
		mResults->AddFrame( frame );
		mResults->CommitResults();
		ReportProgress( frame.mEndingSampleInclusive );

		// Look for a 4.5ms space
		mSerial->AdvanceToNextEdge();
		tick = mSerial->GetSampleNumber();

		mtick = U32((tick - ntick)*1000000/mSampleRateHz);

		if (mtick > 4250 && mtick < 4750)
		{
			// Found 4.5ms space
			Frame frame;
			frame.mData1 = 0x2;
			frame.mFlags = 0;
			frame.mStartingSampleInclusive = ntick;
			frame.mEndingSampleInclusive = tick;
			mResults->AddFrame( frame );
			mResults->CommitResults();
			ReportProgress( frame.mEndingSampleInclusive );

			mSerial->AdvanceToNextEdge();
			tick = mSerial->GetSampleNumber();

			// Decode address of receiving device
			tick = this->DecodeAddr(tick, 8, IRAnalyzerResults::IADDR);

			// Decode logical inverse of address
			tick = this->DecodeAddr(tick, 8, IRAnalyzerResults::ADDR);

			// Decode command
			tick = this->DecodeAddr(tick, 8, IRAnalyzerResults::CMD);

			// Decode logical inverse of command
			tick = this->DecodeAddr(tick, 8, IRAnalyzerResults::ICMD);

			// Space
			mSerial->AdvanceToNextEdge();
			ntick = mSerial->GetSampleNumber();
			mtick = U32((ntick - tick)*1000000/mSampleRateHz);
			if (mtick > 40500 && mtick < 42500)
			{
				Frame frame;
				frame.mData1 = 0x2;
				frame.mFlags = 0;
				frame.mStartingSampleInclusive = tick;
				frame.mEndingSampleInclusive = ntick;
				mResults->AddFrame( frame );
				mResults->CommitResults();
				ReportProgress( frame.mEndingSampleInclusive );
			}

			// Repeat
			tick = ntick;
			sample = ntick;
			mSerial->AdvanceToNextEdge();
			ntick = mSerial->GetSampleNumber();
			mtick = U32((ntick - sample)*1000000/mSampleRateHz);
			if (mtick > 8700 && mtick < 9300)
			{
				sample = ntick;
				mSerial->AdvanceToNextEdge();
				ntick = mSerial->GetSampleNumber();
				mtick = U32((ntick - sample)*1000000/mSampleRateHz);
				if (mtick > 2100 && mtick < 2400)
				{
					sample = ntick;
					mSerial->AdvanceToNextEdge();
					ntick = mSerial->GetSampleNumber();
					mtick = U32((ntick - sample)*1000000/mSampleRateHz);
					if (mtick > 550 && mtick < 620)
					{
						Frame frame;
						frame.mData1 = 0x4;
						frame.mFlags = 0;
						frame.mStartingSampleInclusive = tick;
						frame.mEndingSampleInclusive = ntick;
						mResults->AddFrame( frame );
						mResults->CommitResults();
						ReportProgress( frame.mEndingSampleInclusive );
					}
				}
			}
		}
	}
	}

	mResults->CommitResults();
}
Esempio n. 23
0
void ManchesterAnalyzer::WorkerThread()
{
	mManchester = GetAnalyzerChannelData( mSettings->mInputChannel );

	mSampleRateHz = this->GetSampleRate();

	double half_peroid = 1.0 / double( mSettings->mBitRate * 2 );
	half_peroid *= 1000000.0;
	mT = U32( ( mSampleRateHz * half_peroid ) / 1000000.0 );
	switch( mSettings->mTolerance )
	{
	case TOL25:
		mTError = mT / 2;
		break;
	case TOL5:
		mTError = mT / 10;
		break;
	case TOL05:
		mTError = mT / 100;
		break;
	}
	if( mTError < 3 )
		mTError = 3;
	//mTError = mT / 2;
	mSynchronized = false;
	//mResults->AddMarker( mManchester->GetSampleNumber(), AnalyzerResults::One, mSettings->mInputChannel );
	mManchester->AdvanceToNextEdge();
	mBitsForNextByte.clear();
	mUnsyncedLocations.clear();
	mIgnoreBitCount = mSettings->mBitsToIgnore;


	for( ; ; )
	{
		switch( mSettings->mMode )
		{
		case MANCHESTER:
			{
				SynchronizeManchester();
				ProcessManchesterData();
			}
			break;
		case DIFFERENTIAL_MANCHESTER:
			{
				SynchronizeDifferential();
				ProcessDifferential();
			}
			break;
		case BI_PHASE_MARK:
			{
				SynchronizeBiPhase();
				ProcessBiPhaseData();
			}
			break;
		case BI_PHASE_SPACE:
			{
				SynchronizeBiPhase();
				ProcessBiPhaseData();
			}
			break;
		}
		//mManchester->AdvanceToNextEdge();
		//mResults->CommitResults();
		ReportProgress( mManchester->GetSampleNumber() );
		CheckIfThreadShouldExit();

	}
}
Esempio n. 24
0
void AcuriteAnalyzer::WorkerThread()
{
  AcuRiteDecoder decoder;
  U32 lastPulse = 0;
  Frame frame; // for saving/printing data
  frame.mFlags = 0;
  frame.mStartingSampleInclusive = 0;

  mResults.reset( new AcuriteAnalyzerResults( this, mSettings.get() ) );
  SetAnalyzerResults( mResults.get() );
  mResults->AddChannelBubblesWillAppearOn( mSettings->mInputChannel );
  
  mSampleRateHz = GetSampleRate();
  log("mSampleRateHz is %lu", mSampleRateHz);
  mSampleRateMs = mSampleRateHz / 1000000;
  log("mSampleRateMs is %lu", mSampleRateMs);
  
  mSerial = GetAnalyzerChannelData( mSettings->mInputChannel );

  log("Looking for start low...");

  // Have to start on a low pulse...
  if( mSerial->GetBitState() == BIT_HIGH )
    mSerial->AdvanceToNextEdge();
  
  while (1) {
    // Find the leading edge
    log("looking for next leading edge");
    mSerial->AdvanceToNextEdge();

    // Determine the time of this pulse
    U64 samplepos = mSerial->GetSampleNumber() / mSampleRateMs;

    if ( (!frame.mStartingSampleInclusive) || 
	 decoder.state == DecodeOOK::UNKNOWN ) {
      frame.mStartingSampleInclusive = mSerial->GetSampleNumber();
      mResults->AddMarker( mSerial->GetSampleNumber(), AnalyzerResults::Dot, mSettings->mInputChannel );
    }

    // Pass the pulse to the decoder
    log("calling decoder.nextPulse(%lu)", (unsigned long)samplepos - lastPulse);
    if (decoder.nextPulse((unsigned long)samplepos - lastPulse)) {
      byte size;

      log("nextPulse is now done");

      const byte *data = decoder.getData(size);
      char output[1024];
      interpretData(data, size, output);
      decoder.resetDecoder();

      // Display the data
      mResults->AddMarker( mSerial->GetSampleNumber(), AnalyzerResults::Dot, mSettings->mInputChannel );
      frame.mEndingSampleInclusive = mSerial->GetSampleNumber();
      frame.mData1 = (U64)output; // fixme - this is fugly.
      mResults->AddFrame( frame );
      mResults->CommitResults();

      ReportProgress( frame.mEndingSampleInclusive );

      // reset frame for next one
      frame.mStartingSampleInclusive = 0;
      
      // make sure we're at a low level when we're done decoding
      if ( mSerial->GetBitState() == BIT_HIGH)
	mSerial->AdvanceToNextEdge();
    }

    log("Decoder state is now %d", decoder.state);
    lastPulse = samplepos;
  }


}
Esempio n. 25
0
void SerialAnalyzer::WorkerThread()
{
	mSampleRateHz = GetSampleRate();
	ComputeSampleOffsets();
	U32 num_bits = mSettings->mBitsPerTransfer;

	if( mSettings->mSerialMode != SerialAnalyzerEnums::Normal )
		num_bits++;

	if( mSettings->mInverted == false )
	{
		mBitHigh = BIT_HIGH;
		mBitLow = BIT_LOW;
	}else
	{
		mBitHigh = BIT_LOW;
		mBitLow = BIT_HIGH;
	}

	U64 bit_mask = 0;
	U64 mask = 0x1ULL;
	for( U32 i=0; i<num_bits; i++ )
	{
		bit_mask |= mask;
		mask <<= 1;
	}
	
	mSerial = GetAnalyzerChannelData( mSettings->mInputChannel );
	mSerial->TrackMinimumPulseWidth();
	
	if( mSerial->GetBitState() == mBitLow )
		mSerial->AdvanceToNextEdge();

	for( ; ; )
	{
		//we're starting high.  (we'll assume that we're not in the middle of a byte. 

		mSerial->AdvanceToNextEdge();

		//we're now at the beginning of the start bit.  We can start collecting the data.
		U64 frame_starting_sample = mSerial->GetSampleNumber();

		U64 data = 0;
		bool parity_error = false;
		bool framing_error = false;
		bool mp_is_address = false;
		
		DataBuilder data_builder;
		data_builder.Reset( &data, mSettings->mShiftOrder, num_bits );
		U64 marker_location = frame_starting_sample;

		for( U32 i=0; i<num_bits; i++ )
		{
			mSerial->Advance( mSampleOffsets[i] );
			data_builder.AddBit( mSerial->GetBitState() );

			marker_location += mSampleOffsets[i];
			mResults->AddMarker( marker_location, AnalyzerResults::Dot, mSettings->mInputChannel );
		}

		if( mSettings->mInverted == true )
			data = (~data) & bit_mask;

		if( mSettings->mSerialMode != SerialAnalyzerEnums::Normal )
		{
			//extract the MSB
			U64 msb = data >> (num_bits - 1);
			msb &= 0x1;
			if( mSettings->mSerialMode == SerialAnalyzerEnums::MpModeMsbOneMeansAddress )
			{
				if( msb == 0x0 )
					mp_is_address = false;
				else
					mp_is_address = true;
			}
			if( mSettings->mSerialMode == SerialAnalyzerEnums::MpModeMsbZeroMeansAddress )
			{
				if( msb == 0x0 )
					mp_is_address = true;
				else
					mp_is_address = false;
			}
			//now remove the msb.
			data &= ( bit_mask >> 1 );
		}
			
		parity_error = false;

		if( mSettings->mParity != AnalyzerEnums::None )
		{
			mSerial->Advance( mParityBitOffset );
			bool is_even = AnalyzerHelpers::IsEven( AnalyzerHelpers::GetOnesCount( data ) );

			if( mSettings->mParity == AnalyzerEnums::Even )
			{
				if( is_even == true )
				{
					if( mSerial->GetBitState() != mBitLow ) //we expect a low bit, to keep the parity even.
						parity_error = true;
				}else
				{
					if( mSerial->GetBitState() != mBitHigh ) //we expect a high bit, to force parity even.
						parity_error = true;
				}
			}else  //if( mSettings->mParity == AnalyzerEnums::Odd )
			{
				if( is_even == false )
				{
					if( mSerial->GetBitState() != mBitLow ) //we expect a low bit, to keep the parity odd.
						parity_error = true;
				}else
				{
					if( mSerial->GetBitState() != mBitHigh ) //we expect a high bit, to force parity odd.
						parity_error = true;
				}
			}

			marker_location += mParityBitOffset;
			mResults->AddMarker( marker_location, AnalyzerResults::Square, mSettings->mInputChannel );
		}

		//now we must dermine if there is a framing error.
		framing_error = false;

		mSerial->Advance( mStartOfStopBitOffset );

		if( mSerial->GetBitState() != mBitHigh )
		{
			framing_error = true;
		}else
		{
			U32 num_edges = mSerial->Advance( mEndOfStopBitOffset );
			if( num_edges != 0 )
				framing_error = true;
		}

		if( framing_error == true )
		{
			marker_location += mStartOfStopBitOffset;
			mResults->AddMarker( marker_location, AnalyzerResults::ErrorX, mSettings->mInputChannel );

			if( mEndOfStopBitOffset != 0 )
			{
				marker_location += mEndOfStopBitOffset;
				mResults->AddMarker( marker_location, AnalyzerResults::ErrorX, mSettings->mInputChannel );
			}
		}

		//ok now record the value!
		//note that we're not using the mData2 or mType fields for anything, so we won't bother to set them.
		Frame frame;
		frame.mStartingSampleInclusive = frame_starting_sample;
		frame.mEndingSampleInclusive = mSerial->GetSampleNumber();
		frame.mData1 = data;
		frame.mFlags = 0;
		if( parity_error == true )
			frame.mFlags |= PARITY_ERROR_FLAG | DISPLAY_AS_ERROR_FLAG;

		if( framing_error == true )
			frame.mFlags |= FRAMING_ERROR_FLAG | DISPLAY_AS_ERROR_FLAG;

		if( mp_is_address == true )
			frame.mFlags |= MP_MODE_ADDRESS_FLAG;

		if( mp_is_address == true )
			mResults->CommitPacketAndStartNewPacket();

		mResults->AddFrame( frame );

		mResults->CommitResults();

		ReportProgress( frame.mEndingSampleInclusive );
		CheckIfThreadShouldExit();

		if( framing_error == true )  //if we're still low, let's fix that for the next round.
		{
			if( mSerial->GetBitState() == mBitLow )
				mSerial->AdvanceToNextEdge();
		}
	}
Esempio n. 26
0
status_t
POP3Protocol::RetrieveInternal(const char *command, int32 message,
	BPositionIO *write_to, bool post_progress)
{
	const int bufSize = 1024 * 30;

	// To avoid waiting for the non-arrival of the next data packet, try to
	// receive only the message size, plus the 3 extra bytes for the ".\r\n"
	// after the message.  Of course, if we get it wrong (or it is a huge
	// message or has lines starting with escaped periods), it will then switch
	// back to receiving full buffers until the message is done.
	int amountToReceive = MessageSize (message) + 3;
	if (amountToReceive >= bufSize || amountToReceive <= 0)
		amountToReceive = bufSize - 1;

	BString bufBString; // Used for auto-dealloc on return feature.
	char *buf = bufBString.LockBuffer (bufSize);
	int amountInBuffer = 0;
	int amountReceived;
	int testIndex;
	char *testStr;
	bool cont = true;
	bool flushWholeBuffer = false;
	write_to->Seek(0,SEEK_SET);

	if (SendCommand(command) != B_OK)
		return B_ERROR;

	struct timeval tv;
	tv.tv_sec = POP3_RETRIEVAL_TIMEOUT / 1000000;
	tv.tv_usec = POP3_RETRIEVAL_TIMEOUT % 1000000;

	struct fd_set readSet;
	FD_ZERO(&readSet);
	FD_SET(fSocket, &readSet);

	while (cont) {
		int result = 0;

#ifdef USE_SSL
		if (fUseSSL && SSL_pending(fSSL))
			result = 1;
		else
#endif
		result = select(fSocket + 1, &readSet, NULL, NULL, &tv);
		if (result == 0) {
			// No data available, even after waiting a minute.
			fLog = "POP3 timeout - no data received after a long wait.";
			return B_ERROR;
		}
		if (amountToReceive > bufSize - 1 - amountInBuffer)
			amountToReceive = bufSize - 1 - amountInBuffer;
#ifdef USE_SSL
		if (fUseSSL) {
			amountReceived = SSL_read(fSSL, buf + amountInBuffer,
				amountToReceive);
		} else
#endif
		amountReceived = recv(fSocket, buf + amountInBuffer, amountToReceive, 0);
		if (amountReceived < 0) {
			fLog = strerror(errno);
			return errno;
		}
		if (amountReceived == 0) {
			fLog = "POP3 data supposedly ready to receive but not received!";
			return B_ERROR;
		}

		amountToReceive = bufSize - 1; // For next time, read a full buffer.
		amountInBuffer += amountReceived;
		buf[amountInBuffer] = 0; // NUL stops tests past the end of buffer.

		// Look for lines starting with a period.  A single period by itself on
		// a line "\r\n.\r\n" marks the end of the message (thus the need for
		// at least five characters in the buffer for testing).  A period
		// "\r\n.Stuff" at the start of a line get deleted "\r\nStuff", since
		// POP adds one as an escape code to let you have message text with
		// lines starting with a period.  For convenience, assume that no
		// messages start with a period on the very first line, so we can
		// search for the previous line's "\r\n".

		for (testIndex = 0; testIndex <= amountInBuffer - 5; testIndex++) {
			testStr = buf + testIndex;
			if (testStr[0] == '\r' && testStr[1] == '\n' && testStr[2] == '.') {
				if (testStr[3] == '\r' && testStr[4] == '\n') {
					// Found the end of the message marker.  Ignore remaining data.
					if (amountInBuffer > testIndex + 5)
						printf ("POP3Protocol::RetrieveInternal Ignoring %d bytes "
							"of extra data past message end.\n",
							amountInBuffer - (testIndex + 5));
					amountInBuffer = testIndex + 2; // Don't include ".\r\n".
					buf[amountInBuffer] = 0;
					cont = false;
				} else {
					// Remove an extra period at the start of a line.
					// Inefficient, but it doesn't happen often that you have a
					// dot starting a line of text.  Of course, a file with a
					// lot of double period lines will get processed very
					// slowly.
					memmove (buf + testIndex + 2, buf + testIndex + 3,
						amountInBuffer - (testIndex + 3) + 1 /* for NUL at end */);
					amountInBuffer--;
					// Watch out for the end of buffer case, when the POP text
					// is "\r\n..X".  Don't want to leave the resulting
					// "\r\n.X" in the buffer (flush out the whole buffer),
					// since that will get mistakenly evaluated again in the
					// next loop and delete a character by mistake.
					if (testIndex >= amountInBuffer - 4 && testStr[2] == '.') {
						printf ("POP3Protocol::RetrieveInternal: Jackpot!  You have "
							"hit the rare situation with an escaped period at the "
							"end of the buffer.  Aren't you happy it decodes it "
							"correctly?\n");
						flushWholeBuffer = true;
					}
				}
			}
		}

		if (cont && !flushWholeBuffer) {
			// Dump out most of the buffer, but leave the last 4 characters for
			// comparison continuity, in case the line starting with a period
			// crosses a buffer boundary.
			if (amountInBuffer > 4) {
				write_to->Write(buf, amountInBuffer - 4);
				if (post_progress)
					ReportProgress(amountInBuffer - 4,0);
				memmove (buf, buf + amountInBuffer - 4, 4);
				amountInBuffer = 4;
			}
		} else { // Dump everything - end of message or flushing the whole buffer.
			write_to->Write(buf, amountInBuffer);
			if (post_progress)
				ReportProgress(amountInBuffer,0);
			amountInBuffer = 0;
		}
	}
	return B_OK;
}
Esempio n. 27
0
//------------------------------------------------------------------------------
void BatchEstimator::CheckCompletion()
{
   #ifdef WALK_STATE_MACHINE
      MessageInterface::ShowMessage("BatchEstimator state is CHECKINGRUN\n");
   #endif

   #ifdef DEBUG_VERBOSE
      MessageInterface::ShowMessage("\nCompleted iteration %d\n\n",
            iterationsTaken+1);
   #endif

   std::string convergenceReason = "";
   converged = TestForConvergence(convergenceReason);

   #ifdef RUN_SINGLE_PASS
      converged = true;
   #endif

   ++iterationsTaken;
   if ((converged) || (iterationsTaken >= maxIterations))
   {
      #ifdef DEBUG_VERBOSE
         if (converged)
            MessageInterface::ShowMessage("Estimation has converged\n%s\n\n",
                  convergenceReason.c_str());
         else
            MessageInterface::ShowMessage("Estimation has reached the maximum "
                  "iteration count, but has not converged\n\n");
      #endif
      currentState = FINISHED;
   }
   else
   {
      if (showAllResiduals)
         PlotResiduals();

      // Reset to the new initial state, clear the processed data, etc
      esm.RestoreObjects(&outerLoopBuffer);
      esm.MapVectorToObjects();
      esm.MapObjectsToSTM();
      currentEpoch = estimationEpoch;
      measManager.Reset();
      nextMeasurementEpoch = measManager.GetEpoch();

      // Need to reset STM and covariances
      hAccum.clear();
      if (useApriori)
         information = stateCovariance->GetCovariance()->Inverse();
      else
      {
         information.SetSize(stateSize, stateSize);
         for (UnsignedInt i = 0; i <  stateSize; ++i)
            for (UnsignedInt j = 0; j <  stateSize; ++j)
               information(i,j) = 0.0;
      }
      measurementResiduals.clear();
      measurementEpochs.clear();
      measurementResidualID.clear();

      for (UnsignedInt i = 0; i <  stateSize; ++i)
         for (UnsignedInt j = 0; j <  stateSize; ++j)
            if (i == j)
               (*stm)(i,j) = 1.0;
            else
               (*stm)(i,j) = 0.0;
      esm.MapSTMToObjects();

      for (Integer i = 0; i < information.GetNumRows(); ++i)
      {
         residuals[i] = 0.0;
         x0bar[i] -= dx[i];
      }
      if (useApriori)
         for (Integer i = 0; i < information.GetNumRows(); ++i)
         {
            for (UnsignedInt j = 0; j < stateSize; ++j)
            {
               residuals[i] += information(i,j) * x0bar[j];
            }
         }

      #ifdef DEBUG_VERBOSE
         MessageInterface::ShowMessage("Starting iteration %d\n\n",
               iterationsTaken+1);
      #endif

      #ifdef DEBUG_ITERATIONS
         MessageInterface::ShowMessage(
               "Init complete!\n   STM = %s\n   Covariance = %s\n",
               stm->ToString().c_str(), covariance->ToString().c_str());
      #endif

      WriteToTextFile();
      ReportProgress();

      if (GmatMathUtil::IsEqual(currentEpoch, nextMeasurementEpoch))
         currentState = CALCULATING;
      else
      {
         timeStep = (nextMeasurementEpoch - currentEpoch) *
               GmatTimeConstants::SECS_PER_DAY;
         currentState = PROPAGATING;
      }
   }
}
Esempio n. 28
0
status_t
POP3Protocol::Login(const char *uid, const char *password, int method)
{
	status_t err;

	BString error_msg;
	error_msg << MDR_DIALECT_CHOICE("Error while authenticating user ",
		"ユーザー認証中にエラーが発生しました ") << uid;

	if (method == 1) {	//APOP
		int32 index = fLog.FindFirst("<");
		if(index != B_ERROR) {
			ReportProgress(0, 0, MDR_DIALECT_CHOICE(
				"Sending APOP authentication...", "APOP認証情報を送信中..."));
			int32 end = fLog.FindFirst(">",index);
			BString timestamp("");
			fLog.CopyInto(timestamp, index, end - index + 1);
			timestamp += password;
			char md5sum[33];
			MD5Digest((unsigned char*)timestamp.String(), md5sum);
			BString cmd = "APOP ";
			cmd += uid;
			cmd += " ";
			cmd += md5sum;
			cmd += CRLF;

			err = SendCommand(cmd.String());
			if (err != B_OK) {
				error_msg << MDR_DIALECT_CHOICE(". The server said:\n",
					"サーバのメッセージです\n") << fLog;
				ShowError(error_msg.String());
				return err;
			}

			return B_OK;
		} else {
			error_msg << MDR_DIALECT_CHOICE(": The server does not support APOP.",
				"サーバはAPOPをサポートしていません");
			ShowError(error_msg.String());
			return B_NOT_ALLOWED;
		}
	}
	ReportProgress(0, 0, MDR_DIALECT_CHOICE("Sending username...",
		"ユーザーID送信中..."));

	BString cmd = "USER ";
	cmd += uid;
	cmd += CRLF;

	err = SendCommand(cmd.String());
	if (err != B_OK) {
		error_msg << MDR_DIALECT_CHOICE(". The server said:\n",
			"サーバのメッセージです\n") << fLog;
		ShowError(error_msg.String());
		return err;
	}

	ReportProgress(0, 0, MDR_DIALECT_CHOICE("Sending password...",
		"パスワード送信中..."));
	cmd = "PASS ";
	cmd += password;
	cmd += CRLF;

	err = SendCommand(cmd.String());
	if (err != B_OK) {
		error_msg << MDR_DIALECT_CHOICE(". The server said:\n",
			"サーバのメッセージです\n") << fLog;
		ShowError(error_msg.String());
		return err;
	}

	return B_OK;
}
void SimpleParallelAnalyzer::WorkerThread()
{
	mResults->AddChannelBubblesWillAppearOn( mSettings->mClockChannel );

	mSampleRateHz = GetSampleRate();

	AnalyzerResults::MarkerType clock_arrow;
	if( mSettings->mClockEdge == AnalyzerEnums::NegEdge )
		clock_arrow = AnalyzerResults::DownArrow;
	else
		clock_arrow = AnalyzerResults::UpArrow;


	mClock = GetAnalyzerChannelData( mSettings->mClockChannel );
	mData.clear();
	mDataMasks.clear();

	U32 count = mSettings->mDataChannels.size();
	for( U32 i=0; i<count; i++ )
	{
		if( mSettings->mDataChannels[i] != UNDEFINED_CHANNEL )
		{
			mData.push_back( GetAnalyzerChannelData( mSettings->mDataChannels[i] ) );
			mDataMasks.push_back( 1 << i );
			mDataChannels.push_back( mSettings->mDataChannels[i] );
		}
	}


	U32 num_data_lines = mData.size();

	if( mSettings->mClockEdge == AnalyzerEnums::NegEdge )
	{
		if( mClock->GetBitState() == BIT_LOW )
			mClock->AdvanceToNextEdge();
	}else
	{
		if( mClock->GetBitState() == BIT_HIGH )
			mClock->AdvanceToNextEdge();
	}


	mClock->AdvanceToNextEdge();  //this is the data-valid edge

	for( ; ; )
	{
		
		
		U64 sample = mClock->GetSampleNumber();
		mResults->AddMarker( sample, clock_arrow, mSettings->mClockChannel );

		U16 result = 0;

		for( U32 i=0; i<num_data_lines; i++ )
		{
			mData[i]->AdvanceToAbsPosition( sample );
			if( mData[i]->GetBitState() == BIT_HIGH )
			{
				result |= mDataMasks[i];
			}
			mResults->AddMarker( sample, AnalyzerResults::Dot, mDataChannels[i] );
		}	

		mClock->AdvanceToNextEdge(); 
		mClock->AdvanceToNextEdge();  //this is the data-valid edge

		//we have a byte to save. 
		Frame frame;
		frame.mData1 = result;
		frame.mFlags = 0;
		frame.mStartingSampleInclusive = sample;
		frame.mEndingSampleInclusive = mClock->GetSampleNumber() - 1;

		mResults->AddFrame( frame );
		mResults->CommitResults();
		ReportProgress( frame.mEndingSampleInclusive );
	}
}
Esempio n. 30
0
status_t
POP3Protocol::Open(const char *server, int port, int)
{
	ReportProgress(0, 0, MDR_DIALECT_CHOICE("Connecting to POP3 server...",
		"POP3サーバに接続しています..."));

	if (port <= 0) {
#ifdef USE_SSL
		port = fUseSSL ? 995 : 110;
#else
		port = 110;
#endif
	}

	fLog = "";

	// Prime the error message
	BString error_msg;
	error_msg << MDR_DIALECT_CHOICE("Error while connecting to server ",
		"サーバに接続中にエラーが発生しました ") << server;
	if (port != 110)
		error_msg << ":" << port;

	uint32 hostIP = inet_addr(server);
		// first see if we can parse it as a numeric address
	if (hostIP == 0 || hostIP == ~0UL) {
		struct hostent * he = gethostbyname(server);
		hostIP = he ? *((uint32*)he->h_addr) : 0;
	}

	if (hostIP == 0) {
		error_msg << MDR_DIALECT_CHOICE(": Connection refused or host not found",
			": :接続が拒否されたかサーバーが見つかりません");
		ShowError(error_msg.String());

		return B_NAME_NOT_FOUND;
	}

	fSocket = socket(AF_INET, SOCK_STREAM, 0);
	if (fSocket >= 0) {
		struct sockaddr_in saAddr;
		memset(&saAddr, 0, sizeof(saAddr));
		saAddr.sin_family = AF_INET;
		saAddr.sin_port = htons(port);
		saAddr.sin_addr.s_addr = hostIP;
		int result = connect(fSocket, (struct sockaddr *) &saAddr, sizeof(saAddr));
		if (result < 0) {
			close(fSocket);
			fSocket = -1;
			error_msg << ": " << strerror(errno);
			ShowError(error_msg.String());
			return errno;
		}
	} else {
		error_msg << ": Could not allocate socket.";
		ShowError(error_msg.String());
		return B_ERROR;
	}

#ifdef USE_SSL
	if (fUseSSL) {
		SSL_library_init();
		SSL_load_error_strings();
		RAND_seed(this,sizeof(POP3Protocol));
		/*--- Because we're an add-on loaded at an unpredictable time, all
			the memory addresses and things contained in ourself are
			esssentially random. */

		fSSLContext = SSL_CTX_new(SSLv23_method());
		fSSL = SSL_new(fSSLContext);
		fSSLBio = BIO_new_socket(fSocket, BIO_NOCLOSE);
		SSL_set_bio(fSSL, fSSLBio, fSSLBio);

		if (SSL_connect(fSSL) <= 0) {
			BString error;
			error << "Could not connect to POP3 server "
				<< fSettings.FindString("server");
			if (port != 995)
				error << ":" << port;
			error << ". (SSL connection error)";
			ShowError(error.String());
			SSL_CTX_free(fSSLContext);
			close(fSocket);
			return B_ERROR;
		}
	}
#endif

	BString line;
	status_t err = ReceiveLine(line);

	if (err < 0) {
		close(fSocket);
		fSocket = -1;
		error_msg << ": " << strerror(err);
		ShowError(error_msg.String());
		return B_ERROR;
	}

	if (strncmp(line.String(), "+OK", 3) != 0) {
		if (line.Length() > 0) {
			error_msg << MDR_DIALECT_CHOICE(". The server said:\n",
				"サーバのメッセージです\n") << line.String();
		} else
			error_msg << ": No reply.\n";

		ShowError(error_msg.String());
		return B_ERROR;
	}

	fLog = line;
	return B_OK;
}