public static void GetEndByte(InputPort digitalIn) { //Better be a 0 if (digitalIn.Read()) { Thread.Sleep(sleep); //And still a 0 if (digitalIn.Read()) { Thread.Sleep(sleep); state = TokenState.READ; return; } state = TokenState.LISTEN; } state = TokenState.LISTEN; }
public static void GetListenByte(InputPort digitalIn) { while (true) { //Found our first one...now wait for a 0 if (!digitalIn.Read()) { while (digitalIn.Read()) { //noop } } state = TokenState.STARTBYTE; Thread.Sleep(sleep); break; } }
private void ColorNone(string line, ColoredCharacter[] result, ref int index) { while (index < line.Length) { if (OutputIfNext(line, result, ref index, "//", CommentColor)) { for (var i = index; i < line.Length; i++, index++) { result[i] = new ColoredCharacter(line[i], CommentColor); } return; } if (OutputIfNext(line, result, ref index, "/*", CommentColor)) { _state = TokenState.MultiComment; _multiCommentDepth = 1; return; } var ch = line[index]; if (OutputIfNext(line, result, ref index, "\"", StringColor) || OutputIfNext(line, result, ref index, "\'", StringColor)) { _state = TokenState.String; _stringTerminator = ch; return; } if (Operators.TryGetValue(ch, out var operators)) { var idx = index; var op = operators.FirstOrDefault(s => IsNext(line, idx, s)); if (op != null) { Output(result, ref index, op, OperatorColor); continue; } } if (char.IsLetter(ch) || ch == '_' || ch == '`') { var start = index; var isBacktick = ch == '`'; if (isBacktick) { index++; // opening backtick } while (index < line.Length && (char.IsLetterOrDigit(line[index]) || line[index] == '_')) { index++; } if (isBacktick && index < line.Length && line[index] == '`') { index++; // closing backtick } var word = line.Substring(start, index - start); index = start; if (isBacktick) { Output(result, ref index, word, OperatorColor); continue; } if (Keywords.Contains(word)) { Output(result, ref index, word, KeywordColor); continue; } Output(result, ref index, word, IdentifierColor); continue; } if (char.IsDigit(ch)) { var format = NumberFormat.Decimal; var hasDecimal = false; var hasExp = false; var justTake = false; if (ch == '0' && index + 1 < line.Length) { var nextChar = line[index + 1]; if (nextChar == 'x' || nextChar == 'X') { format = NumberFormat.Hexadecimal; } if (nextChar == 'b' || nextChar == 'B') { format = NumberFormat.Binary; } if (format != NumberFormat.Decimal) { if (index + 2 < line.Length && line[index + 2] == '_') { result[index++] = new ColoredCharacter('0', NumberColor); continue; } result[index + 0] = new ColoredCharacter('0', NumberColor); result[index + 1] = new ColoredCharacter(nextChar, NumberColor); index += 2; } } bool IsDigit(char c) => char.IsDigit(c) || (format == NumberFormat.Hexadecimal && HexChars.Contains(c)); while (index < line.Length) { var c = line[index]; if (justTake) { justTake = false; result[index++] = new ColoredCharacter(c, NumberColor); continue; } if (c == '_' && (index + 1 < line.Length && IsDigit(line[index + 1]))) { result[index++] = new ColoredCharacter(c, NumberColor); continue; } if (format == NumberFormat.Decimal) { if (c == '.' && !hasDecimal && !hasExp) { hasDecimal = true; if (index + 1 >= line.Length || !IsDigit(line[index + 1])) { break; } result[index++] = new ColoredCharacter(c, NumberColor); continue; } if ((c == 'e' || c == 'E') && !hasExp) { if (index + 1 < line.Length) { var next = line[index + 1]; if (next == '+' || next == '-') { justTake = true; } } hasExp = true; result[index++] = new ColoredCharacter(c, NumberColor); continue; } } if (!IsDigit(c)) { break; } result[index++] = new ColoredCharacter(c, NumberColor); } continue; } result[index] = new ColoredCharacter(line[index], OtherColor); index++; } }
/// <summary> /// This will return the tokens that this site currently has to the /// other participants, thus ensuring that they can propagate their /// changes back to us. /// </summary> private void FlushToken() { if (TokenState == TokenState.HavingToken) { SendPatches(); TokenState = TokenState.WaitingForToken; } }
public void SetState(TokenState targetState) { _exitStateActions[state](); _enterStateActions[targetState](); state = targetState; }
public static void GetStartByte(InputPort digitalIn) { //Better be a 1 if (!digitalIn.Read()) { Thread.Sleep(sleep); //And still a 1 if (!digitalIn.Read()) { Thread.Sleep(sleep); state = TokenState.MESSAGE; return; } state = TokenState.LISTEN; } state = TokenState.LISTEN; }
public IHttpResponse HandleRequest(IHttpRequest request, TokenState tokenState) { IHttpResponse response = _container.GetInstance <IHttpResponse>(true); if (tokenState == TokenState.Invalid || tokenState == TokenState.Expired || tokenState == TokenState.NotYetValid) { return(UnauthorisedResponse); } logger.Trace($"{nameof(RequestBroker)}.{nameof(HandleRequest)}", new LogItem("Event", "GetRequestHandler started")); Stopwatch timer = Stopwatch.StartNew(); IActivityHandler handler = GetRequestHandler(request, out ActivityHandlerAttribute attribute); var handlerName = handler != null?handler.GetType().Name : "null"; logger.Trace($"{nameof(RequestBroker)}.{nameof(HandleRequest)}", new LogItem("Event", "GetRequestHandler completed"), new LogItem("DurationMilliseconds", timer.Elapsed.TotalMilliseconds), new LogItem("FoundHandler", handlerName)); if (handler == null) { switch (request.Verb) { case HttpVerb.Options: handler = _container.GetInstance <OptionsActivityHandler>(); attribute = new ActivityHandlerAttribute("", request.Verb, "") { SkipAuthorisation = true }; break; default: return(null); } } JwtSecurityToken token = request.SecurityToken; if (!activityAuthorisationManager.CheckAuthorisation(token, attribute)) { var unauthorised = _container.GetInstance <IHttpResponse>(true); unauthorised.HttpStatusCode = HttpStatusCode.Unauthorized; return(unauthorised); } logger.Trace($"{nameof(RequestBroker)}.{nameof(HandleRequest)}", new LogItem("Event", "Handler Handle called")); timer.Restart(); try { handler.Handle(request, response); } catch (Exception exception) { logger.Exception($"{nameof(RequestBroker)}.{nameof(HandleRequest)}", "Exception caught handling request", exception); response.SetStringContent(string.Empty); response.HttpStatusCode = HttpStatusCode.InternalServerError; } var elapsedMilliseconds = timer.Elapsed.TotalMilliseconds; logger.Trace($"{nameof(RequestBroker)}.{nameof(HandleRequest)}", new LogItem("Event", "Handler Handle completed"), new LogItem("DurationMilliseconds", elapsedMilliseconds)); apiMetrics.RecordHandlerDuration(elapsedMilliseconds, handlerName, response.HttpStatusCode); return(response); }
public Token(TokenState type, string token) { this.type = type; this.token = token; }
/// <summary> /// Validates the specified token. /// </summary> /// <param name="tokenString">The token.</param> /// <param name="claim">The claim obtained from token.</param> /// <param name="payload">The payload obtained from token.</param> /// <param name="tokenState">The state of the token.</param> /// <param name="errorMessage">A message indicating that the token is invalid.</param> /// <returns>true if it is valid; otherwise false.</returns> public bool ValidateToken(string tokenString, out ITokenClaim claim, out TPayload payload, out TokenState tokenState, out string errorMessage) { TokenValidationParameters parameters = new TokenValidationParameters { }; parameters.IssuerSigningKey = m_SecurityKey; parameters.ValidateIssuerSigningKey = true; if (ValidIssuers != null && ValidIssuers.Length > 0) { if (ValidIssuers.Length == 1) { parameters.ValidIssuer = ValidIssuers.First(); } else { parameters.ValidIssuers = ValidIssuers; } parameters.ValidateIssuer = true; } else { parameters.ValidateIssuer = false; } if (ValidAudiences != null && ValidAudiences.Length > 0) { if (ValidAudiences.Length == 1) { parameters.ValidAudience = ValidAudiences.First(); } else { parameters.ValidAudiences = ValidAudiences; } parameters.ValidateAudience = true; } else { parameters.ValidateAudience = false; } parameters.ValidateLifetime = true; parameters.LifetimeValidator = m_LifetimeValidator; try { ClaimsPrincipal claims = m_TokenHandler.ValidateToken(tokenString, parameters, out SecurityToken token); claim = new TokenClaim() { JwtID = GetClaim(claims, KnownJwtClaims.JwtID), Audience = GetClaim(claims, KnownJwtClaims.Audience), Expiration = ToDateTimeOffset(GetClaim(claims, KnownJwtClaims.Expiration)), NotBefore = ToDateTimeOffset(GetClaim(claims, KnownJwtClaims.NotBefore)), }; string payloadJson = claims.FindFirst(KnownJwtClaims.UserPayload)?.Value; if (string.IsNullOrEmpty(payloadJson)) { payload = default(TPayload); } else { payload = Newtonsoft.Json.JsonConvert.DeserializeObject <TPayload>(payloadJson); } tokenState = TokenState.Valid; errorMessage = null; return(true); } catch (SecurityTokenInvalidLifetimeException ex) { claim = null; payload = default(TPayload); if (ValidateLifetime(ex.NotBefore, ex.Expires, out tokenState, out errorMessage)) { tokenState = TokenState.Invalid; errorMessage = "The token is invalid."; } return(false); } catch (SecurityTokenInvalidIssuerException) { claim = null; payload = default(TPayload); tokenState = TokenState.InvalidIssuer; errorMessage = "The issuer is invalid."; return(false); } catch (SecurityTokenInvalidAudienceException) { claim = null; payload = default(TPayload); tokenState = TokenState.InvalidAudience; errorMessage = "The audience is invalid."; return(false); } catch (Exception) { claim = null; payload = default(TPayload); tokenState = TokenState.Invalid; errorMessage = "The token is invalid."; return(false); } }
private void ColorString(string line, ColoredCharacter[] result, ref int index) { while (index < line.Length) { var ch = line[index]; if (ch == '\\' && index + 1 < line.Length && line[index + 1] == _stringTerminator) { result[index + 0] = new ColoredCharacter('\\', StringColor); result[index + 1] = new ColoredCharacter(_stringTerminator, StringColor); index += 2; continue; } result[index] = new ColoredCharacter(ch, StringColor); index++; if (ch == _stringTerminator) { _state = TokenState.None; _stringTerminator = '\0'; return; } } }
private void ColorNone(string line, ColoredCharacter[] result, ref int index) { while (index < line.Length) { if (OutputIfNext(line, result, ref index, "//", CommentColor)) { for (var i = index; i < line.Length; i++, index++) { result[i] = new ColoredCharacter(line[i], CommentColor); } return; } if (OutputIfNext(line, result, ref index, "/*", CommentColor)) { _state = TokenState.MultiComment; _multiCommentDepth = 1; return; } var ch = line[index]; if (OutputIfNext(line, result, ref index, "\"", StringColor) || OutputIfNext(line, result, ref index, "\'", StringColor)) { _state = TokenState.String; _stringTerminator = ch; return; } string[] operators; if (Operators.TryGetValue(ch, out operators)) { var idx = index; var op = operators.FirstOrDefault(s => IsNext(line, idx, s)); if (op != null) { Output(result, ref index, op, OperatorColor); continue; } } if (char.IsLetter(ch) || ch == '_') { var start = index; while (index < line.Length && (char.IsLetterOrDigit(line[index]) || line[index] == '_')) { index++; } var word = line.Substring(start, index - start); index = start; if (Keywords.Contains(word)) { Output(result, ref index, word, KeywordColor); continue; } Output(result, ref index, word, IdentifierColor); continue; } if (char.IsDigit(ch)) { var format = NumberFormat.Decimal; var hasDecimal = false; var hasExp = false; var justTake = false; if (ch == '0' && index + 1 < line.Length) { var nextChar = line[index + 1]; if (nextChar == 'x' || nextChar == 'X') format = NumberFormat.Hexadecimal; if (nextChar == 'b' || nextChar == 'B') format = NumberFormat.Binary; if (format != NumberFormat.Decimal) { if (index + 2 < line.Length && line[index + 2] == '_') { result[index++] = new ColoredCharacter('0', NumberColor); continue; } result[index + 0] = new ColoredCharacter('0', NumberColor); result[index + 1] = new ColoredCharacter(nextChar, NumberColor); index += 2; } } Func<char, bool> isDigit = c => char.IsDigit(c) || (format == NumberFormat.Hexadecimal && HexChars.Contains(c)); while (index < line.Length) { var c = line[index]; if (justTake) { justTake = false; result[index++] = new ColoredCharacter(c, NumberColor); continue; } if (c == '_' && (index + 1 < line.Length && isDigit(line[index + 1]))) { result[index++] = new ColoredCharacter(c, NumberColor); continue; } if (format == NumberFormat.Decimal) { if (c == '.' && !hasDecimal && !hasExp) { hasDecimal = true; if (index + 1 >= line.Length || !isDigit(line[index + 1])) break; result[index++] = new ColoredCharacter(c, NumberColor); continue; } if ((c == 'e' || c == 'E') && !hasExp) { if (index + 1 < line.Length) { var next = line[index + 1]; if (next == '+' || next == '-') justTake = true; } hasExp = true; result[index++] = new ColoredCharacter(c, NumberColor); continue; } } if (!isDigit(c)) break; result[index++] = new ColoredCharacter(c, NumberColor); } continue; } result[index] = new ColoredCharacter(line[index], OtherColor); index++; } }
private void ColorMultiComment(string line, ColoredCharacter[] result, ref int index) { while (_multiCommentDepth > 0) { if (index >= line.Length) return; if (OutputIfNext(line, result, ref index, "/*", CommentColor)) { _multiCommentDepth++; continue; } if (OutputIfNext(line, result, ref index, "*/", CommentColor)) { _multiCommentDepth--; continue; } result[index] = new ColoredCharacter(line[index], CommentColor); index++; } _state = TokenState.None; }
/// <summary> /// Initialises a new token with the given type. /// </summary> /// <param name="tokenType">The type of the token, should be on of <see cref="XmlNodeType.DocumentType"/>, <see cref="XmlNodeType.Element"/>, <see cref="XmlNodeType.EndElement"/>, <see cref="XmlNodeType.Text"/>, <see cref="XmlNodeType.Whitespace"/> or <see cref="XmlNodeType.Comment"/></param> private void InitToken(XmlNodeType newTokenType) { Debug.Assert(newTokenType == XmlNodeType.DocumentType || newTokenType == XmlNodeType.Element || newTokenType == XmlNodeType.EndElement || newTokenType == XmlNodeType.Comment); Debug.Assert(_tokenState != TokenState.Initialized); _tokenState = TokenState.Initialized; _tokenType = newTokenType; _name = null; _value = null; _attributes.Clear(); _trailingSolidus = false; _forceQuirks = false; }
private void EmitToken() { Debug.Assert(_tokenState == TokenState.Initialized); if (_tokenType == XmlNodeType.Element) { _lastEmittedStartTagName = _name; } _tokenState = TokenState.Complete; }
private Element Build(List <IToken> body, Document document, List <IToken> defaultStyles) { var attachmentIndex = 0; var footnotes = new List <IToken>(); var footnoteIndex = 0; var lastParagraphStyle = default(TokenState); var lastBreak = default(IToken); var root = new Element(ElementType.Document, new Element(ElementType.Section, new Element(ElementType.Paragraph))); var paragraph = root.Elements().First().Elements().First(); root.SetStyles(defaultStyles); root.Elements().First().SetStyles(defaultStyles); var groups = new Stack <TokenState>(); groups.Push(new TokenState(body, defaultStyles)); while (groups.Count > 0) { while (groups.Peek().Tokens.MoveNext()) { var token = groups.Peek().Tokens.Current; if (token is Group childGroup) { var dest = childGroup.Destination; var fallbackDest = default(IWord); if (childGroup.Contents.Count > 1 && (childGroup.Contents[0] is TextToken ignoreText && ignoreText.Value == "*")) { fallbackDest = childGroup.Contents[1] as IWord; } if (childGroup.Contents.Count > 1 && childGroup.Contents[0] is IgnoreUnrecognized && (childGroup.Contents[1].GetType().Name == "GenericTag" || childGroup.Contents[1].GetType().Name == "GenericWord")) { // Ignore groups with the "skip if unrecognized" flag } else if (fallbackDest?.GetType().Name == "GenericTag" || fallbackDest?.GetType().Name == "GenericWord") { groups.Push(new TokenState(new[] { childGroup.Contents[0] }, groups.Peek())); } else if (dest is ListTextFallback) { paragraph.Type = ElementType.ListItem; } else if (dest is NumberingTextFallback || dest?.Type == TokenType.HeaderTag || fallbackDest?.Type == TokenType.HeaderTag || dest is NoNestedTables || dest is BookmarkEnd) { // Ignore fallback content } else if (dest is Header || dest is HeaderLeft || dest is HeaderFirst || dest is HeaderRight || dest is Footer || dest is FooterFirst || dest is FooterRight || dest is FooterLeft) { var section = default(Element); if (dest is Header) { section = (Element)root.InsertBefore(paragraph.Parent, new Element(ElementType.Header)); } else if (dest is HeaderLeft) { section = (Element)root.InsertBefore(paragraph.Parent, new Element(ElementType.HeaderLeft)); } else if (dest is HeaderFirst) { section = (Element)root.InsertBefore(paragraph.Parent, new Element(ElementType.HeaderFirst)); } else if (dest is HeaderRight) { section = (Element)root.InsertBefore(paragraph.Parent, new Element(ElementType.HeaderRight)); } else if (dest is Footer) { section = (Element)root.InsertAfter(paragraph.Parent, new Element(ElementType.Footer)); } else if (dest is FooterFirst) { section = (Element)root.InsertAfter(paragraph.Parent, new Element(ElementType.FooterFirst)); } else if (dest is FooterRight) { section = (Element)root.InsertAfter(paragraph.Parent, new Element(ElementType.FooterRight)); } else if (dest is FooterLeft) { section = (Element)root.InsertAfter(paragraph.Parent, new Element(ElementType.FooterLeft)); } var newState = new TokenState(childGroup.Contents, groups.Peek()) { PreviousParagraph = paragraph }; paragraph = new Element(ElementType.Paragraph); section.Add(paragraph); groups.Push(newState); } else if (dest is FieldInstructions || fallbackDest is FieldInstructions) { var fieldTokens = FieldParser.Parse(childGroup).ToList(); if (fieldTokens.Count > 0 && fieldTokens[0] is FieldTypeTag fieldTypeTag) { switch (fieldTypeTag.Value) { case FieldType.Hyperlink: groups.Peek().AddStyle(new HyperlinkToken(fieldTokens)); break; case FieldType.Symbol: paragraph.Add(FieldParser.ParseSymbol(fieldTokens, groups.Peek().Styles)); break; } } } else if (dest is BookmarkStart) { paragraph.Add(new Anchor(AnchorType.Bookmark, childGroup.Contents.OfType <TextToken>().FirstOrDefault()?.Value)); } else if (dest is PictureTag) { paragraph.Add(new Picture(childGroup)); } else if (dest is ShapeTag) { var shape = new Shape(childGroup); if (shape.Type == ShapeType.PictureFrame && shape.Properties.TryGetValue("pib", out var picObj) && picObj is Picture picture) { paragraph.Add(picture); } } else if (dest is Footnote) { var footnoteId = "footnote" + footnoteIndex.ToString("D2"); if (footnotes.Count > 0) { footnotes.Add(new ParagraphBreak()); } ProcessFootnoteGroups(childGroup.Contents, footnotes, footnoteIndex); } else if (dest is ParagraphNumbering) { if (!childGroup.Contents.OfType <NumberingLevelContinue>().Any()) { paragraph.Type = ElementType.ListItem; } foreach (var child in childGroup.Contents.Where(t => t.Type == TokenType.ParagraphFormat)) { groups.Peek().AddStyle(child); } } else { groups.Push(new TokenState(childGroup.Contents, groups.Peek())); } } else if (token is TextToken text) { var newRun = new Run(text.Value, groups.Peek().Styles); if (!newRun.Styles.OfType <IsHidden>().Any()) { if (paragraph.Nodes().LastOrDefault() is Run run && run.Styles.CollectionEquals(newRun.Styles)) { run.Value += text.Value; } else { paragraph.Add(newRun); } } }
protected override void Consume(Queue <char> InQueue) { if (InQueue.Count == 0) { return; } char c = InQueue.Dequeue(); _ItemConsumed(c); // Console.WriteLine("Tokenizing input..."); if (state == TokenState.Letter) { if (HebrewChar.IsModifier(c)) { sb.Append(c); return; } else { LetterToken lt = new LetterToken(letter, sb.ToString()); Log("Producing letter " + lt.Value); this.Emit(lt); sb.Length = 0; state = TokenState.Neutral; } } switch (state) { case TokenState.Tag: if (c == '/') { state = TokenState.Neutral; TagToken tt = new TagToken(sb.ToString()); Log("Producing tag " + tt.Type); this.Emit(tt); sb.Length = 0; } else { sb.Append(c); } break; case TokenState.Neutral: if (HebrewChar.IsLetter(c) || (c == '/')) { if (sb.Length > 0) { Token t = new Token(sb.ToString()); Log("Producing neutral token " + t.Value); this.Emit(t); } if (c == '/') { state = TokenState.Tag; } else { letter = c; state = TokenState.Letter; } sb.Length = 0; } else if (HebrewChar.IsCantillation(c)) { CantillationToken ct = new CantillationToken(c.ToString()); Log("Producing cantillation mark " + ct.Value); this.Emit(ct); } else if (HebrewChar.IsPunctuation(c)) { PunctuationToken pt = new PunctuationToken(c.ToString()); Log("Producing punctuation " + pt.Value); this.Emit(pt); } else { sb.Append(c); } break; } }
// Constructor public Token(int id, GameColor clr) { this.tokenId = id; this.color = clr; this.state = TokenState.Home; }
public void Collect() { state = TokenState.Inactive; }
void Apply(TokenCirculated @event) => state = Circulated;
public static void Main() { count = 0; d = DateTime.Now; InputPort digitalIn = new InputPort(Pins.GPIO_PIN_D3, false, Port.ResistorMode.Disabled); OutputPort ShieldPort = new OutputPort(Pins.GPIO_PIN_D0, false); OutputPort ManGunPort = new OutputPort(Pins.GPIO_PIN_D1, false); infraredOut = new Microsoft.SPOT.Hardware.PWM(PWMChannels.PWM_PIN_D6, 38000, .5, true); InterruptPort sender = new InterruptPort(Pins.GPIO_PIN_D10, false, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeLow); sender.OnInterrupt += sender_OnInterrupt; state = TokenState.LISTEN; string message = ""; while (true) { switch (state) { case TokenState.LISTEN: GetListenByte(digitalIn); break; case TokenState.STARTBYTE: GetStartByte(digitalIn); break; case TokenState.MESSAGE: message = GetMessage(digitalIn); break; case TokenState.ENDBYTE: GetEndByte(digitalIn); break; case TokenState.READ: if (message == "01") { ShieldPort.Write(true); ManGunPort.Write(false); } else if (message == "10") { ShieldPort.Write(false); ManGunPort.Write(true); } Debug.Print(String.Concat(message, "\n")); state = TokenState.LISTEN; message = ""; break; } } }
void Apply(TokenReserved @event) { state = Reserved; reservedByBillingAccountId = @event.BillingAccountId; reservedForOrderId = @event.OrderId; }
public static void GetListenByte(InputPort digitalIn) { while (true) { //Found our first one...now wait for a 0 if (!digitalIn.Read()) { var d = DateTime.Now; while (digitalIn.Read() && d.AddMilliseconds(500) < DateTime.Now ) { //noop } } state = TokenState.STARTBYTE; Thread.Sleep(sleep); break; } }
void Apply(TokenUnreserved @event) { state = Circulated; reservedByBillingAccountId = null; reservedForOrderId = default(Guid); }
public override bool Read() { if (_tokenState == TokenState.Complete) { if (_textToken.Length > 0) { _textToken.Length = 0; _textTokenIsWhitespace = true; return true; } _tokenState = TokenState.Uninitialized; } _textToken.Length = 0; _textTokenIsWhitespace = true; do { switch (_currentParsingFunction) { case ParsingFunction.Initial: // http://www.whatwg.org/specs/web-apps/current-work/multipage/section-tokenisation.htmlmultipage/section-tokenisation.html#tokenization: // The state machine must start in the data state. _currentParsingFunction = ParsingFunction.Data; break; case ParsingFunction.Eof: if (_textToken.Length == 0) { return false; } _tokenState = TokenState.Initialized; // HACK: to exit the while loop break; case ParsingFunction.ReaderClosed: return false; case ParsingFunction.Data: ParseData(); break; case ParsingFunction.EntityData: ParseEntityData(); break; case ParsingFunction.TagOpen: ParseTagOpen(); break; case ParsingFunction.CloseTagOpen: ParseCloseTagOpen(); break; case ParsingFunction.TagName: ParseTagName(); break; case ParsingFunction.BeforeAttributeName: ParseBeforeAttributeName(); break; case ParsingFunction.AttributeName: ParseAttributeName(); break; case ParsingFunction.AfterAttributeName: ParseAfterAttributeName(); break; case ParsingFunction.BeforeAttributeValue: ParseBeforeAttributeValue(); break; case ParsingFunction.AttributeValueDoubleQuoted: ParseAttributeValueDoubleQuoted(); break; case ParsingFunction.AttributeValueSingleQuoted: ParseAttributeValueSingleQuoted(); break; case ParsingFunction.AttributeValueUnquoted: ParseAttributeValueUnquoted(); break; // case ParsingFunction.EntityInAttributeValue: handled "inline" in the ParseAttributeXXX methods case ParsingFunction.AfterAttributeValueQuoted: ParseAfterAttributeValueQuoted(); break; case ParsingFunction.BogusComment: ParseBogusComment(); break; case ParsingFunction.MarkupDeclarationOpen: ParseMarkupDeclarationOpen(); break; case ParsingFunction.CommentStart: ParseCommentStart(); break; case ParsingFunction.CommentStartDash: ParseCommentStartDash(); break; case ParsingFunction.Comment: ParseComment(); break; case ParsingFunction.CommentEndDash: ParseCommentEndDash(); break; case ParsingFunction.CommentEnd: ParseCommentEnd(); break; case ParsingFunction.Doctype: ParseDoctype(); break; case ParsingFunction.BeforeDoctypeName: ParseBeforeDoctypeName(); break; case ParsingFunction.DoctypeName: ParseDoctypeName(); break; case ParsingFunction.AfterDoctypeName: ParseAfterDoctypeName(); break; case ParsingFunction.BeforeDoctypePublicId: ParseBeforeDoctypePublicId(); break; case ParsingFunction.DoctypePublicIdDoubleQuoted: ParseDoctypePublicIdDoubleQuoted(); break; case ParsingFunction.DoctypePublicIdSingleQuoted: ParseDoctypePublicIdSingleQuoted(); break; case ParsingFunction.AfterDoctypePublicId: ParseAfterDoctypePublicId(); break; case ParsingFunction.BeforeDoctypeSystemId: ParseBeforeDoctypeSystemId(); break; case ParsingFunction.DoctypeSystemIdDoubleQuoted: ParseDoctypeSystemIdDoubleQuoted(); break; case ParsingFunction.DoctypeSystemIdSingleQuoted: ParseDoctypeSystemIdSingleQuoted(); break; case ParsingFunction.AfterDoctypeSystemId: ParseAfterDoctypeSystemId(); break; case ParsingFunction.BogusDoctype: ParseBogusDoctype(); break; default: throw new InvalidOperationException(); } } while (_tokenState == TokenState.Uninitialized || (_tokenState == TokenState.Initialized && _textToken.Length == 0)); if (_tokenState == TokenState.Complete){ switch (_tokenType) { case XmlNodeType.Element: case XmlNodeType.EndElement: // Check duplicate attributes _attributes.RemoveAll( delegate(Attribute attr) { if (attr.isDuplicate) { OnParseError(new ParseErrorEventArgs(String.Concat("Duplicate attribute: ", attr.name), attr)); return true; } return false; } ); if (_tokenType == XmlNodeType.EndElement) { _contentModel = ContentModel.Pcdata; if (_attributes.Count > 0) { OnParseError("End tag with attributes"); } } break; } } return true; }
void Apply(TokenActivated @event) { state = Activated; reservedByBillingAccountId = @event.BillingAccountId; }
private void ContextChanged(object sender, ChangeEventArgs e) { if (e.Issuer == this) return; // If we currently have the token, we can just send this single change... if (TokenState == TokenState.HavingToken) { HasChanged = false; SendPatches(); TokenState = TokenState.WaitingForToken; } // .. otherwise we first have to request it. else { if (!TokenRequestSent) { Connection.Send(new TokenRequestMessage()); } TokenRequestSent = true; HasChanged = true; } }
void Apply(TokenDeactivated @event) => state = reservedByBillingAccountId == null ? Circulated : Reserved;
private void InvokedConnectionReceived(object sender, ReceivedEventArgs e) { lock(this) { if (e.Message is DiffMessage) { Debug.Assert(TokenState == TokenState.WaitingForToken); TokenRequestSent = false; DiffMessage diffMessage = (DiffMessage)e.Message; ApplyPatches(diffMessage); TokenState = TokenState.HavingToken; if (HasChanged) { HasChanged = false; SendPatches(); TokenState = TokenState.WaitingForToken; } } else if (e.Message is TokenRequestMessage) { if (TokenState == TokenState.HavingToken) { HasChanged = false; SendPatches(); TokenState = TokenState.WaitingForToken; } } else { throw new Exception(String.Format("Encountered unknown message type '{0}'", e.Message.GetType().Name)); } } }
void Apply(TokenRedeemed @event) { state = Redeemed; redeemedByAccountId = @event.AccountId; }
/// <summary> /// State machine analysis of the provided message line, to minimize processing cost overhead. /// </summary> /// <param name="line">The message line.</param> /// <returns>Returns a tuple indicating if this was a vote line, whether this line indicated /// that this post should be ignored, and the encapsulated vote line, if applicable.</returns> /// <exception cref="InvalidOperationException">Throws if it gets into an unknown state.</exception> internal static (bool isVoteLine, bool flagIgnore, VoteLine voteLine) AnalyzeLine(string line) { bool isVoteLine = false; bool flagIgnore = false; VoteLine voteLine = null; if (string.IsNullOrEmpty(line)) { return(isVoteLine, flagIgnore, voteLine); } StringBuilder prefixSB = new StringBuilder(); StringBuilder markerSB = new StringBuilder(); StringBuilder taskSB = new StringBuilder(); StringBuilder contentSB = new StringBuilder(); StringBuilder tempContent = new StringBuilder(); MarkerType markerType = MarkerType.None; int markerValue = 0; int ignoreCharCount = 0; Stack <TokenState> state = new Stack <TokenState>(); TokenState currentState = TokenState.None; foreach (var ch in line) { switch (currentState) { case TokenState.None: if (ch == whitespace) { continue; } else if (ch == openBBCode) { state.Push(currentState); currentState = TokenState.BBCode; } else if (ch == prefixChar) { state.Push(currentState); currentState = TokenState.Prefix; prefixSB.Append(ch); } else if (ch == ignoreChar) { state.Push(currentState); currentState = TokenState.Ignore; ignoreCharCount = 1; } else if (ch == openBracket) { state.Push(currentState); currentState = TokenState.Marker; } else { goto doneExamining; } break; case TokenState.BBCode: if (state.Peek() == TokenState.PostMarker) { tempContent.Append(ch); } if (ch == closeBBCode) { currentState = state.Pop(); } break; case TokenState.Ignore: if (ch == ignoreChar) { ignoreCharCount++; if (ignoreCharCount == 5) { flagIgnore = true; goto doneExamining; } } else if (ch == openBBCode) { state.Push(currentState); currentState = TokenState.BBCode; } else { goto doneExamining; } break; case TokenState.Prefix: if (ch == whitespace) { continue; } else if (ch == prefixChar) { prefixSB.Append(ch); } else if (ch == openBBCode) { state.Push(currentState); currentState = TokenState.BBCode; } else if (ch == openBracket) { currentState = TokenState.Marker; } else { goto doneExamining; } break; case TokenState.Marker: if (ch == whitespace) { continue; } else if (ch == openBBCode) { state.Push(currentState); currentState = TokenState.BBCode; } else if (markerChars.Contains(ch)) { markerSB.Append(ch); } else if (ch == closeBracket) { (markerType, markerValue) = GetMarkerType(markerSB.ToString()); if (markerType != MarkerType.None) { isVoteLine = true; currentState = TokenState.PostMarker; } else { goto doneExamining; } } else { goto doneExamining; } break; case TokenState.PostMarker: if (ch == whitespace) { continue; } else if (ch == openBracket && taskSB.Length == 0) { state.Push(currentState); currentState = TokenState.Task; } else if (ch == openBBCode && taskSB.Length == 0) { state.Push(currentState); currentState = TokenState.BBCode; tempContent.Append(ch); } else { contentSB.Append(tempContent.ToString()); contentSB.Append(ch); currentState = TokenState.Content; } break; case TokenState.Task: if (ch == closeBracket) { currentState = state.Pop(); } else if (ch == openBBCode) { state.Push(currentState); currentState = TokenState.BBCode; } else { taskSB.Append(ch); } break; case TokenState.Content: contentSB.Append(ch); break; default: throw new InvalidOperationException($"Unknown token state value: {currentState}."); } } doneExamining: if (isVoteLine) { voteLine = new VoteLine(prefixSB.ToString(), markerSB.ToString(), taskSB.ToString(), contentSB.ToString(), markerType, markerValue); } return(isVoteLine, flagIgnore, voteLine); }
void Apply(TokenVoided @event) => state = Voided;
public TokenState(IEnumerable <IToken> tokens, TokenState previous) { Tokens = tokens.GetEnumerator(); _styles.AddRange(previous.Styles); _defaultStyles = previous._defaultStyles; }
internal void SetAsWinner() { State = TokenState.Winner; }
// Invoked after success of prompt step async. private async Task <DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Get the token from the previous step. Note that we could also have gotten the // token directly from the prompt itself. There is an example of this in the next method. var tokenResponse = (TokenResponse)stepContext.Result; if (tokenResponse != null) { if (stepContext.Context.Activity.Text != null) { if (stepContext.Context.Activity.Text.ToLower().Trim() == "viewfile") { var fileNameList = await SharePointFileHelper.GetSharePointFile(tokenResponse, _configuration["SharePointSiteName"], _configuration["SharePointTenantName"] + ":"); if (fileNameList.Count == 0) { await stepContext.Context.SendActivityAsync(MessageFactory.Text("No files found. Please type 'uploadfile' to upload file to SharePoint site"), cancellationToken); } else { var sharePointTenantName = _configuration["SharePointTenantName"]; var sharePointSiteName = _configuration["SharePointSiteName"]; var fileUrl = ""; var actions = new List <AdaptiveAction>(); foreach (var file in fileNameList) { var extension = file.Split('.')[1]; fileUrl = $"https://teams.microsoft.com/_#/{extension}/viewer/teams/https:~2F~2F{sharePointTenantName}~2Fsites~2F{sharePointSiteName}~2FShared%20Documents~2F{file}"; actions.Add(new AdaptiveOpenUrlAction { Title = file.Split('.')[0], Url = new Uri(fileUrl), }); } await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(GetAdaptiveCardForFileViewerOption(actions)), cancellationToken); } return(await stepContext.EndDialogAsync()); } else if (stepContext.Context.Activity.Text.ToLower().Trim() == "uploadfile") { TokenState token = new TokenState { AccessToken = tokenResponse.Token }; _Token.AddOrUpdate("token", token, (key, newValue) => token); await stepContext.Context.SendActivityAsync(MessageFactory.Attachment(GetAdaptiveCardForUploadFileOption()), cancellationToken); return(await stepContext.EndDialogAsync()); } } } await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login successful"), cancellationToken); await stepContext.Context.SendActivityAsync(MessageFactory.Text("Please type 'uploadfile' to upload file to SharePoint site or 'viewfile' to get card for file viewer"), cancellationToken); return(await stepContext.EndDialogAsync()); }
/// <summary> /// Process data received from the client. /// </summary> /// <param name="args">SocketAsyncEventArgs used in the operation.</param> /// <param name="mediaDir">the directory of the stored media</param> /// <param name="m_factory">the vlc factory for vlm</param> internal void ProcessData(SocketAsyncEventArgs args, String mediaDir) { // Get the message received from the client. String received = this.sb.ToString(0, this.sb.Length); //int nextPo = 1, prePo = 0; //bool end = false; //while (!end) //{ if (this.State == TokenState.Running) { //while (this.currentIndex >= 1 && nextPo < this.currentIndex && tmpMsg[nextPo] != 129) //{ nextPo++; } byte[] tmp = new Byte[this.currentIndex]; Buffer.BlockCopy(tmpMsg, 0, tmp, 0, this.currentIndex); // prePo = nextPo; //if (prePo == this.currentIndex) end = true; ; Message message = valueProtocol.Decode(tmp); if (message.Data != null) { received = message.Data.ToString(); } if (message.header.Opcode == OperType.Close) { this.State = TokenState.Close; } } Console.WriteLine(received); Byte[] sendBuffer = null; if (received.IndexOf("Connection") < 0) { //字符构成 cmd|content|ipaddress|portnumber|channel|username|password String[] options = received.Split('|'); if (options.Length == 7) { if ("vod".Equals(options[0])) { //点播服务 即回放 List <String> mediaList = checkMedia(mediaDir, options[2] + "_554" + "_" + options[4] + "_" + options[1]); //options[1] yyyymmdd if (mediaList.Count > 0) { var jsonSerialiser = new JavaScriptSerializer(); var json = jsonSerialiser.Serialize(mediaList); sendBuffer = valueProtocol.Encode("{name:'vod',value:" + json.ToString() + "}"); } } else if ("ptz".Equals(options[0])) { //云台控制 Int32 m_login = sdkCMD.Login(options[2], Int16.Parse(options[3])); if (m_login >= 0) { if ("UPDown".Equals(options[1])) { sdkCMD.PTZ_UP_btnDown(Int32.Parse(options[4])); } else if ("UPUp".Equals(options[1])) { sdkCMD.PTZ_UP_btnUp(Int32.Parse(options[4])); } else if ("LEFTDown".Equals(options[1])) { sdkCMD.PTZ_LEFT_btnDown(Int32.Parse(options[4])); } else if ("LEFTUp".Equals(options[1])) { sdkCMD.PTZ_LEFT_btnUp(Int32.Parse(options[4])); } else if ("RIGHTDown".Equals(options[1])) { sdkCMD.PTZ_RIGHT_btnDown(Int32.Parse(options[4])); } else if ("RIGHTUp".Equals(options[1])) { sdkCMD.PTZ_RIGHT_btnUp(Int32.Parse(options[4])); } else if ("DOWNDown".Equals(options[1])) { sdkCMD.PTZ_DOWN_btnDown(Int32.Parse(options[4])); } else if ("DOWNUp".Equals(options[1])) { sdkCMD.PTZ_DOWN_btnUp(Int32.Parse(options[4])); } sendBuffer = valueProtocol.Encode("{name:'res',value:'ok'}"); } } else if ("gtc".Equals(options[0])) { Int32 m_login = sdkCMD.Login(options[2], Int16.Parse(options[3])); if (m_login >= 0) { sendBuffer = valueProtocol.Encode("{name:'gtc',value:'" + sdkCMD.GetChannelNumber().ToString() + "'}"); } } //TODO Use message received to perform a specific operation. Console.WriteLine("cmd:{0}, content:{1}", options[0], options[1]); } } else { sendBuffer = valueProtocol.GetResponse(received); this.State = TokenState.Running; // end = true; } //Byte[] sendBuffer = Encoding.ASCII.GetBytes(received); if (sendBuffer == null) { sendBuffer = valueProtocol.Encode("{name:'res',value:'error'}"); } args.SetBuffer(sendBuffer, 0, sendBuffer.Length); // } // Clear StringBuffer, so it can receive more data from a keep-alive connection client. sb.Length = 0; this.currentIndex = 0; }
public Token[] LexTextStream(StreamReader stream) { char nextChar; char[] buffer = new char[128]; // Token[] tokens = new Token[256]; // Only for now. int lexPosition = 0; int currentLine = 1; while(!stream.EndOfStream) { if((nextChar = (char)stream.Read()) == '\r') continue; if(state == TokenState.Token_String || state == TokenState.Token_Chars) { if(nextChar == '\n') { Console.WriteLine("Syntax Error: Line {0} ( {1} )", currentLine, state); return null; } if(nextChar == '"' && state == TokenState.Token_String || nextChar == '\'' && state == TokenState.Token_Chars) { this.tokens.Add(new Token(state, this.bufferToStringToken(buffer, lexPosition))); lexPosition = 0; state = TokenState.Token_Unknown; // IDK What the next char is like. continue; } else { buffer[lexPosition] = nextChar; lexPosition++; continue; } } else if(state == TokenState.Token_Variable || state == TokenState.Token_Keyword) { if(nextChar == ' ' || nextChar == '(' || nextChar == ')' || nextChar == '\n' || nextChar == '=' // || nextChar == '+' // || nextChar == '<' // || nextChar == '>' // || nextChar == '*' // || nextChar == '/' // || nextChar == ':' || nextChar == ',') { this.tokens.Add(new Token(state, this.bufferToStringToken(buffer, lexPosition))); if(nextChar == '=') { // || nextChar == '+' // || nextChar == '*' // || nextChar == '/' // || nextChar == '>' // || nextChar == '<') { state = TokenState.Token_Operator; buffer[0] = nextChar; lexPosition = 1; continue; } //else if(nextChar == ':' && state == TokenState.Token_Keyword) { // state = TokenState.Token_Reference; // lexPosition = 1; // buffer[0] = nextChar; // continue; //} else if(nextChar == '(' || nextChar == ')') { if(nextChar == '(') state = TokenState.Token_Brackets; else state = TokenState.Token_Brackets_Close; lexPosition = 1; buffer[0] = nextChar; continue; } else if(nextChar == ',') { state = TokenState.Token_Comma; buffer[0] = nextChar; lexPosition = 1; continue; } else { state = TokenState.Token_Unknown; } lexPosition = 0; continue; } else { buffer[lexPosition] = nextChar; lexPosition++; continue; } } else if(state == TokenState.Token_Decimal || state == TokenState.Token_Float) { if(nextChar == ' ' || nextChar == '\n' || nextChar == ',' || nextChar == ')') { this.tokens.Add(new Token(state, this.bufferToStringToken(buffer, lexPosition))); if(nextChar == ',' || nextChar == ')') { if(nextChar == ',') state = TokenState.Token_Comma; else if(nextChar == ')') state = TokenState.Token_Brackets_Close; buffer[0] = nextChar; lexPosition = 1; continue; } else state = TokenState.Token_Unknown; lexPosition = 0; continue; } else if(nextChar == '.') { if(state == TokenState.Token_Float) { Console.WriteLine("Syntax Error: Line {0} ( {1} )", currentLine, state); return null; } buffer[lexPosition] = nextChar; lexPosition++; state = TokenState.Token_Float; continue; } else { buffer[lexPosition] = nextChar; lexPosition++; continue; } } else if(state == TokenState.Token_Operator) { if(nextChar == '=') { // || nextChar == '+' // || nextChar == '-') { buffer[lexPosition] = nextChar; lexPosition++; } else if(nextChar == '-' || (nextChar >= '0' && nextChar <= '9') || nextChar == '"' || nextChar == '\'' || nextChar == ' ' || nextChar >= 'a' && nextChar <= 'z' || nextChar >= 'A' && nextChar <= 'Z') { this.tokens.Add(new Token(state, this.bufferToStringToken(buffer, lexPosition))); if(nextChar == '-' || (nextChar >= '0' && nextChar <= '9')) { state = TokenState.Token_Decimal; buffer[0] = nextChar; lexPosition = 1; continue; } else if(nextChar >= 'a' && nextChar <= 'z' || nextChar >= 'A' && nextChar <= 'Z') { state = TokenState.Token_Keyword; // Maybe? Or not xD buffer[0] = nextChar; lexPosition = 1; continue; } else if(nextChar == '"') { state = TokenState.Token_String; } else if(nextChar == '\'') { state = TokenState.Token_Chars; } else state = TokenState.Token_Unknown; lexPosition = 0; continue; } } else if(state == TokenState.Token_Comma) { if(nextChar == ' ' || nextChar >= 'a' && nextChar <= 'z' || nextChar >= 'A' && nextChar <= 'Z' || nextChar == '$' || nextChar >= '0' && nextChar <= '9' || nextChar == '-' || nextChar == '\'' || nextChar == '"') { this.tokens.Add(new Token(state, this.bufferToStringToken(buffer, lexPosition))); if(nextChar == '-' || nextChar >= '0' && nextChar <= '9') { state = TokenState.Token_Decimal; buffer[0] = nextChar; lexPosition = 1; continue; } else if(nextChar >= 'a' && nextChar <= 'z' || nextChar >= 'A' && nextChar <= 'Z' || nextChar == '-') { state = TokenState.Token_Keyword; buffer[0] = nextChar; lexPosition = 1; continue; } else if(nextChar == '"' || nextChar == '\'') { if(nextChar == '"') state = TokenState.Token_String; else state = TokenState.Token_Chars; lexPosition = 0; continue; } else if(nextChar == '$') state = TokenState.Token_Variable; else state = TokenState.Token_Unknown; lexPosition = 0; continue; } } //else if(state == TokenState.Token_Reference) { // if(nextChar != ':' && lexPosition > 1) { // this.tokens.Add(new Token(state, this.bufferToStringToken(buffer, lexPosition))); // if(nextChar >= 'a' && nextChar <= 'z' // || nextChar >= 'A' && nextChar <= 'Z') { // state = TokenState.Token_Keyword; // lexPosition = 1; // buffer[0] = nextChar; // continue; // } // else if(nextChar >= '0' && nextChar <= '9' // || nextChar == '-') { // state = TokenState.Token_Decimal; // lexPosition = 1; // buffer[0] = nextChar; // continue; // } // else if(nextChar == '$') { // state = TokenState.Token_Variable; // } // else if(nextChar == '(') { // state = TokenState.Token_Brackets; // buffer[0] = nextChar; // lexPosition = 1; // continue; // } // else state = TokenState.Token_Unknown; // lexPosition = 0; // continue; // } // else if(nextChar != ':') { // Console.WriteLine("Error Unknown Char ':' on line {0}", currentLine); // //return null; // } // else { // buffer[lexPosition] = nextChar; // lexPosition++; // } //} else if(state == TokenState.Token_Brackets) { this.tokens.Add(new Token(state, this.bufferToStringToken(buffer, lexPosition))); Console.WriteLine("Bracket parse: {0}", nextChar); if(nextChar >= 'a' && nextChar <= 'z' || nextChar >= 'A' && nextChar <= 'Z') { state = TokenState.Token_Keyword; lexPosition = 1; buffer[0] = nextChar; continue; } else if(nextChar >= '0' && nextChar <= '9' || nextChar == '-') { state = TokenState.Token_Decimal; buffer[0] = nextChar; lexPosition = 1; continue; } else if(nextChar == '\'' || nextChar == '"') { if(nextChar == '"') state = TokenState.Token_String; else state = TokenState.Token_Chars; lexPosition = 0; continue; } else if(nextChar == '$') { state = TokenState.Token_Variable; lexPosition = 0; continue; } else if(nextChar == ')') { state = TokenState.Token_Brackets_Close; buffer[0] = nextChar; lexPosition = 1; continue; } else { Console.WriteLine("Unknown char {0}", nextChar); state = TokenState.Token_Unknown; continue; } } else if(state == TokenState.Token_Brackets_Close) { this.tokens.Add(new Token(state, this.bufferToStringToken(buffer, lexPosition))); // Console.WriteLine("Token " + state.ToString() + " buffer: {0}", tokens[tokenPos].token.Length); if(nextChar != ' ') { Console.WriteLine("No empty space after {0}", state); } state = TokenState.Token_Unknown; lexPosition = 0; } else if(nextChar == '\n' && state == TokenState.Token_Unknown) continue; else if(nextChar == '"' && state == TokenState.Token_Unknown) { state = TokenState.Token_String; continue; } else if(nextChar == '\'') { state = TokenState.Token_Chars; continue; } else if(nextChar == '$') { state = TokenState.Token_Variable; continue; } else if(nextChar >= 'a' && nextChar <= 'z' || nextChar >= 'A' && nextChar <= 'Z' || nextChar == '_') { buffer[0] = nextChar; lexPosition++; state = TokenState.Token_Keyword; continue; } else if(nextChar == '-' // This is for a negative number? Hmm... || (nextChar >= '0' && nextChar <= '9')) { buffer[0] = nextChar; lexPosition++; state = TokenState.Token_Decimal; continue; } else if(nextChar == '=') { // || nextChar == '+' // || nextChar == '>' // || nextChar == '<' // || nextChar == '*' // || nextChar == '/') { state = TokenState.Token_Operator; buffer[0] = nextChar; lexPosition++; continue; } else if(nextChar == ',') { state = TokenState.Token_Comma; buffer[0] = nextChar; lexPosition = 1; continue; } else if(nextChar == '(' || nextChar == ')') { if(nextChar == '(') { state = TokenState.Token_Brackets; } else { state = TokenState.Token_Brackets_Close; } buffer[0] = nextChar; lexPosition++; continue; } if(nextChar == '\n') currentLine++; } if(state != TokenState.Token_Unknown) { if(state == TokenState.Token_Keyword || state == TokenState.Token_Decimal || state == TokenState.Token_Float || state == TokenState.Token_Operator || state == TokenState.Token_Brackets_Close) { this.tokens.Add(new Token(state, this.bufferToStringToken(buffer, lexPosition))); } else { Console.WriteLine("Syntax Error: Line {0} ( {1} was not property closed. )", currentLine, state); } } return this.tokens.ToArray(); }
internal ParseResult ParseLALR(Token NextToken) { //This function analyzes a token and either: // 1. Makes a SINGLE reduction and pushes a complete Reduction object on the m_Stack // 2. Accepts the token and shifts // 3. Errors and places the expected symbol indexes in the Tokens list //The Token is assumed to be valid and WILL be checked //If an action is performed that requires controlt to be returned to the user, the function returns true. //The Message parameter is then set to the type of action. LRAction ParseAction = m_loaded.FindLRAction(m_CurrentLALR, NextToken.Symbol); // Work - shift or reduce if ((ParseAction != null)) { //'Debug.WriteLine("Action: " & ParseAction.Text) switch (ParseAction.Type) { case LRActionType.Accept: return(ParseResult.Accept); case LRActionType.Shift: Push(NextToken, ParseAction.Value); return(ParseResult.Shift); case LRActionType.Reduce: //Produce a reduction - remove as many tokens as members in the rule & push a nonterminal token Production Prod = m_loaded.GetProduction(ParseAction); ParseResult Result; Token Head; //======== Create Reduction if (m_TrimReductions & Prod.ContainsOneNonTerminal()) { //The current rule only consists of a single nonterminal and can be trimmed from the //parse tree. Usually we create a new Reduction, assign it to the Data property //of Head and push it on the m_Stack. However, in this case, the Data property of the //Head will be assigned the Data property of the reduced token (i.e. the only one //on the m_Stack). //In this case, to save code, the value popped of the m_Stack is changed into the head. //Build a Reduction Head = m_Stack.Pop().Token; Head.TrimReduction(Prod.Head()); Result = ParseResult.ReduceEliminated; } else { int nTokens = Prod.Handle().Count; List <Token> tokens = new List <Token>(nTokens); for (int i = Prod.Handle().Count - 1; i >= 0; --i) { TokenState popped = Pop(); while (popped.IsExtra) { tokens.Insert(0, popped.Token); popped = Pop(); } tokens.Insert(0, popped.Token); } //Say that the reduction's Position is the Position of its first child. Head = new Reduction(Prod, tokens.ToArray()); Result = ParseResult.ReduceNormal; } //========== Goto short GotoState = m_Stack.Peek().GotoState; LRAction found = m_loaded.FindLRAction(GotoState, Prod.Head()); if ((found != null) && (found.Type == LRActionType.Goto)) { Push(Head, found.Value); return(Result); } else { //========= If action not found here, then we have an Internal Table Error!!!! return(ParseResult.InternalError); } default: return(ParseResult.InternalError); } } else { return(ParseResult.SyntaxError); } }
public void Reset() { state = TokenState.Active; }
private void Processor(Socket s) { try { byte[] buffer = new byte[4096]; byte[] content = null; int contentOffset = 0; HttpRequest request = null; Stopwatch connectionTimer = Stopwatch.StartNew(); using (NetworkStream ns = new NetworkStream(s)) { while (true) { int bytesReceived; do { bytesReceived = ns.Read(buffer, 0, buffer.Length); if (bytesReceived != 0) { break; } Thread.Sleep(1); } while (connectionTimer.ElapsedMilliseconds < requestTimeout); if (bytesReceived == 0) { s.Shutdown(SocketShutdown.Both); s.Dispose(); ns.Dispose(); logger.Trace($"{nameof(NanoHttp)}.{nameof(Processor)}", new LogItem("Event", "Closed socket"), new LogItem("Reason", $"No request received in {requestTimeout}ms")); return; } byte[] received = new byte[bytesReceived]; Array.Copy(buffer, 0, received, 0, bytesReceived); if (request == null) { int i = received.FindPattern((byte)13, (byte)10, (byte)13, (byte)10); // If we have a double CRLF then we have a complete header, otherwise keep looping if (i == -1) { continue; } request = ParseHeader(i, ref received, ref content, ref contentOffset, ref bytesReceived); if (request == null) { s.Shutdown(SocketShutdown.Both); s.Dispose(); ns.Dispose(); return; } } Array.Copy(received, 0, content, contentOffset, bytesReceived); contentOffset += bytesReceived; if (contentOffset < content.Length - 1) { continue; } // Completed loading body, which could have urlencoded content :( TokenState tokenState = request.FinaliseLoad(request.Verb != HttpVerb.Options && validJwtRequired, TokenValidationParameters); request.Body = content; logger.Trace($"{nameof(NanoHttp)}.{nameof(Processor)}", new LogItem("Event", "HandleRequest started")); Stopwatch responseTimer = Stopwatch.StartNew(); IHttpResponse response = null; foreach (IRequestBroker requestBroker in requestBrokers.OrderBy(x => x.Precedence)) { response = requestBroker.HandleRequest(request, tokenState); if (response != null) { break; } } if (response == null) { response = container.GetInstance <IHttpResponse>(true); response.HttpStatusCode = HttpStatusCode.NotFound; response.HttpContent = new NotFoundHttpContent(); } logger.Trace($"{nameof(NanoHttp)}.{nameof(Processor)}", new LogItem("Event", "HandleRequest completed"), new LogItem("DurationMilliseconds", responseTimer.Elapsed.TotalMilliseconds)); response.Headers.Add("Access-Control-Allow-Origin", "*"); response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS"); response.Headers.Add("Access-Control-Allow-Headers", "authorization"); response.Headers.Add("Connection", "close"); if (response.CachingDisabled) { if (!response.Headers.ContainsKey("Expires")) { response.Headers.Add("Expires", "-1"); } if (!response.Headers.ContainsKey("Pragma")) { response.Headers.Add("Pragma", "no-cache"); } if (!response.Headers.ContainsKey("Cache-Control")) { response.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate"); } } response.WriteToStream(ns); ns.Flush(); if (response.HttpStatusCode == HttpStatusCode.SwitchingProtocols) { // ####################################### // # WebSocket Stuff Goes Here # // # https://tools.ietf.org/html/rfc6455 # // ####################################### // There's a blocking call here into a message loop // while true ... // wait for a websocket message // ... etc // end } s.Shutdown(SocketShutdown.Both); s.Dispose(); ns.Dispose(); logger.Trace($"{nameof(NanoHttp)}.{nameof(Processor)}", new LogItem("Event", "Closed socket"), new LogItem("Reason", "Response complete"), new LogItem("DurationMilliseconds", connectionTimer.Elapsed.TotalMilliseconds)); return; } } } catch (Exception ex) { logger.Error($"{nameof(NanoHttp)}.{nameof(Processor)}", new LogItem("Event", "An error occurred processing request"), new LogItem("Exception", ex.ToString)); throw; } }
public Token(TokenState state, Symbol symbol, string value, int line, int col) : base(symbol, value, line, col) { this.State = state; }
public CompleteableExecutionToken() { _state = TokenState.Active; }
public void CompleteWith(TokenState state) { _state = state; }
public void Cancel() { _state = TokenState.Cancelled; }
public static void Main() { InputPort digitalIn = new InputPort(Pins.GPIO_PIN_D3, false, Port.ResistorMode.Disabled); OutputPort healthOut0 = new OutputPort(Pins.GPIO_PIN_D1, false); OutputPort healthOut1 = new OutputPort(Pins.GPIO_PIN_D2, false); OutputPort healthOut2 = new OutputPort(Pins.GPIO_PIN_D4, false); OutputPort healthOut3 = new OutputPort(Pins.GPIO_PIN_D5, false); OutputPort healthOut4 = new OutputPort(Pins.GPIO_PIN_D7, false); OutputPort healthOut5 = new OutputPort(Pins.GPIO_PIN_D8, false); OutputPort healthOut6 = new OutputPort(Pins.GPIO_PIN_D9, false); while (true) { DisplayHealth(healthOut0, healthOut1, healthOut2, healthOut3, healthOut4, healthOut5, healthOut6); switch (state) { case TokenState.LISTEN: GetListenByte(digitalIn); break; case TokenState.STARTBYTE: GetStartByte(digitalIn); break; case TokenState.MESSAGE: message = GetMessage(digitalIn); break; case TokenState.ENDBYTE: GetEndByte(digitalIn); break; case TokenState.READ: Debug.Print(String.Concat(message + " " + "PlayerHealth" + ": " + playerHealth, "\n")); UpdatePlayer(message); state = TokenState.LISTEN; message = ""; break; } } }
/// <summary> /// Advances the stream reader until the closing delimiter of a multi-line token has been discovered. /// </summary> /// <param name="sr"></param> /// <param name="tokenState"></param> /// <param name="myValue"></param> public static void AdvanceToNewLineUntilPartialTokenEnds(this StreamReader sr, ref TokenState tokenState, ref string myValue) { if (sr is null || tokenState is null || myValue is null) { return; } tokenState.PartialToken += "\n"; myValue += sr.CaptureAndEscapeTokens(sr.ReadLine(), ref tokenState); }
public static string GetMessage(InputPort digitalIn) { var message = ""; DateTime startTime; if (!digitalIn.Read()) { message += "1"; } else { message += "0"; } Thread.Sleep(sleep); if (!digitalIn.Read()) { message += "1"; } else { message += "0"; } Thread.Sleep(sleep); if (message == "11" || message == "00") { state = TokenState.LISTEN; message = ""; return ""; } state = TokenState.ENDBYTE; return message; }
/// <summary> /// Tokenizes escaped sections of the value and stores captured tokens in a TokenState object /// </summary> /// <param name="sr"></param> /// <param name="line"></param> /// <param name="tokenState"></param> /// <returns></returns> public static string CaptureAndEscapeTokens(this StreamReader sr, string line, ref TokenState tokenState) { if (sr is null || line is null || tokenState is null) { return(string.Empty); } var inMiddleOfPartialToken = !string.IsNullOrEmpty(tokenState.PartialToken); var myValue = string.Empty; if (!line.Contains("``")) { if (inMiddleOfPartialToken) { tokenState.PartialToken += line; sr.AdvanceToNewLineUntilPartialTokenEnds(ref tokenState, ref myValue); return(myValue); } else { return(line); } } var chunked = line.Split(new[] { "``" }, StringSplitOptions.None).ToList(); if (inMiddleOfPartialToken) { myValue = tokenState.CaptureAndEscapeThePartialToken(myValue, chunked); } bool lineHasTrailingPartialToken = chunked.Count % 2 == 0; if (lineHasTrailingPartialToken) { tokenState.StartPartialToken(chunked); } myValue = tokenState.CaptureAndEscapeOddIndexedChunks(myValue, chunked); if (lineHasTrailingPartialToken) { sr.AdvanceToNewLineUntilPartialTokenEnds(ref tokenState, ref myValue); } return(myValue); }
public static void Main() { count = 0; d = DateTime.Now; c = DateTime.Now; InputPort digitalIn = new InputPort(Pins.GPIO_PIN_D3, false, Port.ResistorMode.Disabled); OutputPort powerUpPort = new OutputPort(Pins.GPIO_PIN_D0, false); OutputPort healthOut0 = new OutputPort(Pins.GPIO_PIN_D1, false); OutputPort healthOut1 = new OutputPort(Pins.GPIO_PIN_D2, false); OutputPort healthOut2 = new OutputPort(Pins.GPIO_PIN_D4, false); OutputPort healthOut3 = new OutputPort(Pins.GPIO_PIN_D5, false); OutputPort healthOut4 = new OutputPort(Pins.GPIO_PIN_D7, false); OutputPort healthOut5 = new OutputPort(Pins.GPIO_PIN_D8, false); OutputPort healthOut6 = new OutputPort(Pins.GPIO_PIN_D9, false); OutputPort sanityPort = new OutputPort(Pins.GPIO_PIN_D13, true); infraredOut = new Microsoft.SPOT.Hardware.PWM(PWMChannels.PWM_PIN_D6, 38000, .5, true); InterruptPort sender = new InterruptPort(Pins.GPIO_PIN_D10, false, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeLow); sender.OnInterrupt += sender_OnInterrupt; state = TokenState.LISTEN; string message = ""; while (true) { sanityPort.Write(true); GetPowerUp(); DisplayHeath(healthOut0, healthOut1, healthOut2, healthOut3, healthOut4, healthOut5, healthOut6); powerUpPort.Write(powerUp); switch (state) { case TokenState.LISTEN: GetListenByte(digitalIn); break; case TokenState.STARTBYTE: GetStartByte(digitalIn); break; case TokenState.MESSAGE: message = GetMessage(digitalIn); break; case TokenState.ENDBYTE: GetEndByte(digitalIn); break; case TokenState.READ: Debug.Print(String.Concat(message + " " + "PlayerHealth" + ": " + playerHeath , "\n")); UpdatePlayer(message); state = TokenState.LISTEN; message = ""; break; } } }
private void PrepareTextToken(char value) { _tokenState = TokenState.Uninitialized; if (_textTokenIsWhitespace && !Constants.IsSpaceCharacter(value)) { _textTokenIsWhitespace = false; } _textToken.Append(value); }