public void ToggleIndex(GameObject Target) { string TargetName = Target.transform.parent.parent.gameObject.name; ProcessingState TargetState = null; foreach (var State in ProcessingStateList) { if (State.Title == TargetName) { TargetState = State; } } TargetState.Activated = !TargetState.Activated; Image TargetStateImage = Target.transform.parent.GetChild(1).gameObject.GetComponent <Image>(); if (TargetState.Activated) { TargetStateImage.color = new Color(1f, 1f, 1f, 0); } else { TargetStateImage.color = new Color(1f, 1f, 1f, 1f); } ClearAllGraph(); DrawGraph(); }
/// <summary> /// Processing for the excessive Decimal Separators.<para/> /// With caret managment. /// </summary> /// <param name="state"></param> private void DecimalSeparatorExcessiveProcessingWithCaret(ProcessingState state) { if (PartialDisabledCurrent) { return; } var separatorCount = state.Formatting.Text.Count(el => el == DecimalSeparator); if (separatorCount < 2) { return; } // Let's stay just the first decimal separator. var index = state.Formatting.Text.IndexOf(DecimalSeparator); state.Formatting.Text = state.Formatting.Text .Replace(DecimalSeparatorChar, String.Empty) .Insert(index, DecimalSeparatorChar); if (index + 1 < state.Formatting.CaretPosition) { state.Formatting.CaretPosition -= separatorCount - 1; } }
protected LanguageForgeProject(LfMergeSettingsIni settings, string projectCode) { _settings = settings; _projectCode = projectCode.ToLowerInvariant(); _state = ProcessingState.Deserialize(projectCode); IsInitialClone = false; }
public void CleanupAndRescheduleJobs_NothingToDo(ProcessingState.SendReceiveStates srState) { // Setup var state = new ProcessingState(TestContext.CurrentContext.Test.Name, _env.Settings) { SRState = srState }; state.Serialize(); // Execute var janitor = new Janitor(_env.Settings, _env.Logger); janitor.CleanupAndRescheduleJobs(); // Verify var queue = Queue.GetQueue(QueueNames.Synchronize); Assert.That(queue.IsEmpty, Is.True); var newState = ProcessingState.Deserialize(TestContext.CurrentContext.Test.Name); Assert.That(newState.SRState, Is.EqualTo(srState)); Assert.That(_exceptionLoggingDouble.Exceptions.Count, Is.EqualTo(0)); }
/// <summary> /// Delegates <c>WriteEndElement</c> calls when the element's prefix does not /// match a zip command. /// Otherwise, close the archive or flush the delegate writer. /// </summary> public override void WriteEndElement() { Node elt = (Node)elements.Pop(); if (!elt.Ns.Equals(ZIP_POST_PROCESS_NAMESPACE)) { Debug.WriteLine("delegate - </" + elt.Name + ">"); if (delegateWriter != null) { delegateWriter.WriteEndElement(); } } else { switch (elt.Name) { case ARCHIVE_ELEMENT: if (zipOutputStream != null) { // Copy binaries before closing the archive CopyBinaries(); Debug.WriteLine("[closing archive]"); zipOutputStream.Close(); zipOutputStream = null; } if (processingState == ProcessingState.EntryWaiting) { processingState = ProcessingState.None; } break; case PART_ELEMENT: if (delegateWriter != null) { Debug.WriteLine("[end part]"); delegateWriter.WriteEndDocument(); delegateWriter.Flush(); delegateWriter.Close(); delegateWriter = null; } if (processingState == ProcessingState.EntryStarted) { processingState = ProcessingState.EntryWaiting; } break; case COPY_ELEMENT: if (binarySource != null && binaryTarget != null) { if (binaries != null && !binaries.ContainsKey(binarySource)) { binaries.Add(binarySource, binaryTarget); } binarySource = null; binaryTarget = null; } break; } } }
public void CleanupAndRescheduleJobs_UnknownState(ProcessingState.SendReceiveStates srState) { // Setup var testName = TestContext.CurrentContext.Test.Name; var state = new ProcessingState(testName, _env.Settings) { SRState = srState }; state.Serialize(); // Execute var janitor = new Janitor(_env.Settings, _env.Logger); janitor.CleanupAndRescheduleJobs(); // Verify var queue = Queue.GetQueue(QueueNames.Synchronize); Assert.That(queue.QueuedProjects, Is.EqualTo(new[] { testName })); var newState = ProcessingState.Deserialize(testName); Assert.That(newState.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.IDLE)); Assert.That(_exceptionLoggingDouble.Exceptions.Count, Is.EqualTo(1)); var report = _exceptionLoggingDouble.Exceptions[0]; Assert.That(report.OriginalException, Is.TypeOf <ProjectInUncleanStateException>()); Assert.That(report.OriginalException.Message, Is.EqualTo("QueueManager detected unknown state '42' for project 'CleanupAndRescheduleJobs_UnknownState(42)'; rescheduled")); }
void notify(ProcessingState state) { if (NotificationEventHandler != null) { NotificationEventHandler.Invoke(this, new RunProgramBeforeOrAfterBackupEventArgs(_taskInfo, state)); } }
/// <summary> /// Restores the Decimal Separator if it lost and manage caret position. /// <seealso cref="DecimalSeparatorMissed"/> /// </summary> /// <param name="state"></param> private void DecimalSeparatorDeletedProcessingWithCaret(ProcessingState state) { if (PartialDisabledCurrent) { return; } if (state.FormattingType != FormattingAfter.OneSymbolDeleted) { return; } // Restoring of the Decimal Separator and carret promotion. // The Decimal Separator delition means onle caret promotion. var wasDeletedSeparator = state.Formatting.Text.Contains(DecimalSeparator) == false; if (wasDeletedSeparator == false) { return; } state.Formatting.Text = state.Formatting.Text.Insert(state.Formatting.CaretPosition, DecimalSeparatorChar); if (state.OneSymbolDeletionType == DeletionDirection.DeleteButton) { state.Formatting.CaretPosition++; } }
public void Deserialize_ValidStateFile_MatchesState() { var expectedState = new ProcessingState("ProjC", _env.Settings) { SRState = ProcessingState.SendReceiveStates.SYNCING, PercentComplete = 30, ElapsedTimeSeconds = 40, TimeRemainingSeconds = 50, TotalSteps = 3, CurrentStep = 2, RetryCounter = 1, UncommittedEditCounter = 0 }; expectedState.LastStateChangeTicks = 635683277459459160; // Make sure this gets set last so the value isn't UtcNow.Ticks const string json = "{\"SRState\":\"SYNCING\",\"LastStateChangeTicks\":635683277459459160," + "\"PercentComplete\":30,\"ElapsedTimeSeconds\":40,\"TimeRemainingSeconds\":50," + "\"TotalSteps\":3,\"CurrentStep\":2,\"RetryCounter\":1,\"UncommittedEditCounter\":0," + "\"ErrorMessage\":null,\"ErrorCode\":0,\"ProjectCode\":\"ProjC\"}"; Directory.CreateDirectory(_env.Settings.StateDirectory); var filename = _env.Settings.GetStateFileName("ProjC"); File.WriteAllText(filename, json); var state = ProcessingState.Deserialize("ProjC"); Assert.That(state, Is.EqualTo(expectedState)); }
public void CleanupAndRescheduleJobs() { foreach (var file in Directory.EnumerateFiles(Settings.StateDirectory)) { var projectCode = Path.GetFileNameWithoutExtension(file); var state = ProcessingState.Deserialize(projectCode); switch (state.SRState) { case ProcessingState.SendReceiveStates.CLONED: case ProcessingState.SendReceiveStates.IDLE: case ProcessingState.SendReceiveStates.HOLD: case ProcessingState.SendReceiveStates.ERROR: // Nothing to do break; case ProcessingState.SendReceiveStates.CLONING: case ProcessingState.SendReceiveStates.SYNCING: RescheduleProject(projectCode, state, string.Format("QueueManager detected project '{0}' in unclean state '{1}'; rescheduled", projectCode, state.SRState)); break; default: RescheduleProject(projectCode, state, string.Format("QueueManager detected unknown state '{0}' for project '{1}'; rescheduled", state.SRState, projectCode)); break; } } }
private static void InitOggStream(int sampleRate, int channels, out OggStream oggStream, out ProcessingState processingState) { // Stores all the static vorbis bitstream settings var info = VorbisInfo.InitVariableBitRate(channels, sampleRate, 0.5f); // set up our packet->stream encoder var serial = new Random().Next(); oggStream = new OggStream(serial); // ========================================================= // HEADER // ========================================================= // Vorbis streams begin with three headers; the initial header (with // most of the codec setup parameters) which is mandated by the Ogg // bitstream spec. The second header holds any comment fields. The // third header holds the bitstream codebook. var comments = new Comments(); comments.AddTag("ARTIST", "TTS"); var infoPacket = HeaderPacketBuilder.BuildInfoPacket(info); var commentsPacket = HeaderPacketBuilder.BuildCommentsPacket(comments); var booksPacket = HeaderPacketBuilder.BuildBooksPacket(info); oggStream.PacketIn(infoPacket); oggStream.PacketIn(commentsPacket); oggStream.PacketIn(booksPacket); // ========================================================= // BODY (Audio Data) // ========================================================= processingState = ProcessingState.Create(info); }
public ThreadExecuteTask(ExecuteMeOnAnotherThread functionToCall) { //Create an object we can use for a lock for the //state-machine transition function m_useForStateMachineLock = new Object(); //Mark our execution as ready to start m_processingState = ProcessingState.notYetStarted; //Store the function we are supposed to call on the new //thread m_CallFunction = functionToCall; //------------------------------------------------------ //Create a new thread and have it start executing on: // this.ThreadStartPoint() //------------------------------------------------------ System.Threading.ThreadStart threadStart; threadStart = new System.Threading.ThreadStart(ThreadStartPoint); workerThread = new System.Threading.Thread(threadStart); //Mark our execution as ready to start (for determinism, //it is important to do this before we start the thread!) setProcessingState(ProcessingState.waitingToStartAsync); //Tell the OS to start our new thread async. workerThread.Start(); //Return control to the caller on this thread }
public void Deserialize_NonexistingStateFile_ReturnsCloning() { var state = ProcessingState.Deserialize("ProjB"); Assert.That(state.ProjectCode, Is.EqualTo("ProjB")); Assert.That(state.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.CLONING)); }
public void Convert(string inputFile, string outputFile) { using (var outputStream = File.Create(outputFile)) { var channels = AudioSampleReader.ReadChannels(inputFile, out var waveFormat); var oggStream = new OggStream(StaticRandom.Rng.Next()); // Build header var headerBuilder = new HeaderPacketBuilder(); var audioInfo = VorbisInfo.InitVariableBitRate(channels.Count, waveFormat.SampleRate, 0.1f); var infoPacket = headerBuilder.BuildInfoPacket(audioInfo); var commentsPacket = headerBuilder.BuildCommentsPacket(new Comments()); var booksPacket = headerBuilder.BuildBooksPacket(audioInfo); oggStream.PacketIn(infoPacket); oggStream.PacketIn(commentsPacket); oggStream.PacketIn(booksPacket); WriteHeader(oggStream, outputStream); // Store audio var processingState = ProcessingState.Create(audioInfo); var normalizedChannels = Normalize(channels); processingState.WriteData(normalizedChannels, normalizedChannels[0].Length); processingState.WriteEndOfStream(); WriteAudio(oggStream, outputStream, processingState); } }
private void RequireState(ProcessingState state) { if (this.processingState != state) { GotoState(state); } }
public virtual void BeginPolygon() { RequireState(ProcessingState.Dormant); processingState = ProcessingState.InPolygon; cacheCount = 0; emptyCache = false; mesh = null; }
public static IPossibleState GetProcessingStateInstance() { if (processing == null) { processing = new ProcessingState(); } return(processing); }
private void RescheduleProject(string projectCode, ProcessingState state, string message) { Logger.Error(message); ExceptionLogging.Client.Notify(new ProjectInUncleanStateException(message)); state.SRState = ProcessingState.SendReceiveStates.IDLE; state.Serialize(); Queue.GetQueue(QueueNames.Synchronize).EnqueueProject(projectCode); }
public LatencyTimeoutAttributeFacts() { var state = new ProcessingState("Default", "1"); _context = new ElectStateContextMock(); _context.ApplyContext.BackgroundJob.Id = JobId; _context.ApplyContext.NewStateObject = state; }
/// <summary> /// VorbisFileWriter that actually writes to a stream /// </summary> /// <param name="outStream">Stream to be written to</param> /// <param name="sampleRate">The sample rate to use</param> /// <param name="channels">The number of channels to use</param> /// <param name="quality">The base quality for Vorbis encoding</param> public VorbisFileWriter(Stream outStream, int sampleRate, int channels, float quality = 0.5f) { this.outStream = outStream; SampleRate = sampleRate; Channels = channels; if (!startBuffers.ContainsKey(sampleRate)) { throw new InvalidOperationException($"Vorbis writer does not support {sampleRate} sample rate."); } // Stores all the static vorbis bitstream settings Console.WriteLine($"Initiating variable bit rate: {channels} channels, {sampleRate} sample rate, {quality} quality"); var info = VorbisInfo.InitVariableBitRate(channels, sampleRate, quality); // set up our packet->stream encoder var serial = MainWindow.MainRandom.Next(); oggStream = new OggStream(serial); // ========================================================= // HEADER // ========================================================= // Vorbis streams begin with three headers; the initial header (with // most of the codec setup parameters) which is mandated by the Ogg // bitstream spec. The second header holds any comment fields. The // third header holds the bitstream codebook. var headerBuilder = new HeaderPacketBuilder(); var comments = new Comments(); var infoPacket = headerBuilder.BuildInfoPacket(info); var commentsPacket = headerBuilder.BuildCommentsPacket(comments); var booksPacket = headerBuilder.BuildBooksPacket(info); oggStream.PacketIn(infoPacket); oggStream.PacketIn(commentsPacket); oggStream.PacketIn(booksPacket); // Flush to force audio data onto its own page per the spec FlushPages(oggStream, outStream, true); // ========================================================= // BODY (Audio Data) // ========================================================= processingState = ProcessingState.Create(info); // Append some zeros at the start so the result has the same length as the input int bufferSize = startBuffers[sampleRate]; float[][] outSamples = new float[channels][]; for (int ch = 0; ch < channels; ch++) { outSamples[ch] = new float[bufferSize]; } processingState.WriteData(outSamples, bufferSize); }
/// <summary> /// Queues a message for processing by the session /// </summary> /// <param name="message">The message to process</param> public void QueueMessage(IMessage message) { _messageQueue.Enqueue(message); if (_state == ProcessingState.Idle) { ThreadPool.QueueUserWorkItem(_processingCallback); _state = ProcessingState.ProcessingQueued; } }
void OnImagesFinished() { m_state = ProcessingState.DoneProcessing; m_btnFinish.Content = "Finish"; m_tbDesc.Visibility = System.Windows.Visibility.Collapsed; m_tbFinishedDesc.Visibility = System.Windows.Visibility.Visible; m_stackProgress.Visibility = System.Windows.Visibility.Collapsed; m_lblProgress.Content = ""; }
public Tesselator() { /* Only initialize fields which can be changed by the api. Other fields * are initialized where they are used. */ _processingState = ProcessingState.Dormant; _windingRule = Tesselator.WindingRuleType.Odd;//default _boundaryOnly = false; }
public readonly List <int[]> outerProductPermutations = new List <int[]>(); // To keep sample concise public override bool DoBeforeLoop() { if (ProcessingState.IsInnermostLoop) { //Log (CollectionToSequenceString (ProcessingState.DimensionIndices)); outerProductPermutations.Add(ProcessingState.GetDimensionIndicesCopy()); } return(true); }
private static void ProcessChunk(float[][] floatSamples, ProcessingState processingState, OggStream oggStream, int writeBufferSize) { processingState.WriteData(floatSamples, writeBufferSize, 0); while (!oggStream.Finished && processingState.PacketOut(out OggPacket packet)) { oggStream.PacketIn(packet); } }
/// <summary> /// Processing of the partial part of a number. /// </summary> /// <param name="state"></param> /// <returns></returns> private void PartialPartProcessingWithCaret(ProcessingState state) { if (PartialDisabledCurrent) { return; } // After the decimal separator should be two digits for now (PartialBitness is not implemented). var decimalSeparatorPosition = state.Formatting.Integer.InvokeNotNull(el => el.Length) + DecimalSeparatorChar.Length; if (state.Formatting.Partial.Length == 0) { state.Formatting.Partial = ZerosPartialString; } else if (state.Formatting.Partial.Length == 1) { if (state.Formatting.CaretPosition == decimalSeparatorPosition && state.OneSymbolDeletionType == DeletionDirection.BackspaceButton) { state.Formatting.Partial = ZeroString + state.Formatting.Partial; } else if (state.Formatting.CaretPosition == decimalSeparatorPosition && state.OneSymbolDeletionType == DeletionDirection.DeleteButton) { if (state.PartialPrevious.StartsWith(ZeroString)) { state.Formatting.Partial = ZerosPartialString; } else { state.Formatting.Partial = ZeroString + state.Formatting.Partial; } } else { state.Formatting.Partial = state.Formatting.Partial + ZeroString; } } else if (2 < state.Formatting.Partial.Length) { var needCutSecondPartialDigit = state.Formatting.Partial.Length == 3 && state.Formatting.CaretPosition == (decimalSeparatorPosition + 1); if (needCutSecondPartialDigit) { state.Formatting.Partial = state.Formatting.Partial.Remove(1, 1); } else { state.Formatting.Partial = state.Formatting.Partial.Substring(0, 2); } } }
/// <summary> /// The Constructor /// </summary> /// <param name="taskInfo">The task is served now</param> /// <param name="state">The state of an operation</param> /// <exception cref="ArgumentNullException">taskInfo is null</exception> public RunProgramBeforeOrAfterBackupEventArgs(BackupEventTaskInfo taskInfo, ProcessingState state) : base() { if (taskInfo == null) { throw new ArgumentNullException("taskInfo"); } _taskInfo = taskInfo; _state = state; }
public void JsonSerialize_ReturnsCorrectString_After170() { var state = new ProcessingState("server1", "worker1"); var serialized = SerializationHelper.Serialize <IState>(state, SerializationOption.TypedInternal); Assert.Equal( "{\"$type\":\"Hangfire.States.ProcessingState, Hangfire.Core\",\"ServerId\":\"server1\"," + "\"WorkerId\":\"worker1\"}", serialized); }
public Tesselator() { /* Only initialize fields which can be changed by the api. Other fields * are initialized where they are used. */ this.processingState = ProcessingState.Dormant; this.windingRule = WindingRuleType.NonZero; this.boundaryOnly = false; }
public void BeginContour() { RequireState(ProcessingState.InPolygon); processingState = ProcessingState.InContour; lastHalfEdge = null; if (cacheCount > 0) { // Just set a flag so we don't get confused by empty contours emptyCache = true; } }
public void SetErrorState_MissingMessage() { // Setup var sut = new ProcessingState("proja", _env.Settings) { SRState = ProcessingState.SendReceiveStates.IDLE }; // Exercise/Verify Assert.That(() => sut.SetErrorState(ProcessingState.SendReceiveStates.ERROR, ProcessingState.ErrorCodes.EmptyProject, null), Throws.Exception.TypeOf <ArgumentNullException>()); }
public void State(ActionNames actionName, ProcessingState.SendReceiveStates expectedState) { // Setup var lfProj = LanguageForgeProject.Create(_env.Settings, "proja"); var sut = Action.GetAction(actionName); // Exercise sut.Run(lfProj); // Verify Assert.That(ProcessState.SavedStates, Is.EqualTo(new[] { expectedState })); Assert.That(lfProj.State.SRState, Is.EqualTo(expectedState)); }
public DataProcessor(MainForm parent) { owner = parent; majorSoftwareVersion = 0x00; minorSoftwareVersion = 0x00; messageIdHighByte = 0x00; messageIdLowByte = 0x00; payloadLength = 0x00; payloadPosition = 0x00; CRC_BYTE_0 = 0x00; CRC_BYTE_1 = 0x00; currentState = (int)ProcessingState.WAITING_FOR_START_OF_HEADER; currentCRC = 0; crcCheckFails = 0; }
public void State_SettingProperty_SerializesState() { // Setup var sut = new ProcessingState("proja", _env.Settings) { SRState = ProcessingState.SendReceiveStates.SYNCING, PercentComplete = 50, ElapsedTimeSeconds = 10, TimeRemainingSeconds = 20, TotalSteps = 5, CurrentStep = 1, RetryCounter = 2, UncommittedEditCounter = 0, }; // Exercise sut.SRState = ProcessingState.SendReceiveStates.SYNCING; // Have to calculate the expected value AFTER setting the state var expectedJson = string.Format(@"{{ ""SRState"": ""{0}"", ""LastStateChangeTicks"": {1}, ""StartTimestamp"": 0, ""PercentComplete"": 50, ""ElapsedTimeSeconds"": 10, ""TimeRemainingSeconds"": 20, ""TotalSteps"": 5, ""CurrentStep"": 1, ""RetryCounter"": 2, ""UncommittedEditCounter"": 0, ""ErrorMessage"": null, ""ErrorCode"": 0, ""PreviousRunTotalMilliseconds"": 0, ""ProjectCode"": ""proja"" }}", ProcessingState.SendReceiveStates.SYNCING, sut.LastStateChangeTicks); // Verify Directory.CreateDirectory(_env.Settings.StateDirectory); var filename = _env.Settings.GetStateFileName("proja"); Assert.That(File.ReadAllText(filename), Is.EqualTo(expectedJson)); }
/// <summary> /// Function invoked on a thread pool thread to handle incoming messages /// </summary> /// <param name="nothing">The state, which is nothing</param> private void _processMessages(object nothing) { _state = ProcessingState.Processing; while (_messageQueue.Count > 0) { var message = _messageQueue.Dequeue(); try { _processMessage(message); } catch (Exception ex) { Console.WriteLine(ex); } } _state = ProcessingState.Idle; }
private void RequireState(ProcessingState state) { if (processingState != state) { GotoState(state); } }
public void ProcessData(byte[] data) { byte dataCrcHighByte, dataCrcLowByte; for (int i = 0; i < data.Length; i++) { switch (currentState) { case ProcessingState.WAITING_FOR_START_OF_HEADER: if (data[i] == START_OF_HEADER) { currentCRC = XModemCRC.CalculateCRC(data[i], 0); currentState = ProcessingState.WAITING_FOR_SYSTEM_ID; } break; case ProcessingState.WAITING_FOR_SYSTEM_ID: if (data[i] == SYSTEM_ID) { currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_SUBSYSTEM_ID; } else { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_SUBSYSTEM_ID: if (data[i] == SUBSYSTEM_ID) { currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_NODE_ID; } else { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_NODE_ID: if (data[i] == NODE_ID) { currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_COMPONENT_ID; } else { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_COMPONENT_ID: if (data[i] == COMPONENT_ID) { currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_MAJOR_SOFTWARE_VERSION; } else { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_MAJOR_SOFTWARE_VERSION: if (data[i] <= MAJOR_SOFTWARE_VERSION) { majorSoftwareVersion = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_MINOR_SOFTWARE_VERSION; } else { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_MINOR_SOFTWARE_VERSION: if ((majorSoftwareVersion == MAJOR_SOFTWARE_VERSION && data[i] <= MINOR_SOFTWARE_VERSION) || (majorSoftwareVersion < MAJOR_SOFTWARE_VERSION)) { minorSoftwareVersion = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_MESSAGE_ID_0; } else//if majorSoftwareVersion == MAJOR_SOFTWARE_VERSION && minorSoftwareVersion > MINOR_SOFTWARE_VERSION { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_MESSAGE_ID_0: messageIdHighByte = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_MESSAGE_ID_1; break; case ProcessingState.WAITING_FOR_MESSAGE_ID_1: messageIdLowByte = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_PAYLOAD_LENGTH; break; case ProcessingState.WAITING_FOR_PAYLOAD_LENGTH: payloadLength = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); if(payloadLength > 0) { payload = new byte[payloadLength]; payloadPosition = 0; currentState = ProcessingState.PROCESSING_PAYLOAD; } else //payloadLength == 0 { payload = null; currentState = ProcessingState.WAITING_FOR_CRC_BYTE_0; } break; case ProcessingState.PROCESSING_PAYLOAD: payload[payloadPosition++] = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); if(payloadPosition >= payloadLength) { currentState = ProcessingState.WAITING_FOR_CRC_BYTE_0; } break; case ProcessingState.WAITING_FOR_CRC_BYTE_0: CRC_BYTE_0 = data[i]; currentState = ProcessingState.WAITING_FOR_CRC_BYTE_1; break; case ProcessingState.WAITING_FOR_CRC_BYTE_1: CRC_BYTE_1 = data[i]; dataCrcHighByte = (byte)(currentCRC >> 8); dataCrcLowByte = (byte)(currentCRC & 0x00FF); if((dataCrcHighByte == CRC_BYTE_0) && (dataCrcLowByte == CRC_BYTE_1)) { owner.LogData(new Message(majorSoftwareVersion, minorSoftwareVersion, messageIdHighByte, messageIdLowByte, payload)); } else //Failed CRC Check { crcCheckFails++; } currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; break; default: MessageBox.Show("Unexpected Default Case in Process Data"); break; } } }
ProcessingState processingState; /* what begin/end calls have we seen? */ #endregion Fields #region Constructors public Tesselator() { /* Only initialize fields which can be changed by the api. Other fields * are initialized where they are used. */ this.processingState = ProcessingState.Dormant; this.windingRule = Tesselator.WindingRuleType.NonZero; this.boundaryOnly = false; }
void Step(int n) { PrintDebugLog("LSystem::Step() - Starting string construction."); currentState = ProcessingState.ConstructingString; for (int j = 0; j < n; j++) { currentStep = j + 1; Interpreter interp = (Interpreter)symbols[0].interpreter; if (interp != null) interp.EmptyValues(); if (current == "") current = axiom; string newCurrent = ""; for (int i = 0; i < current.Length; i++) { currentChar = i; try { newCurrent += ApplyRules(current, i); } catch (ArgumentOutOfRangeException e) { PrintDebugLog("LSystem::Step() - Error on applying rules: " + e); } } current = newCurrent; stringLength = current.Length; } PrintDebugLog("LSystem::Step() - String construction finished."); currentState = ProcessingState.CallingInterpreter; CallInterpreter(); }
void CallInterpreter() { currentState = ProcessingState.None; PrintDebugLog("LSystem::Step() - Starting the interpreter calls."); for (int i = 0; i < current.Length; i++) { currentChar = i; stringLength = current.Length; Symbol s = CharToSymbol(current[i]); if (s != null && s.interpreterMethod != "Null") { typeof(Interpreter) .GetMethod(s.interpreterMethod, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) .Invoke(s.interpreter, new object[0]); //sInterp.SendMessage(s.interpreterMethod, SendMessageOptions.DontRequireReceiver); } } PrintDebugLog("LSystem::Step() - The interpreter calls finished."); }
internal void ProcessLine(string line) { switch(state) { case ProcessingState.RequestLine: { string[] protocol = line.Split(' '); if(protocol.Length != 3) { RequestError("400", "Invalid protocol string"); return; } switch(protocol[0]) { case "GET": case "POST": case "HEAD": method = protocol[0]; break; case "PUT": case "DELETE": case "OPTIONS": case "TRACE": default: RequestError("501", StatusCodes.GetDescription("501")); return; } if(protocol[1].Length > 2500) { RequestError("414", StatusCodes.GetDescription("414")); return; } requestUri = protocol[1]; if(!protocol[2].StartsWith("HTTP/") || !(protocol[2].Length > "HTTP/".Length)) { RequestError("400", "Invalid protocol string"); return; } httpVersion = protocol[2].Substring("HTTP/".Length); date = DateTime.Now; connMode = httpVersion == "1.0" ? ConnectionMode.Close : ConnectionMode.KeepAlive; state = ProcessingState.Headers; break; } case ProcessingState.Headers: { if(headers.Count > maxHeaderLines) { RequestError("400", "Maximum header line count exceeded"); return; } if(line.Length == 0) { PostProcessHeaders(); return; } int colonIndex = line.IndexOf(":"); if(colonIndex <= 1) return; string val = line.Substring(colonIndex + 1).Trim(); string name = line.Substring(0, colonIndex); try { headers.Add(name, val); } catch { } switch(name.ToLower(CultureInfo.InvariantCulture)) { case "host": host = val; break; case "authorization": { if(val.Length < 6) break; string encoded = val.Substring(6, val.Length - 6); byte[] byteAuth; try { byteAuth = Convert.FromBase64String(encoded); } catch(FormatException) { break; } string[] strings = Encoding.UTF8.GetString(byteAuth).Split(':'); if(strings.Length != 2) break; username = strings[0]; password = strings[1]; break; } case "content-type": contentType = val; break; case "content-length": try { contentLength = long.Parse(val, NumberStyles.Integer, CultureInfo.InvariantCulture); } catch(FormatException) { } if(contentLength > client.server.MaxPostLength) { RequestError("413", StatusCodes.GetDescription("413")); return; } else if(contentLength < 0) { RequestError("400", StatusCodes.GetDescription("400")); return; } break; case "accept": accept = val; break; case "accept-language": acceptLanguage = val; break; case "user-agent": userAgent = val; break; case "connection": if(string.Compare(val, "close", true, CultureInfo.InvariantCulture) == 0) connMode = ConnectionMode.Close; else connMode = ConnectionMode.KeepAlive; break; case "if-modified-since": try { ifModifiedSince = ParseHttpTime(val); } catch(FormatException) { } break; case "if-unmodified-since": try { ifUnmodifiedSince = ParseHttpTime(val); } catch(FormatException) { } break; case "range": try { string[] rangeStrings = val.Split(','); this.ranges = new ByteRange[rangeStrings.Length]; for(int i = 0; i < rangeStrings.Length; i++) ranges[i] = new ByteRange(rangeStrings[i]); } catch(FormatException) { this.ranges = null; } break; default: break; } break; } } }
void RequireState(ProcessingState state) { if(this.processingState != state ) { GotoState(state); } }
/// <summary> /// Processes the request text received so far. /// </summary> void ProcessRequestText() { if (processingComplete) return; switch (processingState) { case ProcessingState.InitialLine: { var lfIndex = requestText.IndexOf("\n"); if (lfIndex > -1) { var initialLine = requestText.Substring(0, lfIndex + 1).Trim(); requestText = requestText.Substring(lfIndex + 1); ParseInitialLine(initialLine); if (!processingComplete) { processingState = ProcessingState.Headers; ProcessRequestText(); } } } break; case ProcessingState.Headers: { var lfIndex = requestText.IndexOf("\n"); while (lfIndex > -1) { var line = requestText.Substring(0, lfIndex + 1).Trim(); if (line == "") { processingState = ProcessingState.Body; break; } requestText = requestText.Substring(lfIndex + 1); ParseHeader(line); if (processingComplete) return; lfIndex = requestText.IndexOf("\n"); } if (processingState == ProcessingState.Body) { // determine if a body should be read or not if ((request.Method == HttpMethod.POST || request.Method == HttpMethod.PUT || request.Method == HttpMethod.PATCH) && request.Headers.ContainsKey("Content-Length")) { // body required InitRequestBody(); } else { // done reading processingComplete = true; if (ReadComplete != null) ReadComplete(request); } } } break; } }
void GotoState(ProcessingState newProcessingState) { while (this.processingState != newProcessingState) { /* We change the current state one level at a time, to get to * the desired state. */ if (this.processingState < newProcessingState) { switch (this.processingState) { case ProcessingState.Dormant: throw new Exception("MISSING_BEGIN_POLYGON"); case ProcessingState.InPolygon: throw new Exception("MISSING_BEGIN_CONTOUR"); default: break; } } else { switch (this.processingState) { case ProcessingState.InContour: throw new Exception("MISSING_END_CONTOUR"); case ProcessingState.InPolygon: throw new Exception("MISSING_END_POLYGON"); default: break; } } } }
/// <summary> /// Raises the <see cref="ProcessingStateChanged"/> event. /// </summary> /// <param name="state">The <see cref="ProcessingState"/>.</param> /// <remarks></remarks> protected virtual void OnProcessingStateChanged(ProcessingState state) { if (state == State) return; EventHandler<ProcessingStateEventArgs> handler = ProcessingStateChanged; if (handler != null) handler(this, new ProcessingStateEventArgs(state)); }
public void EndPolygon() { RequireState(ProcessingState.InPolygon); processingState = ProcessingState.Dormant; if (this.mesh == null) { if (!this.EdgeCallBackSet && this.callMesh == null) { /* Try some special code to make the easy cases go quickly * (eg. convex polygons). This code does NOT handle multiple contours, * intersections, edge flags, and of course it does not generate * an explicit mesh either. */ if (RenderCache()) { return; } } EmptyCache(); /* could've used a label*/ } /* Determine the polygon normal and project vertices onto the plane * of the polygon. */ ProjectPolygon(); /* __gl_computeInterior( this ) computes the planar arrangement specified * by the given contours, and further subdivides this arrangement * into regions. Each region is marked "inside" if it belongs * to the polygon, according to the rule given by this.windingRule. * Each interior region is guaranteed to be monotone. */ ActiveRegion.ComputeInterior(this); bool rc = true; /* If the user wants only the boundary contours, we throw away all edges * except those which separate the interior from the exterior. * Otherwise we tessellate all the regions marked "inside". */ if (this.boundaryOnly) { rc = this.mesh.SetWindingNumber(1, true); } else { rc = this.mesh.TessellateInterior(); } this.mesh.CheckMesh(); if (this.callBegin != null || this.callEnd != null || this.callVertex != null || this.callEdgeFlag != null) { if (this.boundaryOnly) { RenderBoundary(mesh); /* output boundary contours */ } else { RenderMesh(mesh); /* output strips and fans */ } } if (this.callMesh != null) { /* Throw away the exterior faces, so that all faces are interior. * This way the user doesn't have to check the "inside" flag, * and we don't need to even reveal its existence. It also leaves * the freedom for an implementation to not generate the exterior * faces in the first place. */ mesh.DiscardExterior(); callMesh(mesh); /* user wants the mesh itself */ this.mesh = null; return; } this.mesh = null; }
public void EndContour() { RequireState(ProcessingState.InContour); processingState = ProcessingState.InPolygon; }
public void State_SettingProperty_ChangesLastStateChangeTicks() { // Setup var sut = new ProcessingState("proja", _env.Settings) { SRState = ProcessingState.SendReceiveStates.IDLE, }; var oldTicks = sut.LastStateChangeTicks; // Exercise sut.SRState = ProcessingState.SendReceiveStates.SYNCING; // Have to calculate the expected value AFTER setting the state var newTicks = sut.LastStateChangeTicks; // Verify Assert.That(newTicks, Is.GreaterThan(oldTicks)); }
public void Serialization_Roundtrip() { var expectedState = new ProcessingState("ProjA", _env.Settings) { SRState = ProcessingState.SendReceiveStates.SYNCING, LastStateChangeTicks = DateTime.Now.Ticks, PercentComplete = 50, ElapsedTimeSeconds = 10, TimeRemainingSeconds = 20, TotalSteps = 5, CurrentStep = 1, RetryCounter = 2, UncommittedEditCounter = 0 }; expectedState.Serialize(); var state = ProcessingState.Deserialize("ProjA"); Assert.That(state, Is.EqualTo(expectedState)); }
public int ProcessData(byte[] data) { busy = true; //TODO - take these out and turn functions back into void function DateTime timestamp1 = DateTime.Now; DateTime timestamp2; byte dataCrcHighByte, dataCrcLowByte; for (int i = 0; i < data.Length; i++) { switch (currentState) { case ProcessingState.WAITING_FOR_START_OF_HEADER: if (data[i] == START_OF_HEADER) { timestamp = DateTime.Now; currentCRC = XModemCRC.CalculateCRC(data[i], 0); currentState = ProcessingState.WAITING_FOR_SYSTEM_ID; } break; case ProcessingState.WAITING_FOR_SYSTEM_ID: if (data[i] == SYSTEM_ID) { currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_SUBSYSTEM_ID; } else { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_SUBSYSTEM_ID: if (data[i] == SUBSYSTEM_ID) { currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_NODE_ID; } else { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_NODE_ID: if (data[i] == NODE_ID) { currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_COMPONENT_ID; } else { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_COMPONENT_ID: if (data[i] == COMPONENT_ID) { currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_MAJOR_SOFTWARE_VERSION; } else { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_MAJOR_SOFTWARE_VERSION: if (data[i] <= MAJOR_SOFTWARE_VERSION) { majorSoftwareVersion = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_MINOR_SOFTWARE_VERSION; } else { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_MINOR_SOFTWARE_VERSION: if ((majorSoftwareVersion == MAJOR_SOFTWARE_VERSION && data[i] <= MINOR_SOFTWARE_VERSION) || (majorSoftwareVersion < MAJOR_SOFTWARE_VERSION)) { minorSoftwareVersion = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_MESSAGE_ID_0; } else//if majorSoftwareVersion == MAJOR_SOFTWARE_VERSION && minorSoftwareVersion > MINOR_SOFTWARE_VERSION || majorSoftwareVersion > MAJOR_SOFTWARE_VERSION { currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; goto case ProcessingState.WAITING_FOR_START_OF_HEADER; } break; case ProcessingState.WAITING_FOR_MESSAGE_ID_0: messageIdHighByte = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_MESSAGE_ID_1; break; case ProcessingState.WAITING_FOR_MESSAGE_ID_1: messageIdLowByte = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); currentState = ProcessingState.WAITING_FOR_PAYLOAD_LENGTH; break; case ProcessingState.WAITING_FOR_PAYLOAD_LENGTH: payloadLength = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); if(payloadLength > 0) { payload = new byte[payloadLength]; payloadPosition = 0; currentState = ProcessingState.PROCESSING_PAYLOAD; } else //payloadLength == 0 { payload = null; currentState = ProcessingState.WAITING_FOR_CRC_BYTE_0; } break; case ProcessingState.PROCESSING_PAYLOAD: payload[payloadPosition++] = data[i]; currentCRC = XModemCRC.CalculateCRC(data[i], currentCRC); if(payloadPosition >= payloadLength) { currentState = ProcessingState.WAITING_FOR_CRC_BYTE_0; } break; case ProcessingState.WAITING_FOR_CRC_BYTE_0: CRC_BYTE_0 = data[i]; currentState = ProcessingState.WAITING_FOR_CRC_BYTE_1; break; case ProcessingState.WAITING_FOR_CRC_BYTE_1: CRC_BYTE_1 = data[i]; dataCrcHighByte = (byte)(currentCRC >> 8); dataCrcLowByte = (byte)(currentCRC & 0x00FF); if((dataCrcHighByte == CRC_BYTE_0) && (dataCrcLowByte == CRC_BYTE_1)) { owner.LogData(new Message(majorSoftwareVersion, minorSoftwareVersion, messageIdHighByte, messageIdLowByte, payload, timestamp)); } else //Failed CRC Check { crcCheckFails++; } currentState = ProcessingState.WAITING_FOR_START_OF_HEADER; break; default: MessageBox.Show("Unexpected Default Case in Process Data"); break; } } //TODO - take timestamp comparision out timestamp2 = DateTime.Now; int time; if(timestamp1.Millisecond > timestamp2.Millisecond) { time = timestamp2.Millisecond + (1000 - timestamp1.Millisecond); } else { time = timestamp2.Millisecond - timestamp1.Millisecond; } busy = false; return time; }
/// <summary> /// Initializes a new instance of the <see cref="ProcessingStateEventArgs"/> class. /// </summary> /// <param name="state">The state.</param> public ProcessingStateEventArgs(ProcessingState state) { State = state; }