text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports InternalSyntaxFactory = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.SyntaxFactory

Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax

    Friend Partial Class Parser
        ' File: Parser.cpp
        ' Lines: 14199 - 14199
        ' Initializer* .Parser::ParseSelectListInitializer( [ _Inout_ bool& ErrorInConstruct ] )

        Private Function ParseSelectListInitializer() As ExpressionRangeVariableSyntax

            Dim nameEqualsOpt As VariableNameEqualsSyntax = Nothing

            If ((CurrentToken.Kind = SyntaxKind.IdentifierToken OrElse CurrentToken.IsKeyword()) AndAlso
                PeekToken(1).Kind = SyntaxKind.EqualsToken OrElse
                (PeekToken(1).Kind = SyntaxKind.QuestionToken AndAlso PeekToken(2).Kind = SyntaxKind.EqualsToken)) Then

                Dim varName As ModifiedIdentifierSyntax = Nothing
                Dim Equals As PunctuationSyntax = Nothing

                ' // Parse form: <IdentiferOrKeyword> '=' <Expression>
                varName = ParseSimpleIdentifierAsModifiedIdentifier()

                ' NOTE: do not need to resync here. we should land on "="
                Debug.Assert(CurrentToken.Kind = SyntaxKind.EqualsToken)

                Equals = DirectCast(CurrentToken, PunctuationSyntax)
                GetNextToken() '// move off the '='
                TryEatNewLine() ' // line continuation allowed after  '='

                nameEqualsOpt = SyntaxFactory.VariableNameEquals(varName, Nothing, Equals)
            End If

            Dim expr As ExpressionSyntax = ParseExpressionCore()

            Return SyntaxFactory.ExpressionRangeVariable(
                nameEqualsOpt,
                expr)
        End Function

        ' File: Parser.cpp
        ' Lines: 14290 - 14290
        ' InitializerList* .Parser::ParseSelectList( [ _Inout_ bool& ErrorInConstruct ] )

        Private Function ParseSelectList() As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax)

            Dim RangeVariables = Me._pool.AllocateSeparated(Of ExpressionRangeVariableSyntax)()

            Do
                Dim rangeVar = ParseSelectListInitializer()

                If rangeVar.ContainsDiagnostics Then
                    rangeVar = ResyncAt(rangeVar, SyntaxKind.CommaToken, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                                 SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                                 SyntaxKind.FromKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword,
                                                 SyntaxKind.IntoKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
                End If

                RangeVariables.Add(rangeVar)

                If CurrentToken.Kind = SyntaxKind.CommaToken Then
                    Dim comma = DirectCast(CurrentToken, PunctuationSyntax)
                    GetNextToken()
                    TryEatNewLine()
                    RangeVariables.AddSeparator(comma)
                Else
                    Exit Do
                End If
            Loop

            Dim result = RangeVariables.ToList
            Me._pool.Free(RangeVariables)

            Return result
        End Function

        ' File: Parser.cpp
        ' Lines: 14333 - 14333
        ' Expression* .Parser::ParseAggregationExpression( [ _Inout_ bool& ErrorInConstruct ] )

        Private Function ParseAggregationExpression() As AggregationSyntax

            If CurrentToken.Kind = SyntaxKind.IdentifierToken Then
                Dim curIdent = DirectCast(CurrentToken, IdentifierTokenSyntax)
                If curIdent.PossibleKeywordKind = SyntaxKind.GroupKeyword Then
                    Debug.Assert(PeekToken(1).Kind = SyntaxKind.OpenParenToken)

                    curIdent = ReportSyntaxError(curIdent, ERRID.ERR_InvalidUseOfKeyword)
                    GetNextToken()
                    Return SyntaxFactory.FunctionAggregation(curIdent, Nothing, Nothing, Nothing)
                End If
            End If

            Dim aggName = ParseIdentifier()

            Dim aggregateFunc As FunctionAggregationSyntax = Nothing

            If Not aggName.ContainsDiagnostics AndAlso CurrentToken.Kind = SyntaxKind.OpenParenToken Then
                Dim lParen = DirectCast(CurrentToken, PunctuationSyntax)
                GetNextToken()  ' get off lparen

                TryEatNewLine()

                Dim arg As ExpressionSyntax = Nothing
                If CurrentToken.Kind <> SyntaxKind.CloseParenToken Then
                    arg = ParseExpressionCore()
                End If

                Dim rParen As PunctuationSyntax = Nothing
                If TryEatNewLineAndGetToken(SyntaxKind.CloseParenToken, rParen, createIfMissing:=True) Then
                    ' // check that expression doesn't continue
                    If arg IsNot Nothing Then
                        CheckForEndOfExpression(arg)
                    End If
                End If

                aggregateFunc = SyntaxFactory.FunctionAggregation(aggName, lParen, arg, rParen)
            Else
                aggregateFunc = SyntaxFactory.FunctionAggregation(aggName, Nothing, Nothing, Nothing)
                ' // check that expression doesn't continue
                CheckForEndOfExpression(aggregateFunc)
            End If

            Return aggregateFunc
        End Function

        ' // check that expression doesn't continue
        ' File: Parser.cpp
        ' Lines: 14420 - 14420

        ' bool .Parser::CheckForEndOfExpression( [ Token* Start ] [ bool& ErrorInConstruct ] )
        Private Function CheckForEndOfExpression(Of T As VisualBasicSyntaxNode)(ByRef syntax As T) As Boolean
            Debug.Assert(syntax IsNot Nothing)

            'TODO: this is very different from original implementation.
            ' originally we would try to parse the whole thing as an expression and see if we
            ' will not consume more than "syntax". It seems that "syntax" is always a term
            ' so the only way ParseExpressionCore could consume more is if there is a binary operator.
            ' Hopefully checking for binary operator is enough...
            If Not CurrentToken.IsBinaryOperator AndAlso
                CurrentToken.Kind <> SyntaxKind.DotToken Then
                Return True
            End If

            syntax = ReportSyntaxError(syntax, ERRID.ERR_ExpectedEndOfExpression)
            Return False
        End Function

        ' Several places the syntax trees allow a modified identifier, but we actually don't want to
        ' allow a trailing ?. This function encapsulates that.
        Private Function ParseSimpleIdentifierAsModifiedIdentifier() As ModifiedIdentifierSyntax
            Dim varName As IdentifierTokenSyntax = ParseIdentifier()

            If CurrentToken.Kind = SyntaxKind.QuestionToken Then
                Dim unexpectedNullable As SyntaxToken = CurrentToken
                varName = varName.AddTrailingSyntax(ReportSyntaxError(unexpectedNullable, ERRID.ERR_NullableTypeInferenceNotSupported))
                GetNextToken()   ' get off the "?"
            End If

            Return SyntaxFactory.ModifiedIdentifier(varName, Nothing, Nothing, Nothing)
        End Function

        ' File: Parser.cpp
        ' Lines: 14447 - 14447
        ' Initializer* .Parser::ParseAggregateListInitializer( [ bool AllowGroupName ] [ _Inout_ bool& ErrorInConstruct ] )

        Private Function ParseAggregateListInitializer(AllowGroupName As Boolean) As AggregationRangeVariableSyntax

            Dim varName As ModifiedIdentifierSyntax = Nothing
            Dim Equals As PunctuationSyntax = Nothing
            If ((CurrentToken.Kind = SyntaxKind.IdentifierToken OrElse CurrentToken.IsKeyword()) AndAlso
                PeekToken(1).Kind = SyntaxKind.EqualsToken _
                 OrElse
                (PeekToken(1).Kind = SyntaxKind.QuestionToken AndAlso PeekToken(2).Kind = SyntaxKind.EqualsToken)) Then

                ' // Parse form: <IdentiferOrKeyword> '=' <Expression>
                varName = ParseSimpleIdentifierAsModifiedIdentifier()

                ' NOTE: do not need to resync here. we should land on "="
                Debug.Assert(CurrentToken.Kind = SyntaxKind.EqualsToken)

                Equals = DirectCast(CurrentToken, PunctuationSyntax)
                GetNextToken() '// move off the '='
                TryEatNewLine() ' // line continuation allowed after  '='
            End If

            Dim expr As AggregationSyntax = Nothing

            If CurrentToken.Kind = SyntaxKind.IdentifierToken OrElse CurrentToken.IsKeyword() Then
                Dim groupKw As KeywordSyntax = Nothing
                If TryTokenAsContextualKeyword(CurrentToken, SyntaxKind.GroupKeyword, groupKw) AndAlso
                                        PeekToken(1).Kind <> SyntaxKind.OpenParenToken Then

                    If Not AllowGroupName Then
                        groupKw = ReportSyntaxError(groupKw, ERRID.ERR_UnexpectedGroup)
                    End If

                    expr = SyntaxFactory.GroupAggregation(groupKw)

                    ' // check that expression doesn't continue
                    CheckForEndOfExpression(expr)
                    GetNextToken() ' // Move off 'Group
                Else
                    expr = ParseAggregationExpression() ' // this must be an Aggregation
                End If

            Else
                Dim missingIdent = InternalSyntaxFactory.MissingIdentifier()
                If AllowGroupName Then
                    missingIdent = ReportSyntaxError(missingIdent, ERRID.ERR_ExpectedIdentifierOrGroup)
                Else
                    missingIdent = ReportSyntaxError(missingIdent, ERRID.ERR_ExpectedIdentifier)
                End If
                expr = SyntaxFactory.FunctionAggregation(missingIdent, Nothing, Nothing, Nothing)
            End If

            Debug.Assert((varName Is Nothing) = (Equals Is Nothing))
            Dim variableNameEquals As VariableNameEqualsSyntax = Nothing
            If varName IsNot Nothing AndAlso Equals IsNot Nothing Then
                variableNameEquals = SyntaxFactory.VariableNameEquals(varName, Nothing, Equals)
            End If

            Return SyntaxFactory.AggregationRangeVariable(
                variableNameEquals,
                expr)
        End Function

        ' File: Parser.cpp
        ' Lines: 14615 - 14615
        ' InitializerList* .Parser::ParseAggregateList( [ bool AllowGroupName ] [ bool IsGroupJoinProjection ] [ _Inout_ bool& ErrorInConstruct ] )
        Private Function ParseAggregateList(
            AllowGroupName As Boolean,
            IsGroupJoinProjection As Boolean) As SeparatedSyntaxList(Of AggregationRangeVariableSyntax)

            Dim RangeVariables = Me._pool.AllocateSeparated(Of AggregationRangeVariableSyntax)()

            Do
                Dim rangeVar = ParseAggregateListInitializer(AllowGroupName)

                If rangeVar.ContainsDiagnostics Then
                    If IsGroupJoinProjection Then
                        rangeVar = ResyncAt(rangeVar, SyntaxKind.CommaToken, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                 SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                 SyntaxKind.FromKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword,
                                 SyntaxKind.IntoKeyword, SyntaxKind.OnKeyword, SyntaxKind.SkipKeyword,
                                 SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
                    Else
                        rangeVar = ResyncAt(rangeVar, SyntaxKind.CommaToken, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                 SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                 SyntaxKind.FromKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword,
                                 SyntaxKind.IntoKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword,
                                 SyntaxKind.LetKeyword)
                    End If
                End If

                RangeVariables.Add(rangeVar)

                If CurrentToken.Kind = SyntaxKind.CommaToken Then
                    Dim comma = DirectCast(CurrentToken, PunctuationSyntax)
                    GetNextToken()
                    TryEatNewLine()
                    RangeVariables.AddSeparator(comma)
                Else
                    Exit Do
                End If
            Loop

            Dim result = RangeVariables.ToList
            Me._pool.Free(RangeVariables)

            Return result
        End Function

        ' File: Parser.cpp
        ' Lines: 14666 - 14666
        ' FromList* .Parser::ParseFromList( [ bool AssignmentList ] [ _Inout_ bool& ErrorInConstruct ] )

        ' TODO: Merge with ParseFromControlVars. The two methods are almost identical.
        Private Function ParseLetList() As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax)

            Dim RangeVariables = Me._pool.AllocateSeparated(Of ExpressionRangeVariableSyntax)()

            Do
                Dim varName As ModifiedIdentifierSyntax = ParseNullableModifiedIdentifer()

                If varName.ContainsDiagnostics Then
                    ' // If we see As or In before other query operators, then assume that
                    ' // we are still on the Control Variable Declaration.
                    ' // Otherwise, don't resync and allow the caller to
                    ' // decide how to recover.

                    Dim peek = PeekAheadFor(SyntaxKind.AsKeyword, SyntaxKind.InKeyword, SyntaxKind.CommaToken,
                        SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                        SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                        SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
                        SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)

                    Select Case (peek)
                        Case SyntaxKind.AsKeyword,
                            SyntaxKind.InKeyword,
                            SyntaxKind.CommaToken

                            varName = varName.AddTrailingSyntax(ResyncAt({peek}))
                    End Select
                End If

                If CurrentToken.Kind = SyntaxKind.QuestionToken AndAlso
                    (PeekToken(1).Kind = SyntaxKind.InKeyword OrElse
                      PeekToken(1).Kind = SyntaxKind.EqualsToken) Then

                    Dim unexpectedNullable As SyntaxToken = CurrentToken
                    varName = varName.AddTrailingSyntax(ReportSyntaxError(unexpectedNullable, ERRID.ERR_NullableTypeInferenceNotSupported))
                    GetNextToken()   ' get off the "?"
                End If

                Dim AsClause As SimpleAsClauseSyntax = Nothing
                Dim TokenFollowingAsWasIn As Boolean = False

                ' // Parse the type if specified

                If CurrentToken.Kind = SyntaxKind.AsKeyword Then
                    Dim AsKw As KeywordSyntax = DirectCast(CurrentToken, KeywordSyntax)
                    Debug.Assert(AsKw IsNot Nothing)

                    ' // Parse the type
                    GetNextToken() ' // get off AS

                    If CurrentToken.Kind = SyntaxKind.InKeyword Then
                        TokenFollowingAsWasIn = True
                    End If

                    Dim Type As TypeSyntax = ParseGeneralType()
                    AsClause = SyntaxFactory.SimpleAsClause(AsKw, Nothing, Type)

                    ' // try to recover
                    If Type.ContainsDiagnostics Then
                        Dim peek = PeekAheadFor(SyntaxKind.InKeyword, SyntaxKind.CommaToken, SyntaxKind.EqualsToken,
                                                SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                                SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                                SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
                                                SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
                        Select Case (peek)
                            Case SyntaxKind.AsKeyword,
                                SyntaxKind.InKeyword,
                                SyntaxKind.CommaToken

                                AsClause = AsClause.AddTrailingSyntax(ResyncAt({peek}))
                        End Select
                    End If
                End If

                Dim Equals As PunctuationSyntax = Nothing
                Dim source As ExpressionSyntax = Nothing
                If Not TryGetToken(SyntaxKind.EqualsToken, Equals) Then
                    Equals = InternalSyntaxFactory.MissingPunctuation(SyntaxKind.EqualsToken)
                    Equals = ReportSyntaxError(Equals, ERRID.ERR_ExpectedAssignmentOperator)
                Else
                    If Not TokenFollowingAsWasIn Then
                        TryEatNewLine() ' // enable implicit LC after 'In' or '=' But not if somebody did from x as IN
                    End If
                    source = ParseExpressionCore()
                End If

                ' // try to recover
                If source Is Nothing OrElse source.ContainsDiagnostics Then
                    ' Fix up source
                    source = If(source, InternalSyntaxFactory.MissingExpression)

                    Dim peek = PeekAheadFor(SyntaxKind.CommaToken,
                                            SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                            SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                            SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
                                            SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)

                    If peek = SyntaxKind.CommaToken Then
                        source = source.AddTrailingSyntax(ResyncAt({peek}))
                    End If
                End If

                Dim rangeVar = SyntaxFactory.ExpressionRangeVariable(
                    SyntaxFactory.VariableNameEquals(varName, AsClause, Equals),
                    source)

                RangeVariables.Add(rangeVar)

                ' // check for list continuation
                Dim comma As PunctuationSyntax = Nothing
                If TryGetTokenAndEatNewLine(SyntaxKind.CommaToken, comma) Then
                    RangeVariables.AddSeparator(comma)
                Else
                    Exit Do
                End If
            Loop

            Dim result = RangeVariables.ToList
            Me._pool.Free(RangeVariables)

            Return result
        End Function

        Private Function ParseFromControlVars() As SeparatedSyntaxList(Of CollectionRangeVariableSyntax)
            Dim RangeVariables = Me._pool.AllocateSeparated(Of CollectionRangeVariableSyntax)()

            Do
                Dim varName As ModifiedIdentifierSyntax = ParseNullableModifiedIdentifer()

                If varName.ContainsDiagnostics Then
                    ' // If we see As or In before other query operators, then assume that
                    ' // we are still on the Control Variable Declaration.
                    ' // Otherwise, don't resync and allow the caller to
                    ' // decide how to recover.

                    Dim peek = PeekAheadFor(SyntaxKind.AsKeyword, SyntaxKind.InKeyword, SyntaxKind.CommaToken,
                                            SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                            SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                            SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
                                            SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)

                    Select Case (peek)
                        Case SyntaxKind.AsKeyword,
                            SyntaxKind.InKeyword,
                            SyntaxKind.CommaToken

                            varName = varName.AddTrailingSyntax(ResyncAt({peek}))
                    End Select
                End If

                If CurrentToken.Kind = SyntaxKind.QuestionToken AndAlso
                    (PeekToken(1).Kind = SyntaxKind.InKeyword OrElse
                      PeekToken(1).Kind = SyntaxKind.EqualsToken) Then

                    Dim unexpectedNullable As SyntaxToken = CurrentToken
                    varName = varName.AddTrailingSyntax(ReportSyntaxError(unexpectedNullable, ERRID.ERR_NullableTypeInferenceNotSupported))
                    GetNextToken()   ' get off the "?"
                End If

                Dim AsClause As SimpleAsClauseSyntax = Nothing
                Dim TokenFollowingAsWasIn As Boolean = False

                ' // Parse the type if specified

                If CurrentToken.Kind = SyntaxKind.AsKeyword Then
                    Dim AsKw As KeywordSyntax = DirectCast(CurrentToken, KeywordSyntax)
                    Debug.Assert(AsKw IsNot Nothing)

                    ' // Parse the type
                    GetNextToken() ' // get off AS

                    If CurrentToken.Kind = SyntaxKind.InKeyword Then
                        TokenFollowingAsWasIn = True
                    End If

                    Dim Type As TypeSyntax = ParseGeneralType()
                    AsClause = SyntaxFactory.SimpleAsClause(AsKw, Nothing, Type)

                    ' // try to recover
                    If Type.ContainsDiagnostics Then
                        Dim peek = PeekAheadFor(SyntaxKind.InKeyword, SyntaxKind.CommaToken, SyntaxKind.EqualsToken,
                                                SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                                SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                                SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
                                                SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)

                        Select Case (peek)
                            Case SyntaxKind.AsKeyword,
                                SyntaxKind.InKeyword,
                                SyntaxKind.CommaToken

                                AsClause = AsClause.AddTrailingSyntax(ResyncAt({peek}))
                        End Select
                    End If
                End If

                Dim [In] As KeywordSyntax = Nothing
                Dim source As ExpressionSyntax = Nothing
                If TryEatNewLineAndGetToken(SyntaxKind.InKeyword, [In], createIfMissing:=True) Then
                    If Not TokenFollowingAsWasIn Then
                        TryEatNewLine() ' // enable implicit LC after 'In' or '=' But not if somebody did from x as IN
                    End If
                    source = ParseExpressionCore()
                End If

                ' // try to recover
                If source Is Nothing OrElse source.ContainsDiagnostics Then
                    ' Fix up source
                    source = If(source, InternalSyntaxFactory.MissingExpression)

                    ' resync
                    Dim peek = PeekAheadFor(SyntaxKind.CommaToken,
                                            SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                            SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                            SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
                                            SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)

                    If peek = SyntaxKind.CommaToken Then
                        source = source.AddTrailingSyntax(ResyncAt({peek}))
                    End If
                End If

                Dim rangeVar = SyntaxFactory.CollectionRangeVariable(varName, AsClause, [In], source)
                RangeVariables.Add(rangeVar)

                ' // check for list continuation
                Dim comma As PunctuationSyntax = Nothing
                If TryGetTokenAndEatNewLine(SyntaxKind.CommaToken, comma) Then
                    RangeVariables.AddSeparator(comma)
                Else
                    Exit Do
                End If
            Loop

            Dim result = RangeVariables.ToList
            Me._pool.Free(RangeVariables)

            Return result
        End Function

        ' /*********************************************************************
        ' ;ParsePotentialQuery
        '
        ' The parser determined that we might be on a query expression because we were on 'From' or
        ' 'Aggregate'  We now see if we actually are on a query expression and parse it if we are.
        ' **********************************************************************/
        ' // the query expression if this is in fact a query we are on

        ' // [out] true = that we were on a query and that we handled it / false = not a query
        ' // [out] whether we encountered an error processing the query statement (assuming this actually is a query statement)

        ' Expression* .Parser::ParsePotentialQuery( [ _Inout_ ParseTree::LineContinuationState& continuationState ] [ _Out_ bool& ParsedQuery ] [ _Out_ bool& ErrorInConstruct ] )
        Private Function ParsePotentialQuery(contextualKeyword As KeywordSyntax) As ExpressionSyntax
            Debug.Assert(contextualKeyword IsNot Nothing)
            Debug.Assert(contextualKeyword.Kind = SyntaxKind.FromKeyword OrElse contextualKeyword.Kind = SyntaxKind.AggregateKeyword)

            Debug.Assert(CurrentToken.Text = contextualKeyword.Text)
            ' // Look ahead and see if it looks like a query, i.e.
            ' // {AGGREGATE | FROM } <id>[?] {In | As | = }

            Dim newLineAfterFrom As Boolean = False

            Dim curIndex = 1
            Dim current As SyntaxToken = PeekToken(curIndex)

            If current IsNot Nothing AndAlso current.IsEndOfLine() Then
                If Not NextLineStartsWithStatementTerminator(1) Then '// we don't allow two EOLs in a row here
                    curIndex += 1
                    current = PeekToken(curIndex)
                    newLineAfterFrom = True
                End If
            End If

            ' <id>
            If current Is Nothing OrElse (current.Kind <> SyntaxKind.IdentifierToken AndAlso Not current.IsKeyword) Then
                Return Nothing
            End If

            ' "FROM <id> <EOL>" on the same line is enough to consider this a query.  Only do the full check if
            ' there is a new line between the FROM and the <id>, if this is a keyword after the FROM or if the identifier is
            ' a contextual keyword.
            '
            ' These are query expressions:
            ' x = From y    (it's important for the IDE to have this classified as a query to offer correct highlighting
            '                and completion suggestions)
            '   or
            ' x = from y
            '     In ...
            ' This logic is needed to not classify the identifier "From" in the following JoinCondition as query:
            ' dim f = Join x On From Equals y
            '
            ' These are two assignments:
            ' x = From
            ' y =
            '   and
            ' x = from a With
            '
            ' See Bugs 1678 and 10020 for more context.
            '

            Dim identifierAsContextualKeyword As KeywordSyntax = Nothing
            If newLineAfterFrom OrElse
                current.IsKeyword OrElse
                (current.Kind = SyntaxKind.IdentifierToken AndAlso
                TryTokenAsContextualKeyword(current, identifierAsContextualKeyword)) Then

                ' Note: this block is used to reject queries. Everything that skips this if
                ' will be classified as a query.

                curIndex += 1
                current = PeekToken(curIndex)

                ' // Look ahead for 'IN' as it can start it's own line
                If current IsNot Nothing Then
                    If current.Kind = SyntaxKind.StatementTerminatorToken Then
                        current = PeekToken(curIndex + 1)

                        If current Is Nothing OrElse current.Kind <> SyntaxKind.InKeyword Then
                            Return Nothing
                        End If
                    ElseIf current.Kind = SyntaxKind.QuestionToken Then
                        ' // Skip '?'
                        curIndex += 1
                        current = PeekToken(curIndex)
                    End If
                End If

                If current Is Nothing Then
                    Return Nothing
                End If

                ' check for As, In or  =
                ' note that = may not come after EoL
                If current.Kind <> SyntaxKind.InKeyword AndAlso
                    current.Kind <> SyntaxKind.AsKeyword AndAlso
                    (newLineAfterFrom OrElse current.Kind <> SyntaxKind.EqualsToken) Then

                    Return Nothing
                End If

            End If

            If contextualKeyword.Kind = SyntaxKind.FromKeyword Then
                GetNextToken() 'get off the From
                Return ParseFromQueryExpression(contextualKeyword)
            Else
                Debug.Assert(contextualKeyword.Kind = SyntaxKind.AggregateKeyword)
                GetNextToken() 'get off the Aggregate
                Return ParseAggregateQueryExpression(contextualKeyword)
            End If
        End Function

        Private Function ParseGroupByExpression(groupKw As KeywordSyntax) As GroupByClauseSyntax
            Debug.Assert(groupKw IsNot Nothing)

            Dim byKw As KeywordSyntax = Nothing
            Dim elements As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax) = Nothing
            If Not TryEatNewLineAndGetContextualKeyword(SyntaxKind.ByKeyword, byKw, createIfMissing:=False) Then
                TryEatNewLine()
                ' // parse element selector
                elements = ParseSelectList()
            End If

            Dim keys As SeparatedSyntaxList(Of ExpressionRangeVariableSyntax) = Nothing
            If byKw IsNot Nothing OrElse TryEatNewLineAndGetContextualKeyword(SyntaxKind.ByKeyword, byKw, createIfMissing:=True) Then
                TryEatNewLine()
                ' // parse key selector
                keys = ParseSelectList()
            Else
                Dim rangeVariables = Me._pool.AllocateSeparated(Of ExpressionRangeVariableSyntax)()
                rangeVariables.Add(InternalSyntaxFactory.ExpressionRangeVariable(Nothing, InternalSyntaxFactory.MissingExpression()))
                keys = rangeVariables.ToList
                Me._pool.Free(rangeVariables)
            End If

            Dim intoKw As KeywordSyntax = Nothing
            Dim Aggregation As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = Nothing
            If TryEatNewLineAndGetContextualKeyword(SyntaxKind.IntoKeyword, intoKw, createIfMissing:=True) Then
                TryEatNewLine()
                ' // parse result selector
                Aggregation = ParseAggregateList(True, False)
            Else
                Aggregation = Me.MissingAggregationRangeVariables()
            End If

            Return SyntaxFactory.GroupByClause(groupKw, elements, byKw, keys, intoKw, Aggregation)
        End Function

        Private Function MissingAggregationRangeVariables() As SeparatedSyntaxList(Of AggregationRangeVariableSyntax)
            Dim rangeVariables = Me._pool.AllocateSeparated(Of AggregationRangeVariableSyntax)()
            rangeVariables.Add(InternalSyntaxFactory.AggregationRangeVariable(Nothing, SyntaxFactory.FunctionAggregation(InternalSyntaxFactory.MissingIdentifier(), Nothing, Nothing, Nothing)))
            Dim result As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = rangeVariables.ToList
            Me._pool.Free(rangeVariables)
            Return result
        End Function

        ' File: Parser.cpp
        ' Lines: 15016 - 15016
        ' GroupJoinExpression* .Parser::ParseGroupJoinExpression( [ _In_ Token* beginSourceToken ] [ _In_opt_ ParseTree::LinqExpression* Source ] [ _Inout_ bool& ErrorInConstruct ] )

        Private Function ParseInnerJoinOrGroupJoinExpression(groupKw As KeywordSyntax,
                                                  joinKw As KeywordSyntax) As JoinClauseSyntax

            Debug.Assert(joinKw IsNot Nothing)

            ' // Make sure control var on the left is always named
            ' TODO: semantics
            ' MakeSureLeftControlVarIsNamed(source)

            TryEatNewLine()
            Dim joinVariable = ParseJoinControlVar()

            Dim moreJoinsBuilder = _pool.Allocate(Of JoinClauseSyntax)()
            Do
                Dim nextJoin = ParseOptionalJoinOperator()
                If nextJoin Is Nothing Then
                    Exit Do
                End If
                moreJoinsBuilder.Add(nextJoin)
            Loop

            Dim onKw As KeywordSyntax = Nothing
            Dim Predicate As SeparatedSyntaxList(Of JoinConditionSyntax) = Nothing
            If TryEatNewLineAndGetToken(SyntaxKind.OnKeyword, onKw, createIfMissing:=True) Then
                TryEatNewLine()
                Predicate = ParseJoinPredicateExpression()
            Else
                Dim missingEq = SyntaxFactory.JoinCondition(InternalSyntaxFactory.MissingExpression,
                                        InternalSyntaxFactory.MissingKeyword(SyntaxKind.EqualsKeyword),
                                        InternalSyntaxFactory.MissingExpression)
                Predicate = New SeparatedSyntaxList(Of JoinConditionSyntax)(missingEq)
            End If

            Dim joinVarList = New SeparatedSyntaxList(Of CollectionRangeVariableSyntax)(joinVariable)
            Dim moreJoins = moreJoinsBuilder.ToList()
            _pool.Free(moreJoinsBuilder)

            If groupKw Is Nothing Then
                Return SyntaxFactory.SimpleJoinClause(joinKw, joinVarList, moreJoins, onKw, Predicate)
            Else
                Dim intoKw As KeywordSyntax = Nothing
                Dim Aggregation As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = Nothing
                If TryEatNewLineAndGetContextualKeyword(SyntaxKind.IntoKeyword, intoKw, createIfMissing:=True) Then
                    TryEatNewLine()

                    ' // parse result selector
                    Aggregation = ParseAggregateList(True, True)
                Else
                    Aggregation = Me.MissingAggregationRangeVariables()
                End If

                Return SyntaxFactory.GroupJoinClause(groupKw, joinKw, joinVarList, moreJoins, onKw, Predicate, intoKw, Aggregation)
            End If
        End Function

        ' File: Parser.cpp
        ' Lines: 15260 - 15260
        ' LinqExpression* .Parser::ParseJoinSourceExpression( [ _Inout_ bool& ErrorInConstruct ] )

        Private Function ParseOptionalJoinOperator() As JoinClauseSyntax
            Dim joinKw As KeywordSyntax = Nothing
            If TryEatNewLineAndGetContextualKeyword(SyntaxKind.JoinKeyword, joinKw) Then
                Return ParseInnerJoinOrGroupJoinExpression(Nothing, joinKw)
            End If

            Dim groupKw As KeywordSyntax = Nothing
            If TryEatNewLineAndGetContextualKeyword(SyntaxKind.GroupKeyword, groupKw) Then
                TryGetContextualKeyword(SyntaxKind.JoinKeyword, joinKw, createIfMissing:=True)
                Return ParseInnerJoinOrGroupJoinExpression(groupKw, joinKw)
            End If
            Return Nothing
        End Function

        ' File: Parser.cpp
        ' Lines: 15107 - 15107
        ' LinqSourceExpression* .Parser::ParseJoinControlVarExpression( [ _Inout_ bool& ErrorInConstruct ] )

        Private Function ParseJoinControlVar() As CollectionRangeVariableSyntax

            Dim varName As ModifiedIdentifierSyntax = ParseNullableModifiedIdentifer()
            If varName.ContainsDiagnostics Then
                ' // If we see As or In before other query operators, then assume that
                ' // we are still on the Control Variable Declaration.
                ' // Otherwise, don't resync and allow the caller to
                ' // decide how to recover.

                Dim peek = PeekAheadFor(SyntaxKind.AsKeyword, SyntaxKind.InKeyword, SyntaxKind.OnKeyword,
                                        SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                        SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                        SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
                                        SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)

                Select Case (peek)
                    Case SyntaxKind.AsKeyword,
                        SyntaxKind.InKeyword,
                        SyntaxKind.GroupKeyword,
                        SyntaxKind.JoinKeyword,
                        SyntaxKind.OnKeyword

                        varName = varName.AddTrailingSyntax(ResyncAt({peek}))
                End Select
            End If

            If CurrentToken.Kind = SyntaxKind.QuestionToken AndAlso
                PeekToken(1).Kind = SyntaxKind.InKeyword Then

                Dim unexpectedNullable As SyntaxToken = CurrentToken
                varName = varName.AddTrailingSyntax(ReportSyntaxError(unexpectedNullable, ERRID.ERR_NullableTypeInferenceNotSupported))
                GetNextToken()   ' get off the "?"
            End If

            Dim AsClause As SimpleAsClauseSyntax = Nothing

            ' // Parse the type if specified
            If CurrentToken.Kind = SyntaxKind.AsKeyword Then
                Dim AsKw As KeywordSyntax = DirectCast(CurrentToken, KeywordSyntax)
                Debug.Assert(AsKw IsNot Nothing)

                ' // Parse the type
                GetNextToken() ' // get off AS

                Dim Type As TypeSyntax = ParseGeneralType()
                AsClause = SyntaxFactory.SimpleAsClause(AsKw, Nothing, Type)

                ' // try to recover
                If Type.ContainsDiagnostics Then
                    Dim peek = PeekAheadFor(SyntaxKind.InKeyword, SyntaxKind.OnKeyword, SyntaxKind.EqualsToken,
                                            SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                            SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                            SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
                                            SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)

                    Select Case (peek)
                        Case SyntaxKind.EqualsToken,
                            SyntaxKind.InKeyword,
                            SyntaxKind.GroupKeyword,
                            SyntaxKind.JoinKeyword,
                            SyntaxKind.OnKeyword

                            AsClause = AsClause.AddTrailingSyntax(ResyncAt({peek}))
                    End Select
                End If
            End If

            Dim [In] As KeywordSyntax = Nothing
            Dim source As ExpressionSyntax = Nothing
            If TryEatNewLineAndGetToken(SyntaxKind.InKeyword, [In], createIfMissing:=True) Then
                TryEatNewLine() ' // dev10_500708 allow line continuation after 'IN'
                source = ParseExpressionCore()
            End If

            ' // try to recover
            If source Is Nothing OrElse source.ContainsDiagnostics Then
                ' Fix up source
                source = If(source, InternalSyntaxFactory.MissingExpression)

                ' resync
                Dim peek = PeekAheadFor(SyntaxKind.CommaToken,
                                        SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                        SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                        SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword,
                                        SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)

                If peek = SyntaxKind.CommaToken Then
                    source = source.AddTrailingSyntax(ResyncAt({peek}))
                End If
            End If

            Return SyntaxFactory.CollectionRangeVariable(varName, AsClause, [In], source)
        End Function

        ' File: Parser.cpp
        ' Lines: 15293 - 15293
        ' Expression* .Parser::ParseJoinPredicateExpression( [ _Inout_ bool& ErrorInConstruct ] )

        Private Function ParseJoinPredicateExpression() As SeparatedSyntaxList(Of JoinConditionSyntax)

            Dim Exprs = Me._pool.AllocateSeparated(Of JoinConditionSyntax)()
            Dim AndTk As KeywordSyntax = Nothing

            Do
                Dim element As JoinConditionSyntax = Nothing

                If CurrentToken.Kind <> SyntaxKind.StatementTerminatorToken Then
                    Dim Left = ParseExpressionCore(OperatorPrecedence.PrecedenceRelational)

                    ' // try to recover
                    If Left.ContainsDiagnostics Then
                        Left = ResyncAt(Left, SyntaxKind.EqualsToken, SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword,
                                        SyntaxKind.GroupKeyword, SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword,
                                        SyntaxKind.JoinKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword,
                                        SyntaxKind.IntoKeyword, SyntaxKind.OnKeyword, SyntaxKind.AndKeyword, SyntaxKind.AndAlsoKeyword,
                                        SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.SkipKeyword, SyntaxKind.SkipKeyword,
                                        SyntaxKind.LetKeyword)
                    End If

                    Dim eqKw As KeywordSyntax = Nothing
                    Dim Right As ExpressionSyntax = Nothing
                    If TryGetContextualKeywordAndEatNewLine(SyntaxKind.EqualsKeyword, eqKw, createIfMissing:=True) Then
                        Right = ParseExpressionCore(OperatorPrecedence.PrecedenceRelational)
                    Else
                        Right = InternalSyntaxFactory.MissingExpression
                    End If

                    element = SyntaxFactory.JoinCondition(Left, eqKw, Right)
                Else
                    element = SyntaxFactory.JoinCondition(InternalSyntaxFactory.MissingExpression,
                                                             InternalSyntaxFactory.MissingKeyword(SyntaxKind.EqualsKeyword),
                                                             InternalSyntaxFactory.MissingExpression)

                    element = ReportSyntaxError(element, ERRID.ERR_ExpectedExpression)
                End If

                ' // try to recover
                If element.ContainsDiagnostics Then
                    element = ResyncAt(element, SyntaxKind.AndKeyword, SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword,
                                       SyntaxKind.GroupKeyword, SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                       SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword, SyntaxKind.OnKeyword,
                                       SyntaxKind.AndAlsoKeyword, SyntaxKind.OrKeyword, SyntaxKind.OrElseKeyword, SyntaxKind.SkipKeyword,
                                       SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
                End If

                If Exprs.Count > 0 Then
                    Exprs.AddSeparator(AndTk)
                End If
                Exprs.Add(element)

                If TryGetTokenAndEatNewLine(SyntaxKind.AndKeyword, AndTk) Then
                    Continue Do

                ElseIf CurrentToken.Kind = SyntaxKind.AndAlsoKeyword OrElse
                       CurrentToken.Kind = SyntaxKind.OrKeyword OrElse
                       CurrentToken.Kind = SyntaxKind.OrElseKeyword Then

                    Exprs(Exprs.Count - 1) = Exprs(Exprs.Count - 1).AddTrailingSyntax(CurrentToken, ERRID.ERR_ExpectedAnd)
                    GetNextToken() ' consume bad token
                End If
                Exit Do
            Loop

            Dim result = Exprs.ToList
            Me._pool.Free(Exprs)

            ' // try to recover
            If result.Node.ContainsDiagnostics Then
                Dim elements = result.Node
                elements = ResyncAt(elements, SyntaxKind.FromKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                   SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword, SyntaxKind.DistinctKeyword,
                                   SyntaxKind.AggregateKeyword, SyntaxKind.IntoKeyword, SyntaxKind.OnKeyword, SyntaxKind.SkipKeyword,
                                   SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)

                result = New SeparatedSyntaxList(Of JoinConditionSyntax)(New SyntaxList(Of JoinConditionSyntax)(elements))
            End If

            Return result
        End Function

        ' File: Parser.cpp
        ' Lines: 14861 - 14861
        ' LinqExpression* .Parser::ParseFromExpression( [ bool StartingQuery ] [ bool ImplicitFrom ] [ _Inout_ bool& ErrorInConstruct ] )

        Private Function ParseFromOperator(FromKw As KeywordSyntax) As FromClauseSyntax
            Debug.Assert(FromKw IsNot Nothing)

            TryEatNewLine()
            Return SyntaxFactory.FromClause(FromKw, ParseFromControlVars())
        End Function

        Private Function ParseLetOperator(LetKw As KeywordSyntax) As LetClauseSyntax
            Debug.Assert(LetKw IsNot Nothing)

            TryEatNewLine()
            Return SyntaxFactory.LetClause(LetKw, ParseLetList())
        End Function

        ' File: Parser.cpp
        ' Lines: 15389 - 15389
        'ParseTree::OrderByList *
        'Parser::ParseOrderByList
        '(
        '    _Inout_ bool &ErrorInConstruct
        '    _Inout_ ParseTree::LineContinuationState &OrderExprContinuationState, // [out] the continuation situation for the Order statement as relates to the Ascending/Descending keywords
        '    _Inout_ bool &ErrorInConstruct // [out] whether we ran into an error processing the OrderBy list.
        ')

        Private Function ParseOrderByList() As SeparatedSyntaxList(Of OrderingSyntax)

            Dim exprs = Me._pool.AllocateSeparated(Of OrderingSyntax)()

            Do
                Dim OrderExpression = ParseExpressionCore()

                ' // try to recover
                If OrderExpression.ContainsDiagnostics Then
                    OrderExpression = ResyncAt(OrderExpression, SyntaxKind.CommaToken, SyntaxKind.AscendingKeyword,
                                               SyntaxKind.DescendingKeyword, SyntaxKind.WhereKeyword, SyntaxKind.GroupKeyword,
                                               SyntaxKind.SelectKeyword, SyntaxKind.OrderKeyword, SyntaxKind.JoinKeyword,
                                               SyntaxKind.FromKeyword, SyntaxKind.DistinctKeyword, SyntaxKind.AggregateKeyword,
                                               SyntaxKind.IntoKeyword, SyntaxKind.SkipKeyword, SyntaxKind.TakeKeyword, SyntaxKind.LetKeyword)
                End If

                Dim element As OrderingSyntax = Nothing
                Dim directionKw As KeywordSyntax = Nothing
                If TryEatNewLineAndGetContextualKeyword(SyntaxKind.DescendingKeyword, directionKw) Then
                    element = SyntaxFactory.DescendingOrdering(OrderExpression, directionKw)
                Else
                    TryEatNewLineAndGetContextualKeyword(SyntaxKind.AscendingKeyword, directionKw)
                    element = SyntaxFactory.AscendingOrdering(OrderExpression, directionKw)
                End If

                exprs.Add(element)

                Dim comma As PunctuationSyntax = Nothing
                If TryEatNewLineAndGetToken(SyntaxKind.CommaToken, comma, createIfMissing:=False) Then
                    TryEatNewLine()
                    exprs.AddSeparator(comma)
                Else
                    Exit Do
                End If
            Loop

            Dim result = exprs.ToList
            Me._pool.Free(exprs)

            Return result
        End Function

        ' File: Parser.cpp
        ' Lines: 15508 - 15508
        ' LinqExpression* .Parser::ParseFromQueryExpression( [ bool ImplicitFrom ] [ _Inout_ bool& ErrorInConstruct ] )
        Private Sub ParseMoreQueryOperators(ByRef operators As SyntaxListBuilder(Of QueryClauseSyntax))
            Do
                ' // try to recover
                If operators.Count > 0 AndAlso operators(operators.Count - 1).ContainsDiagnostics Then

                    operators(operators.Count - 1) = ResyncAt(operators(operators.Count - 1),
                        SyntaxKind.FromKeyword,
                        SyntaxKind.WhereKeyword,
                        SyntaxKind.GroupKeyword,
                        SyntaxKind.SelectKeyword,
                        SyntaxKind.OrderKeyword,
                        SyntaxKind.JoinKeyword,
                        SyntaxKind.DistinctKeyword,
                        SyntaxKind.AggregateKeyword,
                        SyntaxKind.IntoKeyword,
                        SyntaxKind.SkipKeyword,
                        SyntaxKind.TakeKeyword,
                        SyntaxKind.LetKeyword)
                End If

                Dim clause = ParseNextQueryOperator()
                If clause Is Nothing Then
                    Return
                End If

                operators.Add(clause)
            Loop
        End Sub

        Private Function ParseNextQueryOperator() As QueryClauseSyntax
            Dim Start = CurrentToken

            ' //We allow implicit line continuations before query keywords when in a query context.
            If Start.Kind = SyntaxKind.StatementTerminatorToken Then

                If NextLineStartsWithStatementTerminator() OrElse
                   Not IsContinuableQueryOperator(PeekToken(1)) Then

                    Return Nothing
                End If

                ' we are going to use this EoL and next token since we know it is a valid operator.
                ' so it is ok to move to the next token and grab EoL as a trivia.
                TryEatNewLine()
                Start = CurrentToken
            End If

            ' // it must be Id or Keyword from here

            Select Case Start.Kind
                Case SyntaxKind.SelectKeyword
                    GetNextToken() ' get off Select
                    TryEatNewLine()

                    Dim Projection = ParseSelectList()
                    Return InternalSyntaxFactory.SelectClause(DirectCast(Start, KeywordSyntax), Projection)

                Case SyntaxKind.LetKeyword
                    GetNextToken() ' get off Let
                    Return ParseLetOperator(DirectCast(Start, KeywordSyntax))

                Case SyntaxKind.IdentifierToken
                    Dim kw As KeywordSyntax = Nothing
                    If Not TryTokenAsContextualKeyword(Start, kw) Then
                        Return Nothing
                    End If

                    Select Case kw.Kind

                        Case SyntaxKind.WhereKeyword
                            GetNextToken() ' get off where
                            TryEatNewLine()
                            Return InternalSyntaxFactory.WhereClause(kw, ParseExpressionCore())

                        Case SyntaxKind.SkipKeyword
                            GetNextToken() ' get off Skip

                            If CurrentToken.Kind = SyntaxKind.WhileKeyword Then
                                ' // Note: no line continuation if Skip is followed by While, i.e. Skip While is treated as a unit
                                Dim whileKw = DirectCast(CurrentToken, KeywordSyntax)
                                GetNextToken() ' get off While
                                TryEatNewLine()
                                Return InternalSyntaxFactory.SkipWhileClause(kw, whileKw, ParseExpressionCore())
                            Else
                                TryEatNewLineIfNotFollowedBy(SyntaxKind.WhileKeyword) ' // when Skip ends the line, allow a implicit line continuation
                                Return InternalSyntaxFactory.SkipClause(kw, ParseExpressionCore())
                            End If

                        Case SyntaxKind.TakeKeyword
                            GetNextToken() ' get off Take

                            If CurrentToken.Kind = SyntaxKind.WhileKeyword Then
                                ' // Note: no line continuation if Skip is followed by While, i.e. Skip While is treated as a unit
                                Dim whileKw = DirectCast(CurrentToken, KeywordSyntax)
                                GetNextToken() ' get off While
                                TryEatNewLine()
                                Return InternalSyntaxFactory.TakeWhileClause(kw, whileKw, ParseExpressionCore())
                            Else
                                TryEatNewLineIfNotFollowedBy(SyntaxKind.WhileKeyword) ' // when Skip ends the line, allow a implicit line continuation
                                Return InternalSyntaxFactory.TakeClause(kw, ParseExpressionCore())
                            End If

                        Case SyntaxKind.GroupKeyword
                            GetNextToken() 'get off Group

                            ' // See if this is a 'Group Join'
                            Dim joinKw As KeywordSyntax = Nothing
                            If TryGetContextualKeyword(SyntaxKind.JoinKeyword, joinKw) Then
                                Return ParseInnerJoinOrGroupJoinExpression(kw, joinKw)
                            Else
                                Return ParseGroupByExpression(kw)
                            End If

                        Case SyntaxKind.AggregateKeyword
                            GetNextToken() ' get off Aggregate
                            Return ParseAggregateClause(kw)

                        Case SyntaxKind.OrderKeyword
                            GetNextToken() ' get off Order

                            Dim byKw As KeywordSyntax = Nothing
                            TryGetContextualKeywordAndEatNewLine(SyntaxKind.ByKeyword, byKw, createIfMissing:=True)

                            TryEatNewLine()
                            Dim OrderByItems = ParseOrderByList()

                            Return InternalSyntaxFactory.OrderByClause(kw, byKw, OrderByItems)

                        Case SyntaxKind.DistinctKeyword
                            GetNextToken()   ' get off Distinct

                            If CurrentToken.Kind = SyntaxKind.StatementTerminatorToken Then
                                ' Eat the new line only if the distinct is followed by a token that can continue a term or an expression
                                Dim tokenAfterEOL = PeekToken(1)
                                Select Case tokenAfterEOL.Kind
                                    Case SyntaxKind.DotToken, SyntaxKind.ExclamationToken, SyntaxKind.QuestionToken, SyntaxKind.OpenParenToken
                                        TryEatNewLine()
                                    Case Else
                                        If tokenAfterEOL.IsBinaryOperator Then
                                            TryEatNewLine()
                                        End If
                                End Select
                            End If

                            Return InternalSyntaxFactory.DistinctClause(kw)

                        Case SyntaxKind.JoinKeyword
                            GetNextToken()   ' get off Join
                            Return ParseInnerJoinOrGroupJoinExpression(Nothing, kw)

                        Case SyntaxKind.FromKeyword
                            GetNextToken() ' get off From
                            Return ParseFromOperator(kw)

                    End Select
            End Select

            Return Nothing
        End Function

        Private Function ParseFromQueryExpression(fromKw As KeywordSyntax) As QueryExpressionSyntax
            Debug.Assert(fromKw IsNot Nothing)

            Dim operators = Me._pool.Allocate(Of QueryClauseSyntax)()

            operators.Add(ParseFromOperator(fromKw))
            ParseMoreQueryOperators(operators)

            Dim result = operators.ToList
            Me._pool.Free(operators)

            Return SyntaxFactory.QueryExpression(result)
        End Function

        Private Function ParseAggregateQueryExpression(AggregateKw As KeywordSyntax) As QueryExpressionSyntax
            Debug.Assert(AggregateKw IsNot Nothing)

            Dim operators = Me._pool.Allocate(Of QueryClauseSyntax)()

            operators.Add(ParseAggregateClause(AggregateKw))

            Dim result = operators.ToList
            Me._pool.Free(operators)

            Return SyntaxFactory.QueryExpression(result)
        End Function

        Private Function ParseAggregateClause(AggregateKw As KeywordSyntax) As AggregateClauseSyntax
            Debug.Assert(AggregateKw IsNot Nothing)

            TryEatNewLine()

            Dim controlVariables = ParseFromControlVars()

            Dim moreOperators = Me._pool.Allocate(Of QueryClauseSyntax)()
            ParseMoreQueryOperators(moreOperators)
            Dim operatorList = moreOperators.ToList
            Me._pool.Free(moreOperators)

            Dim intoKw As KeywordSyntax = Nothing
            Dim variables As SeparatedSyntaxList(Of AggregationRangeVariableSyntax) = Nothing
            If TryEatNewLineAndGetContextualKeyword(SyntaxKind.IntoKeyword, intoKw, createIfMissing:=True) Then
                ' //ILC:  I took the liberty of adding implicit line continuations after query keywords in addition to before them...
                TryEatNewLine()

                ' // parse result selector
                variables = ParseAggregateList(False, False)
            Else
                variables = Me.MissingAggregationRangeVariables()
            End If

            Return SyntaxFactory.AggregateClause(AggregateKw, controlVariables, operatorList, intoKw, variables)

        End Function

        ' bool .Parser::IsContinuableQueryOperator( [ Token* pToken ] )
        Private Function IsContinuableQueryOperator(pToken As SyntaxToken) As Boolean
            Debug.Assert(pToken IsNot Nothing)

            Debug.Assert(pToken.Text Is PeekToken(1).Text)

            Dim kind As SyntaxKind = Nothing
            If Not TryTokenAsKeyword(pToken, kind) Then
                Return False
            End If

            Dim isQueryKwd As Boolean = KeywordTable.IsQueryClause(kind)

            If isQueryKwd AndAlso kind = SyntaxKind.SelectKeyword Then
                ' //We do not want to allow an implicit line continuation before a "select" keyword if it is immedietly
                ' //followed by the "case" keyword. This allows code like the following to parse correctly:
                ' //    dim a = from x in xs
                ' //    select case b
                ' //    end select

                Dim nextToken = PeekToken(2)
                If nextToken.Kind = SyntaxKind.CaseKeyword Then
                    isQueryKwd = False
                End If
            End If

            Return isQueryKwd
        End Function

        ' File: Parser.cpp
        ' Lines: 14918 - 14918
        ' .::MakeSureLeftControlVarIsNamed( [ _In_opt_ ParseTree::LinqExpression* Source ] )

        ' TODO: this should be done in semantics.

        'Private Shared Sub MakeSureLeftControlVarIsNamed( _
        '    ByVal Source As ParseTree.LinqExpression _
        ')
        '    While Source IsNot Nothing
        '        Select Case (Source.Opcode)

        '            Case ParseTree.Expression.Opcodes.InnerJoin, _
        '                  ParseTree.Expression.Opcodes.GroupJoin, _
        '                  ParseTree.Expression.Opcodes.CrossJoin, _
        '                  ParseTree.Expression.Opcodes.From, _
        '                  ParseTree.Expression.Opcodes.Let, _
        '                  ParseTree.Expression.Opcodes.GroupBy, _
        '                  ParseTree.Expression.Opcodes.Aggregate, _
        '                  ParseTree.Expression.Opcodes.LinqSource
        '                Return ' // these operators do not produce unnamed vars

        '            Case ParseTree.Expression.Opcodes.Where, _
        '                       ParseTree.Expression.Opcodes.SkipWhile, _
        '                       ParseTree.Expression.Opcodes.TakeWhile, _
        '                       ParseTree.Expression.Opcodes.Take, _
        '                       ParseTree.Expression.Opcodes.Skip, _
        '                       ParseTree.Expression.Opcodes.Distinct, _
        '                       ParseTree.Expression.Opcodes.OrderBy
        '                Source = Source.AsLinqOperator().Source ' // these operators do not declare control vars

        '            Case ParseTree.Expression.Opcodes.Select
        '                AssertIfTrue(Source.AsSelect().ForceNameInferenceForSingleElement)
        '                Source.AsSelect().ForceNameInferenceForSingleElement = True
        '                Return ' // done

        '            Case Else
        '                AssertIfFalse(False) ' // unknown Opcode
        '                Return
        '        End Select
        '    End While
        'End Sub

    End Class
End Namespace


text:
#include <bx/allocator.h>
#include <bx/debug.h>
#include <bx/math.h>
#include "common.h"
#include "bgfx_utils.h"
#include "imgui/imgui.h"

namespace
{
	struct PosTextCoord0Vertex
	{
		float m_x;
		float m_y;
		float m_z;
		float m_u;
		float m_v;

		static void init()
		{
			ms_layout
				.begin()
				.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
				.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
				.end();
		}

		static bgfx::VertexLayout ms_layout;
	};

	bgfx::VertexLayout PosTextCoord0Vertex::ms_layout;

	static PosTextCoord0Vertex s_screenSpaceQuadVertices[] =
	{
		{-1.0f, 0.0f, -1.0f, 0.0, 0.0 },
		{-1.0f, 0.0f,  1.0f, 0.0, 1.0 },
		{ 1.0f, 0.0f, -1.0f, 1.0, 0.0 },
		{ 1.0f, 0.0f,  1.0f, 1.0, 1.0 },
	};

	static const uint16_t s_screenSpaceQuadIndices[] =
	{
		2, 3, 1,
		0, 2, 1,
	};

	struct HextileData
	{
		bool    m_showWeights = false;
		int		m_tileRate = 10;
		float	m_tileRotationStrength = 0.0f;
		bool	m_useRegularTiling = false;
		bool	m_pauseAnimation;
	};

	class ExampleHextile : public entry::AppI
	{
	public:
		ExampleHextile(const char* _name, const char* _description, const char* _url)
			: entry::AppI(_name, _description, _url)
			, m_width(0)
			, m_height(0)
			, m_debug(BGFX_DEBUG_NONE)
			, m_reset()
		{
		}

		void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
		{
			Args args(_argc, _argv);

			m_width = _width;
			m_height = _height;
			m_debug = BGFX_DEBUG_NONE;
			m_reset = BGFX_RESET_VSYNC;

			bgfx::Init init;
			init.type = args.m_type;
			init.vendorId = args.m_pciId;
			init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
			init.platformData.ndt = entry::getNativeDisplayHandle();
			init.resolution.width = m_width;
			init.resolution.height = m_height;
			init.resolution.reset = m_reset;
			bgfx::init(init);

			// Enable m_debug text.
			bgfx::setDebug(m_debug);

			// Set view 0 clear state.
			bgfx::setViewClear(0
				, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
				, 0x303030ff
				, 1.0f
				, 0
			);

			m_hexTileData.m_showWeights = false;
			m_hexTileData.m_pauseAnimation = false;

			// Create vertex stream declaration.
			PosTextCoord0Vertex::init();

			// Create static vertex buffer.
			m_vbh = bgfx::createVertexBuffer(
				// Static data can be passed with bgfx::makeRef
				bgfx::makeRef(s_screenSpaceQuadVertices, sizeof(s_screenSpaceQuadVertices))
				, PosTextCoord0Vertex::ms_layout
			);

			// Create static index buffer
			m_ibh = bgfx::createIndexBuffer(
				// Static data can be passed with bgfx::makeRef
				bgfx::makeRef(s_screenSpaceQuadIndices, sizeof(s_screenSpaceQuadIndices))
			);

			// Create program from shaders.
			m_hextileProgram = loadProgram("vs_hextile", "fs_hextile");

			// load texture to hextile
			m_tileTexture = loadTexture("textures/aerial_rocks_04_diff_2k.ktx");

			// Imgui.
			imguiCreate();

			m_timeOffset = bx::getHPCounter();

			s_tileSampler = bgfx::createUniform("s_trx_d", bgfx::UniformType::Sampler);

			u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, 3);
		}

		virtual int shutdown() override
		{
			// Cleanup.
			imguiDestroy();

			if (bgfx::isValid(m_ibh))
			{
				bgfx::destroy(m_ibh);
			}

			if (bgfx::isValid(m_vbh))
			{
				bgfx::destroy(m_vbh);
			}

			if (bgfx::isValid(m_tileTexture))
			{
				bgfx::destroy(m_tileTexture);
			}

			if (bgfx::isValid(s_tileSampler))
			{
				bgfx::destroy(s_tileSampler);
			}

			if (bgfx::isValid(u_params))
			{
				bgfx::destroy(u_params);
			}

			bgfx::destroy(m_hextileProgram);

			/// When data is passed to bgfx via makeRef we need to make
			/// sure library is done with it before freeing memory blocks.
			bgfx::frame();

			// Shutdown bgfx.
			bgfx::shutdown();

			return 0;
		}

		bool update() override
		{
			if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
			{
				int64_t now = bx::getHPCounter();
				static int64_t last = now;
				const int64_t frameTime = now - last;
				last = now;
				const double freq = double(bx::getHPFrequency());
				const float deltaTime = float(frameTime / freq);

				imguiBeginFrame(m_mouseState.m_mx
					, m_mouseState.m_my
					, (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
					| (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
					| (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
					, m_mouseState.m_mz
					, uint16_t(m_width)
					, uint16_t(m_height)
				);

				showExampleDialog(this);

				ImGui::SetNextWindowPos(
					ImVec2(m_width - m_width / 4.5f - 5.0f, 10.0f)
					, ImGuiCond_FirstUseEver
				);
				ImGui::SetNextWindowSize(
					ImVec2(m_width / 4.5f, m_height / 4.0f)
					, ImGuiCond_FirstUseEver
				);
				ImGui::Begin("Settings"
					, NULL
					, 0
				);

				ImGui::Separator();

				ImGui::Checkbox("Use Regular Tiling", &m_hexTileData.m_useRegularTiling);
				ImGui::Checkbox("Show Weights", &m_hexTileData.m_showWeights);
				ImGui::Checkbox("Pause Animation", &m_hexTileData.m_pauseAnimation);

				ImGui::SliderInt("Tile Rate", &m_hexTileData.m_tileRate, 2, 25);

				ImGui::SliderFloat("Tile Rotation", &m_hexTileData.m_tileRotationStrength, 0.0f, 20.0f);

				ImGui::Separator();

				ImGui::End();
				imguiEndFrame();

				// This dummy draw call is here to make sure that view 0 is cleared
				// if no other draw calls are submitted to view 0.
				bgfx::touch(0);

				const bx::Vec3 at = { 0.0f, 0.0f, 0.0f };

				if (!m_hexTileData.m_pauseAnimation)
				{
					m_eye.z = bx::abs(m_eye.z) + (deltaTime / 4.0f);

					if (m_eye.z < 10.0f)
					{
						m_eye.z *= -1;
					}
					else
					{
						m_eye.z = -0.01f;
					}
				}

				float viewMtx[16];
				bx::mtxLookAt(viewMtx, m_eye, at);

				float projMtx[16];
				bx::mtxProj(projMtx, 30.0f, float(m_width) / float(m_height), 0.1f, 1000.0f, bgfx::getCaps()->homogeneousDepth);

				bgfx::setViewTransform(0, viewMtx, projMtx);

				// Set view 0 default viewport.
				bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height));

				float modelTransform[16];
				bx::mtxSRT(modelTransform, 30.0f, 30.0f, 30.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
				bgfx::setTransform(modelTransform);

				bgfx::setVertexBuffer(0, m_vbh);
				bgfx::setIndexBuffer(m_ibh);

				bgfx::setTexture(0, s_tileSampler, m_tileTexture);

				const float data[4] = { float(m_hexTileData.m_showWeights), float(m_hexTileData.m_tileRate),
										float(m_hexTileData.m_tileRotationStrength), float(m_hexTileData.m_useRegularTiling) };
				bgfx::setUniform(u_params, data);

				bgfx::setState(0
					| BGFX_STATE_WRITE_RGB
					| BGFX_STATE_WRITE_A
					| BGFX_STATE_WRITE_Z
					| BGFX_STATE_DEPTH_TEST_LESS
					| BGFX_STATE_MSAA
				);

				bgfx::submit(0, m_hextileProgram);

				// Advance to next frame. Rendering thread will be kicked to
				// process submitted rendering primitives.
				bgfx::frame();

				return true;
			}

			return false;
		}

		bgfx::VertexBufferHandle m_vbh;
		bgfx::IndexBufferHandle m_ibh;

		bgfx::ProgramHandle m_hextileProgram;
		bgfx::UniformHandle s_tileSampler;
		bgfx::TextureHandle m_tileTexture;

		uint32_t m_width;
		uint32_t m_height;
		uint32_t m_debug;
		uint32_t m_reset;

		HextileData m_hexTileData;

		entry::MouseState m_mouseState;

		bgfx::UniformHandle u_params;

		int64_t m_timeOffset;

		bx::Vec3 m_eye = { 0.0f, 2.0f, -0.01f };
	};

} // namespace

ENTRY_IMPLEMENT_MAIN(
	ExampleHextile
	, "49-hextile"
	, "Hextile example."
	, "https://bkaradzic.github.io/bgfx/examples.html#hextile"
);

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;

namespace ASC.Migration.OwnCloud.Models
{
    public class OCCalendars
    {
        public int Id { get; set; }
        public List<OCCalendarObjects> CalendarObject { get; set; }
        public string DisplayName { get; set; }
    }

    public class OCCalendarObjects
    {
        public int Id { get; set; }
        public byte[] CalendarData { get; set; }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Cohn, Krypt. -Fl. Schlesien (Breslau) 3. 2(3): 339 (1894)

#### Original name
Sphaeria lineolata Roberge ex Desm., 1843

### Remarks
null


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/datacatalog/v1/datacatalog.proto

namespace Google\Cloud\DataCatalog\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Request message for
 * [StarEntry][google.cloud.datacatalog.v1.DataCatalog.StarEntry].
 *
 * Generated from protobuf message google.cloud.datacatalog.v1.StarEntryRequest
 */
class StarEntryRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The name of the entry to mark as starred.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $name = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. The name of the entry to mark as starred.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Datacatalog\V1\Datacatalog::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. The name of the entry to mark as starred.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. The name of the entry to mark as starred.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

}


text:
import {ROUTER_DIRECTIVES, RouteConfig, Router} from 'angular2/router';

import {Component} from 'angular2/core';
import {Home} from '../views/home';
import {PixelsRow} from '../views/pixels-row';
import {Search} from '../views/search';

@RouteConfig([
  { path: '/home', component: Home, name: 'Home', useAsDefault: true },
  { path: '/pixelsrow', component: PixelsRow, name: 'PixelsRow' },
  { path: '/search', component: Search, name: 'Search' },
  { path: '/**', redirectTo: ['Home'] }
])
@Component({
  selector: 'app',
  directives: [ ROUTER_DIRECTIVES ],
  templateUrl: '/partials/app.html'
})
export class App {

}


text:
package roaring64

import "github.com/RoaringBitmap/roaring"

type roaringArray64 struct {
	keys            []uint32
	containers      []*roaring.Bitmap
	needCopyOnWrite []bool
	copyOnWrite     bool
}

// runOptimize compresses the element containers to minimize space consumed.
// Q: how does this interact with copyOnWrite and needCopyOnWrite?
// A: since we aren't changing the logical content, just the representation,
//    we don't bother to check the needCopyOnWrite bits. We replace
//    (possibly all) elements of ra.containers in-place with space
//    optimized versions.
func (ra *roaringArray64) runOptimize() {
	for i := range ra.containers {
		ra.containers[i].RunOptimize()
	}
}

func (ra *roaringArray64) appendContainer(key uint32, value *roaring.Bitmap, mustCopyOnWrite bool) {
	ra.keys = append(ra.keys, key)
	ra.containers = append(ra.containers, value)
	ra.needCopyOnWrite = append(ra.needCopyOnWrite, mustCopyOnWrite)
}

func (ra *roaringArray64) appendWithoutCopy(sa roaringArray64, startingindex int) {
	mustCopyOnWrite := sa.needCopyOnWrite[startingindex]
	ra.appendContainer(sa.keys[startingindex], sa.containers[startingindex], mustCopyOnWrite)
}

func (ra *roaringArray64) appendCopy(sa roaringArray64, startingindex int) {
	// cow only if the two request it, or if we already have a lightweight copy
	copyonwrite := (ra.copyOnWrite && sa.copyOnWrite) || sa.needsCopyOnWrite(startingindex)
	if !copyonwrite {
		// since there is no copy-on-write, we need to clone the container (this is important)
		ra.appendContainer(sa.keys[startingindex], sa.containers[startingindex].Clone(), copyonwrite)
	} else {
		ra.appendContainer(sa.keys[startingindex], sa.containers[startingindex], copyonwrite)
		if !sa.needsCopyOnWrite(startingindex) {
			sa.setNeedsCopyOnWrite(startingindex)
		}
	}
}

func (ra *roaringArray64) appendWithoutCopyMany(sa roaringArray64, startingindex, end int) {
	for i := startingindex; i < end; i++ {
		ra.appendWithoutCopy(sa, i)
	}
}

func (ra *roaringArray64) appendCopyMany(sa roaringArray64, startingindex, end int) {
	for i := startingindex; i < end; i++ {
		ra.appendCopy(sa, i)
	}
}

func (ra *roaringArray64) appendCopiesUntil(sa roaringArray64, stoppingKey uint32) {
	// cow only if the two request it, or if we already have a lightweight copy
	copyonwrite := ra.copyOnWrite && sa.copyOnWrite

	for i := 0; i < sa.size(); i++ {
		if sa.keys[i] >= stoppingKey {
			break
		}
		thiscopyonewrite := copyonwrite || sa.needsCopyOnWrite(i)
		if thiscopyonewrite {
			ra.appendContainer(sa.keys[i], sa.containers[i], thiscopyonewrite)
			if !sa.needsCopyOnWrite(i) {
				sa.setNeedsCopyOnWrite(i)
			}

		} else {
			// since there is no copy-on-write, we need to clone the container (this is important)
			ra.appendContainer(sa.keys[i], sa.containers[i].Clone(), thiscopyonewrite)
		}
	}
}

func (ra *roaringArray64) appendCopiesAfter(sa roaringArray64, beforeStart uint32) {
	// cow only if the two request it, or if we already have a lightweight copy
	copyonwrite := ra.copyOnWrite && sa.copyOnWrite

	startLocation := sa.getIndex(beforeStart)
	if startLocation >= 0 {
		startLocation++
	} else {
		startLocation = -startLocation - 1
	}

	for i := startLocation; i < sa.size(); i++ {
		thiscopyonewrite := copyonwrite || sa.needsCopyOnWrite(i)
		if thiscopyonewrite {
			ra.appendContainer(sa.keys[i], sa.containers[i], thiscopyonewrite)
			if !sa.needsCopyOnWrite(i) {
				sa.setNeedsCopyOnWrite(i)
			}
		} else {
			// since there is no copy-on-write, we need to clone the container (this is important)
			ra.appendContainer(sa.keys[i], sa.containers[i].Clone(), thiscopyonewrite)
		}
	}
}

func (ra *roaringArray64) removeIndexRange(begin, end int) {
	if end <= begin {
		return
	}

	r := end - begin

	copy(ra.keys[begin:], ra.keys[end:])
	copy(ra.containers[begin:], ra.containers[end:])
	copy(ra.needCopyOnWrite[begin:], ra.needCopyOnWrite[end:])

	ra.resize(len(ra.keys) - r)
}

func (ra *roaringArray64) resize(newsize int) {
	for k := newsize; k < len(ra.containers); k++ {
		ra.containers[k] = nil
	}

	ra.keys = ra.keys[:newsize]
	ra.containers = ra.containers[:newsize]
	ra.needCopyOnWrite = ra.needCopyOnWrite[:newsize]
}

func (ra *roaringArray64) clear() {
	ra.resize(0)
	ra.copyOnWrite = false
}

func (ra *roaringArray64) clone() *roaringArray64 {

	sa := roaringArray64{}
	sa.copyOnWrite = ra.copyOnWrite

	// this is where copyOnWrite is used.
	if ra.copyOnWrite {
		sa.keys = make([]uint32, len(ra.keys))
		copy(sa.keys, ra.keys)
		sa.containers = make([]*roaring.Bitmap, len(ra.containers))
		copy(sa.containers, ra.containers)
		sa.needCopyOnWrite = make([]bool, len(ra.needCopyOnWrite))

		ra.markAllAsNeedingCopyOnWrite()
		sa.markAllAsNeedingCopyOnWrite()

		// sa.needCopyOnWrite is shared
	} else {
		// make a full copy

		sa.keys = make([]uint32, len(ra.keys))
		copy(sa.keys, ra.keys)

		sa.containers = make([]*roaring.Bitmap, len(ra.containers))
		for i := range sa.containers {
			sa.containers[i] = ra.containers[i].Clone()
		}

		sa.needCopyOnWrite = make([]bool, len(ra.needCopyOnWrite))
	}
	return &sa
}

// clone all containers which have needCopyOnWrite set to true
// This can be used to make sure it is safe to munmap a []byte
// that the roaring array may still have a reference to.
func (ra *roaringArray64) cloneCopyOnWriteContainers() {
	for i, needCopyOnWrite := range ra.needCopyOnWrite {
		if needCopyOnWrite {
			ra.containers[i] = ra.containers[i].Clone()
			ra.needCopyOnWrite[i] = false
		}
	}
}

// unused function:
// func (ra *roaringArray64) containsKey(x uint32) bool {
//	return (ra.binarySearch(0, int64(len(ra.keys)), x) >= 0)
// }

func (ra *roaringArray64) getContainer(x uint32) *roaring.Bitmap {
	i := ra.binarySearch(0, int64(len(ra.keys)), x)
	if i < 0 {
		return nil
	}
	return ra.containers[i]
}

func (ra *roaringArray64) getContainerAtIndex(i int) *roaring.Bitmap {
	return ra.containers[i]
}

func (ra *roaringArray64) getWritableContainerAtIndex(i int) *roaring.Bitmap {
	if ra.needCopyOnWrite[i] {
		ra.containers[i] = ra.containers[i].Clone()
		ra.needCopyOnWrite[i] = false
	}
	return ra.containers[i]
}

func (ra *roaringArray64) getIndex(x uint32) int {
	// before the binary search, we optimize for frequent cases
	size := len(ra.keys)
	if (size == 0) || (ra.keys[size-1] == x) {
		return size - 1
	}
	return ra.binarySearch(0, int64(size), x)
}

func (ra *roaringArray64) getKeyAtIndex(i int) uint32 {
	return ra.keys[i]
}

func (ra *roaringArray64) insertNewKeyValueAt(i int, key uint32, value *roaring.Bitmap) {
	ra.keys = append(ra.keys, 0)
	ra.containers = append(ra.containers, nil)

	copy(ra.keys[i+1:], ra.keys[i:])
	copy(ra.containers[i+1:], ra.containers[i:])

	ra.keys[i] = key
	ra.containers[i] = value

	ra.needCopyOnWrite = append(ra.needCopyOnWrite, false)
	copy(ra.needCopyOnWrite[i+1:], ra.needCopyOnWrite[i:])
	ra.needCopyOnWrite[i] = false
}

func (ra *roaringArray64) remove(key uint32) bool {
	i := ra.binarySearch(0, int64(len(ra.keys)), key)
	if i >= 0 { // if a new key
		ra.removeAtIndex(i)
		return true
	}
	return false
}

func (ra *roaringArray64) removeAtIndex(i int) {
	copy(ra.keys[i:], ra.keys[i+1:])
	copy(ra.containers[i:], ra.containers[i+1:])

	copy(ra.needCopyOnWrite[i:], ra.needCopyOnWrite[i+1:])

	ra.resize(len(ra.keys) - 1)
}

func (ra *roaringArray64) setContainerAtIndex(i int, c *roaring.Bitmap) {
	ra.containers[i] = c
}

func (ra *roaringArray64) replaceKeyAndContainerAtIndex(i int, key uint32, c *roaring.Bitmap, mustCopyOnWrite bool) {
	ra.keys[i] = key
	ra.containers[i] = c
	ra.needCopyOnWrite[i] = mustCopyOnWrite
}

func (ra *roaringArray64) size() int {
	return len(ra.keys)
}

func (ra *roaringArray64) binarySearch(begin, end int64, ikey uint32) int {
	low := begin
	high := end - 1
	for low+16 <= high {
		middleIndex := low + (high-low)/2 // avoid overflow
		middleValue := ra.keys[middleIndex]

		if middleValue < ikey {
			low = middleIndex + 1
		} else if middleValue > ikey {
			high = middleIndex - 1
		} else {
			return int(middleIndex)
		}
	}
	for ; low <= high; low++ {
		val := ra.keys[low]
		if val >= ikey {
			if val == ikey {
				return int(low)
			}
			break
		}
	}
	return -int(low + 1)
}

func (ra *roaringArray64) equals(o interface{}) bool {
	srb, ok := o.(roaringArray64)
	if ok {

		if srb.size() != ra.size() {
			return false
		}
		for i, k := range ra.keys {
			if k != srb.keys[i] {
				return false
			}
		}

		for i, c := range ra.containers {
			if !c.Equals(srb.containers[i]) {
				return false
			}
		}
		return true
	}
	return false
}

func (ra *roaringArray64) hasRunCompression() bool {
	for _, c := range ra.containers {
		if c.HasRunCompression() {
			return true
		}
	}
	return false
}

func (ra *roaringArray64) advanceUntil(min uint32, pos int) int {
	lower := pos + 1

	if lower >= len(ra.keys) || ra.keys[lower] >= min {
		return lower
	}

	spansize := 1

	for lower+spansize < len(ra.keys) && ra.keys[lower+spansize] < min {
		spansize *= 2
	}
	var upper int
	if lower+spansize < len(ra.keys) {
		upper = lower + spansize
	} else {
		upper = len(ra.keys) - 1
	}

	if ra.keys[upper] == min {
		return upper
	}

	if ra.keys[upper] < min {
		// means
		// array
		// has no
		// item
		// >= min
		// pos = array.length;
		return len(ra.keys)
	}

	// we know that the next-smallest span was too small
	lower += (spansize >> 1)

	mid := 0
	for lower+1 != upper {
		mid = (lower + upper) >> 1
		if ra.keys[mid] == min {
			return mid
		} else if ra.keys[mid] < min {
			lower = mid
		} else {
			upper = mid
		}
	}
	return upper
}

func (ra *roaringArray64) markAllAsNeedingCopyOnWrite() {
	for i := range ra.needCopyOnWrite {
		ra.needCopyOnWrite[i] = true
	}
}

func (ra *roaringArray64) needsCopyOnWrite(i int) bool {
	return ra.needCopyOnWrite[i]
}

func (ra *roaringArray64) setNeedsCopyOnWrite(i int) {
	ra.needCopyOnWrite[i] = true
}

// should be dirt cheap
func (ra *roaringArray64) serializedSizeInBytes() uint64 {
	answer := uint64(8)
	for _, c := range ra.containers {
		answer += 4
		answer += c.GetSerializedSizeInBytes()
	}
	return answer
}


text:
package services.schools

import model.School
import org.mockito.Mockito._
import repositories.csv.{ SchoolsCSVRepository, SchoolsRepository }
import testkit.MockitoImplicits._
import testkit.{ ShortTimeout, UnitWithAppSpec }

class SchoolsServiceSpec extends UnitWithAppSpec with ShortTimeout {

  val schoolsRepo = new SchoolsCSVRepository(app)
  val service = new SchoolsService(schoolsRepo) {
    override val MaxNumberOfSchools = Integer.MAX_VALUE
  }

  "Schools Service" should {
    "return simple 3 letter matches from beginning of school name" in {
      val term = "Abb"
      val result = service.getSchools(term).futureValue

      expect23SchoolsContains("Abb", result)
    }

    "return simple 3 letter matches from beginning of school name ignoring case" in {
      val term = "aBB"

      val result = service.getSchools(term).futureValue

      result.size mustBe 23
      result.foreach(s => withClue(s"school name: ${s.name}") {
        s.name.toLowerCase.contains("abb") mustBe true
      })
    }

    "match on middle words" in {
      val school1WithGrammarName = School("IRN", "341-0209", "Antrim Grammar School", None, None, None, None, None, None, None)
      val school2WithGrammarName = School("IRN", "142-0277", "Aquinas Diocesan Grammar School", None, None, None, None, None, None, None)
      val schoolWithoutGrammarName = School("IRN", "542-0059", "Abbey Christian Brothers School", None, None, None, None, None, None, None)
      val schoolsData = List(school1WithGrammarName, schoolWithoutGrammarName, school2WithGrammarName)

      val schoolsRepoMock = mock[SchoolsRepository]
      when(schoolsRepoMock.schools).thenReturnAsync(schoolsData)
      val service = new SchoolsService(schoolsRepoMock)

      val term = "Grammar"

      service.getSchools(term).futureValue mustBe
        List(school1WithGrammarName, school2WithGrammarName)
    }

    "ignore whitespace in term" in {
      val term = "A b b "
      val result = service.getSchools(term).futureValue

      expect23SchoolsContains("Abb", result)
    }

    "ignore punctuation in term" in {
      val term = "-A?(b_@'b,)&"

      val result = service.getSchools(term).futureValue

      expect23SchoolsContains("Abb", result)
    }

    "ignore punctuation in school name" in {
      val term = "Girls High"

      val result = service.getSchools(term).futureValue

      result.size mustBe 20
      result.foreach(s => withClue(s"school name: ${s.name}") {
        s.name.contains("Girls") && s.name.contains("High") mustBe true
      })
    }

    "should limit number of results to 16" in {
      val service = new SchoolsService(new SchoolsCSVRepository(app))
      val term = "aBB"
      val result = service.getSchools(term).futureValue

      result.size mustBe 16
      result.foreach(s => withClue(s"school name: ${s.name}") {
        s.name.toLowerCase.contains("abb") mustBe true
      })
    }

    "should return less than 16 if the criteria narrows down the result" in {
      val service = new SchoolsService(new SchoolsCSVRepository(app))
      val term = "Abbey Community"
      val result = service.getSchools(term).futureValue

      result.size mustBe 1
      result.foreach(s => withClue(s"school name: ${s.name}") {
        s.name.contains("Abbey Community") mustBe true
      })
    }
  }

  private def expect23SchoolsContains(term: String, actualResult: List[School]) = {
    actualResult.size mustBe 23
    actualResult.foreach(s => withClue(s"school name: ${s.name}") {
      s.name.contains(term) mustBe true
    })
  }
}


text:
"""Let's Encrypt client errors."""

class Error(Exception):
    """Generic Let's Encrypt client error."""

class AccountStorageError(Error):
    """Generic `.AccountStorage` error."""

class AccountNotFound(AccountStorageError):
    """Account not found error."""

class ReverterError(Error):
    """Let's Encrypt Reverter error."""

class SubprocessError(Error):
    """Subprocess handling error."""

class CertStorageError(Error):
    """Generic `.CertStorage` error."""

# Auth Handler Errors
class AuthorizationError(Error):
    """Authorization error."""

class FailedChallenges(AuthorizationError):
    """Failed challenges error.

    :ivar set failed_achalls: Failed `.AnnotatedChallenge` instances.

    """
    def __init__(self, failed_achalls):
        assert failed_achalls
        self.failed_achalls = failed_achalls
        super(FailedChallenges, self).__init__()

    def __str__(self):
        return "Failed authorization procedure. {0}".format(
            ", ".join(
                "{0} ({1}): {2}".format(achall.domain, achall.typ, achall.error)
                for achall in self.failed_achalls if achall.error is not None))

class ContAuthError(AuthorizationError):
    """Let's Encrypt Continuity Authenticator error."""

class DvAuthError(AuthorizationError):
    """Let's Encrypt DV Authenticator error."""

# Authenticator - Challenge specific errors
class DvsniError(DvAuthError):
    """Let's Encrypt DVSNI error."""

# Plugin Errors
class PluginError(Error):
    """Let's Encrypt Plugin error."""

class NoInstallationError(PluginError):
    """Let's Encrypt No Installation error."""

class MisconfigurationError(PluginError):
    """Let's Encrypt Misconfiguration error."""

class NotSupportedError(PluginError):
    """Let's Encrypt Plugin function not supported error."""

class RevokerError(Error):
    """Let's Encrypt Revoker error."""


text:
describe('Hello Controller', () => {
  let helloService;
  let controller;

  beforeEach(() => {
    angular.module('test', [])
      .controller('HelloController', require('./hello_controller'));
  });
  beforeEach(angular.mock.module('test'));

  beforeEach(angular.mock.module($provide => {
    helloService = jasmine.createSpyObj('HelloService', ['hello']);
    helloService.hello.and.returnValue('test');
    $provide.value('HelloService', helloService);
  }));

  beforeEach(angular.mock.inject($injector => {
    controller = $injector.get('$controller')('HelloController');
  }));

  it('should have `test` property', () => {
    expect(controller.test).toEqual('test');
  });
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="icon" type="image/png" href="https://just2us.com/img/favicon-180.png" />
    <link rel="apple-touch-icon" href="https://just2us.com/img/favicon-192.png"/>

    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/clean-blog.min.css">
    <link rel="stylesheet" href="/css/syntax.css">

    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic&display=swap' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&display=swap' rel='stylesheet' type='text/css'>

    <link type="application/atom+xml" rel="alternate" href="https://just2me.com/feed.xml" title="Just2me" />

<title>The Evil Obstetrician | Just2me</title>
<meta name="generator" content="Jekyll v4.0.0" />
<meta property="og:title" content="The Evil Obstetrician" />
<meta name="author" content="Junda Ong" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="Here is a story about the evil doctor who delivered our baby." />
<meta property="og:description" content="Here is a story about the evil doctor who delivered our baby." />
<link rel="canonical" href="https://just2me.com/2015/08/20/the-evil-obstetrician/" />
<meta property="og:url" content="https://just2me.com/2015/08/20/the-evil-obstetrician/" />
<meta property="og:site_name" content="Just2me" />
<meta property="og:image" content="https://just2me.com/img/jewel-fountain.jpeg" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2015-08-20T21:22:00+08:00" />
<meta name="twitter:card" content="summary" />
<meta property="twitter:image" content="https://just2me.com/img/jewel-fountain.jpeg" />
<meta property="twitter:title" content="The Evil Obstetrician" />
<meta name="twitter:site" content="@samwize" />
<meta name="twitter:creator" content="@Junda Ong" />
<meta property="fb:admins" content="704185456" />

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            Just2me

                  Stories

                  Apps

                  Quotes

                  About

The Evil Obstetrician

                    Published on August 20, 2015

Here is a story about the evil doctor who delivered our baby.

Long story short: Our obstetrician hide from us about his traveling schedule, and repeatedly advised us to have induced labour.

On Week 37

Firstly, Kate was born on week 40. But our visit to our obstetrician/gynae (OB) on week 37 was a big surprise.

The OB told us 2 problems:

AFI (amniotic fluid index) is at a low level of 5 cm

Fetus growth is stagnant at 3.1 kg

Everything else is okay - fetus heart rate 140, regular movement, wife feeling good

Without asking for our opinions, he asked us to go to hospital on that night to have induced labour!

We were shocked, and said we want to think about it.

And he impatiently rescheduled us 2 days later for another checkup.

Research on AFI

And so I researched on AFI, and what it means to have 5 cm of amniotic fluid.

I learnt more from Contemporary OB/GYN:

There are 2 techniques to measure the amount of amniotic fluid

AFI - Sum of 4 pockets

SDP - Single deepest pocket

Oligohydramnios

The condition when amniotic fluid is low

AFI < 5cm

SDP < 2cm

Polyhydramnios - is the condition when amniotic fluid is too much (I will not discussed this condition here)

Using ultrasound to measure AFI and SDP is not that accurate (e.g.. 60% positive predictive value when tested AFI < 5 cm)

Reading up on MidwifeThinking reassured me:

"AFI increases the detection of oligohydramnios resulting in increased rates of induction without improving outcomes for babies."

"There is a lack of evidence supporting induction for oligohydramnios in 'low risk' pregnancies ie. when there is nothing else 'abnormal' going on with mother or baby"

AFV reduces significantly after 37 weeks – this is normal.

The intervention used to manage polyhydramnios or oligohydramnios ie. induction also carries risks which need to be taken into consideration.

The other alternatives are planned c-section or awaiting spontaneous labour.

I was pretty confident that Kate is fine.

I decided to decline induce labour unless the foetus is in critical condition.

The Next Checkup

We went for the scheduled checkup (48 hours after that surprise diagnosis).

The AFI is 4.95 cm, and the weight is 3.2 kg.

There is still growth in the foetus weight - that's fine. The AFI remains roughly the same, which is too low.

The OB still recommends induced labour, and even suggested c-section — but we declined.

And so he referred us to do a 1-hr doppler test at a hospital to check on the blood flow, etc.

We went to the hospital immediately, and the result: AFI is 8.5 cm!

The AFI measure is much higher than his measurement (only 5 cm).

We took the result to our OB, and he congratulated us on the good result.

The Dishonest Obstetrician

The most interesting part of our story is this.

The OB then informed us that our next checkup will be next week, with his partner, because he will be overseas at a conference!

How could he!?

I mean, shouldn't he inform us about his unavailability much earlier?

He didn't tell us the number of days he will be in his conference. We had to separately check with the nurse, and she told us the doctor will be on leave for 10 days. What a long conference, over SG50 long weekend..

We are not the only case

At the clinic, we suspected he must be using the same technique on other patients.

And so we chatted to another mother, and she told us she will be induced that night, because her AFI is 5 cm!

What a coincidence!

Saying NO to Induction

I shared the story at midwifethinking.com, and she replied:

Unfortunately this seems quite common ie. and OB suggesting induction to fit with their own schedule – but not being honest about it. I am please you had the courage to say 'no' and stand your ground.

We have to learn to say "no" to induction.

PS: I shall not mention the doctor name. I do believe he is capable and he handled the caesarean well. But we will never find him again, if we have our second.

 "I earned extra 2 weeks to have bigger head!"

    TAGGED WITH

    baby,

    kate,

    whinings

                        Hardcopy is More Genuine than Softcopy - that's what SingPost thinks →

                        ← Baby Kate is born!

                Please enable JavaScript to view the comments powered by Disqus.

Copyright © Junda Ong 1983-2021


text:
require 'chef/provisioning/aws_driver'

with_driver 'aws::us-west-2'

machine 'ref-machine-1' do
  action :allocate
end

machine 'ref-machine-1' do
  machine_options aws_tags: {:marco => 'polo', :happyhappy => 'joyjoy'}
  converge false
end

machine 'ref-machine-1' do
  machine_options aws_tags: {:othercustomtags => 'byebye'}
  converge false
end

machine 'ref-machine-1' do
  machine_options aws_tags: {:Name => 'new-name'}
  converge false
end

machine 'ref-machine-1' do
  action :destroy
end

machine_batch "ref-batch" do
  machine 'ref-machine-2' do
    machine_options aws_tags: {:marco => 'polo', :happyhappy => 'joyjoy'}
    converge false
  end
  machine 'ref-machine-3' do
    machine_options aws_tags: {:othercustomtags => 'byebye'}
    converge false
  end
end

load_balancer 'ref-elb' do
  load_balancer_options availability_zones: ['us-west-1a', 'us-west-1b']
end

load_balancer 'ref-elb' do
  load_balancer_options aws_tags: {:marco => 'polo', :happyhappy => 'joyjoy'}
end

load_balancer 'ref-elb' do
  load_balancer_options aws_tags: {:othercustomtags => 'byebye'}
end

load_balancer 'ref-elb' do
  action :destroy
end

machine_batch "ref-batch" do
  action :destroy
end

machine_image "ref-image" do
  image_options aws_tags: {:marco => 'polo', :happyhappy => 'joyjoy'}
end

# There is a bug where machine_images do not update - so we cannot update
# the tags on it
machine_image "ref-image" do
  image_options aws_tags: {:othercustomtags => 'byebye'}
end

machine_image "ref-image" do
  action :destroy
end