text:
from itertools import groupby

from azure.mgmt.resource.resources.models import ChangeType, PropertyChangeType

from ._symbol import Symbol
from ._color import Color, ColoredStringBuilder
from ._utils import split_resource_id

_change_type_to_color = {
    ChangeType.create: Color.GREEN,
    ChangeType.delete: Color.ORANGE,
    ChangeType.modify: Color.PURPLE,
    ChangeType.deploy: Color.BLUE,
    ChangeType.no_change: Color.RESET,
    ChangeType.ignore: Color.GRAY,
    ChangeType.unsupported: Color.GRAY,
    PropertyChangeType.no_effect: Color.GRAY,
}

_property_change_type_to_color = {
    PropertyChangeType.create: Color.GREEN,
    PropertyChangeType.delete: Color.ORANGE,
    PropertyChangeType.modify: Color.PURPLE,
    PropertyChangeType.array: Color.PURPLE,
    PropertyChangeType.no_effect: Color.GRAY,
}

_change_type_to_symbol = {
    ChangeType.create: Symbol.PLUS,
    ChangeType.delete: Symbol.MINUS,
    ChangeType.modify: Symbol.TILDE,
    ChangeType.deploy: Symbol.EXCLAMATION_POINT,
    ChangeType.no_change: Symbol.EQUAL,
    ChangeType.ignore: Symbol.ASTERISK,
    ChangeType.unsupported: Symbol.CROSS,
    PropertyChangeType.no_effect: Symbol.CROSS,
}

_property_change_type_to_symbol = {
    PropertyChangeType.create: Symbol.PLUS,
    PropertyChangeType.delete: Symbol.MINUS,
    PropertyChangeType.modify: Symbol.TILDE,
    PropertyChangeType.array: Symbol.TILDE,
    PropertyChangeType.no_effect: Symbol.CROSS,
}

_change_type_to_weight = {
    ChangeType.delete: 0,
    ChangeType.create: 1,
    ChangeType.deploy: 2,
    ChangeType.modify: 3,
    ChangeType.no_change: 4,
    ChangeType.unsupported: 5,
    ChangeType.ignore: 6,
    PropertyChangeType.no_effect: 7,
}

_property_change_type_to_weight = {
    PropertyChangeType.delete: 0,
    PropertyChangeType.create: 1,
    PropertyChangeType.modify: 2,
    PropertyChangeType.array: 2,
    PropertyChangeType.no_effect: 3,
}

def format_what_if_operation_result(what_if_operation_result, enable_color=True):
    builder = ColoredStringBuilder(enable_color)
    _format_noise_notice(builder)
    _format_change_type_legend(builder, what_if_operation_result.changes)
    _format_resource_changes(builder, what_if_operation_result.changes)
    _format_resource_changes_stats(builder, what_if_operation_result.changes)
    return builder.build()

def _format_noise_notice(builder):
    builder.append_line(
        """Note: The result may contain false positive predictions (noise).
You can help us improve the accuracy of the result by opening an issue here: https://aka.ms/WhatIfIssues"""
    )
    builder.append_line()

def _format_change_type_legend(builder, resource_changes):
    if not resource_changes:
        return

    def populate_change_type_set(property_changes):
        if not property_changes:
            return

        for property_change in property_changes:
            property_change_type = property_change.property_change_type
            change_type_set.add(
                ChangeType.modify if property_change_type == PropertyChangeType.array else property_change_type
            )
            populate_change_type_set(property_change.children)

    change_type_set = set()

    for resource_change in resource_changes:
        change_type_set.add(resource_change.change_type)
        populate_change_type_set(resource_change.delta)

    change_types = sorted(change_type_set, key=lambda x: _change_type_to_weight[x])

    builder.append("Resource and property changes are indicated with ")
    builder.append_line("this symbol:" if len(change_types) == 1 else "these symbols:")

    for change_type in change_types:
        change_type_symbol = _change_type_to_symbol[change_type]
        change_type_color = _change_type_to_color[change_type]
        _format_indent(builder)
        builder.append(change_type_symbol, change_type_color).append(Symbol.WHITE_SPACE)
        builder.append_line(change_type.title())

def _format_resource_changes_stats(builder, resource_changes):
    builder.append_line().append("Resource changes: ")

    if not resource_changes:
        builder.append("no change.")
        return

    sorted_resource_changes = sorted(resource_changes, key=lambda x: _change_type_to_weight[x.change_type])
    resource_changes_by_change_type = groupby(sorted_resource_changes, lambda x: x.change_type)
    count_by_change_type = map(lambda x: (x[0], len(list(x[1]))), resource_changes_by_change_type)
    count_by_change_type = filter(lambda x: x[1] > 0, count_by_change_type)
    change_type_stats = map(lambda x: _format_change_type_count(x[0], x[1]), count_by_change_type)

    builder.append(", ".join(change_type_stats)).append(".")

def _format_change_type_count(change_type, count):  # pylint: disable=too-many-return-statements
    if change_type == ChangeType.create:
        return f"{count} to create"
    if change_type == ChangeType.delete:
        return f"{count} to delete"
    if change_type == ChangeType.deploy:
        return f"{count} to deploy"
    if change_type == ChangeType.modify:
        return f"{count} to modify"
    if change_type == ChangeType.ignore:
        return f"{count} to ignore"
    if change_type == ChangeType.no_change:
        return f"{count} no change"
    if change_type == ChangeType.unsupported:
        return f"{count} unsupported"

    raise ValueError(f"Invalid ChangeType: {change_type}")

def _format_resource_changes(builder, resource_changes):
    if not resource_changes:
        return

    num_scopes = len(set(map(_get_scope_uppercase, resource_changes)))
    resource_changes_by_scope = groupby(sorted(resource_changes, key=_get_scope_uppercase), _get_scope_uppercase)

    builder.append_line()
    builder.append_line(f"The deployment will update the following {'scope:' if num_scopes == 1 else 'scopes'}")

    for _, resource_changes_in_scope in resource_changes_by_scope:
        resource_changes_in_scope_list = list(resource_changes_in_scope)
        scope = _get_scope(resource_changes_in_scope_list[0])
        _format_resource_changes_in_scope(builder, scope, resource_changes_in_scope_list)

def _format_resource_changes_in_scope(builder, scope, resource_changes_in_scope):
    builder.append_line().append_line(f"Scope: {scope}")

    sorted_resource_changes = sorted(
        resource_changes_in_scope,
        # Sort by change_type and then by relative_resource_id.
        key=lambda x: (_change_type_to_weight[x.change_type], _get_relative_resource_id(x)),
    )

    for change_type, resource_changes in groupby(sorted_resource_changes, lambda x: x.change_type):
        with builder.new_color_scope(_change_type_to_color[change_type]):
            for resource_change in resource_changes:
                is_last = resource_change == sorted_resource_changes[-1]
                _format_resource_change(builder, resource_change, is_last)

def _format_resource_change(builder, resource_change, is_last):
    change_type = resource_change.change_type
    relative_resource_id = _get_relative_resource_id(resource_change)
    api_version = _get_api_version(resource_change)

    builder.append_line()
    _format_resource_change_path(builder, change_type, relative_resource_id, api_version)

    if change_type == ChangeType.create and resource_change.after:
        _format_json(builder, resource_change.after, indent_level=2)

    elif change_type == ChangeType.delete and resource_change.before:
        _format_json(builder, resource_change.before, indent_level=2)

    elif resource_change.delta:
        with builder.new_color_scope(Color.RESET):
            builder.append_line()
            _format_property_changes(
                builder,
                sorted(
                    resource_change.delta,
                    key=lambda x: (_property_change_type_to_weight[x.property_change_type], x.path),
                ),
            )

    elif is_last:
        builder.append_line()

def _format_resource_change_path(builder, change_type, resource_change_id, api_version):
    return _format_path(
        builder,
        resource_change_id,
        0,
        1,
        lambda builder: _format_resource_change_type(builder, change_type),
        lambda builder: _format_resource_change_api_verion(builder, api_version),
    )

def _format_resource_change_type(builder, change_type):
    change_symbol = _change_type_to_symbol[change_type]
    builder.append(change_symbol).append(Symbol.WHITE_SPACE)

def _format_resource_change_api_verion(builder, api_version):
    if not api_version:
        return

    with builder.new_color_scope(Color.RESET):
        builder.append(Symbol.WHITE_SPACE)
        builder.append(Symbol.LEFT_SQUARE_BRACKET)
        builder.append(api_version)
        builder.append(Symbol.RIGHT_SQUARE_BRACKET)

def _format_property_changes(builder, property_changes, indent_level=2):
    max_path_length = _get_max_path_length_from_property_changes(property_changes)

    for property_change in property_changes:
        _format_property_change(builder, property_change, max_path_length, indent_level)
        builder.append_line()

def _format_property_change(builder, property_change, max_path_length, indent_level):
    property_change_type = property_change.property_change_type
    before, after, children = property_change.before, property_change.after, property_change.children

    if property_change_type == PropertyChangeType.create:
        _format_property_change_path(builder, property_change, "after", max_path_length, indent_level)
        _format_property_create(builder, after, indent_level + 1)
    elif property_change_type == PropertyChangeType.delete:
        _format_property_change_path(builder, property_change, "before", max_path_length, indent_level)
        _format_property_delete(builder, before, indent_level + 1)
    elif property_change_type == PropertyChangeType.modify:
        _format_property_change_path(builder, property_change, "before", max_path_length, indent_level)
        _format_property_modify(builder, before, after, children, indent_level + 1)
    elif property_change_type == PropertyChangeType.array:
        _format_property_change_path(builder, property_change, "children", max_path_length, indent_level)
        _format_property_array_change(builder, children, indent_level + 1)
    elif property_change_type == PropertyChangeType.no_effect:
        _format_property_change_path(builder, property_change, "after", max_path_length, indent_level)
        _format_property_no_effect(builder, after, indent_level + 1)
    else:
        raise ValueError(f"Unknown property change type: {property_change_type}.")

def _format_property_change_path(builder, property_change, value_name, max_path_length, indent_level):
    path, property_change_type = property_change.path, property_change.property_change_type
    value = getattr(property_change, value_name)

    padding_width = max_path_length - len(path) + 1

    if _is_non_empty_array(value):
        padding_width = 1
    if _is_non_empty_object(value):
        padding_width = 0
    if property_change_type == PropertyChangeType.modify and property_change.children:
        # Has nested changes.
        padding_width = 0

    _format_path(
        builder,
        path,
        padding_width,
        indent_level,
        format_head=lambda builder: _format_property_change_type(builder, property_change_type),
        format_tail=_format_colon,
    )

def _format_property_change_type(builder, property_change_type):
    property_change_symbol = _property_change_type_to_symbol[property_change_type]
    property_change_color = _property_change_type_to_color[property_change_type]
    builder.append(property_change_symbol, property_change_color).append(Symbol.WHITE_SPACE)

def _format_property_no_effect(builder, value, indent_level):
    with builder.new_color_scope(_property_change_type_to_color[PropertyChangeType.no_effect]):
        _format_json(builder, value, indent_level=indent_level)

def _format_property_create(builder, value, indent_level):
    with builder.new_color_scope(_property_change_type_to_color[PropertyChangeType.create]):
        _format_json(builder, value, indent_level=indent_level)

def _format_property_delete(builder, value, indent_level):
    with builder.new_color_scope(_property_change_type_to_color[PropertyChangeType.delete]):
        _format_json(builder, value, indent_level=indent_level)

def _format_property_modify(builder, before, after, children, indent_level):
    if children:
        # Has nested changes.
        builder.append_line().append_line()
        _format_property_changes(
            builder,
            sorted(children, key=lambda x: (_property_change_type_to_weight[x.property_change_type], x.path)),
            indent_level,
        )
    else:
        _format_property_delete(builder, before, indent_level)

        # Space before =>
        if _is_non_empty_object(before):
            builder.append_line()
            _format_indent(builder, indent_level)
        else:
            builder.append(Symbol.WHITE_SPACE)

        builder.append("=>")

        # Space after =>
        if not _is_non_empty_object(after):
            builder.append(Symbol.WHITE_SPACE)

        _format_property_create(builder, after, indent_level)

        if not _is_leaf(before) and _is_leaf(after):
            builder.append_line()

def _format_property_array_change(builder, property_changes, indent_level):
    if not property_changes:
        builder.append_line("[]")
        return

    # [
    builder.append(Symbol.LEFT_SQUARE_BRACKET).append_line()

    _format_property_changes(
        builder,
        sorted(property_changes, key=lambda x: (int(x.path), _property_change_type_to_weight[x.property_change_type])),
        indent_level,
    )

    # ]
    _format_indent(builder, indent_level)
    builder.append(Symbol.RIGHT_SQUARE_BRACKET)

def _get_api_version(resource_change):
    if resource_change.before:
        return resource_change.before.get("apiVersion")
    if resource_change.after:
        return resource_change.after.get("apiVersion")
    return None

def _get_scope(resource_change):
    scope, _ = split_resource_id(resource_change.resource_id)
    return scope

def _get_scope_uppercase(resource_change):
    return _get_scope(resource_change).upper()

def _get_relative_resource_id(resource_change):
    _, relative_resource_id = split_resource_id(resource_change.resource_id)
    return relative_resource_id

def _get_max_path_length_from_property_changes(property_changes):
    if not property_changes:
        return 0

    filtered_property_changes = filter(_should_consider_property_change_path, property_changes)
    path_lengths = map(lambda x: len(x.path), filtered_property_changes)

    return max(path_lengths, default=0)

def _should_consider_property_change_path(property_change):
    property_change_type = property_change.property_change_type

    if property_change_type == PropertyChangeType.create:
        return _is_leaf(property_change.after)

    if property_change_type in (PropertyChangeType.delete, PropertyChangeType.modify):
        return _is_leaf(property_change.before)

    return not property_change.children

def format_json(value, enable_color=True):
    builder = ColoredStringBuilder(enable_color)
    _format_json(builder, value)
    return builder.build()

def _format_json(builder, value, path="", max_path_length=0, indent_level=0):
    if _is_leaf(value):
        _format_json_path(builder, path, max_path_length - len(path) + 1, indent_level)
        _format_leaf(builder, value)
    elif _is_non_empty_array(value):
        _format_json_path(builder, path, 1, indent_level)
        _format_non_empty_array(builder, value, indent_level)
    elif _is_non_empty_object(value):
        _format_non_empty_object(builder, value, path, max_path_length, indent_level)
    else:
        raise ValueError(f"Invalid JSON value: {value}")

def _format_leaf(builder, value):
    if value is None:
        builder.append("null")
    elif isinstance(value, bool):
        builder.append(str(value).lower())
    elif isinstance(value, str):
        builder.append(Symbol.QUOTE).append(value).append(Symbol.QUOTE)
    else:
        builder.append(value)

def _format_non_empty_array(builder, value, indent_level):
    builder.append(Symbol.LEFT_SQUARE_BRACKET, Color.RESET).append_line()

    max_path_length = _get_max_path_length_from_array(value)

    for index, child_value in enumerate(value):
        child_path = str(index)

        if _is_non_empty_object(child_value):
            _format_json_path(builder, child_path, 0, indent_level + 1)
            _format_non_empty_object(builder, child_value, indent_level=indent_level + 1)
        else:
            _format_json(builder, child_value, child_path, max_path_length, indent_level + 1)

        builder.append_line()

    _format_indent(builder, indent_level)
    builder.append(Symbol.RIGHT_SQUARE_BRACKET, Color.RESET)

def _format_non_empty_object(builder, value, path=None, max_path_length=0, indent_level=0):
    is_root = not path

    if not path:
        # root object.
        builder.append_line().append_line()
        max_path_length = _get_max_path_length_from_object(value)
        indent_level += 1

    for child_path, child_value in value.items():
        child_path = child_path if is_root else f"{path}{Symbol.DOT}{child_path}"
        _format_json(builder, child_value, child_path, max_path_length, indent_level)

        # if _is_non_empty_array(child_value) or _is_leaf(child_value):
        if not _is_non_empty_object(child_value):
            builder.append_line()

def _format_json_path(builder, path, padding_width, indent_level):
    return _format_path(builder, path, padding_width, indent_level, format_tail=_format_colon)

def _format_path(builder, path, padding_width, indent_level, format_head=None, format_tail=None):
    if not path:
        return

    _format_indent(builder, indent_level)

    if format_head:
        format_head(builder)

    builder.append(path)

    if format_tail:
        format_tail(builder)

    builder.append(str(Symbol.WHITE_SPACE) * padding_width)

def _format_colon(builder):
    builder.append(Symbol.COLON, Color.RESET)

def _format_indent(builder, indent_level=1):
    builder.append(str(Symbol.WHITE_SPACE) * 2 * indent_level)

def _get_max_path_length_from_array(value):
    maxLengthIndex = 0

    for index, child_value in enumerate(value):
        if _is_leaf(child_value):
            maxLengthIndex = index

    return len(str(maxLengthIndex))

def _get_max_path_length_from_object(value):
    max_path_length = 0

    for key, child_value in value.items():
        if _is_non_empty_array(child_value):
            # Ignoring array paths to avoid long padding like this:
            #
            #   short.path:                   "foo"
            #   another.short.path:           "bar"
            #   very.very.long.path.to.array: [
            #     ...
            #   ]
            #   path.after.array:             "foobar"
            #
            # The following is what we want:
            #
            #   short.path:         "foo"
            #   another.short.path: "bar"
            #   very.very.long.path.to.array: [
            #     ...
            #   ]
            #   path.after.array:   "foobar"
            #
            continue

        current_path_length = (
            # Add one for dot.
            len(key) + 1 + _get_max_path_length_from_object(child_value)
            if _is_non_empty_object(child_value)
            else len(key)
        )

        max_path_length = max(max_path_length, current_path_length)

    return max_path_length

def _is_leaf(value):
    return (
        isinstance(value, (type(None), bool, int, float, str)) or
        (isinstance(value, list) and not value) or
        (isinstance(value, dict) and not value)
    )

def _is_non_empty_array(value):
    return isinstance(value, list) and value

def _is_non_empty_object(value):
    return isinstance(value, dict) and value


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind

Namespace Microsoft.CodeAnalysis.VisualBasic
    Partial Friend NotInheritable Class LocalRewriter

        ''' <summary>
        ''' Rewrites a for each statement.
        ''' </summary>
        ''' <param name="node">The node.</param><returns></returns>
        Public Overrides Function VisitForEachStatement(node As BoundForEachStatement) As BoundNode
            Dim locals = ArrayBuilder(Of LocalSymbol).GetInstance()
            Dim statements = ArrayBuilder(Of BoundStatement).GetInstance()

            ' there can be a conversion on top of an one dimensional array to cause the ConvertedType of the semantic model
            ' to show the IEnumerable type.
            ' we need to ignore this conversion for the rewriting.
            ' Strings and multidimensional arrays match the pattern and will not have this artificial conversion.
            Dim collectionType As TypeSymbol
            Dim originalCollection As BoundExpression
            If node.Collection.Kind = BoundKind.Conversion Then
                Dim conversion = DirectCast(node.Collection, BoundConversion)
                Dim operand = conversion.Operand
                If Not conversion.ExplicitCastInCode AndAlso Not operand.IsNothingLiteral AndAlso
                    (operand.Type.IsArrayType OrElse operand.Type.IsStringType) Then
                    originalCollection = operand
                Else
                    originalCollection = node.Collection
                End If
            Else
                originalCollection = node.Collection
            End If
            collectionType = originalCollection.Type

            Dim replacedCollection As BoundExpression = originalCollection

            ' LIFTING OF FOR-EACH CONTROL VARIABLES
            '
            ' For Each <ControlVariable> In <CollectionExpression>
            '	<Body>
            ' Next
            '
            ' VB has two forms of "For Each". The first is where the <ControlVariable>
            ' binds to an already-existing variable. The second is where it introduces a new
            ' control variable.
            '
            ' Execution of For Each (the form that introduces a new control variable) is as follows:
            ' [1] Allocate a new temporary local symbol for the control variable
            ' [2] Evaluate <CollectionExpression>, where any reference to "<ControlVariable>" binds to the location in [1]
            ' [3] Allocate a new temporary and initialize it to the result of calling GetEnumerator() on [2]
            ' [4] We will call MoveNext/Current to execute the <Body> a number of times...
            ' For each iteration of the body,
            ' [5] Allocate a new storage location for the control variable
            ' [6] Initialize it to [3].Current
            ' [7] Execute <Body>, where any reference to "<ControlVariable>" binds to the location in [5] for this iteration
            '
            ' Of course, none of this allocation is observable unless there are lambdas.
            ' If there are no lambdas then we can make do with only a single allocation for the whole thing.
            ' But there may be lambdas in either <EnumeratorExpression> or <Body>...
            '
            '
            ' IMPLEMENTATION:
            '
            ' The LambdaRewriter code will, if there were a lambda inside <Body> that captures "<ControlVariable>",
            ' lift "<ControlVariable>" into a closure which is allocated once for each iteration of the body and initialized with the
            ' (This allocation is initialized by copying the previously allocated closure if there was one).
            '
            ' However, if <EnumeratorExpression> referred to "<ControlVariable>", then we'll need to allocate another one for it.
            ' This rewrite is how we do it:
            '	 Dim tmp ' implicitly initialized with default(CollectionVariableType)
            '	 For Each <ControlVariable> In <CollectionExpression> {tmp/<ControlVariable>}
            '	   <Body>
            '	 Next
            '

            ' if the for each loop declares a variable we need to check if the collection expression references
            ' it. If it does, we allocate a new temporary variable of the control variable's type. All references to
            ' the control variable in the collection expression will be replaced with a reference to the temporary local.
            ' This way capturing this local will be correct.
            ' The variable will not be initialized, because a declared control variable is also not initialized when
            ' executing the collection expression.
            If node.DeclaredOrInferredLocalOpt IsNot Nothing Then
                Dim tempLocal = New SynthesizedLocal(Me._currentMethodOrLambda, node.ControlVariable.Type, SynthesizedLocalKind.LoweringTemp)
                Dim tempForControlVariable = New BoundLocal(node.Syntax, tempLocal, node.ControlVariable.Type)

                Dim replacedControlVariable As Boolean = False
                replacedCollection = DirectCast(LocalVariableSubstituter.Replace(originalCollection,
                                                                                node.DeclaredOrInferredLocalOpt,
                                                                                tempLocal,
                                                                                RecursionDepth,
                                                                                replacedControlVariable), BoundExpression)

                ' if a reference to the control variable was found we add the temporary local and we need to make sure
                ' that this variable does not get captured by using a copy constructor.
                ' Example:
                ' for i = 0 to 3 do
                '     for each x in (function() {x+1})()
                '     next x
                ' next i
                '
                ' Should always capture x in the collection expression uninitialized.
                If replacedControlVariable Then
                    locals.Add(tempLocal)

                    If Me._symbolsCapturedWithoutCopyCtor Is Nothing Then
                        Me._symbolsCapturedWithoutCopyCtor = New HashSet(Of Symbol)()
                    End If

                    Me._symbolsCapturedWithoutCopyCtor.Add(tempLocal)
                End If
            End If

            ' Either replace the placeholder with the original collection or the one that the referenced replaced.
            If node.EnumeratorInfo.CollectionPlaceholder IsNot Nothing Then
                AddPlaceholderReplacement(node.EnumeratorInfo.CollectionPlaceholder,
                                          VisitExpressionNode(replacedCollection).MakeRValue)
            End If

            If collectionType.IsArrayType AndAlso DirectCast(collectionType, ArrayTypeSymbol).IsSZArray Then
                ' Optimized rewrite for one dimensional arrays (iterate over index is faster than IEnumerable)
                RewriteForEachArrayOrString(node, statements, locals, isArray:=True, collectionExpression:=replacedCollection)
            ElseIf collectionType.IsStringType Then
                ' Optimized rewrite for strings (iterate over index is faster than IEnumerable)
                RewriteForEachArrayOrString(node, statements, locals, isArray:=False, collectionExpression:=replacedCollection)
            ElseIf Not node.Collection.HasErrors Then
                RewriteForEachIEnumerable(node, statements, locals)
            End If

            If node.EnumeratorInfo.CollectionPlaceholder IsNot Nothing Then
                RemovePlaceholderReplacement(node.EnumeratorInfo.CollectionPlaceholder)
            End If

            Return New BoundBlock(node.Syntax,
                                  Nothing,
                                  locals.ToImmutableAndFree(),
                                  statements.ToImmutableAndFree)
        End Function

        ''' <summary>
        ''' Rewrites a for each over an one dimensional array or a string.
        '''
        ''' As an optimization, if c is an array type of rank 1, the form becomes:
        '''
        '''     Dim collectionCopy As C = c
        '''     Dim collectionIndex As Integer = 0
        '''     Do While collectionIndex < len(collectionCopy)    ' len(a) represents the LDLEN opcode
        '''         dim controlVariable = DirectCast(collectionCopy(collectionIndex), typeOfControlVariable)
        '''         <loop body>
        '''     continue:
        '''         collectionIndex += 1
        '''     postIncrement:
        '''     Loop
        '''
        ''' An iteration over a string becomes
        '''     Dim collectionCopy As String = c
        '''     Dim collectionIndex As Integer = 0
        '''     Dim limit as Integer = s.Length
        '''     Do While collectionIndex < limit
        '''         dim controlVariable = DirectCast(collectionCopy.Chars(collectionIndex), typeOfControlVariable)
        '''         <loop body>
        '''     continue:
        '''         collectionIndex += 1
        '''     postIncrement:
        '''     Loop
        ''' </summary>
        ''' <param name="node">The node.</param>
        ''' <param name="statements">The statements.</param>
        ''' <param name="locals">The locals.</param>
        ''' <param name="isArray">if set to <c>true</c> [is array].</param>
        Private Sub RewriteForEachArrayOrString(
            node As BoundForEachStatement,
            statements As ArrayBuilder(Of BoundStatement),
            locals As ArrayBuilder(Of LocalSymbol),
            isArray As Boolean,
            collectionExpression As BoundExpression
        )

            Dim syntaxNode = DirectCast(node.Syntax, ForEachBlockSyntax)

            Dim generateUnstructuredExceptionHandlingResumeCode As Boolean = ShouldGenerateUnstructuredExceptionHandlingResumeCode(node)

            Dim loopResumeTarget As ImmutableArray(Of BoundStatement) = Nothing

            If generateUnstructuredExceptionHandlingResumeCode Then
                loopResumeTarget = RegisterUnstructuredExceptionHandlingResumeTarget(syntaxNode, canThrow:=True)
            End If

            Dim controlVariableType = node.ControlVariable.Type
            Dim enumeratorInfo = node.EnumeratorInfo

            If collectionExpression.Kind = BoundKind.Conversion Then
                Dim conversion = DirectCast(collectionExpression, BoundConversion)
                If Not conversion.ExplicitCastInCode AndAlso conversion.Operand.Type.IsArrayType Then
                    collectionExpression = conversion.Operand
                End If
            End If
            Dim collectionType = collectionExpression.Type

            Debug.Assert(collectionExpression.Type.SpecialType = SpecialType.System_String OrElse
             (collectionType.IsArrayType AndAlso DirectCast(collectionType, ArrayTypeSymbol).IsSZArray))

            ' Where do the bound expressions of the bound for each node get rewritten?
            ' The collection will be assigned to a local copy. This assignment is rewritten by using "CreateLocalAndAssignment"
            ' The current value will be assigned to the control variable once per iteration. This is done in this method
            ' The casts and conversions get rewritten in "RewriteWhileStatement"

            '
            ' Loop initialization: collection copy + index & limit
            '

            ' Dim collectionCopy As C = c
            Dim boundCollectionLocal As BoundLocal = Nothing
            Dim boundCollectionAssignment = CreateLocalAndAssignment(syntaxNode.ForEachStatement,
                                                                     collectionExpression.MakeRValue(),
                                                                     boundCollectionLocal,
                                                                     locals,
                                                                     SynthesizedLocalKind.ForEachArray)

            If Not loopResumeTarget.IsDefaultOrEmpty Then
                boundCollectionAssignment = New BoundStatementList(boundCollectionAssignment.Syntax, loopResumeTarget.Add(boundCollectionAssignment))
            End If

            If Instrument(node) Then
                ' first sequence point to highlight the for each statement
                boundCollectionAssignment = _instrumenterOpt.InstrumentForEachLoopInitialization(node, boundCollectionAssignment)
            End If

            statements.Add(boundCollectionAssignment)

            ' Dim collectionIndex As Integer = 0
            Dim boundIndex As BoundLocal = Nothing
            Dim integerType = GetSpecialTypeWithUseSiteDiagnostics(SpecialType.System_Int32, syntaxNode)
            Dim boundIndexInitialization = CreateLocalAndAssignment(syntaxNode.ForEachStatement,
                                                                    New BoundLiteral(syntaxNode,
                                                                                ConstantValue.Default(SpecialType.System_Int32),
                                                                                integerType),
                                                                    boundIndex,
                                                                    locals,
                                                                    SynthesizedLocalKind.ForEachArrayIndex)
            statements.Add(boundIndexInitialization)

            ' build either
            ' Array.Length(collectionCopy)
            ' or
            ' collectionCopy.Length
            Dim boundLimit As BoundExpression = Nothing
            If isArray Then
                ' in case of an array, the upper limit is Array.Length. This will be the ldlen opcode later on
                boundLimit = New BoundArrayLength(syntaxNode, boundCollectionLocal, integerType)
            Else
                ' for strings we use String.Length
                Dim lengthPropertyGet = GetSpecialTypeMember(SpecialMember.System_String__Length)
                boundLimit = New BoundCall(syntaxNode,
                                                      DirectCast(lengthPropertyGet, MethodSymbol),
                                                      Nothing,
                                                      boundCollectionLocal,
                                                      ImmutableArray(Of BoundExpression).Empty,
                                                      Nothing,
                                                      integerType)
            End If

            '
            ' new statements for the loop body (getting current value + index increment)
            '

            Dim boundCurrent As BoundExpression
            Dim elementType As TypeSymbol
            If isArray Then
                elementType = DirectCast(collectionType, ArrayTypeSymbol).ElementType
                boundCurrent = New BoundArrayAccess(syntaxNode,
                                                    boundCollectionLocal.MakeRValue(),
                                                    ImmutableArray.Create(Of BoundExpression)(boundIndex.MakeRValue()),
                                                    isLValue:=False,
                                                    type:=elementType)
            Else
                elementType = GetSpecialType(SpecialType.System_Char)

                ' controlVariable = StringCopy.Chars(arrayIndex)
                ' because the controlVariable can be any LValue, this might have side effects (e.g. ObjArray(SomeFunc()).field)
                ' we will evaluate the expression once per iteration, the side effects are intended.
                Dim charsPropertyGet As MethodSymbol = Nothing
                If TryGetSpecialMember(charsPropertyGet, SpecialMember.System_String__Chars, syntaxNode) Then
                    boundCurrent = New BoundCall(syntaxNode,
                                             DirectCast(charsPropertyGet, MethodSymbol),
                                             Nothing,
                                             boundCollectionLocal,
                                             ImmutableArray.Create(Of BoundExpression)(boundIndex.MakeRValue()),
                                             constantValueOpt:=Nothing,
                                             type:=elementType)
                Else
                    boundCurrent = New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty,
                                                          ImmutableArray.Create(Of BoundExpression)(boundIndex.MakeRValue()), elementType, hasErrors:=True)
                End If
            End If
            ' now we know the bound node for the current value; add it to the replacement map to get inserted into the
            ' conversion from current to the type of the control variable
            If enumeratorInfo.CurrentPlaceholder IsNot Nothing Then
                AddPlaceholderReplacement(enumeratorInfo.CurrentPlaceholder, boundCurrent)
            End If

            ' controlVariable = arrayCopy(arrayIndex)
            ' because the controlVariable can be any LValue, this might have side effects (e.g. ObjArray(SomeFunc()).field)
            ' we will evaluate the expression once per iteration, the side effects are intended.
            Dim boundCurrentAssignment As BoundStatement = New BoundAssignmentOperator(syntaxNode,
                                                                                node.ControlVariable,
                                                                                enumeratorInfo.CurrentConversion,
                                                                                suppressObjectClone:=False,
                                                                                type:=node.ControlVariable.Type).ToStatement
            boundCurrentAssignment.SetWasCompilerGenerated() ' used to not create sequence points
            boundCurrentAssignment = DirectCast(Visit(boundCurrentAssignment), BoundStatement)

            Dim boundIncrementAssignment = CreateIndexIncrement(syntaxNode, boundIndex)

            '
            ' build loop statement
            '

            ' now build while loop
            Dim boundWhileStatement = CreateLoweredWhileStatements(node,
                                                                   boundLimit,
                                                                   boundIndex,
                                                                   boundCurrentAssignment,
                                                                   boundIncrementAssignment,
                                                                   generateUnstructuredExceptionHandlingResumeCode)

            statements.AddRange(DirectCast(boundWhileStatement, BoundStatementList).Statements)

            If enumeratorInfo.CurrentPlaceholder IsNot Nothing Then
                RemovePlaceholderReplacement(enumeratorInfo.CurrentPlaceholder)
            End If
        End Sub

        ''' <summary>
        ''' Creates a local and assigns it the given bound expression.
        ''' </summary>
        ''' <param name="syntaxNode">The syntax node.</param>
        ''' <param name="initExpression">The initialization expression.</param>
        ''' <param name="boundLocal">The bound local.</param>
        ''' <param name="locals">The locals.</param>
        Private Function CreateLocalAndAssignment(
            syntaxNode As StatementSyntax,
            initExpression As BoundExpression,
            <Out()> ByRef boundLocal As BoundLocal,
            locals As ArrayBuilder(Of LocalSymbol),
            kind As SynthesizedLocalKind
        ) As BoundStatement
            ' Dim collectionCopy As C = c
            Dim expressionType = initExpression.Type
            Debug.Assert(kind.IsLongLived())
            Dim collectionCopy = New SynthesizedLocal(Me._currentMethodOrLambda, expressionType, kind, syntaxNode)
            locals.Add(collectionCopy)
            boundLocal = New BoundLocal(syntaxNode, collectionCopy, expressionType)

            ' if this ever fails, you found a test case to see how the suppressObjectClone flag should be set to match
            ' Dev10 behavior.
            Debug.Assert(expressionType.SpecialType <> SpecialType.System_Object)
            Dim boundCollectionAssignment = New BoundAssignmentOperator(syntaxNode,
                                                                        boundLocal,
                                                                        VisitAndGenerateObjectCloneIfNeeded(initExpression),
                                                                        suppressObjectClone:=True,
                                                                        type:=expressionType).ToStatement
            boundCollectionAssignment.SetWasCompilerGenerated() ' used to not create sequence points

            Return boundCollectionAssignment
        End Function

        ''' <summary>
        ''' Creates the index increment statement.
        ''' </summary>
        ''' <param name="syntaxNode">The syntax node.</param>
        ''' <param name="boundIndex">The bound index expression (bound local).</param>
        Private Function CreateIndexIncrement(
            syntaxNode As VisualBasicSyntaxNode,
            boundIndex As BoundLocal
        ) As BoundStatement
            ' collectionIndex += 1
            Dim expressionType = boundIndex.Type
            Dim boundAddition = New BoundBinaryOperator(syntaxNode,
                                                        BinaryOperatorKind.Add,
                                                        boundIndex.MakeRValue(),
                                                        New BoundLiteral(syntaxNode, ConstantValue.Create(1), expressionType),
                                                        checked:=True,
                                                        type:=expressionType)

            ' if this ever fails, you found a test case to see how the suppressObjectClone flag should be set to match
            ' Dev10 behavior.
            Debug.Assert(expressionType.SpecialType <> SpecialType.System_Object)
            Dim boundIncrementAssignment As BoundStatement = New BoundAssignmentOperator(syntaxNode,
                                                                                boundIndex,
                                                                                boundAddition,
                                                                                suppressObjectClone:=False,
                                                                                type:=expressionType).ToStatement.MakeCompilerGenerated

            boundIncrementAssignment = DirectCast(Visit(boundIncrementAssignment), BoundStatement)

            If Instrument Then
                ' create a hidden sequence point for the index increment to not stop on it while debugging
                boundIncrementAssignment = SyntheticBoundNodeFactory.HiddenSequencePoint(boundIncrementAssignment)
            End If

            Return boundIncrementAssignment
        End Function

        ''' <summary>
        ''' Creates the while statement for the for each rewrite
        ''' </summary>
        ''' <param name="limit">The limit to check the index against.</param>
        ''' <param name="index">The index.</param>
        ''' <param name="currentAssignment">The assignment statement of the current value.</param>
        ''' <param name="incrementAssignment">The increment statement.</param>
        ''' <param name="forEachStatement">The bound for each node.</param>
        ''' <returns>The lowered statement list for the while statement.</returns>
        Private Function CreateLoweredWhileStatements(
            forEachStatement As BoundForEachStatement,
            limit As BoundExpression,
            index As BoundLocal,
            currentAssignment As BoundStatement,
            incrementAssignment As BoundStatement,
            generateUnstructuredExceptionHandlingResumeCode As Boolean
        ) As BoundStatementList

            Dim body = DirectCast(Visit(forEachStatement.Body), BoundStatement)
            Dim statementSyntax = forEachStatement.Syntax
            Dim epilogue As BoundStatement = Nothing

            If generateUnstructuredExceptionHandlingResumeCode Then
                epilogue = New BoundStatementList(statementSyntax, RegisterUnstructuredExceptionHandlingResumeTarget(statementSyntax, canThrow:=True))
            End If

            If Instrument(forEachStatement) Then
                epilogue = _instrumenterOpt.InstrumentForEachLoopEpilogue(forEachStatement, epilogue)
            End If

            If epilogue IsNot Nothing Then
                incrementAssignment = New BoundStatementList(statementSyntax, ImmutableArray.Create(epilogue, incrementAssignment))
            End If

            ' Note: we're moving the continue label before the increment of the array index to not create an infinite loop
            ' if somebody uses "Continue For". This will then increase the index and start a new iteration.
            ' Also: see while node creation below
            Dim rewrittenBodyStatements = ImmutableArray.Create(Of BoundStatement)(currentAssignment,
                                                                                body,
                                                                                New BoundLabelStatement(statementSyntax, forEachStatement.ContinueLabel),
                                                                                incrementAssignment)

            ' declare the control variable inside of the while loop to capture it for each
            ' iteration of this loop with a copy constructor
            Dim rewrittenBodyBlock As BoundBlock = New BoundBlock(statementSyntax,
                                                                  Nothing,
                                                                  If(forEachStatement.DeclaredOrInferredLocalOpt IsNot Nothing,
                                                                     ImmutableArray.Create(Of LocalSymbol)(forEachStatement.DeclaredOrInferredLocalOpt),
                                                                     ImmutableArray(Of LocalSymbol).Empty),
                                                                  rewrittenBodyStatements)

            Dim booleanType = GetSpecialTypeWithUseSiteDiagnostics(SpecialType.System_Boolean, statementSyntax)
            Dim boundCondition = TransformRewrittenBinaryOperator(
                                    New BoundBinaryOperator(statementSyntax,
                                                            BinaryOperatorKind.LessThan,
                                                            index.MakeRValue(),
                                                            limit,
                                                            checked:=False,
                                                            type:=booleanType))

            ' now build while loop
            ' Note: we're creating a new label for the while loop that get's used for the initial jump from the
            ' beginning of the loop to the condition to check it for the first time.
            ' Also: see while body creation above
            Dim boundWhileStatement = RewriteWhileStatement(forEachStatement,
                                                            VisitExpressionNode(boundCondition),
                                                            rewrittenBodyBlock,
                                                            New GeneratedLabelSymbol("postIncrement"),
                                                            forEachStatement.ExitLabel)
            Return DirectCast(boundWhileStatement, BoundStatementList)
        End Function

        ''' <summary>
        ''' Rewrite a for each that uses IEnumerable. It's basic form is:
        '''
        '''     Dim e As E = c.GetEnumerator()
        '''     Do While e.MoveNext()
        '''        controlVariable = e.Current
        '''        <loop body>
        '''     Loop
        '''
        ''' To support disposable enumerators, the compiler will generate code to dispose the
        ''' enumerator after loop termination.  Only when E implements IDisposable can this be done.
        ''' The one exception to this rule is when E is specifically IEnumerator, in which case
        ''' the compiler will generate code to dynamically query the enumerator to determine
        ''' if it implements IDisposable.
        '''
        ''' If E is IEnumerator the loop becomes:
        '''
        '''     Dim e As IEnumerator = c.GetEnumerator()
        '''     Try
        '''         Do While e.MoveNext()
        '''            dim controlVariable = e.Current
        '''            <loop body>
        '''         Loop
        '''     Finally
        '''         If TryCast(e, IDisposable) IsNot Nothing then
        '''             CType(e, IDisposable).Dispose()
        '''         End If
        '''     End Try
        '''
        ''' If E is known at compile time to implement IDisposable the loop becomes:
        '''
        '''     Dim e As E = c.GetEnumerator()
        '''     Try
        '''         Do While e.MoveNext()
        '''            dim controlVariable = e.Current
        '''            <loop body>
        '''         Loop
        '''     Finally
        '''         If Not e Is Nothing Then
        '''             CType(e, IDisposable).Dispose()
        '''         End If
        '''     End Try
        '''
        ''' The exception to these forms is the existence of On Error in which case the Try/Finally
        ''' block will be eliminated (instead the body of the Finally will immediately follow
        ''' the end of the loop).
        ''' </summary>
        ''' <param name="node"></param>
        ''' <param name="statements"></param>
        ''' <param name="locals"></param>
        Private Sub RewriteForEachIEnumerable(
            node As BoundForEachStatement,
            statements As ArrayBuilder(Of BoundStatement),
            locals As ArrayBuilder(Of LocalSymbol)
        )
            Dim syntaxNode = DirectCast(node.Syntax, ForEachBlockSyntax)
            Dim enumeratorInfo = node.EnumeratorInfo

            ' We don't wrap the loop with a Try block if On Error is present.
            Dim needTryFinally As Boolean = enumeratorInfo.NeedToDispose AndAlso Not InsideValidUnstructuredExceptionHandlingOnErrorContext()

            Dim saveState As UnstructuredExceptionHandlingContext = Nothing

            If needTryFinally Then
                ' Unstructured Exception Handling should be disabled inside compiler generated Try/Catch/Finally.
                saveState = LeaveUnstructuredExceptionHandlingContext(node)
            End If

            Dim generateUnstructuredExceptionHandlingResumeCode As Boolean = ShouldGenerateUnstructuredExceptionHandlingResumeCode(node)

            Dim loopResumeTarget As ImmutableArray(Of BoundStatement) = Nothing

            If generateUnstructuredExceptionHandlingResumeCode Then
                loopResumeTarget = RegisterUnstructuredExceptionHandlingResumeTarget(syntaxNode, canThrow:=True)
            End If

            ' Where do the bound expressions of the bound for each node get rewritten?
            ' The collection will be used in a call to GetEnumerator() and assigned to a local. This assignment is rewritten
            ' by using "CreateLocalAndAssignment"
            ' The current value will be assigned to the control variable once per iteration. This is done in this method
            ' The casts and conversions get rewritten in "RewriteWhileStatement".

            ' Get Enumerator and store it in a temporary
            ' FYI: The GetEnumerator call accesses the collection and does not contain a placeholder.
            Dim boundEnumeratorLocal As BoundLocal = Nothing
            Dim boundEnumeratorAssignment = CreateLocalAndAssignment(syntaxNode.ForEachStatement,
                                                                     enumeratorInfo.GetEnumerator,
                                                                     boundEnumeratorLocal,
                                                                     locals,
                                                                     SynthesizedLocalKind.ForEachEnumerator)

            If Not loopResumeTarget.IsDefaultOrEmpty Then
                boundEnumeratorAssignment = New BoundStatementList(boundEnumeratorAssignment.Syntax, loopResumeTarget.Add(boundEnumeratorAssignment))
            End If

            If Instrument(node) Then
                ' first sequence point; highlight for each statement
                boundEnumeratorAssignment = _instrumenterOpt.InstrumentForEachLoopInitialization(node, boundEnumeratorAssignment)
            End If

            Debug.Assert(enumeratorInfo.EnumeratorPlaceholder IsNot Nothing)
            AddPlaceholderReplacement(enumeratorInfo.EnumeratorPlaceholder, boundEnumeratorLocal)

            ' Dev10 adds a conversion here from the result of MoveNext to Boolean. However we know for sure that the return
            ' type must be boolean because we check specifically for the return type in case of the design pattern, or we look
            ' up the method by using GetSpecialTypeMember which has the return type encoded.
            Debug.Assert(enumeratorInfo.MoveNext.Type.SpecialType = SpecialType.System_Boolean)

            If enumeratorInfo.CurrentPlaceholder IsNot Nothing Then
                AddPlaceholderReplacement(enumeratorInfo.CurrentPlaceholder, VisitExpressionNode(enumeratorInfo.Current))
            End If

            ' assign the returned value from current to the control variable
            Dim boundCurrentAssignment = New BoundAssignmentOperator(syntaxNode,
                                                                     node.ControlVariable,
                                                                     enumeratorInfo.CurrentConversion,
                                                                     suppressObjectClone:=False,
                                                                     type:=node.ControlVariable.Type).ToStatement
            boundCurrentAssignment.SetWasCompilerGenerated() ' used to not create sequence points

            Dim rewrittenBodyStatements = ImmutableArray.Create(Of BoundStatement)(DirectCast(Visit(boundCurrentAssignment), BoundStatement),
                                                                                DirectCast(Visit(node.Body), BoundStatement))

            ' declare the control variable inside of the while loop to capture it for each
            ' iteration of this loop with a copy constructor
            Dim rewrittenBodyBlock As BoundBlock = New BoundBlock(syntaxNode, Nothing, If(node.DeclaredOrInferredLocalOpt IsNot Nothing, ImmutableArray.Create(Of LocalSymbol)(node.DeclaredOrInferredLocalOpt), ImmutableArray(Of LocalSymbol).Empty), rewrittenBodyStatements)

            Dim bodyEpilogue As BoundStatement = New BoundLabelStatement(syntaxNode, node.ContinueLabel)

            If generateUnstructuredExceptionHandlingResumeCode Then
                bodyEpilogue = Concat(bodyEpilogue, New BoundStatementList(syntaxNode, RegisterUnstructuredExceptionHandlingResumeTarget(syntaxNode, canThrow:=True)))
            End If

            If Instrument(node) Then
                bodyEpilogue = _instrumenterOpt.InstrumentForEachLoopEpilogue(node, bodyEpilogue)
            End If

            rewrittenBodyBlock = AppendToBlock(rewrittenBodyBlock, bodyEpilogue)

            ' now build while loop
            Dim boundWhileStatement = RewriteWhileStatement(node,
                                                            VisitExpressionNode(enumeratorInfo.MoveNext),
                                                            rewrittenBodyBlock,
                                                            New GeneratedLabelSymbol("MoveNextLabel"),
                                                            node.ExitLabel)

            Dim visitedWhile = DirectCast(boundWhileStatement, BoundStatementList)

            If enumeratorInfo.CurrentPlaceholder IsNot Nothing Then
                RemovePlaceholderReplacement(enumeratorInfo.CurrentPlaceholder)
            End If

            If enumeratorInfo.NeedToDispose Then
                Dim disposalStatement = GenerateDisposeCallForForeachAndUsing(node.Syntax,
                                                                              boundEnumeratorLocal,
                                                                              VisitExpressionNode(enumeratorInfo.DisposeCondition),
                                                                              enumeratorInfo.IsOrInheritsFromOrImplementsIDisposable,
                                                                              VisitExpressionNode(enumeratorInfo.DisposeCast))

                If Not needTryFinally Then
                    statements.Add(boundEnumeratorAssignment)
                    statements.Add(visitedWhile)

                    If generateUnstructuredExceptionHandlingResumeCode Then
                        ' Do not reenter the loop if Dispose throws.
                        RegisterUnstructuredExceptionHandlingResumeTarget(syntaxNode, canThrow:=True, statements:=statements)
                    End If

                    statements.Add(disposalStatement)
                Else
                    Dim boundTryFinally = New BoundTryStatement(syntaxNode,
                                                                New BoundBlock(syntaxNode,
                                                                               Nothing, ImmutableArray(Of LocalSymbol).Empty,
                                                                               ImmutableArray.Create(Of BoundStatement)(boundEnumeratorAssignment,
                                                                                visitedWhile)),
                                                                ImmutableArray(Of BoundCatchBlock).Empty,
                                                                New BoundBlock(syntaxNode,
                                                                               Nothing, ImmutableArray(Of LocalSymbol).Empty,
                                                                               ImmutableArray.Create(Of BoundStatement)(disposalStatement)),
                                                                           exitLabelOpt:=Nothing)
                    boundTryFinally.SetWasCompilerGenerated() ' used to not create sequence points
                    statements.Add(boundTryFinally)
                End If
            Else
                Debug.Assert(Not needTryFinally)
                statements.Add(boundEnumeratorAssignment)
                statements.AddRange(visitedWhile)
            End If

            If needTryFinally Then
                RestoreUnstructuredExceptionHandlingContext(node, saveState)
            End If

            RemovePlaceholderReplacement(enumeratorInfo.EnumeratorPlaceholder)
        End Sub

        ''' <summary>
        ''' Depending on whether the bound local's type is, implements or inherits IDisposable for sure, or might implement it,
        ''' this function returns the statements to call Dispose on the bound local.
        '''
        ''' If it's known to implement IDisposable, the generated code looks like this for reference types:
        '''     If e IsNot Nothing Then
        '''       CType(e, IDisposable).Dispose()
        '''     End If
        ''' or
        ''' e.Dispose()
        ''' for value types (including type parameters with a value constraint).
        ''' Otherwise it looks like the following
        '''     If TryCast(e, IDisposable) IsNot Nothing then
        '''       CType(e, IDisposable).Dispose()
        '''     End If
        ''' </summary>
        ''' <remarks>This method is used by the for each rewriter and the using rewriter. The latter should only call
        ''' this method with both IsOrInheritsFromOrImplementsIDisposable and needToDispose set to true, as using is not
        ''' pattern based and must implement IDisposable.
        ''' </remarks>
        ''' <param name="syntaxNode">The syntax node.</param>
        ''' <param name="rewrittenBoundLocal">The bound local.</param>
        ''' <param name="rewrittenCondition">The condition used in the if statement around the dispose call</param>
        ''' <param name="IsOrInheritsFromOrImplementsIDisposable">A flag indicating whether the bound local's type is,
        ''' inherits or implements IDisposable or not.</param>
        ''' <param name="rewrittenDisposeConversion">Conversion from the local type to IDisposable</param>
        Public Function GenerateDisposeCallForForeachAndUsing(
            syntaxNode As SyntaxNode,
            rewrittenBoundLocal As BoundLocal,
            rewrittenCondition As BoundExpression,
            IsOrInheritsFromOrImplementsIDisposable As Boolean,
            rewrittenDisposeConversion As BoundExpression
        ) As BoundStatement
            Dim disposeMethod As MethodSymbol = Nothing
            If Not TryGetSpecialMember(disposeMethod, SpecialMember.System_IDisposable__Dispose, syntaxNode) Then
                Return New BoundBadExpression(syntaxNode, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty,
                                              If(rewrittenCondition IsNot Nothing,
                                                 ImmutableArray.Create(rewrittenBoundLocal, rewrittenCondition),
                                                 ImmutableArray.Create(Of BoundExpression)(rewrittenBoundLocal)),
                                              ErrorTypeSymbol.UnknownResultType, hasErrors:=True).ToStatement()
            End If

            Dim voidType = GetSpecialTypeWithUseSiteDiagnostics(SpecialType.System_Void, syntaxNode)

            Dim localType = rewrittenBoundLocal.Type

            ' the bound nodes for the condition and the cast both come from the initial binding and are contained in
            ' the bound for each node.
            ' This way the construction of the "reference type implements IDisposable" case and the case of
            ' "may implement IDisposable" can be handled by the same code fragment. Only the value types know to implement
            ' IDisposable need to be handled differently

            Dim boundCall As BoundStatement
            If IsOrInheritsFromOrImplementsIDisposable AndAlso
                (localType.IsValueType OrElse localType.IsTypeParameter) Then

                ' there's no need to cast the enumerator if it's known to be a value type, because they are implicitly
                ' sealed the methods cannot ever be overridden.

                ' this will be a constrained call, because the receiver is a value type and the method is an
                ' interface method:
                ' e.Dispose()    ' constrained call
                boundCall = New BoundCall(syntaxNode,
                                          disposeMethod,
                                          Nothing,
                                          rewrittenBoundLocal,
                                          ImmutableArray(Of BoundExpression).Empty,
                                          constantValueOpt:=Nothing,
                                          type:=voidType).ToStatement
                boundCall.SetWasCompilerGenerated() ' used to not create sequence points

                If localType.IsValueType Then
                    Return boundCall
                End If
            Else
                Debug.Assert(rewrittenDisposeConversion IsNot Nothing)

                ' call to Dispose
                boundCall = New BoundCall(syntaxNode,
                                          disposeMethod,
                                          Nothing,
                                          rewrittenDisposeConversion,
                                          ImmutableArray(Of BoundExpression).Empty, Nothing, voidType).ToStatement
                boundCall.SetWasCompilerGenerated() ' used to not create sequence points
            End If

            ' if statement (either the condition is "e IsNot nothing" or "TryCast(e, IDisposable) IsNot Nothing", see comment above)
            Return RewriteIfStatement(syntaxNode, rewrittenCondition, boundCall, Nothing, instrumentationTargetOpt:=Nothing)
        End Function

        ''' <summary>
        ''' Internal helper class to replace local symbols in bound locals of a given bound tree.
        ''' </summary>
        Private NotInheritable Class LocalVariableSubstituter
            Inherits BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator

            Private ReadOnly _original As LocalSymbol
            Private ReadOnly _replacement As LocalSymbol
            Private _replacedNode As Boolean = False

            Public Shared Function Replace(
                node As BoundNode,
                original As LocalSymbol,
                replacement As LocalSymbol,
                recursionDepth As Integer,
                ByRef replacedNode As Boolean
            ) As BoundNode
                Dim rewriter As New LocalVariableSubstituter(original, replacement, recursionDepth)

                Dim result = rewriter.Visit(node)
                replacedNode = rewriter.ReplacedNode

                Return result
            End Function

            Private ReadOnly Property ReplacedNode As Boolean
                Get
                    Return _replacedNode
                End Get
            End Property

            Private Sub New(original As LocalSymbol, replacement As LocalSymbol, recursionDepth As Integer)
                MyBase.New(recursionDepth)
                _original = original
                _replacement = replacement
            End Sub

            Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode

                If node.LocalSymbol Is _original Then
                    _replacedNode = True

                    Return node.Update(_replacement, node.IsLValue, node.Type)
                End If

                Return node
            End Function
        End Class

    End Class
End Namespace

redpajama_set_name: RedPajamaGithub


text:
// The LL layer for MMU register operations

#pragma once

#include "stdint.h"
#include "soc/extmem_reg.h"
#include "soc/ext_mem_defs.h"
#include "hal/assert.h"
#include "hal/mmu_types.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * Convert MMU virtual address to linear address
 *
 * @param vaddr  virtual address
 *
 * @return linear address
 */
static inline uint32_t mmu_ll_vaddr_to_laddr(uint32_t vaddr)
{
    return vaddr & SOC_MMU_LINEAR_ADDR_MASK;
}

/**
 * Convert MMU linear address to virtual address
 *
 * @param laddr       linear address
 * @param vaddr_type  virtual address type, could be instruction type or data type. See `mmu_vaddr_t`
 *
 * @return virtual address
 */
static inline uint32_t mmu_ll_laddr_to_vaddr(uint32_t laddr, mmu_vaddr_t vaddr_type)
{
    uint32_t vaddr_base = 0;
    if (vaddr_type == MMU_VADDR_DATA) {
        vaddr_base = SOC_MMU_DBUS_VADDR_BASE;
    } else {
        vaddr_base = SOC_MMU_IBUS_VADDR_BASE;
    }

    return vaddr_base | laddr;
}

/**
 * Get MMU page size
 *
 * @param mmu_id  MMU ID
 *
 * @return MMU page size code
 */
__attribute__((always_inline))
static inline mmu_page_size_t mmu_ll_get_page_size(uint32_t mmu_id)
{
    //On esp32s2, MMU Page size is always 64KB
    (void)mmu_id;
    return MMU_PAGE_64KB;
}

/**
 * Set MMU page size
 *
 * @param size  MMU page size
 *
 * @note On esp32s2, only supports `MMU_PAGE_64KB`
 */
__attribute__((always_inline))
static inline void mmu_ll_set_page_size(uint32_t mmu_id, uint32_t size)
{
    HAL_ASSERT(size == MMU_PAGE_64KB);
}

/**
 * Check if the external memory vaddr region is valid
 *
 * @param mmu_id      MMU ID
 * @param vaddr_start start of the virtual address
 * @param len         length, in bytes
 *
 * @return
 *         True for valid
 */
__attribute__((always_inline))
static inline bool mmu_ll_check_valid_ext_vaddr_region(uint32_t mmu_id, uint32_t vaddr_start, uint32_t len)
{
    (void)mmu_id;
    uint32_t vaddr_end = vaddr_start + len - 1;

    //DROM0 is an alias of the IBUS2
    bool on_ibus = ((vaddr_start >= DROM0_ADDRESS_LOW) && (vaddr_end < DROM0_ADDRESS_HIGH)) ||
                   ((vaddr_start >= IRAM0_CACHE_ADDRESS_LOW) && (vaddr_end < IRAM1_ADDRESS_HIGH));

    bool on_dbus = (vaddr_start >= DPORT_CACHE_ADDRESS_LOW) && (vaddr_end < DRAM0_CACHE_ADDRESS_HIGH);

    return (on_ibus || on_dbus);
}

/**
 * To get the MMU table entry id to be mapped
 *
 * @param mmu_id  MMU ID
 * @param vaddr   virtual address to be mapped
 *
 * @return
 *         MMU table entry id
 */
__attribute__((always_inline))
static inline uint32_t mmu_ll_get_entry_id(uint32_t mmu_id, uint32_t vaddr)
{
    (void)mmu_id;
    uint32_t offset = 0;

    if (ADDRESS_IN_DROM0(vaddr)) {
        offset = PRO_CACHE_IBUS2_MMU_START / 4;
    } else if (ADDRESS_IN_IRAM0_CACHE(vaddr)) {
        offset = PRO_CACHE_IBUS0_MMU_START / 4;
    } else if (ADDRESS_IN_IRAM1(vaddr)) {
        offset = PRO_CACHE_IBUS1_MMU_START / 4;
    } else if (ADDRESS_IN_DPORT_CACHE(vaddr)) {
        offset = PRO_CACHE_DBUS2_MMU_START / 4;
    } else if (ADDRESS_IN_DRAM1(vaddr)) {
        offset = PRO_CACHE_DBUS1_MMU_START / 4;
    } else if (ADDRESS_IN_DRAM0_CACHE(vaddr)) {
        offset = PRO_CACHE_DBUS0_MMU_START / 4;
    } else {
        HAL_ASSERT(false);
    }

    return offset + ((vaddr & MMU_VADDR_MASK) >> 16);
}

/**
 * Format the paddr to be mappable
 *
 * @param mmu_id  MMU ID
 * @param paddr   physical address to be mapped
 *
 * @return
 *         mmu_val - paddr in MMU table supported format
 */
__attribute__((always_inline))
static inline uint32_t mmu_ll_format_paddr(uint32_t mmu_id, uint32_t paddr)
{
    (void)mmu_id;
    return paddr >> 16;
}

/**
 * Write to the MMU table to map the virtual memory and the physical memory
 *
 * @param mmu_id   MMU ID
 * @param entry_id MMU entry ID
 * @param mmu_val  Value to be set into an MMU entry, for physical address
 * @param target   MMU target physical memory.
 */
__attribute__((always_inline))
static inline void mmu_ll_write_entry(uint32_t mmu_id, uint32_t entry_id, uint32_t mmu_val, mmu_target_t target)
{
    (void)mmu_id;
    HAL_ASSERT(entry_id < MMU_ENTRY_NUM);

    uint32_t target_code = (target == MMU_TARGET_FLASH0) ? MMU_ACCESS_FLASH : MMU_ACCESS_SPIRAM;
    *(uint32_t *)(DR_REG_MMU_TABLE + entry_id * 4) = mmu_val | target_code | MMU_VALID;
}

/**
 * Read the raw value from MMU table
 *
 * @param mmu_id   MMU ID
 * @param entry_id MMU entry ID
 * @param mmu_val  Value to be read from MMU table
 */
__attribute__((always_inline))
static inline uint32_t mmu_ll_read_entry(uint32_t mmu_id, uint32_t entry_id)
{
    (void)mmu_id;
    HAL_ASSERT(entry_id < MMU_ENTRY_NUM);

    return *(uint32_t *)(DR_REG_MMU_TABLE + entry_id * 4);
}

/**
 * Set MMU table entry as invalid
 *
 * @param mmu_id   MMU ID
 * @param entry_id MMU entry ID
 */
__attribute__((always_inline))
static inline void mmu_ll_set_entry_invalid(uint32_t mmu_id, uint32_t entry_id)
{
    (void)mmu_id;
    HAL_ASSERT(entry_id < MMU_ENTRY_NUM);

    *(uint32_t *)(DR_REG_MMU_TABLE + entry_id * 4) = MMU_INVALID;
}

/**
 * Unmap all the items in the MMU table
 *
 * @param mmu_id MMU ID
 */
__attribute__((always_inline))
static inline void mmu_ll_unmap_all(uint32_t mmu_id)
{
    for (int i = 0; i < MMU_ENTRY_NUM; i++) {
        mmu_ll_set_entry_invalid(mmu_id, i);
    }
}

/**
 * Get MMU table entry is invalid
 *
 * @param mmu_id   MMU ID
 * @param entry_id MMU entry ID
 * return ture for MMU entry is invalid, false for valid
 */
__attribute__((always_inline))
static inline bool mmu_ll_get_entry_is_invalid(uint32_t mmu_id, uint32_t entry_id)
{
    (void)mmu_id;
    HAL_ASSERT(entry_id < MMU_ENTRY_NUM);

    return (*(uint32_t *)(DR_REG_MMU_TABLE + entry_id * 4) & MMU_INVALID) ? true : false;
}

#ifdef __cplusplus
}
#endif


text:
<?php

if (!defined('_ECRIRE_INC_VERSION')) return;

include_spip('inc/presentation');

// http://doc.spip.org/@exec_controle_petition_dist
function exec_controle_petition_dist()
{
	exec_controle_petition_args(intval(_request('id_article')),
		_request('type'),
		_request('date'),
		intval(_request('debut')),
		intval(_request('id_signature')),
		intval(_request('pas'))); // a proposer grapiquement
}

// http://doc.spip.org/@exec_controle_petition_args
function exec_controle_petition_args($id_article, $type, $date, $debut, $id_signature, $pas=NULL)
{
	if ($id_signature) {
		$id_article = sql_getfetsel("id_article", "spip_signatures", "id_signature=$id_signature");
		$where = '(id_signature=' . sql_quote($id_signature) . ') AND ';
	} else 	$where = '';
	if ($id_article AND !($titre = sql_getfetsel("titre", "spip_articles", "id_article=$id_article"))) {
		include_spip('inc/minipres');
                echo minipres(_T('public:aucun_article'));
	}	else controle_petition_args($id_article, $type, $date, $debut, $titre, $where, $pas);
}

function controle_petition_args($id_article, $type, $date, $debut, $titre, $where, $pas)
{
	if (!preg_match('/^\w+$/',$type)) $type = 'public';
	if ($id_article) $where .= "id_article=$id_article AND ";
	$extrait = "(statut='publie' OR statut='poubelle')";
	if ($type == 'interne') $extrait = "NOT($extrait)";
	$where .= $extrait;
	$order = "date_time DESC";
	if (!$pas) $pas = 10;
	if ($date) {
		include_spip('inc/forum');
		$query = array('SELECT' => 'UNIX_TIMESTAMP(date_time) AS d',
				'FROM' => 'spip_signatures',
				'WHERE' => $where,
				'ORDER BY' => $order);
		$debut = navigation_trouve_date($date, 'd', $pas, $query);
	}
	$signatures = charger_fonction('signatures', 'inc');

	$res = $signatures('controle_petition', $id_article, $debut, $pas, $where, $order, $type);

	if (_AJAX) {
			ajax_retour($res);
	} else {

		if (autoriser('modererpetition')
		OR (
			$id_article > 0
			AND autoriser('modererpetition', 'article', $id_article)
			))
			$ong = controle_petition_onglet($id_article, $debut, $type);
		else {
		  $type = 'public';
		  $ong = '';
		}
		controle_petition_page($id_article, $titre, $ong, $res);
	}
}

// http://doc.spip.org/@controle_petition_page
function controle_petition_page($id_article, $titre,  $ong, $corps)
{
	if ($id_article) {
		$a =  generer_url_ecrire("statistiques_visites","id_article=$id_article");
		$rac = "

" .
		bloc_des_raccourcis(icone_horizontale(_T('icone_statistiques_visites'),$a, "statistiques-24.gif","rien.gif", false));

		$titre = "" .
			typo($titre) .
			"" .
			" (" .
			_T('info_numero_abbreviation') .
			$id_article .
			")";

		if (!sql_countsel('spip_petitions', "id_article=$id_article"))
			$titre .= '
' . _T('info_petition_close');

		$args = array('id_article' => $id_article);
	} else  {
		$args = array();
		$rac = $titre = '';
	}

	$head = _T('titre_page_controle_petition');
	$idom = "editer_signature-" . $id_article;
	$commencer_page = charger_fonction('commencer_page', 'inc');

	echo $commencer_page($head, "forum", "suivi-petition");
	echo debut_gauche('', true);
	echo $rac;
	echo debut_droite('', true);
	echo gros_titre(_T('titre_suivi_petition'),'', false);
	echo $ong;
	echo bouton_spip_rss('signatures', $args);
	echo $titre;
	echo  "

";
	echo "
", $corps, "
";
	echo fin_gauche(), fin_page();
}

// http://doc.spip.org/@controle_petition_onglet
function controle_petition_onglet($id_article, $debut, $type, $arg='')
{
	$arg .= ($id_article ? "id_article=$id_article&" :'');
	$arg2 = ($debut ? "debut=$debut&" : '');
	if ($type=='public') {
	  $argp = $arg2;
	  $argi = '';
	} else {
	  $argi = $arg2;
	  $argp = '';
	}

	return debut_onglet()
	  . onglet(_T('titre_signatures_confirmees'), generer_url_ecrire('controle_petition', $argp . $arg . "type=public"), "public", $type=='public', "forum-public-24.gif")
	.  onglet(_T('titre_signatures_attente'), generer_url_ecrire('controle_petition', $argi . $arg .  "type=interne"), "interne", $type=='interne', "forum-interne-24.gif")
	. fin_onglet()
	. '
';
}
?>


text:
import psutil
import win32com.client
import win32gui
import win32process

parr = {}
for proc in psutil.process_iter():
  #try:
  pinfo = proc.as_dict(attrs=['pid', 'name'])
  parr[pinfo['pid']]=pinfo['name']
  #except psutil.NoSuchProcess:
  #    pass
  #else:
  #    print(pinfo)
#print(parr)
hwnd = win32gui.GetForegroundWindow()
pid = win32process.GetWindowThreadProcessId(hwnd)
print hwnd


text:
<?php
namespace Concrete\Core\Application\Service\UserInterface\Help;

class AbstractManager implements ManagerInterface, RegistryInterface
{

    protected $messages;

    public function registerMessages($messages)
    {
        foreach($messages as $identifier => $message) {
            $this->registerMessageString($identifier, $message);
        }
    }

    public function registerMessageString($identifier, $message)
    {
        $m = new Message();
        if (is_array($message)) {
            $m->setMessageContent($message[0]);
            $m->addGuide($message[1]);
        } else {
            $m->setMessageContent($message);
        }
        $m->setIdentifier($identifier);
        $this->messages[$identifier] = $m;
    }

    public function getMessage($identifier)
    {
        return $this->messages[$identifier];
    }

    public function getFormatter(Message $message)
    {
        return new Formatter();
    }

}


text:
author: Philipp Montazem
date: 2017-02-11T09:00:15+01:00
publishdate: 2017-02-11T09:00:15+01:00
draft: false
title: Order Himapan's coconut oil straight to your home
slug: webshop
subtitle: Shopping made easy and safe
description: Buy Himapan's coconut oil in the Webshop - Shopping made easy and safe
weight: 10
menusection: Himapan
alternatelocales:
  - de-AT
tags:
  - Webshop
  - Suppliers
  - Buy coconut oil
  - coconut oil
  - Where to buy?
topics:
  - Himapan
  - Supplilers
  - Coconut oil
aliases:
  - /eshop
images:
  - /img/ban-table.jpg
formcheckboxes:
  - Question
  - Webshop service
menu:
  side:
    Name: Webshop
    Weight: 10
    Identifier: webshop
    Url: /webshop
    Parent: quellen
---

## Himapan's Webshop
Our webshop is run as service from a service provider and therefore has all required security and provides you with a hopefully very comfortable shopping experience.

More Details to our Online-Shopping can be found in the Webshop

#### Thank you for visiting Himapan's webshop!

    shopping_cart

Buy Premium Coconut Oil at

zu himapan's webshop

##### Privacy Information
We would like to inform you, that our webhop service provider uses Google Analytics. If you do not want your website visits tracked by Google, installing Tracking-blockers is an option: For more information, please visit [Privacy Badger](https://www.eff.org/privacybadger "Visit Website of Privacy Badger")


text:
[![CI Status](http://img.shields.io/travis/nbabaka/CMDFramework.svg?style=flat)](https://travis-ci.org/nbabaka/CMDFramework)
[![Version](https://img.shields.io/cocoapods/v/CMDFramework.svg?style=flat)](http://cocoapods.org/pods/CMDFramework)
[![License](https://img.shields.io/cocoapods/l/CMDFramework.svg?style=flat)](http://cocoapods.org/pods/CMDFramework)
[![Platform](https://img.shields.io/cocoapods/p/CMDFramework.svg?style=flat)](http://cocoapods.org/pods/CMDFramework)

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

CMDFramework is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "CMDFramework"
```

## Author

nbabaka, babaka@cinemood.com

## License

CMDFramework is available under the MIT license. See the LICENSE file for more info.


text:
{-# LANGUAGE NoImplicitPrelude #-}
module Utils.Vigilance.Worker ( workForeverWith
                              , workForeverWithDelayed
                              , workForever) where

import ClassyPrelude
import Control.Concurrent (threadDelay)

workForeverWithDelayed :: Int -> (SomeException -> IO ()) -> IO () -> IO ()
workForeverWithDelayed d handler action = workForeverWith handler doAction
  where doAction     = action >> threadDelay microseconds
        microseconds = d * 1000000

workForeverWith :: (SomeException -> IO ()) -> IO () -> IO ()
workForeverWith handler = forever . handleAny handler

-- eats errors
workForever :: IO () -> IO ()
workForever = workForeverWith (const $ return ())


text:
package org.eclipse.e4.ui.progress.internal;

/**
 * The IJobProgressManagerListener is a class that listeners to the JobProgressManager.
 */
interface IJobProgressManagerListener {

    /**
     * Refresh the viewer as a result of an addition of info.
     * @param info
     */
    void addJob(final JobInfo info);

    /**
     * Refresh the viewer as a result of an addition of group.
     * @param info
     */
    void addGroup(final GroupInfo info);

    /**
     * Refresh the IJobProgressManagerListeners as a result of a change in info.
     * @param info
     */
    public void refreshJobInfo(JobInfo info);

    /**
     * Refresh the IJobProgressManagerListeners as a result of a change in groups.
     * @param info
     */
    public void refreshGroup(GroupInfo info);

    /**
     * Refresh the viewer for all jobs.
     * @param info
     */
    void refreshAll();

    /**
     * Refresh the viewer as a result of a removal of info.
     * @param info
     */
    void removeJob(final JobInfo info);

    /**
     * Refresh the viewer as a result of a removal of group.
     * @param info
     */
    void removeGroup(final GroupInfo group);

    /**
     * Return whether or not this listener shows debug information.
     * @return boolean
     */
    boolean showsDebug();
}


text:
#ifndef __SGE_RENDERER_HPP
#define __SGE_RENDERER_HPP

#include <sge/assets/loaders/image.hpp>
#include <sge/assets/loaders/font.hpp>
#include <sge/utils/vector.hpp>
#include <sge/utils/shape.hpp>

#include <SDL.h>
#include <SDL2_gfxPrimitives.h>
#include <functional>

namespace sge
{
    using DrawRequest = std::function<bool (void)>;

    class Renderer
    {
        public:
            void set_renderer(SDL_Renderer *rdr);

            bool clear();
            void present();

            bool draw_point(const Vector &pos, const SDL_Color &color);
            bool draw_line(const Vector &start, const Vector &end, const SDL_Color &color);

            bool draw_rect(const SDL_Rect &r, const SDL_Color &color);
            bool draw_rect(const SDL_Rect &r, float angle, const SDL_Color &color);

            bool draw_filled_rect(const SDL_Rect &r, const SDL_Color &color);
            bool draw_filled_rect(const SDL_Rect &r, float angle, const SDL_Color &color);

            bool draw_circle(const Vector &center, int radius, const SDL_Color &color);
            bool draw_filled_circle(const Vector &center, int radius, const SDL_Color &color);

            bool draw_ellipse(const Vector &center, int hradius, int vradius, const SDL_Color &color);
            bool draw_ellipse(const Vector &center, int hradius, int vradius, float angle, const SDL_Color &color);
            bool draw_ellipse(const Vector &center, int hradius, int vradius, SDL_RendererFlip flip, const SDL_Color &color);
            bool draw_ellipse(const Vector &center, int hradius, int vradius, float angle, SDL_RendererFlip flip, const SDL_Color &color);

            bool draw_filled_ellipse(const Vector &center, int hradius, int vradius, const SDL_Color &color);
            bool draw_filled_ellipse(const Vector &center, int hradius, int vradius, float angle, const SDL_Color &color);
            bool draw_filled_ellipse(const Vector &center, int hradius, int vradius, SDL_RendererFlip flip, const SDL_Color &color);
            bool draw_filled_ellipse(const Vector &center, int hradius, int vradius, float angle, SDL_RendererFlip flip, const SDL_Color &color);

            bool draw_shape(const Shape &shape, const SDL_Color &color);
            bool draw_filled_shape(const Shape &shape, const SDL_Color &color);

            bool draw_image(std::shared_ptr<Image> asset, const SDL_Rect &dest);
            bool draw_image(std::shared_ptr<Image> asset, const SDL_Rect &src, const SDL_Rect &dest);
            bool draw_image(std::shared_ptr<Image> asset, const SDL_Rect &dest, float angle, const SDL_Point &center, SDL_RendererFlip flip);
            bool draw_image(std::shared_ptr<Image> asset, const SDL_Rect &src, const SDL_Rect &dest, float angle, const SDL_Point &center, SDL_RendererFlip flip);

            bool draw_text(std::shared_ptr<Font> asset, const std::string &text, const Vector &pos, const SDL_Color &color);

            std::string get_error() const;

        private:
            bool draw_with_color(DrawRequest req, const SDL_Color &color);
            bool draw_with_target(DrawRequest req, float angle, const SDL_Point &center, SDL_RendererFlip flip);
            void set_error(const std::string &text);

        private:
            SDL_Renderer *renderer;
            std::string error;
    };
}

#endif /* __SGE_RENDERER_HPP */


text:
#ifndef BABYLON_EVENTS_KEYBOARD_EVENT_TYPES_H
#define BABYLON_EVENTS_KEYBOARD_EVENT_TYPES_H

#include <babylon/babylon_api.h>

namespace BABYLON {

/**
 * @brief Gather the list of keyboard event types as constants.
 */
struct BABYLON_SHARED_EXPORT KeyboardEventTypes {
  /**
   * The keydown event is fired when a key becomes active (pressed).
   */
  static constexpr unsigned int KEYDOWN = 0x01;
  /**
   * The keyup event is fired when a key has been released.
   */
  static constexpr unsigned int KEYUP = 0x02;
}; // end of struct KeyboardEventTypes

} // end of namespace BABYLON

#endif // end of BABYLON_EVENTS_KEYBOARD_EVENT_TYPES_H


text:
import React from 'react';

import Dialog from 'material-ui/lib/dialog';
import FlatButton from 'material-ui/lib/flat-button';
import RaisedButton from 'material-ui/lib/raised-button';
import TextField from 'material-ui/lib/text-field';
import axios from 'axios';

export default class PostRide extends React.Component {

  constructor(props) {
    super(props)
  }

  axiosPost = (event) => {
    event.preventDefault();
    axios.post('http://localhost:3000/rides', {
      title: this.refs.postTitle.getValue(),
      available_seats: this.refs.postSeatsAvailable.getValue(),
      origin: this.refs.postOrigin.getValue(),
      destination: this.refs.postDestination.getValue()
    })

      .then(function(response){
        console.log('success, response: ', response)
        })
      .error( res => console.log("Something bad happened", res) )
  }

  render() {

      return (

Offering a ride? Let people know where you're headed, where you're going, and a brief description of the trip.

          <form
            onSubmit={this.axiosPost}
            className = "form-style">
          <TextField
            id="post-title-field"
            hintText="E.g. Daily to downtown Toronto"
            floatingLabelText="Title"
            ref="postTitle"
          />
          <TextField
            id="post-available-seats"
            hintText="E.g. 2"
            floatingLabelText="Seats available"
            ref="postSeatsAvailable"
          />

          <TextField
            id="post-destination-field"
            hintText="E.g. Lighthouse Labs"
            floatingLabelText="Where to?"
            ref="postDestination"
          />
          <TextField
            id="post-origin-field"
            hintText="E.g. Steamwhistle Brewery"
            floatingLabelText="Where from?"
            ref="postOrigin"
          />

          <FlatButton
            label="Buckle up!"
            primary={true}
            keyboardFocused={true}
            type="submit"
            onClick={this.props.handleClose}
          />
          <FlatButton
            label="Cancel"
            secondary={true}
            onTouchTap={this.props.handleClose}
          />
          </form>

      );
    }
  }

// <input type="text" value={this.state.title} onChange={ev => this.setState({title: ev.target.value})} />


text:
Various tools based on the Guild Wars 2 API.

## Requirements
- PHP-Compatible Webserver (Apache, NGinx, etc.)
- PHP 5.6.9 or newer
- MySQL
- Composer

## Installation
- Download the repo and place it in a folder of your choosing.
- Install dependencies using `composer install`.
- Copy `.env.example` to `.env` and edit to match your server's setup.
- Point your webserver to your project's `public` directory.


text:
package org.omg.PortableServer;

import org.omg.CORBA.Policy;
import org.omg.CORBA.portable.IDLEntity;

/**
 * Defines the POA thread policy.
 *
 * The policy can return its current value, as defined.
 * in {@link ThreadPolicyOperations}.
 *
 * @see ThreadPolicyValue for the possible values of this policy.
 *
 * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org)
 */
public interface ThreadPolicy
  extends Policy, ThreadPolicyOperations, IDLEntity
{
}