text:
<!-- markdownlint-disable MD041 Multiple top-level headings in same document -->
<!-- markdownlint-disable MD024 Multiple headings with same title -->
BERG THE FIRST: SEE NO EVIL
===========================

Berg 0.1 is the syntax and structure of Berg. It is a full version of the Berg language with the important exceptions of a compiler, full error system, system interaction and a packaging system. Its purpose is to give a solid read on what Berg *looks* like, to give a foundation to build libraries and other language features on, and to allow others to give feedback on the language and contribute.

1. Base
    [X] UTF-8
    [X] I/O
    [X] CompilerError Reporting
    [X] Tests
    [X] Command Line
2. Expressions
    [X] Integers
    [X] Operators
    [X] Parentheses
3. Objects
    [X] Fields
    [ ] Blocks
    [ ] Fields
    [ ] Extension
4. Control Flow
    [ ] Lazy Evaluation
    [ ] Function Calls
    [ ] Conditionals
    [ ] Recursion
    [ ] Loops
5. Modules
6. Visual Studio Code Extension

BERG 0.2: HEAR NO EVIL
======================

Berg 0.2 completes the control flow features: effects, and host interaction (FFI).

1. Errors
    [ ] CompilerError Objects
    [ ] CompilerError Codes With Properties (MissingOperand, Side=Left/Right/Both)
    [ ] CompilerError Localization
    [ ] CompilerError Propagation
2. Effects
    [ ] I/O
    [ ]
3. FFI
    [ ] FFI

BERG 0.3: SPEAK NO EVIL
=======================

Berg 0.3 introduces compilation, matchers and types to Berg, moving from its interpreted shape to a statically compiled one. 0.1 and 0.2 were designed with this in mind, but this will be the first true exercise of it.

1. Compilation
2. Compilation
    [ ]

Round 1: Integers
=================

Integer
-------

[X] Integer literal
[X] CompilerError: Integer starts with zero

Invalid UTF-8
-------------

[X] CompilerError: Invalid UTF-8
[X] CompilerError: Unsupported Character
[X] CompilerError: SourceRef Not Found
[X] CompilerError: I/O open error
[X] CompilerError: I/O read error
[X] CompilerError: I/O directory join error for relative path

Tools
-----

[X] Unit Test Project
[X] Command Line

Round 2: Expressions
====================

Runtime
-------

[X] TypeChecker: Type, Number, IntegerLiteral.StackValue() -> Number
[X] TypeRuntime { Run(Type) -> Print Result }
[X] Integer tests

Math
----

[X] Add/Subtract Operators
[X] Multiply/Divide Operators
[X] Precedence
[X] Negative/Positive Operators
[X] CompilerError: Divide By Zero
[X] CompilerError: Unrecognized Operator

Round 3: Boolean Logic
======================

Boolean
-------

[X] true, false
[X] CompilerError: cannot use true/false in math operator

Boolean Operators
-----------------

[X] &&, ||, !
[X] anything other than false is true; && and || return determining argument, not necessarily "true"

Comparison Operators
--------------------

[X] ==, !=
[X] >, <, <=, >=
[X] CompilerError: Non-number in comparison operator

Round 4: Expression Syntax
==========================

Parens
------

[X] Expression Operator "(", ")"
[X] Parse CompilerError: Unclosed Paren
[X] Parse CompilerError: Unopened Paren

Nothing
-------

[X] Type::Nothing
[X] Empty source file -> nothing
[X] Empty parentheses -> nothing
[X] CompilerError: cannot apply operator [/*+-] to "nothing" (either left or right side or both)

Space
-----

[X] Whitespace, Tabs
[X] Compound Term Grouping
[X] Newlines; Record Line / Column Data

Round 5: ScopeRef
==============

Statements
----------

[X] Statement Separator ";"
[X] Trailing Semicolon Acceptable
[X] Final Expression In BlockRef is Return StackValue
[X] Newline Statement Separation
[X] Newline Statement Continuation

Fields
---------

*Fields* are accessible in the scope they were first defined and nowhere else.
[X] Field Assignment (a = b)
[X] Field Reassignment (a = b)
[X] Field Reference (a)
[X] CompilerError: No Such Field
[ ] CompilerError: Unused Field Definition
[ ] CompilerError: Reference Before Definition

Round 6: Blocks
===============

Blocks
------

[ ] {} creates a new block
[ ] CompilerError: ) where expected }
[ ] CompilerError: } where expected )

BlockRef ScopeRef
-----------

[ ] Fields in parent block are accessible and assignable
[ ] Fields declared *after* block, in parent scope, are inaccessible
[ ] Fields declared in sibling scopes are inaccessible to each other
[ ] Fields declared in child scope are inaccessible to parents

BlockRef Laziness
--------------

[ ] "output" function so we can test evaluation
[ ] Unused blocks do not evaluate
[ ] Blocks evaluate on first use
[ ] Blocks evaluate no more than once

Short Circuiting
----------------

[ ] && and || do not evaluate the second argument unless needed

Round 7: Objects
================

Fields
------

*Fields* are fields that have been made public, and are thus accessible outside their scope.
[X] Expose field value (:a = b)
[X] Field usable in expression
[ ] "Unused field error" does not apply to field
[ ] "Unused field error" does not apply to field

Field Access
------------

[ ] Field access (a.b)
[ ] CompilerError: no such field
[ ] CompilerError: field not accessible in scope
[ ] CompilerError: field not

Self
----

Return Self
-----------

Extend
------

Round 5: Conditionals
=====================

if
--

else
----

loop
----

break
-----

Round 5: Functions
==================

APPLY
----

Define and run functions

Round 6: Compilation
====================

Round 5: CompilerError Propagation
==========================

CompilerError Properties
----------------

[ ] CompilerError is Berg object
[ ] Errors have arbitrary number of properties

CompilerError Trail
-----------

[ ] CompilerError given opportunity to pick up source or other information at each use

Round 5: Modules
================

Round 7: System Calls
=====================

Round 8: I/O
============

Round 8: Editing Experience
===========================

Round 9: Packaging / Dependencies
=================================

Round 10: Website
=================

Round 11: 0.1 Release
=====================

Space
-----

[ ] Parse CompilerError: Line Too Long (4K characters)
[ ] Single-Line Comment
[ ] Errors: Invalid UTF-8, Comment Too Long. Denormalized OK. Unsupported Characters OK.

Visual Studio Code Extension
----------------------------

[ ] Syntax highlighting
[ ] CompilerError reporting

Command Line
------------

[ ] Display error context
[ ] Display context with possible fixes

Fields
------

[ ] Field Definition (=)
[ ] Field Modification (+=, ++, etc.)
[X] Field Declaration
[X] "Missing" StackValue
[ ] Parse CompilerError: Identifier Too Large
[X] Parse CompilerError: Identifier Starts With Number
[ ] Parse CompilerError: Identifier Must Be Immediately After ":"
[X] Parse CompilerError: Identifier Required In Declaration
[ ] Object Extend On ";" and "\n" (combine / overwrite properties)

Field Reference
------------------

[X] Field Reference (Identifier)
[ ] "nothing"
[ ] Object.GetField(Identifier) -> Object
[ ] CompilerError: Field not declared
[ ] CompilerError: Field not declared - check for misspelled, give suggestion
[ ] Out Of Order Declaration ("[:]A: B; :B: 2")
[ ] Parse CompilerError: Missing : in front of declaration

Field Assignment
-------------------

[ ] Field Assignment (=)
[ ] Parse CompilerError: Missing Operand

Apply
-----

[ ] Apply Operator (Extend With BlockRef) "F <+ A: 1" or "F <+ { A: 1; B: 2 }"
[ ] Because of multiple reasons! Figure out error dedup strategies here ...

Functions
=========

List
------

[ ] List Operator (,)
[ ] Trailing Comma Acceptable

Function Calls
--------------

[ ] APPLY Operator Overload: ("APPLY :: { :Arguments, ... }")
[ ] Function APPLY: "F Arguments"
[ ] Function Declaration Syntax: ":F(:A,:B,:C)"
[ ] Inline Function Declaration Syntax

Indented Function Calls
-----------------------

[ ] Child BlockRef Function Arguments
[ ] Parse CompilerError: Inconsistent Indent Characters (space vs. tab)
[ ] Parse CompilerError: Multiple Undent

Conditionals
============

Booleans
--------

[ ] "true", "false"
[ ] StackValue::True, StackValue::False
[ ] CompilerError: Appropriate Operator Errors

If/Else
-------

Comparison Operators
--------------------

Boolean Operators
-----------------

Structure
=========

Child Objects
-------------

[ ] Object Operator "{", "}"
[ ] Parse CompilerError: Unclosed Curly Brace
[ ] Parse CompilerError: Unopened Curly Brace

[ ] Empty "{}" -> Nothing

Child Access
------------

[ ] Field Access (Dot) Operator
[ ] Parse CompilerError: Identifier Required For Field Access

[ ] Nested BlockRef Declarations

Includes
--------

COMPARISON
----------

[ ] Equal/Not Equal Operators

[ ] Greater Than/Less Than/Greater Than Or Equal To/Less Than Or Equal To Operators

[ ] Comparison Operator ("<=>")

BOOLEAN
-------

[ ] And/Or/Not Operators

CONDITIONAL
-----------

[ ] If: if X Y else Z

[ ] Else: if X Y else Z

CONTEXT
-------

[ ] ::FileContext - file level input properties

STRING
------

[ ] Raw String
[ ] Parse CompilerError: Unclosed String
[ ] Parse CompilerError: Invalid UTF-8 In String

[ ] Hex Byte
[ ] Parse CompilerError: Invalid UTF-8 Across Escape Sequence And String (probably same error)

[ ] Hex Byte Sequence

[ ] String Escapes

INTERPOLATED STRING
-------------------

[ ] Interpolation
[ ] Unclosed Interpolation CompilerError

UNICODE IDENTIFIERS
-------------------

[ ] Unicode Identifiers (XID)

[ ] Incomplete Grapheme CompilerError

[ ] Denormalized Identifier CompilerError

UNICODE STRING ESCAPES
----------------------

[ ] Unicode Escape Character
[ ] Unicode Escape Sequence
[ ] Unicode Character Name

FUNCTION
--------

[ ] Function APPLY Apply "Operator"

FLOW
----

[ ]

EXPLICIT FLOW
-------------

[ ] Statement Sequence Extend "Operator"

[ ] Curly Brace Operator
[ ] Better Unclosed Parenthesis CompilerError
[ ] Better Unclosed Paren CompilerError

ARRAYS
------

[ ] Index Operator
[ ]

HASHES
------

[ ] Pair Operator

HEX/OCT/BIN
-----------

[ ] Hexadecimal Number
[ ] Octal Number
[ ] Binary Number
[ ] Parse CompilerError: Number Starts With Zero
[ ] Parse CompilerError: Hexadecimal With Uppercase X
[ ] Parse CompilerError: Octal With Uppercase O
[ ] Parse CompilerError: Binary With Uppercase B

FLOAT
-----

[ ] Decimal Point Operator

[ ] Exponent Operator
[ ] Exponent Sign Operator
[ ] Missing Exponent CompilerError

IMAGINARY
---------

[ ] Imaginary Operator
[ ] Imaginary With Uppercase I CompilerError


text:
package cmput301w15t07.TravelTracker.model;

import java.util.UUID;

import cmput301w15t07.TravelTracker.serverinterface.Constants.Type;

/**
 * Model object for Claim Tags for Claimant use.
 *
 * @author kdbanman,
 *         therabidsquirel
 *
 */
public class Tag extends Document {
    private UUID user;
    private String title;

    /**
     * Package protected constructor, intended for use only by DataSource.
     *
     * @param docID UUID document identifier
     */
    Tag(UUID docID, UUID userID) {
        super(docID);
        setType(Type.TAG);

        user = userID;
        title = "";
    }

    /**
     * Private no-args constructor for GSON.
     */
    @SuppressWarnings("unused")
    private Tag() {
        this(UUID.randomUUID(), null);
    }

    /**
     * Get the user to which this belongs.
     * @return The user's UUID.
     */
    public UUID getUser() {
        return this.user;
    }

    /**
     * Set the user to which this belongs.
     * @param user The user's UUID.
     */
    public void setUser(UUID user) {
        this.user = user;
        this.<Tag>hasChanged(this);
    }

    /**
     * Get the tag's title.
     * @return The title.
     */
    public String getTitle() {
        return title;
    }

    /**
     * Set the tag's title.
     * @param title The title.
     */
    public void setTitle(String title) {
        this.title = title;
        this.<Tag>hasChanged(this);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = super.hashCode();
        result = prime * result + ((title == null) ? 0 : title.hashCode());
        result = prime * result + ((user == null) ? 0 : user.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (!super.equals(obj))
            return false;
        if (!(obj instanceof Tag))
            return false;
        Tag other = (Tag) obj;
        if (title == null) {
            if (other.title != null)
                return false;
        } else if (!title.equals(other.title))
            return false;
        if (user == null) {
            if (other.user != null)
                return false;
        } else if (!user.equals(other.user))
            return false;
        return true;
    }

    @Override
    protected boolean mergeFrom(Document sourceDoc) {
        if (!(sourceDoc instanceof Tag))
            return false;
        Tag sourceItem = (Tag) sourceDoc;
        boolean changed = false;

        if (this.title != null) {
            if (!this.title.equals(sourceItem.title)) {
                changed |= true;
                this.title = sourceItem.title;
            }
        } else {
            // attribute is null, if source is not null then set it
            if (!(sourceItem.title == null)) {
                changed |= true;
                this.title = sourceItem.title;
            }
        }

        if (this.user != null) {
            if (!this.user.equals(sourceItem.user)) {
                changed |= true;
                this.user = sourceItem.user;
            }
        } else {
            // attribute is null, if source is not null then set it
            if (!(sourceItem.user == null)) {
                changed |= true;
                this.user = sourceItem.user;
            }
        }

        return changed;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.jivesoftware.openfire.handler;

import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.RoutingTable;
import org.jivesoftware.openfire.SessionManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.AuthToken;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.event.SessionEventDispatcher;
import org.jivesoftware.openfire.session.ClientSession;
import org.jivesoftware.openfire.session.LocalClientSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.StreamError;

/**
 * Binds a resource to the stream so that the client's address becomes a full JID. Once a resource
 * has been binded to the session the entity (i.e. client) is considered a "connected resource".
 *

 * Clients may specify a desired resource but if none was specified then the server will create
 * a random resource for the session. The new resource should be in accordance with ResourcePrep.
 * The server will also verify if there are previous sessions from the same user that are already
 * using the resource specified by the user. Depending on the server configuration the old session
 * may be kicked or the new session may be rejected.

 *
 * @author Gaston Dombiak
 */
public class IQBindHandler extends IQHandler {

    private static final Logger Log = LoggerFactory.getLogger(IQBindHandler.class);

    private IQHandlerInfo info;
    private String serverName;
    private RoutingTable routingTable;

    public IQBindHandler() {
        super("Resource Binding handler");
        info = new IQHandlerInfo("bind", "urn:ietf:params:xml:ns:xmpp-bind");
    }

    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        LocalClientSession session = (LocalClientSession) sessionManager.getSession(packet.getFrom());
        // If no session was found then answer an error (if possible)
        if (session == null) {
            Log.error("Error during resource binding. Session not found in " +
                    sessionManager.getPreAuthenticatedKeys() +
                    " for key " +
                    packet.getFrom());
            // This error packet will probably won't make it through
            IQ reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.internal_server_error);
            return reply;
        }

        IQ reply = IQ.createResultIQ(packet);
        reply.setFrom((String)null); // OF-2001: IQ bind requests are made from entities that have no resource yet. Responding with a 'from' value confuses many clients.
        Element child = reply.setChildElement("bind", "urn:ietf:params:xml:ns:xmpp-bind");
        // Check if the client specified a desired resource
        String resource = packet.getChildElement().elementTextTrim("resource");
        if (resource == null || resource.length() == 0) {
            // None was defined so use the random generated resource
            resource = session.getAddress().getResource();
        }
        else {
            // Check that the desired resource is valid
            try {
                resource = JID.resourceprep(resource);
            }
            catch (IllegalArgumentException e) {
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(PacketError.Condition.jid_malformed);
                // Send the error directly since a route does not exist at this point.
                session.process(reply);
                return null;
            }
        }
        // Get the token that was generated during the SASL authentication
        AuthToken authToken = session.getAuthToken();
        if (authToken == null) {
            // User must be authenticated before binding a resource
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.not_authorized);
            // Send the error directly since a route does not exist at this point.
            session.process(reply);
            return reply;
        }
        if (authToken.isAnonymous()) {
            // User used ANONYMOUS SASL so initialize the session as an anonymous login
            session.setAnonymousAuth();
        }
        else {
            String username = authToken.getUsername().toLowerCase();
            // If a session already exists with the requested JID, then check to see
            // if we should kick it off or refuse the new connection
            ClientSession oldSession = routingTable.getClientRoute(new JID(username, serverName, resource, true));
            if (oldSession != null) {
                try {
                    int conflictLimit = sessionManager.getConflictKickLimit();
                    if (conflictLimit == SessionManager.NEVER_KICK) {
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.conflict);
                        // Send the error directly since a route does not exist at this point.
                        session.process(reply);
                        return null;
                    }

                    int conflictCount = oldSession.incrementConflictCount();
                    if (conflictCount > conflictLimit) {
                        Log.debug( "Kick out an old connection that is conflicting with a new one. Old session: {}", oldSession );
                        StreamError error = new StreamError(StreamError.Condition.conflict);
                        oldSession.deliverRawText(error.toXML());
                        oldSession.close();

                        // OF-1923: As the session is now replaced, the old session will never be resumed.
                        // TODO remove detached session if it lives on a remote cluster node. Not doing this should not have functional consequences (but could lead to these warnings in the logs: "Not removing detached session 'foo@example.org/bar' that appears to have been replaced by another session.")
                        if ( oldSession instanceof LocalClientSession ) {
                            // As the new session has already replaced the old session, we're not explicitly closing
                            // the old session again, as that would cause the state of the new session to be affected.
                            sessionManager.removeDetached((LocalClientSession) oldSession);
                        }
                    }
                    else {
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.conflict);
                        // Send the error directly since a route does not exist at this point.
                        session.process(reply);
                        return null;
                    }
                }
                catch (Exception e) {
                    Log.error("Error during login", e);
                }
            }
            // If the connection was not refused due to conflict, log the user in
            session.setAuthToken(authToken, resource);
        }

        child.addElement("jid").setText(session.getAddress().toString());
        // Send the response directly since a route does not exist at this point.
        session.process(reply);
        // After the client has been informed, inform all listeners as well.
        SessionEventDispatcher.dispatchEvent(session, SessionEventDispatcher.EventType.resource_bound);
        return null;
    }

    @Override
    public void initialize(XMPPServer server) {
        super.initialize(server);
        routingTable = server.getRoutingTable();
        serverName = server.getServerInfo().getXMPPDomain();
     }

    @Override
    public IQHandlerInfo getInfo() {
        return info;
    }
}


text:
package org.cloudfoundry.reactor.routing.v1.tcproutes;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultHttpContent;

import java.nio.charset.Charset;

final class EventStreamDecoderChannelHandler extends ChannelInboundHandlerAdapter {

    static final String DELIMITER = "DELIMITER";

    private static final char[] COLON = new char[]{':', ' '};

    private static final char[] CRLF = new char[]{'\r', '\n'};

    private static final Charset UTF8 = Charset.forName("UTF-8");

    private String characters;

    private int colonPosition;

    private int crlfPosition;

    private ServerSentEvent.Builder event;

    private int nameEndPosition;

    private int nameStartPosition;

    private int position;

    private Stage stage;

    private int valueEndPosition;

    private int valueStartPosition;

    EventStreamDecoderChannelHandler() {
        reset();
    }

    @Override
    public void channelRead(ChannelHandlerContext context, Object message) throws Exception {
        if (!(message instanceof DefaultHttpContent)) {
            super.channelRead(context, message);
            return;
        }

        ByteBuf byteBuf = ((DefaultHttpContent) message).content();
        this.characters = this.characters != null ? this.characters + byteBuf.toString(UTF8) : byteBuf.toString(UTF8);
        byteBuf.release();

        while (this.position < this.characters.length()) {
            char c = this.characters.charAt(this.position);

            switch (this.stage) {
                case COLON:
                    colon(c);
                    break;
                case COMMENT:
                    comment(c);
                    break;
                case CRLF:
                    crlf(context, c);
                    break;
                case NAME:
                    name(c);
                    break;
                case VALUE:
                    value(c);
                    break;
            }
        }

        if (Stage.CRLF == this.stage) {
            crlf(context, '\0');
        }

        if (Stage.NAME == this.stage) {
            reset();
        }
    }

    private void colon(char c) {
        if (this.colonPosition < COLON.length) {
            if (COLON[this.colonPosition] == c) {
                this.colonPosition++;
                this.position++;
            } else {
                this.valueStartPosition = this.position;
                this.stage = Stage.VALUE;
                this.position++;
            }
        } else {
            this.valueStartPosition = this.position;
            this.stage = Stage.VALUE;
            this.position++;
        }
    }

    private void comment(char c) {
        if (CRLF[0] == c) {
            this.nameStartPosition = this.position;
            this.nameEndPosition = this.position;
            this.valueStartPosition = this.position;
            this.valueEndPosition = this.position;
            this.stage = Stage.CRLF;
            this.crlfPosition = 1;
            this.position++;
        } else if (CRLF[1] == c) {
            this.nameStartPosition = this.position;
            this.nameEndPosition = this.position;
            this.valueStartPosition = this.position;
            this.valueEndPosition = this.position;
            this.stage = Stage.CRLF;
            this.crlfPosition = 2;
            this.position++;
        } else {
            this.position++;
        }
    }

    private void crlf(ChannelHandlerContext context, char c) {
        if (this.crlfPosition < CRLF.length) {
            if (CRLF[this.crlfPosition] == c) {
                this.crlfPosition++;
                this.position++;
            } else {
                send(context);
            }
        } else {
            send(context);
        }
    }

    private void name(char c) {
        if (this.nameStartPosition == this.position) {
            if (COLON[0] == c) {
                this.stage = Stage.COMMENT;
                this.position++;
            } else if (CRLF[0] == c) {
                this.nameEndPosition = this.position;
                this.valueStartPosition = this.position;
                this.valueEndPosition = this.position;
                this.stage = Stage.CRLF;
                this.crlfPosition = 1;
                this.position++;
            } else if (CRLF[1] == c) {
                this.nameEndPosition = this.position;
                this.valueStartPosition = this.position;
                this.valueEndPosition = this.position;
                this.stage = Stage.CRLF;
                this.crlfPosition = 2;
                this.position++;
            } else {
                this.position++;
            }
        } else if (COLON[0] == c) {
            this.nameEndPosition = this.position;
            this.stage = Stage.COLON;
            this.colonPosition = 1;
            this.position++;
        } else if (CRLF[0] == c) {
            this.nameEndPosition = this.position;
            this.valueStartPosition = this.position;
            this.valueEndPosition = this.position;
            this.stage = Stage.CRLF;
            this.crlfPosition = 1;
            this.position++;
        } else if (CRLF[1] == c) {
            this.nameEndPosition = this.position;
            this.valueStartPosition = this.position;
            this.valueEndPosition = this.position;
            this.stage = Stage.CRLF;
            this.crlfPosition = 2;
            this.position++;
        } else {
            this.position++;
        }
    }

    private void reset() {
        this.characters = null;
        this.event = null;
        this.position = 0;
        this.nameStartPosition = 0;
        this.valueEndPosition = 0;
        this.stage = Stage.NAME;
    }

    private void send(ChannelHandlerContext context) {
        if (this.nameStartPosition == this.valueEndPosition) {
            if (this.event != null) {
                context.fireChannelRead(this.event.build());
                this.event = null;
            }
        } else {
            String name = this.characters.substring(this.nameStartPosition, this.nameEndPosition);
            String value = this.characters.substring(this.valueStartPosition, this.valueEndPosition);

            if ("id".equals(name)) {
                this.event = this.event != null ? this.event.id(value) : ServerSentEvent.builder().id(value);
            } else if ("event".equals(name)) {
                this.event = this.event != null ? this.event.eventType(value) : ServerSentEvent.builder().eventType(value);
            } else if ("data".equals(name)) {
                if (this.event != null) {
                    ServerSentEvent event = this.event.build();
                    String data = event.getData() == null ? value : String.format("%s\n%s", event.getData(), value);

                    this.event = ServerSentEvent.builder()
                        .id(event.getId())
                        .eventType(event.getEventType())
                        .data(data)
                        .retry(event.getRetry());
                } else {
                    this.event = ServerSentEvent.builder().data(value);
                }
            } else if ("retry".equals(name)) {
                this.event = this.event != null ? this.event.retry(Integer.parseInt(value)) : ServerSentEvent.builder().retry(Integer.parseInt(value));
            }
        }

        this.nameStartPosition = this.position;
        this.valueEndPosition = this.position;
        this.stage = Stage.NAME;
    }

    private void value(char c) {
        if (CRLF[0] == c) {
            this.valueEndPosition = this.position;
            this.stage = Stage.CRLF;
            this.crlfPosition = 1;
            this.position++;
        } else if (CRLF[1] == c) {
            this.valueEndPosition = this.position;
            this.stage = Stage.CRLF;
            this.crlfPosition = 2;
            this.position++;
        } else {
            this.position++;
        }
    }

    private enum Stage {

        COLON,

        COMMENT,

        CRLF,

        NAME,

        VALUE

    }

}


text:
import $ from 'jquery';

export function main() {
  var prtSchSelect = $j('#print-school');
  var prtSchString = '~(studentname)
~';
  prtSchSelect.prepend(prtSchString);

  var eppDisabledPref = '~[displaypref:eppdisabledl~(curschoolid)]';
  if (eppDisabledPref === '1') {
    var downloadSelect = $j('[href="studentdata.xml?ac=download"]');
    downloadSelect.remove();
  }

  $j('#legal').append('Enhanced Parent Portal Customization by PDS.');
  var pageVersion = 'Unknown/Stock';
  if ($j('#activePageVersion').length !== 0) {
    pageVersion = $j('#activePageVersion').val();
  }
  $j('#PDS-EPP-details').append('Current Page Version: ' + pageVersion);
  $j('#spanEPPVersion').click(function() {
    $j('#PDS-EPP-details').show().dialog({
      title: 'EPP Version Details',
      width: 450
    });
  });

  // Add EPP links
  var lastNavLi = $j('#nav-main li').last();
  var eppTemplate = $j($j('#epp-template').html());
  eppTemplate.insertAfter(lastNavLi);

  // Remove PowerSchool Information Link, which is replaced with EPP School Information link
  $j('a:contains("School Information")').eq(0).remove();

  // Remove stock PowerSchool nav-main navigation links if preference is set to disable those links.
  if (!psData.showGradesAttendance) {
    $j('#nav-main li:contains("Grades and Attendance")').remove();
  }
  if (!psData.showHistoricalGrades) {
    $j('#nav-main li:contains("Grade History")').remove();
  }
  if (!psData.showAttendance) {
    $j('#nav-main li:contains("Attendance History")').remove();
  }
  if (!psData.showEmail) {
    $j('#nav-main li:contains("Email Notification")').remove();
  }
  if (!psData.showComments) {
    $j('#nav-main li:contains("Teacher Comments")').remove();
  }
  if (!psData.showBulletin) {
    $j('#nav-main li:contains("School Bulletin")').remove();
  }
  if (!psData.showSchedule) {
    $j('#nav-main li:contains("Class Registration")').remove();
  }
  if (!psData.showBalance) {
    $j('#nav-main li:contains("Balance")').remove();
  }
  if (!psData.showCalendars) {
    $j('#nav-main li:contains("My Calendars")').remove();
  }

  // Set correct selected class
  if (window.location.pathname.indexOf('accesslog') !== -1) {
    $j('#nav-main li:contains("Access Logs")').attr('class', 'selected');
  } else if (window.location.pathname.indexOf('parentdemographics') !== -1) {
    $j('#nav-main li:contains("Demographic Change")').attr('class', 'selected');
  } else if (window.location.pathname.indexOf('discipline') !== -1) {
    $j('#nav-main li:contains("Discipline")').attr('class', 'selected');
  } else if (window.location.pathname.indexOf('graduation') !== -1) {
    $j('#nav-main li:contains("Graduation Progress")').attr('class', 'selected');
  } else if (window.location.pathname.indexOf('honorroll') !== -1) {
    $j('#nav-main li:contains("Honor Roll")').attr('class', 'selected');
  } else if (window.location.pathname.indexOf('studentsched') !== -1) {
    $j('#nav-main li:contains("My Schedule")').attr('class', 'selected');
  } else if (window.location.pathname.indexOf('schoolinfo') !== -1) {
    $j('#nav-main li:contains("School Information")').attr('class', 'selected');
  } else if (window.location.pathname.indexOf('testscore') !== -1) {
    $j('#nav-main li:contains("Test Scores")').attr('class', 'selected');
  }
}


text:
'use strict';

const BbPromise = require('bluebird');

module.exports = () => (BbPromise.resolve({
    sessionAttributes: {},
    cardTitle: "Session Ended",
    speechOutput:
        `Thank you for using the Alexa chaos monkey, Have a nice day and enjoy reinvent!`,
    repromptText: "",
    shouldEndSession: true
}));


text:
<!DOCTYPE html>
<html>
  {% include head.html %}
  <body id="page-top" data-spy="scroll" data-target=".navbar-custom">
    {% include navbar.html %}
    {{ content }}
    {% include footer.html %}
  </body>
</html>


text:
using System;

namespace Sce.Sled.Shared.Plugin
{
    ///
    /// This attribute must be placed on SLED network plugins
    /// if they are to be loaded by SLED.
    /// Add the attribute to the AssemblyInfo file as:
    /// [assembly: Sce.Sled.Shared.Plugin.SledNetworkPlugin]
    /// or
    /// [assembly: Sce.Sled.Shared.Plugin.SledNetworkPlugin(user data string)]
    /// <remarks>Copy/paste of ATF's ATFPluginAttribute.cs</remarks>
    ///
    [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
    public class SledNetworkPluginAttribute : Attribute
    {
        ///
        /// Constructor
        ///
        public SledNetworkPluginAttribute()
        {
        }

        ///
        /// Constructor with user data
        ///
        /// <param name="userData">Optional user data to pass in</param>
        public SledNetworkPluginAttribute(string userData)
        {
            Info = userData;
        }

        ///
        /// Get the user data string
        ///
        public string Info { get; private set; }
    }
}


text:
namespace chromeos {

InputEventsBlocker::InputEventsBlocker() {
  ash::Shell::GetInstance()->PrependPreTargetHandler(this);
  VLOG(1) << "InputEventsBlocker " << this << " created.";
}

InputEventsBlocker::~InputEventsBlocker() {
  ash::Shell::GetInstance()->RemovePreTargetHandler(this);
  VLOG(1) << "InputEventsBlocker " << this << " destroyed.";
}

void InputEventsBlocker::OnKeyEvent(ui::KeyEvent* event) {
  event->StopPropagation();
}

void InputEventsBlocker::OnMouseEvent(ui::MouseEvent* event) {
  event->StopPropagation();
}

void InputEventsBlocker::OnTouchEvent(ui::TouchEvent* event) {
  event->StopPropagation();
}

void InputEventsBlocker::OnGestureEvent(ui::GestureEvent* event) {
  event->StopPropagation();
}

}  // namespace chromeos


text:
package binauld.pierre.resume.modules;

import android.app.Fragment;
import android.content.Context;
import android.content.res.Configuration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

import javax.inject.Singleton;

import binauld.pierre.resume.adapters.SkillAdapter;
import binauld.pierre.resume.fragments.SkillFragment;
import binauld.pierre.resume.model.Account;
import binauld.pierre.resume.view.AdapterSpanSizeLookup;
import dagger.Module;
import dagger.Provides;

@Module(
        injects = {
                SkillFragment.class
        },
        complete = false,
        library = true,
        addsTo = ApplicationModule.class
)
public class SkillFragmentModule {

    private Context context;

    public SkillFragmentModule(Fragment fragment) {
        this.context = fragment.getActivity();
    }

    @Provides
    @Singleton
    public RecyclerView.Adapter provideAdapter(Account account) {
        SkillAdapter adapter = new SkillAdapter(
                context,
                account.getSkillCategories()
        );
        return adapter;
    }

    @Provides @Singleton
    public RecyclerView.LayoutManager provideLayoutManager(Account account, RecyclerView.Adapter adapter) {
        int screenSize = context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
        int orientation = context.getResources().getConfiguration().orientation;

        int spanCount;

        if ((screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE || screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE) &&
                orientation == Configuration.ORIENTATION_LANDSCAPE) {
            spanCount = 3;
        } else {
            spanCount = 2;
        }

        AdapterSpanSizeLookup spanSizeLookup = new AdapterSpanSizeLookup(adapter);
        spanSizeLookup.putSpanSize(SkillAdapter.HEADER_VIEW_TYPE, spanCount);
        spanSizeLookup.putSpanSize(SkillAdapter.SKILL_VIEW_TYPE, 1);

        GridLayoutManager layoutManager = new GridLayoutManager(context, spanCount);
        layoutManager.setSpanSizeLookup(spanSizeLookup);
        return layoutManager;
    }
}


text:
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');

var config = require('./webpack.base.config.js');

config.output.path = require('path').resolve('./feelings/assets/dist')

config.plugins = config.plugins.concat([
    new BundleTracker({filename: './feelings/webpack-stats-prod.json'}),

    new webpack.DefinePlugin({
        'process.env': {
            'NODE_ENV': JSON.stringify('production')
        }
    }),

    new webpack.optimize.OccurrenceOrderPlugin(),

    new webpack.optimize.UglifyJsPlugin({
        compressor: {
            warnings: false
        }
    })
])

module.exports = config


text:
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}

module Language.K3.Codegen.CPP.Expression where

import Prelude hiding (any, concat)
import Control.Arrow ((&&&), (***), (>>>))
import Control.Monad.State

import Data.Foldable
import Data.List (nub, sortBy, (\\))
import Data.Maybe
import Data.Ord (comparing)
import Data.Tree
import Data.Traversable

import qualified Data.Map as M
import qualified Data.Set as S

import Language.K3.Core.Annotation
import Language.K3.Core.Common
import Language.K3.Core.Expression
import Language.K3.Core.Literal
import Language.K3.Core.Type
import Language.K3.Core.Utils

import Language.K3.Codegen.Common
import Language.K3.Codegen.CPP.Materialization.Common
import Language.K3.Codegen.CPP.Materialization.Hints
import Language.K3.Codegen.CPP.Preprocessing
import Language.K3.Codegen.CPP.Primitives
import Language.K3.Codegen.CPP.Types

import qualified Language.K3.Codegen.CPP.Representation as R

import Language.K3.Analysis.Core
import qualified Language.K3.Analysis.CArgs as CArgs

-- | The reification context passed to an expression determines how the result of that expression
-- will be stored in the generated code.
--
-- TODO: Add RAssign/RDeclare distinction.
data RContext

    -- | Indicates that the calling context will ignore the callee's result.
    = RForget

    -- | Indicates that the calling context is a C++ function, in which case the result may be
    -- 'returned' from the callee. A true payload indicates that the return value needs to be
    -- manually move wrapped
    | RReturn { byMove :: Bool }

    -- | Indicates that the calling context requires the callee's result to be stored in a variable
    -- of a pre-specified name.
    | RName { targetN :: R.Expression, maybeByMove :: Maybe Bool}
    | RDecl { targetD :: Identifier, maybeByMove :: Maybe Bool}

    -- | A free-form reification context, for special cases.
    | RSplice ([CPPGenR] -> CPPGenR)

instance Show RContext where
    show RForget = "RForget"
    show (RReturn b) = "RReturn " ++ show b
    show (RName i b) = "RName \"" ++ (show i) ++ "\"" ++ " " ++ show b
    show (RDecl i b) = "RDecl \"" ++ (show i) ++ "\"" ++ " " ++ show b
    show (RSplice _) = "RSplice <opaque>"

-- Helper to default to forwarding when declaration pushdown is impossible.
precludeRDecl i b x = do
  xt <- getKType x
  fd <- cDecl xt i
  x' <- reify (RName (R.Variable $ R.Name i) b) x
  return (fd ++ x')

-- | Template Patterns
-- TODO: Check for transformer property.
pattern Fold c <- Node (EProject "fold" :@: _) [c]
pattern InsertWith c <- Node (EProject "insert_with" :@: _) [c]
pattern UpsertWith c <- Node (EProject "upsert_with" :@: _) [c]
pattern Lookup c <- Node (EProject "lookup" :@: _) [c]
pattern Peek c <- Node (EProject "peek" :@: _) [c]
pattern SafeAt c <- Node (EProject "safe_at" :@: _) [c]
pattern UnsafeAt c <- Node (EProject "unsafe_at" :@: _) [c]

pattern (:$:) f x <- Node (EOperate OApp :@: _) [f, x]

dataspaceIn :: K3 Expression -> [Identifier] -> Bool
dataspaceIn e as = isJust $ getKTypeP e >>= \t -> t @~ \case { TAnnotation i -> i `elem` as; _ -> False }

precludeInline :: K3 Expression -> Bool
precludeInline e = isJust $ e @~ \case { (EProperty s) -> ePropertyName s == "NoInline"; _ -> False}

stlLinearDSs :: [Identifier]
stlLinearDSs = ["Collection", "Set", "Vector", "Seq"]

stlAssocDSs :: [Identifier]
stlAssocDSs = ["Map"]

hasMoveProperty :: Annotation Expression -> Bool
hasMoveProperty ae = case ae of
                       (EProperty s) -> ePropertyName s == "Move"
                       _ -> False

forceMoveP :: K3 Expression -> Bool
forceMoveP e = isJust (e @~ hasMoveProperty)

deepHasFusionSource :: K3 Expression -> Bool
deepHasFusionSource f = f @:? "FusionSource" || case f of { f' :$: _ -> deepHasFusionSource f'; _ -> False }

hasBoxableProperty :: Annotation Expression -> Bool
hasBoxableProperty ae = case ae of
                       (EProperty s) -> ePropertyName s == "Boxable"
                       _ -> False

ifIsolateApplicationProp :: K3 Expression -> Bool
ifIsolateApplicationProp e = isJust $ e @~ \case { EProperty s -> ePropertyName s == "IsolateApplication"; _ -> False}

-- Get the materializaitons of a given expression
getMDecisions :: K3 Expression -> M.Map (Identifier, Direction) Method
getMDecisions e = case e @~ isEMaterialization of
                   Just (EMaterialization ms) -> ms
                   Nothing -> M.empty

getInDecisions :: K3 Expression -> M.Map Identifier Method
getInDecisions e = M.fromList [(i, m) | ((i, r), m) <- M.toList (getMDecisions e), r == In]

getExDecisions :: K3 Expression -> M.Map Identifier Method
getExDecisions e = M.fromList [(i, m) | ((i, r), m) <- M.toList (getMDecisions e), r == Ex]

getMethodFor :: Identifier -> Direction -> K3 Expression -> Method
getMethodFor i d e = M.findWithDefault defaultMethod (i, d) (getMDecisions e)

getInMethodFor :: Identifier -> K3 Expression -> Method
getInMethodFor i e = getMethodFor i In e

getExMethodFor :: Identifier -> K3 Expression -> Method
getExMethodFor i e = getMethodFor i Ex e

-- Heuristics
needsMoveCast :: K3 Type -> R.Expression -> Bool
needsMoveCast t e = isNonScalarType t && (not $ R.isMoveInferred e)

-- Move heuristic to avoid code clutter.
move :: K3 Type -> K3 Expression -> Bool
move t e = isNonScalarType t && moveByExprForm e
 where
  moveByExprForm :: K3 Expression -> Bool
  moveByExprForm e =
    case e of
      (tag -> EVariable _) -> True
      (tag -> EProject _) -> True
      (tag -> ELetIn _) -> True
      (tag -> EBindAs _) -> True
      (tag -> ECaseOf _) -> True
      (tag -> EIfThenElse) -> True
      _ -> False

gMoveByE :: K3 Expression -> R.Expression -> R.Expression
gMoveByE e x = fromMaybe x (getKTypeP e >>= \t -> return $ if move t e then R.Move x else x)

gMoveByDE :: Method -> K3 Expression -> R.Expression -> R.Expression
gMoveByDE m e x
  | m == Moved = gMoveByE e x
  | otherwise = x

forwardBy :: R.Expression -> R.Expression
forwardBy x = case x of
  R.Variable _ -> R.FMacro x
  R.Project x' f -> R.Project (forwardBy x') f
  _ -> x

passBy :: Method -> K3 Expression -> R.Expression -> R.Expression
passBy m e x = case m of
  Moved -> gMoveByE e x
  Forwarded -> forwardBy x
  _ -> x

-- | Realization of unary operators.
unarySymbol :: Operator -> CPPGenM Identifier
unarySymbol ONot = return "!"
unarySymbol ONeg = return "-"
unarySymbol u = throwE $ CPPGenE $ "Invalid Unary Operator " ++ show u

-- | Realization of binary operators.
binarySymbol :: Operator -> CPPGenM Identifier
binarySymbol OAdd = return "+"
binarySymbol OSub = return "-"
binarySymbol OMul = return "*"
binarySymbol ODiv = return "/"
binarySymbol OMod = return "%" -- TODO: type based selection of % vs fmod
binarySymbol OEqu = return "=="
binarySymbol ONeq = return "!="
binarySymbol OLth = return "<"
binarySymbol OLeq = return "<="
binarySymbol OGth = return ">"
binarySymbol OGeq = return ">="
binarySymbol OAnd = return "&&"
binarySymbol OOr = return "||"
binarySymbol OConcat = return "+"
binarySymbol b = throwE $ CPPGenE $ "Invalid Binary Operator " ++ show b

-- | Realization of constants.
constant :: Constant -> CPPGenM R.Literal
constant (CBool True) = return $ R.LBool True
constant (CBool False) = return $ R.LBool False
constant (CInt i) = return $ R.LInt i
constant (CReal d) = return $ R.LDouble d
constant (CString s) = return $ R.LString s
constant (CNone _) = return R.LNullptr
constant c = throwE $ CPPGenE $ "Invalid Constant Form " ++ show c

cDecl :: K3 Type -> Identifier -> CPPGenM [R.Statement]
cDecl t i = genCType t >>= \ct -> return [R.Forward $ R.ScalarDecl (R.Name i) ct Nothing]

inline :: K3 Expression -> CPPGenM ([R.Statement], R.Expression)
inline e = do
  isolateApplicationP <- gets (isolateApplicationCG . flags)
  isolateQueryP <- gets (isolateQueryCG . flags)
  boxRecordsP <- gets (boxRecords . flags)
  let doInlineP = True
  case e of
    (tag &&& annotations -> (EConstant (CEmpty t), as)) ->
      case annotationComboIdE as of
        Nothing -> throwE $ CPPGenE $ "No Viable Annotation Combination for Empty " ++ show e
        Just ac -> getKType e >>= genCType >> genCType t >>= \ct -> return ([], R.Initialization (R.Collection ac ct) [])
    (tag -> EConstant c) -> constant c >>= \c' -> return ([], R.Literal c')

    (tag -> EVariable v) -> do
      gEnv <- gets globals
      case lookup v gEnv of
        Just (tag -> TFunction, _) -> return ([], R.Project (R.Dereference $ R.Variable $ R.Name "this") (R.Name v))
        Just (tag -> TForall _, _) -> return ([], R.Project (R.Dereference $ R.Variable $ R.Name "this") (R.Name v))
        _ -> return ([], R.Variable (R.Name v))

    (tag &&& children -> (t', [c])) | t' == ESome || t' == EIndirect -> do
      (e, v) <- inline c
      ct <- getKType c
      t <- genCType ct
      return (e, R.Call (R.Variable $ R.Specialized [t] (R.Name "make_shared")) [v])

    (tag &&& children -> (ETuple, [])) -> return ([], R.Initialization R.Unit [])

    (tag &&& children -> (ETuple, cs)) -> do
      (es, vs) <- unzip <$> mapM inline cs
      return (concat es, R.Call (R.Variable $ R.Name "make_tuple") vs)

    (tag &&& children -> (ERecord is, cs)) -> do
      (es, vs) <- unzip <$> mapM inline cs
      let reifyConstructorField (i, c, v) = do
            let orderAgnosticP = R.isOrderAgnostic v
	    let moveArg = if c @:? "Move" then Moved else getInMethodFor i e
            if moveArg == Moved
              then do
                castMoveP <- needsMoveCast <$> (getKType c) <*> (pure v)
                let moveCastModifier = if castMoveP then R.Move else id

                if orderAgnosticP
                  then return ([], moveCastModifier v)
                  else do
                    g <- genSym
		    let h = if c @:? "Move" then R.Move else R.FMacro
                    return ( [R.Forward $ R.ScalarDecl (R.Name g) (R.RValueReference R.Inferred) (Just $ moveCastModifier v)]
                          , h $ R.Variable $ R.Name g
                          )
              else do
                if orderAgnosticP
                  then return ([], v)
                  else do
                    g <- genSym
                    return ( [R.Forward $ R.ScalarDecl (R.Name g) (R.RValueReference R.Inferred) (Just v)]
                          , R.FMacro $ R.Variable $ R.Name g
                          )

      (concat -> rs, vs') <- unzip <$> mapM reifyConstructorField (zip3 is cs vs)
      let vs'' = snd . unzip . sortBy (comparing fst) $ zip is vs'
      t <- getKType e
      case t of
          (tag &&& children -> (TRecord _, _)) -> do
              sig <- genCType t
              return (concat es ++ rs, R.Initialization sig vs'')
          _ -> throwE $ CPPGenE $ "Invalid Record Type " ++ show t

    (tag &&& children -> (EOperate uop, [c])) -> do
      (ce, cv) <- inline c
      usym <- unarySymbol uop
      return (ce, R.Unary usym cv)

    (tag &&& children -> (EOperate OSeq, [a, b])) -> do
      ae <- reify RForget a
      (be, bv) <- inline b
      return (ae ++ be, bv)

    e@(tag -> ELambda _) -> do
      resetApplyLevel
      -- let isAccumulating = (not isolateQueryP) && e @:? "ReturnsArgument"
      let isAccumulating = False

      let (unzip -> (argNames, fExprs), b) = rollLambdaChain e

      let formalArgNames = ["_A" ++ show i | i <- [0..] | _ <- argNames]

      -- TODO: Need return types, or allow inferral? Need it iff multiple branches return different
      -- but coercible types.
      -- formalArgTypes <- forM_ fExprs $ \f -> getKType f >>= \case
      --   (tag &&& children -> (TFunction, [ta, _])) -> return ta
      --   _ -> throwE $ CPPGenE "Invalid Function Form"

      returnType <- sequence $ fmap (genCType . last . children) (getKTypeP $ last fExprs)

      let getArg (tag -> ELambda i) = i
      let (outerFExpr, innerFExpr) = (head &&& last) fExprs
      let (outerArg, _) = (getArg outerFExpr, getArg innerFExpr)

      -- let nrvo = getExMethodFor anon innerFExpr == Moved

      body <- reify (if isAccumulating then RForget else RReturn False) b

      let captureByMtrlzn i m = case m of
            ConstReferenced -> R.RefCapture (Just (i, Nothing))
            Referenced -> R.RefCapture (Just (i, Nothing))
            Moved -> R.ValueCapture (Just (i, Just $ R.Move $ R.Variable $ R.Name i))
            Copied -> R.ValueCapture (Just (i, Nothing))

      let captures = [R.ThisCapture] ++
                    (M.elems $ M.mapWithKey captureByMtrlzn $ M.filterWithKey (\k _ -> k /= outerArg)
                              $ getInDecisions outerFExpr)

      let reifyArg a g = if a == "_" then [] else
            let discriminator = if a == head (argNames) && isAccumulating then Referenced else (getInMethodFor a innerFExpr)
                reifyType = case discriminator of
                    ConstReferenced -> R.Reference $ R.Const R.Inferred
                    Referenced -> R.Reference R.Inferred
                    Forwarded -> R.RValueReference R.Inferred
                    _ -> R.Inferred
                reifyFrom = case discriminator of
                    -- Copied -> id
                    _ -> R.SForward (R.ConstExpr $ R.Call (R.Variable $ R.Name "decltype") [R.Variable $ R.Name g])
            in [R.Forward $ R.ScalarDecl (R.Name a) reifyType
                (Just $ reifyFrom (R.Variable $ R.Name g))]

      let argReifications = concat [reifyArg a g | a <- argNames | g <- formalArgNames]

      let fullBody = argReifications ++ body

      let argList = [ (if fi == "_" then Nothing else Just ai, R.RValueReference R.Inferred)
                    | ai <- formalArgNames
                    | fi <- argNames
                    ]

      return ([], R.Lambda captures argList True (if isAccumulating then Just R.Void else returnType) fullBody)

    p@(Fold c) :$: f :$: z  | doInlineP -> do
      (ce, cv) <- inline c
      (ze, zv) <- inline z

      -- Accumulating Function
      fs <- genSym
      fe <- reify (RDecl fs Nothing) f

      -- Initial Accumulator
      accVar <- genSym
      let movedAcc = gMoveByDE (if forceMoveP e then Moved else getInMethodFor anonS e) z zv
      let accDecl = R.Forward $ R.ScalarDecl (R.Name accVar) R.Inferred (Just movedAcc)

      -- Index Variable
      eleVar <- genSym
      movedEle <- do
        (tag &&& children -> (TCollection, [t])) <- getKType c
        return $ if getInMethodFor anonS p == Moved && isNonScalarType t
                   then R.Move $ R.Variable $ R.Name eleVar
                   else R.Variable $ R.Name eleVar

      -- TODO: Inline Apply

      -- Core Loop
      -- TODO: Double Reify on Embedded Folds
      let loopBody = R.Assignment
                      (R.Variable $ R.Name accVar)
                      (R.Call
                       (R.Variable $ R.Name fs)
                       [ R.Move $ R.Variable $ R.Name accVar
                       , movedEle
                       ])
      let loop = R.ForEach eleVar (R.Reference R.Inferred) cv (R.Block [loopBody])

      -- Extra Reification for Query Isolation.
      (xe, xv) <- if isolateQueryP
                    then do
                     q <- genSym
                     return ([R.Forward $ R.ScalarDecl (R.Name q) R.Inferred (Just $ R.Variable $ R.Name accVar)], q)
                    else return ([], accVar)
      return (ze ++ [accDecl] ++ ce ++ fe ++ [loop] ++ xe, R.Move $ R.Variable $ R.Name xv)

    p@(InsertWith c) :$: k :$: w | c `dataspaceIn` stlAssocDSs && doInlineP -> do
      (ce, cv) <- inline c
      kn <- genSym
      ke <- reify (RDecl kn Nothing) k
      --(ke, kv) <- case k of
      --  (tag &&& children -> (ERecord fs, cs)) | not br -> do
      --    (unzip -> (fes, catMaybes -> [fv])) <- for (zip fs cs) $ \(f, j) ->
      --      if f == "key"
      --        then do
      --          (fe, fv) <- inline j
      --          return (fe, Just fv)
      --        else do
      --          fe <- reify RForget j
      --          return (fe, Nothing)
      --    return (concat fes, fv)
      --  _ -> inline k >>= \(ke', kv') -> return (ke', R.Project (if br then R.Dereference kv' else kv') (R.Name "key"))
      -- kg <- genSym
      -- ke <- reify (RDecl kg Nothing) k

      br <- gets (boxRecords . flags)

      kt <- getKType k >>= genCType
      rt <- getKType c >>= \(tag &&& children -> (TCollection, [rt])) -> genCType rt
      kp <- genSym
      let kpdecl = R.Forward $ R.ScalarDecl (R.Name kp) (R.Reference R.Inferred) (Just $ R.Project ((if br then R.Dereference else id) $ R.Variable $ R.Name kn) (R.Name "key"))

      ug <- genSym
      let ue = R.Forward $ R.ScalarDecl (R.Name ug) (R.Reference R.Inferred) (Just $  R.Call (R.Project cv (R.Name "getContainer")) [])
      let uv = R.Variable $ R.Name ug

      existing <- genSym
      let existingFind = R.Call (R.Project uv (R.Name "find")) [R.Variable $ R.Name kp]
      let existingDecl = R.Forward $ R.ScalarDecl (R.Name existing) R.Inferred (Just $ existingFind)
      let existingPred = R.Binary "=="
                          (R.Variable $ R.Name existing)
                          (R.Call (R.Variable $ R.Qualified (R.Name "std") (R.Name "end")) [uv])

      let nfe = [R.Assignment (R.Subscript uv (R.Variable $ R.Name kp)) (R.Move $ R.Variable $ R.Name kn)]
      (wfe, wfb) <- inlineApply (RName (R.Project (R.Dereference (R.Variable $ R.Name existing)) (R.Name "second")) (Just True)) w
                      [R.Move $ R.Project (R.Dereference (R.Variable $ R.Name existing)) (R.Name "second"), R.Variable $ R.Name kn]
                      [rt, kt]

      return (ce ++ [ue] ++ ke ++ [kpdecl] ++ [existingDecl] ++ [R.IfThenElse existingPred nfe (wfe ++ wfb)]
            , R.Initialization R.Unit [])

    p@(UpsertWith c) :$: k :$: n :$: w | c `dataspaceIn` stlAssocDSs && doInlineP -> do
      (ce, cv) <- inline c

      rt <- getKType c >>= \(tag &&& children -> (TCollection, [rt])) -> genCType rt

      kg <- genSym
      br <- gets (boxRecords . flags)
      (ke, kv) <- case k of
        (tag &&& children -> (ERecord fs, cs)) | not br -> do
          (unzip -> (fes, catMaybes -> [fv])) <- for (zip fs cs) $ \(f, j) ->
            if f == "key"
              then do
                (fe, fv) <- inline j
                return (fe, Just fv)
              else do
                fe <- reify RForget j
                return (fe, Nothing)
          return (concat fes, fv)
        _ -> inline k >>= \(ke', kv') -> return (ke', R.Project (if br then R.Dereference kv' else kv') (R.Name "key"))

      ug <- genSym
      let ue = R.Forward $ R.ScalarDecl (R.Name ug) (R.Reference R.Inferred) (Just $  R.Call (R.Project cv (R.Name "getContainer")) [])
      let uv = R.Variable $ R.Name ug

      existing <- genSym
      let existingFind = R.Call (R.Project uv (R.Name "find")) [kv]
      let existingDecl = R.Forward $ R.ScalarDecl (R.Name existing) R.Inferred (Just $ existingFind)
      let existingPred = R.Binary "=="
                          (R.Variable $ R.Name existing)
                          (R.Call (R.Variable $ R.Qualified (R.Name "std") (R.Name "end")) [uv])

      (nfe, nfb) <- inlineApply (RName (R.Subscript uv kv) (Just True)) n [R.Initialization R.Unit []] [R.Unit]

      --let rArg = isJust $ w @~ (\case { EProperty (ePropertyName -> "ReturnsArgument") -> True; _ -> False })
      let rArg = False
      let rContext = if rArg
                      then RForget
                      else RName (R.Project (R.Dereference (R.Variable $ R.Name existing)) (R.Name "second")) (Just True)

      (wfe, wfb) <- inlineApply rContext w
                      [(if rArg then id else R.Move) $ R.Project (R.Dereference (R.Variable $ R.Name existing)) (R.Name "second")]
                      [rt]

      return (ce ++ [ue] ++ ke ++ [existingDecl] ++ [R.IfThenElse existingPred (nfe ++ nfb) (wfe ++ wfb)]
            , R.Initialization R.Unit [])

    p@(UpsertWith c) :$: k :$: n :$: w | c `dataspaceIn` ["IntMap"] && doInlineP -> do
      (ce, cv) <- inline c
      (ke, kv) <- inline k

      recordType <- getKType k >>= genCType

      let keyField = if boxRecordsP then R.Project (R.Dereference kv) (R.Name "key") else R.Project kv (R.Name "key")

      mapi <- genSym
      let mapiDecl = R.Forward $ R.ScalarDecl (R.Name mapi) (R.Pointer R.Inferred)
                       (Just $ R.Call (R.Project cv (R.Name "get_mapi")) [])
      let sizeCheck = R.Binary "==" (R.Project (R.Dereference $ R.Variable $ R.Name mapi) (R.Name "size")) (R.Literal $ R.LInt 0)

      let insertionRecord = R.CCast (R.Pointer R.Void) (R.SCast (R.Const $ R.Pointer $ R.Void) (R.TakeReference kv))
      let insertCall = R.SCast (R.Pointer recordType)
                         (R.Call (R.Variable $ R.Name "mapi_insert") [R.Variable $ R.Name mapi, insertionRecord])

      placement <- genSym
      let placementDecl = R.Forward $ R.ScalarDecl (R.Name placement) (R.Pointer R.Inferred) (Just insertCall)

      (nfe, nfs) <- inlineApply (RName (R.Dereference $ R.Variable $ R.Name placement) (Just True)) n [R.Initialization R.Unit []]
                      [R.Unit]

      let missingBranch = [placementDecl] ++ nfe ++ nfe ++ nfs

      existing <- genSym
      let existingDecl = R.Forward $ R.ScalarDecl (R.Name existing) (R.Pointer R.Inferred)
                           (Just $ R.SCast (R.Pointer recordType)
                             (R.Call (R.Variable $ R.Name "mapi_find") [R.Variable $ R.Name mapi, keyField]))

      let existingCheck = R.Binary "==" (R.Variable $ R.Name existing) (R.Literal R.LNullptr)

      (wfe, wfs) <- inlineApply (RName (R.Dereference $ R.Variable $ R.Name existing) (Just True)) w
                                [R.Move (R.Dereference $ R.Variable $ R.Name existing)]
                                [recordType]

      let nonEmptyCase = R.IfThenElse existingCheck missingBranch (wfe ++ wfs)
      let nonEmptyBranch = [existingDecl, nonEmptyCase]
      let fullCase = R.IfThenElse sizeCheck missingBranch nonEmptyBranch

      return (ce ++ ke ++ [mapiDecl, fullCase], R.Initialization R.Unit [])

    p@(Lookup c) :$: k :$: n :$: w | c `dataspaceIn` stlAssocDSs && doInlineP -> do
      (ce, cv) <- inline c
      rt <- getKType c >>= \(tag &&& children -> (TCollection, [rt])) -> genCType rt
      kg <- genSym
      ke <- reify (RDecl kg Nothing) k
      br <- gets (boxRecords . flags)
      let kv = R.Project ((if br then R.Dereference else id) $ R.Variable $ R.Name kg) (R.Name "key")
      (ke, kv) <- case k of
        (tag &&& children -> (ERecord fs, cs)) | br -> do
          (unzip -> (fes, catMaybes -> [fv])) <- for (zip fs cs) $ \(f, j) ->
            if f == "key"
              then do
                (fe, fv) <- inline j
                return (fe, Just fv)
              else do
                fe <- reify RForget j
                return (fe, Nothing)
          return (concat fes, fv)
        _ -> inline k >>= \(ke', kv') -> return (ke', R.Project (if br then R.Dereference kv' else kv') (R.Name "key"))

      ug <- genSym
      let ue = R.Forward $ R.ScalarDecl (R.Name ug) (R.Reference R.Inferred) (Just $  R.Call (R.Project cv (R.Name "getContainer")) [])
      let uv = R.Variable $ R.Name ug

      existing <- genSym
      let existingFind = R.Call (R.Project uv (R.Name "find")) [kv]
      let existingDecl = R.Forward $ R.ScalarDecl (R.Name existing) R.Inferred (Just $ existingFind)
      let existingPred = R.Binary "=="
                          (R.Variable $ R.Name existing)
                          (R.Call (R.Variable $ R.Qualified (R.Name "std") (R.Name "end")) [uv])

      result <- genSym
      resultType <- getKType e >>= genCType
      let resultDecl = R.Forward $ R.ScalarDecl (R.Name result) resultType Nothing

      (nfe, nfb) <- inlineApply (RName (R.Variable $ R.Name result) Nothing) n [R.Initialization R.Unit []] [R.Unit]
      (wfe, wfb) <- inlineApply (RName (R.Variable $ R.Name result) Nothing) w
                      [R.Project (R.Dereference (R.Variable $ R.Name existing)) (R.Name "second")] [rt]

      return (ce ++ [ue] ++ ke ++ [resultDecl, existingDecl] ++ [R.IfThenElse existingPred (nfe ++ nfb) (wfe ++ wfb)]
            , R.Variable $ R.Name result)

    p@(Peek c) :$: n :$: w | c `dataspaceIn` stlLinearDSs && doInlineP -> do
      (ce, cv) <- inline c
      rt <- getKType c >>= \(tag &&& children -> (TCollection, [rt])) -> genCType rt

      ug <- genSym
      let ue = R.Forward $ R.ScalarDecl (R.Name ug) (R.Reference R.Inferred) (Just $  R.Call (R.Project cv (R.Name "getConstContainer")) [])
      let uv = R.Variable $ R.Name ug

      first <- genSym
      let firstCall = R.Call (R.Project uv (R.Name "begin")) []
      let firstDecl = R.Forward $ R.ScalarDecl (R.Name first) R.Inferred (Just $ firstCall)
      let firstPred = R.Binary "=="
                        (R.Variable $ R.Name first)
                        (R.Call (R.Variable $ R.Qualified (R.Name "std") (R.Name "end")) [uv])

      result <- genSym
      resultType <- getKType e >>= genCType
      let resultDecl = R.Forward $ R.ScalarDecl (R.Name result) resultType Nothing
      (nfe, nfb) <- inlineApply (RName (R.Variable $ R.Name result) Nothing) n [R.Initialization R.Unit []] [R.Unit]
      (wfe, wfb) <- inlineApply (RName (R.Variable $ R.Name result) Nothing) w [R.Dereference $ R.Variable $ R.Name first] [rt]

      return (ce ++ [ue] ++ [resultDecl, firstDecl] ++ [R.IfThenElse firstPred (nfe ++ nfb) (wfe ++ wfb)]
            , R.Variable $ R.Name result)

    p@(SafeAt c) :$: i :$: n :$: w | c `dataspaceIn` stlLinearDSs && doInlineP -> do
      (ce, cv) <- inline c
      rt <- getKType c >>= \(tag &&& children -> (TCollection, [rt])) -> genCType rt
      ig <- genSym
      ie <- reify (RDecl ig Nothing) i
      let iv = R.Variable $ R.Name ig

      ug <- genSym
      let ue = R.Forward $ R.ScalarDecl (R.Name ug) (R.Reference R.Inferred) (Just $  R.Call (R.Project cv (R.Name "getConstContainer")) [])
      let uv = R.Variable $ R.Name ug

      let sizeCheck = R.Binary "<" iv (R.Call (R.Project uv (R.Name "size")) [])

      iterator <- genSym
      let advance = [ R.Forward $ R.ScalarDecl (R.Name iterator) R.Inferred (Just $ (R.Call (R.Project uv (R.Name "begin")) []))
                    , R.Ignore $ R.Call (R.Variable $ R.Qualified (R.Name "std") (R.Name "advance")) [R.Variable (R.Name iterator), iv]
                    ]

      result <- genSym
      resultType <- getKType e >>= genCType
      let resultDecl = R.Forward $ R.ScalarDecl (R.Name result) resultType Nothing

      (nfe, nfb) <- inlineApply (RName (R.Variable $ R.Name result) Nothing) n [R.Initialization R.Unit []] [R.Unit]
      (wfe, wfb) <- inlineApply (RName (R.Variable $ R.Name result) Nothing) w [R.Dereference (R.Variable $ R.Name iterator)] [rt]

      return (ce ++ [ue] ++ ie ++ [resultDecl] ++ [R.IfThenElse sizeCheck (advance ++ wfe ++ wfb) (nfe ++ nfb)]
            , R.Variable $ R.Name result)

    p@(UnsafeAt c) :$: i :$: w | c `dataspaceIn` stlLinearDSs && doInlineP -> do
      (ce, cv) <- inline c
      rt <- getKType c >>= \(tag &&& children -> (TCollection, [rt])) -> genCType rt
      ig <- genSym
      ie <- reify (RDecl ig Nothing) i
      let iv = R.Variable $ R.Name ig

      ug <- genSym
      let ue = R.Forward $ R.ScalarDecl (R.Name ug) (R.Reference R.Inferred) (Just $  R.Call (R.Project cv (R.Name "getConstContainer")) [])
      let uv = R.Variable $ R.Name ug

      iterator <- genSym
      let advance = [ R.Forward $ R.ScalarDecl (R.Name iterator) R.Inferred (Just $ (R.Call (R.Project uv (R.Name "begin")) []))
                    , R.Ignore $ R.Call (R.Variable $ R.Qualified (R.Name "std") (R.Name "advance")) [R.Variable (R.Name iterator), iv]
                    ]

      result <- genSym
      resultType <- getKType e >>= genCType
      let resultDecl = R.Forward $ R.ScalarDecl (R.Name result) resultType Nothing

      (wfe, wfb) <- inlineApply (RName (R.Variable $ R.Name result) Nothing) w [R.Dereference (R.Variable $ R.Name iterator)] [rt]

      return (ce ++ [ue] ++ ie ++ [resultDecl] ++ [R.Block (advance ++ wfe ++ wfb)]
            , R.Variable $ R.Name result)

    f :$: x | isolateApplicationP && deepHasFusionSource f && not (e @:? "ApplicationIsolated") -> do
      g <- genSym
      es <- guardDReify serializeRoundTrip (RDecl g Nothing) (e @:+ "ApplicationIsolated")
      return (es, R.Variable $ R.Name g)

    _ :$: _ -> do
      -- Inline both function and argument for call.
      incApplyLevel

      let (f, as) = rollAppChain e
      (fe, fv) <- inline f
      let xs = map (last . children) as
      let inline' e' =
            if deepHasFusionSource f && isolateApplicationP then serializeRoundTripInline e'
            else inline e'

      (unzip -> (xes, xvs)) <- mapM inline' xs

      let reifyArg (x, xv, m) = do
            let orderAgnosticP = R.isOrderAgnostic xv
            let moveArg = if x @:? "Move" then Moved else getInMethodFor anonS m
            if moveArg `elem` [Moved, Forwarded]
              then do
                let castMoveP = maybe True (\m -> needsMoveCast m xv) (getKTypeP x)

                let castModifier = case moveArg of
                      -- _ | not isolateQueryP && f @:? "ReturnsArgument" -> id
                      Moved | castMoveP -> R.Move
                      Forwarded -> R.FMacro
                      _ -> id

                if orderAgnosticP
                  then return ([], castModifier xv)
                  else do
                    g <- genSym
                    return ( [R.Forward $ R.ScalarDecl (R.Name g) (R.RValueReference R.Inferred) (Just $ castModifier xv)]
                          , R.FMacro $ R.Variable $ R.Name g
                          )
              else do
                if orderAgnosticP
                  then return ([], xv)
                  else do
                    g <- genSym
                    return ( [R.Forward $ R.ScalarDecl (R.Name g) (R.RValueReference R.Inferred) (Just xv)]
                          , R.FMacro $ R.Variable $ R.Name g
                          )

      (unzip -> (argDecls, argPasses)) <- mapM reifyArg $ zip3 xs xvs as

      br <- gets (boxRecords . flags)

      let nameMod = if br && isJust (f @~ hasBoxableProperty) then (R.nameConcat "boxed_") else id

      let eName i = maybe (return $ nameMod i) (const $ getKType e >>= genCType >>= \rt -> return $ R.Specialized [rt] (nameMod i))
                      (f @~ CArgs.isErrorFn)
      fv' <- case fv of
              R.Project s i -> R.Project s <$> eName i
              R.Variable i -> R.Variable <$> eName i
              _ -> return fv

      return (fe ++ concat xes ++ concat argDecls , R.Call fv' argPasses)

    (tag &&& children -> (EOperate OSnd, [tag &&& children -> (ETuple, [trig@(tag -> EVariable tName), addr]), val])) -> do
      d <- genSym
      tIdName <- case trig @~ isEProperty of
                  Just (EProperty (ePropertyValue -> Just (tag -> LString nm))) -> return nm
                  _ -> throwE $ CPPGenE $ "No trigger id property attached to " ++ tName
      (te, _)  <- inline trig
      (ae, av)  <- inline addr
      (ve, vv)  <- inline val
      let messageValue = passBy (getInMethodFor "!" e) val vv
      trigTypes <- getKType val >>= genCType
      let me = R.Variable $ R.Name "me"
      let commonSArgs = [me, av, R.Variable $ R.Name tIdName, messageValue]

      (sName, sArgs) <- case (e @~ isEDelay, e @~ isEDelayOverride, e @~ isEDelayOverrideEdge) of
                        (Just (EProperty (ePropertyValue -> Just (tag -> LInt delay))), Nothing, Nothing) ->
                          return ("delayedSend",
                            commonSArgs ++ [R.Variable $ R.Name "TimerType::Delay", R.Literal $ R.LInt delay])

                        (Nothing, Just (EProperty (ePropertyValue -> Just (tag -> LInt delay))), Nothing) ->
                          return ("delayedSend",
                            commonSArgs ++ [R.Variable $ R.Name "TimerType::DelayOverride", R.Literal $ R.LInt delay])

                        (Nothing, Nothing, Just (EProperty (ePropertyValue -> Just (tag -> LInt delay)))) ->
                          return ("delayedSend",
                            commonSArgs ++ [R.Variable $ R.Name "TimerType::DelayOverrideEdge", R.Literal $ R.LInt delay])

                        (Nothing, Nothing, Nothing) -> return ("send", commonSArgs)

                        _ -> throwE $ CPPGenE $ "Invalid delay send properties"

      return (concat [te, ae, ve]
                  ++ [ R.Ignore $ R.Call (R.Project (R.Variable $ R.Name "__engine_") (R.Specialized [trigTypes] (R.Name sName))) sArgs ]
              , R.Initialization R.Unit [])

    (tag &&& children -> (EOperate bop, [a, b])) -> do
      (ae, av) <- inline a
      (be, bv) <- inline b
      bsym <- binarySymbol bop
      return (ae ++ be, R.Binary bsym av bv)

    (tag &&& children -> (EProject v, [k])) -> do
      (ke, kv) <- inline k

      br <- gets (boxRecords . flags)
      kt <- getKType k
      let bw = case tag kt of
                TRecord _ | br -> R.Dereference kv
                _ -> kv
      -- let bw = if br && tag kt /= TCollection then R.Dereference kv else kv
      return (ke, R.Project bw (R.Name v))

    (tag &&& children -> (EAssign x, [e])) -> reify (RName (R.Variable $ R.Name x) Nothing) e >>= \a ->
                                                    return (a, R.Initialization R.Unit [])

    (tag &&& children -> (EAddress, [h, p])) -> do
      (he, hv) <- inline h
      (pe, pv) <- inline p
      return (he ++ pe, R.Call (R.Variable $ R.Name "make_address") [hv, pv])

    _ -> do
      k <- genSym
      effects <- reify (RDecl k Nothing) e
      return (effects, R.Variable $ R.Name k)
 where
  isETriggerId (EProperty (ePropertyName -> "TriggerId")) = True
  isETriggerId _ = False

  isEDelay (EProperty (ePropertyName -> "Delay")) = True
  isEDelay _ = False

  isEDelayOverride (EProperty (ePropertyName -> "DelayOverride")) = True
  isEDelayOverride _ = False

  isEDelayOverrideEdge (EProperty (ePropertyName -> "DelayOverrideEdge")) = True
  isEDelayOverrideEdge _ = False

-- | The generic function to generate code for an expression whose result is to be reified. The
-- method of reification is indicated by the @RContext@ argument.
reify :: RContext -> K3 Expression -> CPPGenM [R.Statement]
reify r e = do
  isolateApplicationP <- gets (isolateApplicationCG . flags)
  isolateQueryP <- gets (isolateQueryCG . flags)
  let doInlineP = True
  case (r, e) of
    (RForget, Fold _ :$: _ :$: _) | doInlineP -> do
      (ee, _) <- inline e
      return ee

    -- TODO: Is this the fix we need for the unnecessary reification issues?
    (RForget, _ :$: _) -> do
      (ee, ev) <- inline e
      return $ ee ++ [R.Ignore ev]

    (_,(tag &&& children -> (EOperate OSeq, [a, b]))) -> do
      ae <- reify RForget a
      be <- reify r b
      return $ ae ++ be

    (RDecl i b, (tag -> ELetIn _)) -> precludeRDecl i b e

    (_, (tag &&& children -> (ELetIn x, [i, b]))) -> do
      let initD = getInMethodFor x e
      ie <- reify (RDecl x (Just $ initD == Moved)) i
      be <- reify r b
      return [R.Block $ ie ++ be]

    (RDecl i b, (tag -> ECaseOf _)) -> precludeRDecl i b e

    (_, k@(tag &&& children -> (ECaseOf x, [e, s, n]))) -> do
      let m = getInMethodFor x k

      initKType <- getKType e
      initCType <- genCType initKType

      let innerCType = case initCType of
                        R.Pointer t -> t
                        R.SharedPointer t -> t
                        _ -> error "Invalid pointer type for case/of"

      -- Code to reify the case/of initializer, and the name of the temporary variable used.
      (initName, initReify) <-
        case tag e of
          EVariable k -> return (k, [])
          _ -> do
            g <- genSym
            ee <- reify (RName (R.Variable $ R.Name g) Nothing) e
            return (g, [R.Forward $ R.ScalarDecl (R.Name g) initCType Nothing] ++ ee)

      let initExpr = R.Dereference $ R.Variable $ R.Name initName

      let cx = R.Name x

      let initSome =
            case m of
              Copied -> [R.Forward $ R.ScalarDecl cx innerCType (Just initExpr)]
              Moved -> [R.Forward $ R.ScalarDecl cx innerCType (Just $ R.Move initExpr)]
              Referenced -> [R.Forward $ R.ScalarDecl cx (R.Reference innerCType) (Just initExpr)]
              ConstReferenced -> [R.Forward $ R.ScalarDecl cx (R.Reference $ R.Const innerCType) (Just initExpr)]

      let writeBackSome = case m of
                            Copied -> [R.Assignment (R.Variable $ R.Name initName) (R.Variable $ R.Name x)]
                            Moved -> [R.Assignment (R.Variable $ R.Name initName) (R.Move $ R.Variable $ R.Name x)]
                            _ -> []

      let writeBackNone = case m of
                            Copied -> [R.Assignment (R.Variable $ R.Name initName) (R.Literal R.LNullptr)]
                            Moved -> [R.Assignment (R.Variable $ R.Name initName) (R.Literal R.LNullptr)]
                            _ -> []

      -- If this case/of is the last expression in the current function and therefore returns,
      -- writeback must happen before the return takes place.
      (someE, noneE, returnDecl, returnStmt) <-
        case r of
          RReturn j | m == Copied || m == Moved -> do
            returnName <- genSym
            returnType <- getKType k >>= genCType
            let returnDecl = [R.Forward $ R.ScalarDecl (R.Name returnName) returnType Nothing]
            let returnStmt = if j then R.Move (R.Variable $ R.Name returnName) else (R.Variable $ R.Name returnName)
            someE <- reify (RName (R.Variable $ R.Name returnName) Nothing) s
            noneE <- reify (RName (R.Variable $ R.Name returnName) Nothing) n

            return (someE, noneE, returnDecl, [R.Return returnStmt])
          _ -> do
            someE <- reify r s
            noneE <- reify r n
            return (someE, noneE, [], [])

      return $ initReify ++ [R.IfThenElse (R.Variable $ R.Name initName)
                                (returnDecl ++ initSome ++ someE ++ writeBackSome ++ returnStmt)
                                (returnDecl ++ noneE ++ writeBackNone ++ returnStmt)]

    (RDecl i b, x@(tag -> EBindAs _)) -> precludeRDecl i b x

    (_, k@(tag &&& children -> (EBindAs b, [a, e]))) -> do
      let newNames =
            case b of
              BIndirection i -> [i]
              BTuple is -> is
              BRecord iis -> snd (unzip iis)
              BSplice _ -> []

      initKType <- getKType a
      initCType <- genCType initKType

      (initName, initReify) <- do
        g <- genSym
        (e, i) <- inline a
        return (g, e ++ [R.Forward $ R.ScalarDecl (R.Name g) (R.RValueReference R.Inferred) (Just i)])

        {- case tag a of
          EVariable v -> return (v, [])
          _ -> do
            g <- genSym
            ee <- reify (RName (R.Variable $ R.Name g) Nothing) a
            return (g, [R.Forward $ R.ScalarDecl (R.Name g) initCType Nothing] ++ ee) -}

      let initExpr = R.Variable (R.Name initName)

      let initSkeleton t m i e = [R.Forward $ R.ScalarDecl (R.Name i) (t R.Inferred) (Just $ m e)]

      let initByDecision d =
            case d of
              Referenced -> initSkeleton R.Reference id
              ConstReferenced -> initSkeleton (R.Const . R.Reference) id
              Moved -> initSkeleton id R.Move
              Copied -> initSkeleton id id

      let bindInit =
            case b of
              BIndirection i -> initByDecision (getInMethodFor i k) i (R.Dereference initExpr)
              BTuple is ->
                concat [initByDecision (getInMethodFor i k) i (R.TGet initExpr n) | i <- is | n <- [0..]]
              BRecord iis ->
                concat [initByDecision (getInMethodFor i k) i (R.Project initExpr (R.Name f)) | (f, i) <- iis]
              BSplice _ -> []

      let wbByDecision d old new =
            case d of
              Referenced -> []
              ConstReferenced -> []
              Moved -> [R.Assignment old (R.Move new)]
              Copied -> [R.Assignment old new]

      let bindWriteBack =
            case b of
              BIndirection i -> wbByDecision (getExMethodFor i k) (R.Dereference initExpr) (R.Variable $ R.Name i)
              BTuple is ->
                concat [wbByDecision (getExMethodFor i k) (R.TGet initExpr n) (R.Variable $ R.Name i) | i <- is | n <- [0..]]
              BRecord iis ->
                concat [wbByDecision (getExMethodFor i k) (R.Project initExpr (R.Name f)) (R.Variable $ R.Name i) | (f, i) <- iis]
              BSplice _ -> []

      (bindBody, returnDecl, returnStmt) <-
        case r of
          RReturn m | any (\d -> d == Moved || d == Copied) (getExDecisions k) -> do
            returnName <- genSym
            returnType <- getKType k >>= genCType
            let returnDecl = [R.Forward $ R.ScalarDecl (R.Name returnName) returnType Nothing]
            let returnExpr = if m then R.Move (R.Variable $ R.Name returnName) else (R.Variable $ R.Name returnName)
            bindBody <- reify (RName (R.Variable $ R.Name returnName) (Just m)) e
            return (bindBody, returnDecl, [R.Return returnExpr])
          _ -> do
            bindBody <- reify r e
            return (bindBody, [], [])

      return $ initReify ++ [R.Block $ bindInit ++ returnDecl ++ bindBody ++ bindWriteBack ++ returnStmt]

    (RDecl i mb, x@(tag -> EIfThenElse)) -> precludeRDecl i mb x

    (_, (tag &&& children -> (EIfThenElse, [p, t, e]))) -> do
        (pe, pv) <- inline p
        te <- reify r t
        ee <- reify r e
        return $ pe ++ [R.IfThenElse pv te ee]

    -- | Catch-all case
    _ -> do
      (effects, value) <- inline e
      reification <- doReify r e value
      return $ effects ++ reification

doReify :: RContext -> K3 Expression -> R.Expression -> CPPGenM [R.Statement]
doReify r e v = case r of
  RForget -> return []
  RName k b -> return [R.Assignment k (if fromMaybe False b then gMoveByE e v else v)]
  RDecl i b -> return [R.Forward $ R.ScalarDecl (R.Name i) (R.Inferred)
                      (Just $ if fromMaybe False b then gMoveByE e v else v)]
  RReturn b -> return $ [R.Return $ (if b then R.Move else id) v]
  RSplice _ -> throwE $ CPPGenE "Unsupported reification by splice."

doubleReify :: RContext -> K3 Expression -> CPPGenM [R.Statement]
doubleReify r e = do
  g <- genSym
  es' <- reify (RDecl g Nothing) e
  let rg = R.Variable $ R.Name g
  es <- doReify r e rg
  return $ es' ++ es

serializeRoundTripCPP :: R.Type -> R.Expression -> CPPGenM ([R.Statement], R.Expression)
serializeRoundTripCPP t v = do
  g <- genSym
  let gDecl = R.Forward $ R.ScalarDecl (R.Name g) R.Inferred
                (Just $ R.Call (R.Variable $ R.Name "pack")
                          [v, R.Variable $ R.Qualified (R.Name "CodecFormat") (R.Name "YASBinary")])
  u <- genSym
  let uDecl = R.Forward $ R.ScalarDecl (R.Name u) R.Inferred
                (Just $ R.Call (R.Variable $ R.Specialized [t] $ R.Name "unpack") [R.Move $ R.Variable $ R.Name g])
  return ([gDecl, uDecl], R.Dereference $ R.Variable $ R.Name u)

serializeRoundTripInline :: K3 Expression -> CPPGenM ([R.Statement], R.Expression)
serializeRoundTripInline e = do
  (es, v) <- inline e
  t <- getKType e >>= genCType
  (es', v') <- serializeRoundTripCPP t v
  return (es ++ es', v')

serializeRoundTrip :: RContext -> K3 Expression -> CPPGenM [R.Statement]
serializeRoundTrip r e = do
  (es, v) <- serializeRoundTripInline e
  es' <- doReify r e v
  return $ es ++ es'

-- serializeRoundTrip

guardDReify :: (RContext -> K3 Expression -> CPPGenM [R.Statement]) -> RContext -> K3 Expression -> CPPGenM [R.Statement]
guardDReify f r e = gets (isolateApplicationCG . flags) >>= \a -> if a then f r e else reify r e

-- ** Template Helpers
inlineApply :: RContext -> K3 Expression -> [R.Expression] -> [R.Type] -> CPPGenM ([R.Statement], [R.Statement])
inlineApply r f xs xts = do
  isolateApplicationP <- gets (isolateApplicationCG . flags)
  case f of
    -- Can only inline lambdas, we do not grab definitions from elsewhere.
    (tag -> ELambda outerArg) -> do
      -- Roll the lambda chain up, we need the inner and outer lambdas, as well as the body. The
      -- outer lambda contains the names of the true captures (closure variables which are not
      -- nested lambda arguments), while the inner lambda contains the relevant materialization
      -- decisions.
      let (unzip -> (argNames, fExprs), body) = rollLambdaChain f

      -- Reify the body of the lambda under the desired context.
      rawBody <- if f @:? "FusionSource" && not (f @:? "BuiltinTransformer")
                   then guardDReify serializeRoundTrip r body
                   else reify r body

      let innerFExpr = last fExprs
      let isTrueCapture k m = k /= outerArg && (m == Copied || m == Moved)

      let trueCaptures = M.filterWithKey isTrueCapture (getInDecisions f)

      let reifyArgument formalName reifiedArg formalType = do
            if formalName == "_" then return [] else do
            let formalType = case getInMethodFor formalName innerFExpr of
                  Referenced -> R.Reference R.Inferred
                  ConstReferenced -> R.Reference $ R.Const $ R.Inferred
                  Copied -> R.Inferred
                  Moved -> R.Inferred
                  Forwarded -> R.RValueReference R.Inferred
            if isolateApplicationP && f @:? "FusionSource" && not (f @:? "BuiltinTransformer")
              then do
                (es, v) <- serializeRoundTripCPP formalType reifiedArg
                let fDecl = R.Forward $ R.ScalarDecl (R.Name formalName) (R.Reference R.Inferred) (Just v)
                return $ es ++ [fDecl]
                -- g <- genSym
                -- let firstAssign = R.Forward $ R.ScalarDecl (R.Name g) R.Inferred (Just reifiedArg)
                -- let secondAssign = R.Forward $ R.ScalarDecl (R.Name formalName) formalType (Just $ R.Variable $ R.Name g)
                -- return [firstAssign, secondAssign]
              else return [R.Forward $ R.ScalarDecl (R.Name formalName) formalType (Just reifiedArg)]

      argumentReifications <- concat <$> (sequence $ zipWith3 reifyArgument argNames xs xts)

      -- We only need to reify captures that need to be isolated (copied/moved), since reference
      -- captures will be in scope as desired. If a capture is to be isolated, generate a symbol for
      -- it, and replace the capture's name for it in the reified body.
      let reifyCapture (name, mtrlzn) (decls, oldBody) = do
            g <- genSym
            let cast = if mtrlzn == Moved then R.Move else id
            let decl = [R.Forward $ R.ScalarDecl (R.Name g) R.Inferred (Just $ cast $ R.Variable $ R.Name name)]
            return (decls ++ decl , R.subst g name <$> oldBody)

      (captureStmts, substBody) <- foldrM reifyCapture ([], rawBody) (M.toList trueCaptures)

      return (captureStmts, argumentReifications ++ substBody)
    _ -> do
      (fe, fv) <- inline f

      (concat -> argReifications, actualArgs) <-
        if isolateApplicationP && f @:? "FusionSource" && not (f @:? "BuiltinTransformer")
          then unzip <$> (sequence $ zipWith serializeRoundTripCPP xts xs)
          else return ([], xs)

      let callStmt = R.Call fv actualArgs

      ft <- getKType f
      let (tag &&& children -> (TFunction, [_, rt])) = ft
      crt <- genCType rt

      (resultLocationE, resultLocationV) <-
        if isolateApplicationP && f @:? "FusionSource" && not (f @:? "BuiltinTransformer")
          then serializeRoundTripCPP crt callStmt
            -- return ([R.Forward $ R.ScalarDecl (R.Name g) R.Inferred (Just callStmt)], R.Variable $ R.Name g)
          else return ([], callStmt)

      resultReification <-
        case r of
          RForget -> return [R.Ignore resultLocationV]
          RName k b -> return [R.Assignment k (if fromMaybe False b then R.Move resultLocationV else resultLocationV)]
          RDecl i b -> return [R.Forward $ R.ScalarDecl (R.Name i) R.Inferred
                              (Just $ if fromMaybe False b then R.Move resultLocationV else resultLocationV)]
          RReturn b -> return [R.Return $ if b then R.Move resultLocationV else resultLocationV]
          RSplice _ -> throwE $ CPPGenE "Unsupported reification by splice"

      return (fe ++ argReifications ++ resultLocationE, resultReification)


text:
from __future__ import unicode_literals

from django.db import transaction, IntegrityError
from django.test import TestCase

from .models import (Place, Restaurant, Bar, Waiter, ManualPrimaryKey, RelatedModel,
    MultiModel)

class OneToOneTests(TestCase):

    def setUp(self):
        self.p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
        self.p1.save()
        self.p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
        self.p2.save()
        self.r = Restaurant(place=self.p1, serves_hot_dogs=True, serves_pizza=False)
        self.r.save()

    def test_getter(self):
        # A Restaurant can access its place.
        self.assertEqual(repr(self.r.place), '<Place: Demon Dogs the place>')
        # A Place can access its restaurant, if available.
        self.assertEqual(repr(self.p1.restaurant), '<Restaurant: Demon Dogs the restaurant>')
        # p2 doesn't have an associated restaurant.
        with self.assertRaisesMessage(Restaurant.DoesNotExist, 'Place has no restaurant'):
            self.p2.restaurant
        # The exception raised on attribute access when a related object
        # doesn't exist should be an instance of a subclass of `AttributeError`
        # refs #21563
        self.assertFalse(hasattr(self.p2, 'restaurant'))

    def test_setter(self):
        # Set the place using assignment notation. Because place is the primary
        # key on Restaurant, the save will create a new restaurant
        self.r.place = self.p2
        self.r.save()
        self.assertEqual(repr(self.p2.restaurant), '<Restaurant: Ace Hardware the restaurant>')
        self.assertEqual(repr(self.r.place), '<Place: Ace Hardware the place>')
        self.assertEqual(self.p2.pk, self.r.pk)
        # Set the place back again, using assignment in the reverse direction.
        self.p1.restaurant = self.r
        self.assertEqual(repr(self.p1.restaurant), '<Restaurant: Demon Dogs the restaurant>')
        r = Restaurant.objects.get(pk=self.p1.id)
        self.assertEqual(repr(r.place), '<Place: Demon Dogs the place>')

    def test_manager_all(self):
        # Restaurant.objects.all() just returns the Restaurants, not the Places.
        self.assertQuerysetEqual(Restaurant.objects.all(), [
            '<Restaurant: Demon Dogs the restaurant>',
        ])
        # Place.objects.all() returns all Places, regardless of whether they
        # have Restaurants.
        self.assertQuerysetEqual(Place.objects.order_by('name'), [
            '<Place: Ace Hardware the place>',
            '<Place: Demon Dogs the place>',
        ])

    def test_manager_get(self):
        def assert_get_restaurant(**params):
            self.assertEqual(repr(Restaurant.objects.get(**params)),
                             '<Restaurant: Demon Dogs the restaurant>')
        assert_get_restaurant(place__id__exact=self.p1.pk)
        assert_get_restaurant(place__id=self.p1.pk)
        assert_get_restaurant(place__exact=self.p1.pk)
        assert_get_restaurant(place__exact=self.p1)
        assert_get_restaurant(place=self.p1.pk)
        assert_get_restaurant(place=self.p1)
        assert_get_restaurant(pk=self.p1.pk)
        assert_get_restaurant(place__pk__exact=self.p1.pk)
        assert_get_restaurant(place__pk=self.p1.pk)
        assert_get_restaurant(place__name__startswith="Demon")

        def assert_get_place(**params):
            self.assertEqual(repr(Place.objects.get(**params)),
                             '<Place: Demon Dogs the place>')
        assert_get_place(restaurant__place__exact=self.p1.pk)
        assert_get_place(restaurant__place__exact=self.p1)
        assert_get_place(restaurant__place__pk=self.p1.pk)
        assert_get_place(restaurant__exact=self.p1.pk)
        assert_get_place(restaurant__exact=self.r)
        assert_get_place(restaurant__pk=self.p1.pk)
        assert_get_place(restaurant=self.p1.pk)
        assert_get_place(restaurant=self.r)
        assert_get_place(id__exact=self.p1.pk)
        assert_get_place(pk=self.p1.pk)

    def test_foreign_key(self):
        # Add a Waiter to the Restaurant.
        w = self.r.waiter_set.create(name='Joe')
        w.save()
        self.assertEqual(repr(w), '<Waiter: Joe the waiter at Demon Dogs the restaurant>')

        # Query the waiters
        def assert_filter_waiters(**params):
            self.assertQuerysetEqual(Waiter.objects.filter(**params), [
                '<Waiter: Joe the waiter at Demon Dogs the restaurant>'
            ])
        assert_filter_waiters(restaurant__place__exact=self.p1.pk)
        assert_filter_waiters(restaurant__place__exact=self.p1)
        assert_filter_waiters(restaurant__place__pk=self.p1.pk)
        assert_filter_waiters(restaurant__exact=self.p1.pk)
        assert_filter_waiters(restaurant__pk=self.p1.pk)
        assert_filter_waiters(restaurant=self.p1.pk)
        assert_filter_waiters(restaurant=self.r)
        assert_filter_waiters(id__exact=self.p1.pk)
        assert_filter_waiters(pk=self.p1.pk)
        # Delete the restaurant; the waiter should also be removed
        r = Restaurant.objects.get(pk=self.p1.pk)
        r.delete()
        self.assertEqual(Waiter.objects.count(), 0)

    def test_multiple_o2o(self):
        # One-to-one fields still work if you create your own primary key
        o1 = ManualPrimaryKey(primary_key="abc123", name="primary")
        o1.save()
        o2 = RelatedModel(link=o1, name="secondary")
        o2.save()

        # You can have multiple one-to-one fields on a model, too.
        x1 = MultiModel(link1=self.p1, link2=o1, name="x1")
        x1.save()
        self.assertEqual(repr(o1.multimodel), '<MultiModel: Multimodel x1>')
        # This will fail because each one-to-one field must be unique (and
        # link2=o1 was used for x1, above).
        mm = MultiModel(link1=self.p2, link2=o1, name="x1")
        with self.assertRaises(IntegrityError):
            with transaction.atomic():
                mm.save()

    def test_unsaved_object(self):
        """
        #10811 -- Assigning an unsaved object to a OneToOneField
        should raise an exception.
        """
        place = Place(name='User', address='London')
        with self.assertRaisesMessage(ValueError,
                            'Cannot assign "%r": "%s" instance isn\'t saved in the database.'
                            % (place, Restaurant.place.field.rel.to._meta.object_name)):
            Restaurant.objects.create(place=place, serves_hot_dogs=True, serves_pizza=False)
        bar = Bar()
        p = Place(name='User', address='London')
        with self.assertRaisesMessage(ValueError,
                            'Cannot assign "%r": "%s" instance isn\'t saved in the database.'
                            % (bar, p._meta.object_name)):
            p.bar = bar


text:
package org.koenighotze.jee7hotel.framework.eventing.feed;

import org.apache.abdera.Abdera;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Produces;
import javax.inject.Named;
import javax.inject.Singleton;

/**
 * @author dschmitz
 */

@Named
@Singleton
public class AbderaProducer {
    private Abdera abdera;

    @PostConstruct
    public void init() {
        abdera = new Abdera();

    }

    @Produces
    public Abdera abdera() {
        return abdera;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE topic
  PUBLIC "-//OASIS//DTD DITA Composite//EN" "ditabase.dtd">
<topic id="topic1" xml:lang="en">
  <title>Expanding a Greenplum System</title>
  <shortdesc>To scale up performance and storage capacity, expand your Greenplum system by adding
    hosts to the array.</shortdesc>

Data warehouses typically grow over time as additional data is gathered and the retention
      periods increase for existing data. At times, it is necessary to increase database capacity to
      consolidate different data warehouses into a single database. Additional computing capacity
      (CPU) may also be needed to accommodate newly added analytics projects. Although it is wise to
      provide capacity for growth when a system is initially specified, it is not generally possible
      to invest in resources long before they are required. Therefore, you should expect to execute
      a database expansion project periodically.

Because of the Greenplum MPP architecture, when you add resources to the system, the capacity
      and performance are the same as if the system had been originally implemented with the added
      resources. Unlike data warehouse systems that require substantial downtime in order to dump
      and restore the data, expanding a Greenplum Database system is a phased process with minimal
      downtime. Regular and ad hoc workloads can continue while data is redistributed and
      transactional consistency is maintained. The administrator can schedule the distribution
      activity to fit into ongoing operations and can pause and resume as needed. Tables can be
      ranked so that datasets are redistributed in a prioritized sequence, either to ensure that
      critical workloads benefit from the expanded capacity sooner, or to free disk space needed to
      redistribute very large tables.

The expansion process uses standard Greenplum Database operations so it is transparent and
      easy for administrators to troubleshoot. Segment mirroring and any replication mechanisms in
      place remain active, so fault-tolerance is uncompromised and disaster recovery measures remain
      effective.

</topic>


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromVsCodeUri = exports.toVsCodeUri = exports.toVsCodeRange = exports.toVsCodePosition = void 0;
const vscode_1 = require("vscode");
const uri_1 = require("../core/model/uri");
exports.toVsCodePosition = (p) => new vscode_1.Position(p.line, p.character);
exports.toVsCodeRange = (r) => new vscode_1.Range(r.start.line, r.start.character, r.end.line, r.end.character);
exports.toVsCodeUri = (u) => vscode_1.Uri.parse(u.toString());
exports.fromVsCodeUri = (u) => uri_1.URI.parse(u.toString());
//# sourceMappingURL=vsc-utils.js.map