text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Interpreter;

namespace Microsoft.PythonTools.Uwp.Interpreter {
    class PythonUwpInterpreter : IPythonInterpreter, IPythonInterpreterWithProjectReferences2, IDisposable {
        readonly Version _langVersion;
        private PythonInterpreterFactoryWithDatabase _factory;
        private PythonTypeDatabase _typeDb;
        private HashSet<ProjectReference> _references;

        public PythonUwpInterpreter(PythonInterpreterFactoryWithDatabase factory) {
            _langVersion = factory.Configuration.Version;
            _factory = factory;
            _typeDb = _factory.GetCurrentDatabase();
            _factory.NewDatabaseAvailable += OnNewDatabaseAvailable;
        }

        private void OnNewDatabaseAvailable(object sender, EventArgs e) {
            var factory = _factory;
            if (factory == null) {
                // We have been disposed already, so ignore this event
                return;
            }

            var evt = ModuleNamesChanged;
            if (evt != null) {
                evt(this, EventArgs.Empty);
            }
        }

        #region IPythonInterpreter Members

        public IPythonType GetBuiltinType(BuiltinTypeId id) {
            if (id == BuiltinTypeId.Unknown) {
                return null;
            }

            if (_typeDb == null) {
                throw new KeyNotFoundException(string.Format("{0} ({1})", id, (int)id));
            }

            var name = GetBuiltinTypeName(id, _typeDb.LanguageVersion);
            var res = _typeDb.BuiltinModule.GetAnyMember(name) as IPythonType;
            if (res == null) {
                throw new KeyNotFoundException(string.Format("{0} ({1})", id, (int)id));
            }
            return res;
        }

        public IList<string> GetModuleNames() {
            if (_typeDb == null) {
                return new string[0];
            }
            return new List<string>(_typeDb.GetModuleNames());
        }

        public IPythonModule ImportModule(string name) {
            if (_typeDb == null) {
                return null;
            }
            return _typeDb.GetModule(name);
        }

        public IModuleContext CreateModuleContext() {
            return null;
        }

        public void Initialize(PythonAnalyzer state) {
        }

        public event EventHandler ModuleNamesChanged;

        public Task AddReferenceAsync(ProjectReference reference, CancellationToken cancellationToken = default(CancellationToken)) {
            if (reference == null) {
                return MakeExceptionTask(new ArgumentNullException("reference"));
            }

            if (_references == null) {
                _references = new HashSet<ProjectReference>();
                // If we needed to set _references, then we also need to clone
                // _typeDb to avoid adding modules to the shared database.
                if (_typeDb != null) {
                    _typeDb = _typeDb.Clone();
                }
            }

            switch (reference.Kind) {
                case ProjectReferenceKind.ExtensionModule:
                    _references.Add(reference);
                    string filename;
                    try {
                        filename = Path.GetFileNameWithoutExtension(reference.Name);
                    } catch (Exception e) {
                        return MakeExceptionTask(e);
                    }

                    if (_typeDb != null) {
                        return Task.Factory.StartNew(EmptyTask);
                    }
                    break;
            }

            return Task.Factory.StartNew(EmptyTask);
        }

        public void RemoveReference(ProjectReference reference) {
            switch (reference.Kind) {
                case ProjectReferenceKind.ExtensionModule:
                    if (_references != null && _references.Remove(reference) && _typeDb != null) {
                        RaiseModulesChanged(null);
                    }
                    break;
            }
        }

        public IEnumerable<ProjectReference> GetReferences() {
            return _references != null ? _references : Enumerable.Empty<ProjectReference>();
        }

        private static Task MakeExceptionTask(Exception e) {
            var res = new TaskCompletionSource<Task>();
            res.SetException(e);
            return res.Task;
        }

        private static void EmptyTask() {
        }

        private void RaiseModulesChanged(Task task) {
            if (task != null && task.Exception != null) {
                throw task.Exception;
            }
            var modNamesChanged = ModuleNamesChanged;
            if (modNamesChanged != null) {
                modNamesChanged(this, EventArgs.Empty);
            }
        }

        public static string GetBuiltinTypeName(BuiltinTypeId id, Version languageVersion) {
            string name;
            switch (id) {
                case BuiltinTypeId.Bool: name = "bool"; break;
                case BuiltinTypeId.Complex: name = "complex"; break;
                case BuiltinTypeId.Dict: name = "dict"; break;
                case BuiltinTypeId.Float: name = "float"; break;
                case BuiltinTypeId.Int: name = "int"; break;
                case BuiltinTypeId.List: name = "list"; break;
                case BuiltinTypeId.Long: name = languageVersion.Major == 3 ? "int" : "long"; break;
                case BuiltinTypeId.Object: name = "object"; break;
                case BuiltinTypeId.Set: name = "set"; break;
                case BuiltinTypeId.Str: name = "str"; break;
                case BuiltinTypeId.Unicode: name = languageVersion.Major == 3 ? "str" : "unicode"; break;
                case BuiltinTypeId.Bytes: name = languageVersion.Major == 3 ? "bytes" : "str"; break;
                case BuiltinTypeId.Tuple: name = "tuple"; break;
                case BuiltinTypeId.Type: name = "type"; break;

                case BuiltinTypeId.BuiltinFunction: name = "builtin_function"; break;
                case BuiltinTypeId.BuiltinMethodDescriptor: name = "builtin_method_descriptor"; break;
                case BuiltinTypeId.DictKeys: name = "dict_keys"; break;
                case BuiltinTypeId.DictValues: name = "dict_values"; break;
                case BuiltinTypeId.DictItems: name = "dict_items"; break;
                case BuiltinTypeId.Function: name = "function"; break;
                case BuiltinTypeId.Generator: name = "generator"; break;
                case BuiltinTypeId.NoneType: name = "NoneType"; break;
                case BuiltinTypeId.Ellipsis: name = "ellipsis"; break;
                case BuiltinTypeId.Module: name = "module_type"; break;
                case BuiltinTypeId.ListIterator: name = "list_iterator"; break;
                case BuiltinTypeId.TupleIterator: name = "tuple_iterator"; break;
                case BuiltinTypeId.SetIterator: name = "set_iterator"; break;
                case BuiltinTypeId.StrIterator: name = "str_iterator"; break;
                case BuiltinTypeId.UnicodeIterator: name = languageVersion.Major == 3 ? "str_iterator" : "unicode_iterator"; break;
                case BuiltinTypeId.BytesIterator: name = languageVersion.Major == 3 ? "bytes_iterator" : "str_iterator"; break;
                case BuiltinTypeId.CallableIterator: name = "callable_iterator"; break;

                case BuiltinTypeId.Property: name = "property"; break;
                case BuiltinTypeId.ClassMethod: name = "classmethod"; break;
                case BuiltinTypeId.StaticMethod: name = "staticmethod"; break;
                case BuiltinTypeId.FrozenSet: name = "frozenset"; break;

                case BuiltinTypeId.Unknown:
                default:
                    return null;
            }
            return name;
        }
        #endregion

        public void Dispose() {
            _typeDb = null;

            var factory = _factory;
            _factory = null;
            if (factory != null) {
                factory.NewDatabaseAvailable -= OnNewDatabaseAvailable;
            }
        }
    }
}


text:
from itertools import cycle, chain
import json
import logging

import inspect
import datetime
import docker
import sys

from docker import utils as docker_utils
from docker.errors import APIError
from time import sleep, time
from os import walk, chown, makedirs
from os.path import exists as path_exists, join as path_join
from shutil import getpwnam, getgrnam
import plugin_loader
from worker_conf import DOCKER_CONF, DOCKER_CONTAINER_USER, INSTANCE_NAME, NETWORKING_CONF

from workdir import internal_path

"""
Global instance of Docker client.
"""
docker_cli = docker.Client(**DOCKER_CONF)

"""
Global network name
"""
network_name = "{}-{}".format(INSTANCE_NAME, NETWORKING_CONF['network_name'])

class PluginError(RuntimeError):
    def __init__(self, message, plugin_path, **kwargs):
        RuntimeError.__init__(self, message, **kwargs)

        self.plugin_path = plugin_path

class QuickStatsNotAvailable(RuntimeError):
    def __init__(self, *args, **kwargs):
        RuntimeError.__init__(self, *args, **kwargs)

def make_container(image, command, binds, host_config, **kwargs):
    return docker_cli.create_container(
        image=image,
        command=command,
        user=DOCKER_CONTAINER_USER,
        host_config=docker_cli.create_host_config(
            binds=binds,
            **host_config
        ),
        labels=["algochecker-{}".format(INSTANCE_NAME)],
        **kwargs
    )

def inspect_container(container):
    return docker_cli.inspect_container(container)

def destroy_container(container):
    docker_cli.stop(container, timeout=0)

    stdout = docker_cli.logs(container, stdout=True, stderr=False, stream=False, timestamps=False).decode('utf-8')
    stderr = docker_cli.logs(container, stdout=False, stderr=True, stream=False, timestamps=False).decode('utf-8')

    docker_cli.remove_container(container, force=True)

    return stdout, stderr

def safe_plugin_call(plugin, func):
    try:
        return func()
    except Exception as e:
        plugin_path = inspect.getfile(plugin)
        raise PluginError('Failed inside plugin code', plugin_path) from e

def save_leak_report(container):
    inspect_data = json.dumps(docker_cli.inspect_container(container), indent=4, separators=(',', ': '))
    logs = docker_cli.logs(container, stdout=True, stderr=True, stream=False, timestamps=True).decode('utf-8')

    try:
        makedirs(internal_path('error_report'))
    except FileExistsError:
        pass

    now = datetime.datetime.now()

    report_name = 'container_leak_{}_{}.log'.format(now.strftime('%Y%m%d_%H%M%S'), container)
    full_report_path = internal_path(path_join('error_report', report_name))

    with open(full_report_path, 'w') as report_f:
        report_f.write('Report about leaked container {}\n'.format(container))
        report_f.write('Generated on: {}\n'.format(now.isoformat()))
        report_f.write('\n=== Inspection data (length: {}) ===\n'.format(len(inspect_data)))
        report_f.write(inspect_data)
        report_f.write('\n=== Container logs (length: {}) ===\n'.format(len(logs)))
        report_f.write(logs)
        report_f.write('\n=== End of report ===\n')

    return full_report_path

def check_lost_containers(no_header=False):
    logging.info('Checking lost containers...')
    algo_label = 'algochecker-{}'.format(INSTANCE_NAME)

    lost = (container['Id'] for container in docker_cli.containers(all=True, filters={"label": algo_label}))
    saved_reports = []

    for container in lost:
        if not no_header:
            logging.error('--- LOST CONTAINER NOTICE ---')
        logging.error('Found lost container: {}. Container leak report will be generated.'.format(container))
        report_path = save_leak_report(container)
        saved_reports.append(report_path)
        logging.error('IMPORTANT! In order to find out the details about this leaked container '
                      + 'please refer to the report stored at: {}'
                      .format(report_path))
        logging.error('Destroying the container...')
        docker_cli.remove_container(container, force=True)
        if not no_header:
            logging.error('-----------------------------')

    return saved_reports

def download_image(image_name):
    spinner = cycle(['oO', 'Oo'])
    last_update = 0
    sys.stdout.write("Please wait, working... " + next(spinner))
    sys.stdout.flush()

    for line in docker_cli.pull(image_name, stream=True):
        info = json.loads(line.decode('utf-8'))

        if 'error' in info:
            logging.error("Failed to download docker image {}".format(image_name))
            logging.error(info['error'])
            raise RuntimeError("Failed to download docker image {}".format(image_name))

        current = time()

        if current - last_update > 1.0:
            last_update = current

            sys.stdout.write("\b\b" + next(spinner))
            sys.stdout.flush()

    sys.stdout.write("\n")
    sys.stdout.flush()

    print("Docker image was fetched successfully.")

def check_image_dependencies():
    logging.info('Checking image dependencies...')

    owned = set(chain.from_iterable(el['RepoTags'] for el in docker_cli.images()))
    required = set()

    for module in plugin_loader.get_all('compilers').values():
        required.update(module.__plugin__['required_images'])

    for module in plugin_loader.get_all('runners').values():
        required.update(module.__plugin__['required_images'])

    for image_name in required:
        if image_name not in owned:
            logging.warning('Docker image {} was not found. Attempting to download it.'.format(image_name))
            download_image(image_name)

    logging.info('Found all {:d} required images.'.format(len(required)))

def file_spinlock(file_name, timeout, step=0.01):
    """
    Run a spinlock, which will last until file with name `file_name` is created.
    Maximal waiting time is determined by `timeout` argument (in seconds).
    File existence will be checked every `step` seconds.
    :return True if spinlock was unlocked; False if timeout occurred
    """
    elapsed = 0.0

    while elapsed < timeout:
        if path_exists(file_name):
            return True

        elapsed += step
        sleep(step)

    return False

def quickly_get_stats(container):
    """
    Cheat method which returns partial stats in the Docker's format without
    using docker.stats() call which has time overhead of few seconds.
    Good alternative to call if the runner would be satisfied with concise stats.
    :param container: Docker container object.
    :return Incomplete statistics in docker.stats() format as described in docker-py docs.
    """
    if type(container) is dict:
        container = container['Id']

    file_name = '/sys/fs/cgroup/memory/docker/{}/memory.max_usage_in_bytes'.format(container)

    # TODO read /var/lib/docker/containers/{}/config.v2.json - exit code, start time and finish time are there

    try:
        with open(file_name, 'r') as f:
            memory_max_usage = int(f.read())
    except IOError:
        logging.exception('Failed to quickly get container stats. Peak memory usage is not available.')
        raise QuickStatsNotAvailable()

    return {
        "memory_stats": {
            "max_usage": memory_max_usage
        }
    }

def reset_memory_peak(container):
    if type(container) is dict:
        container = container['Id']

    file_name = '/sys/fs/cgroup/memory/docker/{}/memory.max_usage_in_bytes'.format(container)

    with open(file_name, 'w') as f:
        f.write('0')

def chown_recursive(path, user, group):
    uid = getpwnam(user).pw_uid
    gid = getgrnam(group).gr_gid

    for root, dirs, files in walk(path):
        for dir_name in dirs:
            chown(path_join(root, dir_name), uid, gid)

        for file_name in files:
            chown(path_join(root, file_name), uid, gid)

def shrink_logs(logs, max_lines=250, max_bytes=12288):
    log_parts = logs.split("\n")
    log_size = len(logs)
    logs = "\n".join(log_parts[:max_lines])

    if log_size > max_bytes:
        logs = logs[:max_bytes]
        logs += "\n\n(algochecker: truncated the rest of output, {} bytes in total)".format(log_size)
    elif len(log_parts) > max_lines:
        logs += "\n\n(algochecker: truncated the rest of output, {} lines in total)".format(len(log_parts))

    return logs

# network

def create_network():
    ipam_config = docker_utils.create_ipam_config(
        pool_configs=[docker_utils.create_ipam_pool(
            subnet=NETWORKING_CONF['ipam']['subnet'],
            iprange=NETWORKING_CONF['ipam']['iprange']
        )]
    )

    network = docker_cli.create_network(
        name=network_name,
        driver=NETWORKING_CONF['network_driver'],
        ipam=ipam_config,
        internal=NETWORKING_CONF['internal']
    )

    return network.get('Id')

def get_endpoint_config(e_type):
    return docker_cli.create_networking_config({
        network_name: docker_cli.create_endpoint_config(
            ipv4_address=NETWORKING_CONF['endpoints']['client_ip' if e_type == 'client' else 'server_ip']
        )
    })

def check_leftover_networks():
    logging.info("Checking leftover networks...")
    try:
        networks = docker_cli.networks(names=["{}-{}".format(INSTANCE_NAME, NETWORKING_CONF['network_name'])])
        for network in networks:
            docker_cli.remove_network(network['Id'])

        if len(networks) > 0:
            logging.info("Removed {} leftover network(s)".format(len(networks)))
    except (APIError, KeyError):
        logging.error("Unable to check for leftover networks")

redpajama_set_name: RedPajamaGithub


text:
namespace v8 {
namespace internal {

class Isolate;

// ExternalReferenceTable is a helper class that defines the relationship
// between external references and their encodings. It is used to build
// hashmaps in ExternalReferenceEncoder and ExternalReferenceDecoder.
class ExternalReferenceTable {
 public:
  static ExternalReferenceTable* instance(Isolate* isolate);
  ~ExternalReferenceTable();

  uint32_t size() const { return static_cast<uint32_t>(refs_.length()); }
  Address address(uint32_t i) { return refs_[i].address; }
  const char* name(uint32_t i) { return refs_[i].name; }
  bool is_api_reference(uint32_t i) { return i >= api_refs_start_; }
  uint32_t num_api_references() { return size() - api_refs_start_; }

#ifdef DEBUG
  void increment_count(uint32_t i) { refs_[i].count++; }
  int count(uint32_t i) { return refs_[i].count; }
  void ResetCount();
  void PrintCount();
#endif  // DEBUG

  static const char* ResolveSymbol(void* address,
                                   std::vector<char**>* = nullptr);

 private:
  struct ExternalReferenceEntry {
    Address address;
    const char* name;
#ifdef DEBUG
    int count;
#endif  // DEBUG
  };

  explicit ExternalReferenceTable(Isolate* isolate);

  void Add(Address address, const char* name) {
#ifdef DEBUG
    ExternalReferenceEntry entry = {address, name, 0};
#else
    ExternalReferenceEntry entry = {address, name};
#endif  // DEBUG
    refs_.Add(entry);
  }

  void AddReferences(Isolate* isolate);
  void AddBuiltins(Isolate* isolate);
  void AddRuntimeFunctions(Isolate* isolate);
  void AddIsolateAddresses(Isolate* isolate);
  void AddAccessors(Isolate* isolate);
  void AddStubCache(Isolate* isolate);
  void AddApiReferences(Isolate* isolate);

  List<ExternalReferenceEntry> refs_;
#ifdef DEBUG
  std::vector<char**> symbol_tables_;
#endif
  uint32_t api_refs_start_;

  DISALLOW_COPY_AND_ASSIGN(ExternalReferenceTable);
};

}  // namespace internal
}  // namespace v8
#endif  // V8_EXTERNAL_REFERENCE_TABLE_H_


text:
We would love for you to contribute to Angular MDC and help make it even better than it is
today! As a contributor, here are the guidelines we would like you to follow:

 - [Code of Conduct](#coc)
 - [Found a Bug?](#found-bug)
 - [Submit an Issue](#submit-issue)
 - [Submit an Pull Request](#pull-req)
 - [Development Process](#dev)

##  Code of Conduct
Help us keep Angular MDC open and inclusive. Please read and follow our [Code of Conduct](https://github.com/trimox/angular-mdc-web/blob/master/CODE_OF_CONDUCT.md).

##  Found a Bug?
If you find a bug in the source code, you can help us by [submitting an issue](#submit-issue). Even better, you can
[submit a Pull Request](#pull-req) with a fix.

##  Submit an Issue
Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available.

We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs we will systematically ask you to provide a minimal reproduction scenario using https://codepen.io. Having a live, reproducible scenario gives us wealth of important information without going back & forth to you with additional questions like:

- version of Angular used
- version of Material Design Components used
- 3rd-party libraries and their versions
- and most importantly - a use-case that fails

You can file new issues by filling out our [new issue form](https://github.com/trimox/angular-mdc-web/issues/new).

##  Submit a Pull Request
When submitting PRs, make sure you're following our commit message conventions; our commit-msg hook should automatically enforce this. We also use [commitizen](https://www.npmjs.com/package/commitizen), which you can use to auto-format commit messages for you.

Commit message type must be one of the following:
* **feat**: A new feature
* **fix**: A bug fix
* **docs**: Documentation only changes
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
* **refactor**: A code change that neither fixes a bug nor adds a feature
* **perf**: A code change that improves performance
* **test**: Adding missing or correcting existing tests
* **chore**: Changes to the build process or auxiliary tools and libraries such as documentation generation

When submitting PRs for large changes, be sure to include an adequate background in the description so that reviewers of the PR know what the changes entail at a high-level, the motivations for making these changes, and what they affect.

##  Development Process
Check out our [Developer guide](https://github.com/trimox/angular-mdc-web/blob/master/docs/developer.md).


text:
package com.basho.riak.client.api.cap;

/**
 * Access the opaque Riak vector clock as either a String or array of bytes.
 *
 * @author Russel Brown <russelldb at basho dot com>
 * @since 1.0
 */
public interface VClock
{
    /**
     * Get the bytes that make up this VClock.
     * @return a copy of this vector clocks bytes
     */
    byte[] getBytes();

    /**
     * Get the string representation of this VClock.
     * @return a UTF-8 String of this vector clocks bytes
     */
    String asString();
}


text:
wintersmith-nunjucka
====================

A new [nunjucks](https://mozilla.github.io/nunjucks/) plugin for
[wintersmith](http://wintersmith.io/)

Forked from [wintersmith-nunjucks](https://github.com/jbuck/wintersmith-nunjucks/tree/880bfe7c83f6efcc192bdf570c391bc19ae283b3).

How to use
----------

1. Install globally using npm: `npm install -g wintersmith-nunjucka`
2. Add to your wintersmith config.json: `"plugins": ["wintersmith-nunjucka"]`
3. Create nunjucks templates ending in `.html`

How to add custom filters
---------------------------

From the nunjucks documentation at https://mozilla.github.io/nunjucks/templating.html#filters:

>Filters are essentially functions that can be applied to variables. They are called with a pipe operator (|) and can take arguments.

For more information on how to write customer Filters, take a look at the API documentation page at: http://mozilla.github.io/nunjucks/api#Registering-custom-filters

### To add a single file with multiple filter functions

Configure "nunjucks" like this in your wintersmith config file:

```javascript
"nunjucks": {
    "filterfile": "nunjucks.filters.js"
}
```

Then create a file called "nunjucks.filters.js" and place it in the same directory as your wintersmith config file with the following contents:

```javascript
// Contents of nunjucks.filters.js

function or(str, defaultValue) {
  return str || defaultValue;
}
exports.or = or;

exports.other = function(str, defaultValue) { return "something else"; };

// ... This is basically just a normal Node.js module that exports functions,
// however the functions all follow the Nunjucks filter function declaration style.
// See https://mozilla.github.io/nunjucks/api.html#custom-filters
```

Now you can use the `or` and `other` filters in your Nunjucks template files like this: `{{ mydata|or('default data value') }}`

### To add a single directory with multiple single-function files

Create a filters directory and put each filter function in its own file, stored in a filters directory. The filename has to be the name of the filter + '.js'.

Configure "nunjucks" like this in your wintersmith config file:

```javascript
"nunjucks": {
    "filterdir": "filters",
    "filters": ["myfirstfilter"]
}
```

Then create a file './filters/myfirstfilter.js' with something like the following contents:

```javascript
// Contents of myfirstfilter.js

module.exports = function(str, opt) {
  return "This filter adds something to your str: " + str;
}
```

and the `myfirstfilter` will be available in your Nunjucks templates for use like this: `{{ somedata|myfirstfilter }}`


text:
package org.onosproject.yms.app.ydt;

/**
 * Represents type of application, which is intended to maintain additional
 * information in YDT node.
 */
public enum AppType {

    /**
     * YANG tree builder application.
     */
    YTB,

    /**
     * YANG object builder application.
     */
    YOB
}


text:
/**
	The DomNodeBuilder kinds extend the DomNode component by providing methods
	for rendering.

	_Rendering_ refers to the process of generating actual DOM content as
	described by the component.

	These rendering methods are important for Controls, all of which descend from DomNodeBuilder.
	Note that a single control typically represents a tree of other controls. Rendering the
	root generally renders the entire tree.

	It's common to render an entire application into a document body like this:

		new MyApp().renderInto(document.body);

	On any DomNodeBuilder-derived object, you can set the canGenerate property to false to
	inhibit HTML generation.  It defaults to undefined.
*/
enyo.kind({
	name: "enyo.DomNodeBuilder",
	kind: enyo.DomNode,
	//* @protected
	published: {
		/** when false, content is treated as plain text. when true, it's treated as HTML -- only use when you trust the content
		    because you generated it yourself or because you've already stripped off potentially malicious tags */
		allowHtml: false,
		/** the content that will be put inside the DOM node created */
		content: ""
	},
	// if we've generated HTML or DOM
	generated: false,
	teardownRender: function() {
		this.node = null;
		this.generated = false;
	},
	hasNode: function() {
		// 'generated' is used to gate access to expensive findNodeById call
		return this.generated ? (this.node || this.findNodeById()) : null;
	},
	contentChanged: function() {
		if (!this.allowHtml) {
			this.content = enyo.string.escapeHtml(this.content);
		}
		this.renderContent();
	},
	/** Returns HTML that is rendered by this Builder. By default, returns <i>this.content</i>.*/
	// FIXME: propose calling this generateInnerHtml (it's not a pure getter, helpul to assert it's HTML)
	getInnerHtml: function() {
		return this.content;
	},
	/**
		Generates HTML that renders this node.
	*/
	generateHtml: function() {
		if (this.canGenerate === false) {
			return '';
		}
		// do this first in case content generation affects styles or attributes
		var c = this.getInnerHtml();
		var h = '<'
			+ this.nodeTag
			+ enyo.attributesToHtml(this.domAttributes);
		// FIXME: this.style vs this.domStyles?
		var s = (this.style ? this.style + ";" : "")
			+ enyo.stylesToHtml(this.domStyles);
		if (s) {
			h += ' style="' + s + '"';
		}
		// FIXME: there are other self-closing tags
		if (this.nodeTag == "img") {
			h += '/>';
		} else {
			h += '>'
				+ c
			+ '</' + this.nodeTag + '>';
		}
		// 'generated' is used to gate access to findNodeById in hasNode, which
		// is expensive.
		// NOTE: we typically use 'generated' to mean 'created in DOM'
		// which has not actually happened at this point.
		// We set this here to avoid having a separate walk of the
		// control tree. The contract is that insertion in DOM
		// will happen synchronously to generateHtml() and before
		// anybody should be calling hasNode().
		this.generated = true;
		return h;
	},
	//* @protected
	/** Renders our attributes to an existing node. Null-valued attributes are removed. */
	renderDomAttributes: function() {
		this.attributesToNode(this.domAttributes);
	},
	/** Renders our styles to an existing node. Ignores null-valued styles, and overwrites existing styles on the node (i.e. style.cssText is replaced). */
	renderDomStyles: function() {
		this.stylesToNode(this.domStyles);
	},
	/** Renders our content to the innerHTML of an existing node. */
	renderDomContent: function() {
		// FIXME: generates node references (old references are strictly invalid now)
		// so node invalidation methods are in the wrong place.
		this.node.innerHTML = this.getInnerHtml();
	},
	/** Renders attributes, styles, and content to an existing DOM node. */
	renderDom: function() {
		this.renderDomAttributes();
		this.renderDomStyles();
		this.renderDomContent();
	},
	/** Generates a DOM node and renders ourselves to it. If we already have a node, it's removed from DOM. The new node is returned without being inserted into DOM. */
	renderNode: function() {
		// NOTE: disallow rendering a node if there is no parent node, as we will
		// end up with an orphaned node. Although this is not obviously an error
		// state, too much of the rendering code assumes that nodes are
		// rendered in-order. Rendering a node before it's parent is therefore
		// a no-no.
		if (this.getParentNode()) {
			this.teardownRender();
			this.createNode();
			// FIXME: oddfellow, maybe roll into a createNode override
			this.generated = true;
			this.renderDom();
			this.rendered();
		}
	},
	//* @public
	//* Renders this object into DOM, generating a DOM node if needed.
	render: function() {
		if (this.hasNode()) {
			this.renderDom();
			this.rendered();
		} else {
			this.renderNode();
		}
	},
	//* @protected
	//* Renders the contents of this object into DOM, but is a no-op if this object has no DOM node.
	// FIXME: DEPRECATED: micro-optimization vs. render, not worth the confusion
	renderContent: function() {
		if (this.hasNode()) {
			this.renderDomContent();
			this.rendered();
		}
	},
	//* @public
	//* Renders this object into the existing DOM node referenced by _inParentNode_.
	renderInto: function(inParentNode) {
		// clean up render flags and memoizations
		this.teardownRender();
		// inParentNode can be a string id or a node reference
		var pn = enyo.byId(inParentNode);
		// 1: fit to nodes with non-auto height (NOTE: webkit td's have "0px" when unsized)
		var cs = window.getComputedStyle(pn, null);
		if (cs.height !== "auto" && cs.height !== "0px") {
			this.addClass(enyo.fittingClassName);
		}
		// 2: fit if rendering into body
		else if (pn == document.body) {
			this.addClass(enyo.fittingClassName);
		}
		// generate our HTML
		pn.innerHTML = this.generateHtml();
		// post-rendering tasks
		this.rendered();
		// return this to support method chaining
		return this;
	},
	/**
		Called whenever this object has been rendered. Override this method to perform
		tasks that require access to an actual DOM node.

			rendered: function() {
				this.inherited(arguments);
				if (this.hasNode()) {
					this.nodeHeight = this.node.offsetHeight;
				}
			}
	*/
	rendered: function() {
	},
	//* @public
	/** Shows this node (alias for _setShowing(true)_). */
	show: function() {
		this.setShowing(true);
	},
	/** Hides this node (alias for _setShowing(false)_). */
	hide: function() {
		this.setShowing(false);
	}
});

//* @protected
enyo.fittingClassName = "enyo-fit";

//* @protected
/**
	Converts a hash to an HTML string suitable for CSS styleText. Names are CSS property names (not camel-case).

		// returns 'position: relative; color: red'
		enyo.stylesToHtml({position: "relative", color: "red", "font-family": null})
*/
enyo.stylesToHtml = function(inStyles) {
	var n, v, h = '';
	for (n in inStyles) {
		v = inStyles[n];
		if ((v !== null) && (v !== undefined) && (v !== "")) {
			// remove underscores
			// FIXME: we used to use underscores for some
			// special style marking, removing as I believe
			// this is vestigial
			//n = n.replace(/_/g, "");
			h +=  n + ':' + v + ';';
		}
	}
	return h;
};

/**
	Converts a hash to an HTML string suitable for an HTML tag.

		// returns 'name="include" type="checkbox"'
		enyo.attributesToHtml({name: "include", type: "checkbox", "checked": null})
*/
enyo.attributesToHtml = function(inAttributes) {
	// inAttributes is a map of attribute names to values
	// names with null values are omitted from output
	var n, v, h = '';
	for (n in inAttributes) {
		v = inAttributes[n];
		if (v !== null && v !== "") {
			if (n == "className") {
				n = "class";
			}
			h += ' ' + n + '="' + enyo.string.escapeHtmlAttribute(v) + '"';
		}
	}
	return h;
};


text:
package doge;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.graphite.Graphite;
import com.codahale.metrics.graphite.GraphiteReporter;

import doge.domain.User;
import doge.domain.UserRepository;
import doge.photo.DogePhotoManipulator;

/**
 * Application configuration and main method.
 *
 * @author Josh Long
 * @author Phillip Webb
 */
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {

	@Bean
	WebMvcConfigurerAdapter mvcViewConfigurer() {
		return new WebMvcConfigurerAdapter() {
			@Override
			public void addViewControllers(ViewControllerRegistry registry) {
				registry.addViewController("/").setViewName("client");
				registry.addViewController("/monitor").setViewName("monitor");
			}
		};
	}

	@Bean
	DogePhotoManipulator dogePhotoManipulator() {
		DogePhotoManipulator dogePhotoManipulator = new DogePhotoManipulator();
		dogePhotoManipulator.addTextOverlay("Docker", "Compose", "microservice");
		dogePhotoManipulator.addTextOverlay("spring", "annotations", "boot");
		dogePhotoManipulator.addTextOverlay("code", "semicolonfree", "groovy");
		dogePhotoManipulator.addTextOverlay("clean", "juergenized", "spring");
		dogePhotoManipulator.addTextOverlay("js", "nonblocking", "wat");
		return dogePhotoManipulator;
	}

	@Bean
	InitializingBean populateTestData(UserRepository repository) {
		return () -> {
			repository.save(new User("philwebb", "Phil Webb"));
			repository.save(new User("joshlong", "Josh Long"));
			repository.findAll().forEach(System.err::println);
		};
	}

	@Configuration
	@EnableWebSocketMessageBroker
	static class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {

		@Override
		public void registerStompEndpoints(StompEndpointRegistry registry) {
			registry.addEndpoint("/doge").withSockJS();
		}

		@Override
		public void configureMessageBroker(MessageBrokerRegistry registry) {
			registry.enableSimpleBroker("/topic/");
		}

	}

	@Configuration
	static class MetricsConfiguration {

		private static final InetSocketAddress ADDRESS = new InetSocketAddress(
				"localhost", 2003);

		@Bean
		@Conditional(GraphiteCondition.class)
		public GraphiteReporter graphiteReporter(MetricRegistry registry) {
			GraphiteReporter reporter = GraphiteReporter.forRegistry(registry)
					.prefixedWith("doge.spring.io").build(new Graphite(ADDRESS));
			reporter.start(2, TimeUnit.SECONDS);
			return reporter;
		}

		public static class GraphiteCondition implements Condition {
			@Override
			public boolean matches(ConditionContext context,
					AnnotatedTypeMetadata metadata) {
				Socket socket = new Socket();
				try {
					socket.connect(ADDRESS);
					socket.close();
					return true;
				}
				catch (Exception ex) {
					return false;
				}
			}
		}
	}

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}


text:
LOCK TABLE categories WRITE;

SELECT @myRight := rgt_categories FROM categories
WHERE id_categories = :id;

UPDATE categories SET rgt_categories = rgt_categories + 2 WHERE rgt_categories >= @myRight;
UPDATE categories SET lft_categories = lft_categories + 2 WHERE lft_categories > @myRight;

INSERT INTO categories(name_categories, lft_categories, rgt_categories, enabled_categories) VALUES(:category_node, @myRight, @myRight + 1, :enabled_category);

UNLOCK TABLES;


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<client_updates>
    <client_update>
        <update_id>2</update_id>
        <update_type>PRINT</update_type>
        <quantity>500</quantity>
        <order_item_id>pg4f7969f8a4891</order_item_id>
        <comment>SHEET ID: '579468'; POSITION: '1'</comment>
        <replyUrl>http://printserver.com/api/client-updates</replyUrl>
        <timestamp>123456789</timestamp>
        <print_customer_invoice>123a33412fg11</print_customer_invoice>
        <misc>misc</misc>
        <tracking_number>1234lfdsaj23434</tracking_number>
        <weight>10.2</weight>
        <cost>11.1</cost>
        <print_provider_invoice>1236433fd1123rf</print_provider_invoice>
    </client_update>
</client_updates>


text:
package com.linecorp.armeria.server;

import static java.util.Objects.requireNonNull;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.linecorp.armeria.common.ServiceInvocationContext;
import com.linecorp.armeria.common.SessionProtocol;
import com.linecorp.armeria.server.ServiceCodec.DecodeResult;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.codec.http2.HttpConversionUtil;
import io.netty.util.AsciiString;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.collection.IntObjectHashMap;
import io.netty.util.collection.IntObjectMap;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;

final class HttpServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(HttpServerHandler.class);

    private static final AsciiString STREAM_ID = HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text();
    private static final AsciiString ERROR_CONTENT_TYPE = new AsciiString("text/plain; charset=UTF-8");

    private static final Pattern IGNORABLE_ERROR_MESSAGE = Pattern.compile(
            "^.*(?:connection.*(?:reset|closed|abort|broken)|broken.*pipe).*$", Pattern.CASE_INSENSITIVE);

    private static final ChannelFutureListener CLOSE = future -> {
        final Throwable cause = future.cause();
        final Channel ch = future.channel();
        if (cause != null) {
            logUnexpectedException(ch, cause);
        }
        ch.close();
    };

    private static final ChannelFutureListener CLOSE_ON_FAILURE = future -> {
        final Throwable cause = future.cause();
        if (cause != null) {
            final Channel ch = future.channel();
            logUnexpectedException(ch, cause);
            ch.close();
        }
    };

    private static final Exception SERVICE_NOT_FOUND = new ServiceNotFoundException();

    private final ServerConfig config;
    private SessionProtocol sessionProtocol;

    private boolean isReading;

    // When head-of-line blocking is enabled (i.e. HTTP/1 without extension),
    // We assign a monotonically increasing integer ('request sequence') to each received request, and
    // assign the integer of the same value when creating its response.

    private boolean useHeadOfLineBlocking = true;

    /**
     * The request sequence of the most recently received request.
     * Incremented when a new request is received.
     */
    private int reqSeq;
    /**
     * The request sequence of the request which was received least recently and has no corresponding response.
     */
    private int resSeq;

    /**
     * The map which maps a sequence number to its related pending response.
     */
    private final IntObjectMap<FullHttpResponse> pendingResponses = new IntObjectHashMap<>();

    private boolean handledLastRequest;

    HttpServerHandler(ServerConfig config, SessionProtocol sessionProtocol) {
        assert sessionProtocol == SessionProtocol.H1 ||
               sessionProtocol == SessionProtocol.H1C ||
               sessionProtocol == SessionProtocol.H2;

        this.config = requireNonNull(config, "config");
        this.sessionProtocol = requireNonNull(sessionProtocol, "protocol");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        isReading = true;

        if (msg instanceof Http2Settings) {
            logger.debug("{} HTTP/2 settings: {}", ctx.channel(), msg);

            useHeadOfLineBlocking = false;
            switch (sessionProtocol) {
            case H1:
                sessionProtocol = SessionProtocol.H2;
                break;
            case H1C:
                sessionProtocol = SessionProtocol.H2C;
                break;
            default:
                logger.warn("{} Duplicate upgrade? {}", ctx.channel(), sessionProtocol);
                break;
            }
            return;
        }

        final FullHttpRequest req = (FullHttpRequest) msg;
        boolean invoked = false;
        try {
            // Ignore the request received after the last request,
            // because we are going to close the connection after sending the last response.
            if (handledLastRequest) {
                return;
            }

            // If we received the message with keep-alive disabled,
            // we should not accept a request anymore.
            if (!HttpUtil.isKeepAlive(req)) {
                handledLastRequest = true;
            }

            final int reqSeq = this.reqSeq++;

            if (!req.decoderResult().isSuccess()) {
                respond(ctx, reqSeq, req, HttpResponseStatus.BAD_REQUEST, req.decoderResult().cause());
                return;
            }

            if (req.method() == HttpMethod.CONNECT) {
                respond(ctx, reqSeq, req, HttpResponseStatus.METHOD_NOT_ALLOWED);
                return;
            }

            final String hostname = hostname(req);
            final VirtualHost host = config.findVirtualHost(hostname);
            final String path = stripQuery(req.uri());

            // Find the service that matches the path.
            final MappedService service = host.findService(path);
            if (!service.isPresent()) {
                respond(ctx, reqSeq, req, HttpResponseStatus.NOT_FOUND);
                return;
            }

            // Decode the request and create a new invocation context from it.
            final String mappedPath = service.mappedPath();
            final ServiceCodec codec = service.codec();
            final Promise<Object> promise = ctx.executor().newPromise();
            final DecodeResult decodeResult = codec.decodeRequest(
                    ctx.channel(), sessionProtocol, hostname, path, mappedPath, req.content(), req, promise);

            switch (decodeResult.type()) {
            case SUCCESS: {
                final ServiceInvocationContext iCtx = decodeResult.invocationContext();
                final long timeoutMillis = config.requestTimeoutPolicy().timeout(iCtx);

                // Perform the actual invocation.
                ServiceInvocationContext.setCurrent(iCtx);
                try {
                    service.handler().invoke(iCtx, config.blockingTaskExecutor(), promise);
                    invoked = true;
                } finally {
                    ServiceInvocationContext.removeCurrent();
                }

                if (promise.isDone()) {
                    // If the invocation has been finished immediately,
                    // there's no need to schedule a timeout nor to add a listener to the promise.
                    handleInvocationResult(ctx, reqSeq, req, iCtx, codec, promise, null);
                } else {
                    final ScheduledFuture<?> timeoutFuture;
                    if (timeoutMillis > 0) {
                        timeoutFuture = ctx.executor().schedule(
                                () -> promise.tryFailure(new RequestTimeoutException(
                                        "request timed out after " + timeoutMillis + "ms: " + iCtx)),
                                timeoutMillis, TimeUnit.MILLISECONDS);
                    } else {
                        timeoutFuture = null;
                    }

                    promise.addListener((Future<Object> future) -> {
                        try {
                            handleInvocationResult(ctx, reqSeq, req, iCtx, codec, future, timeoutFuture);
                        } catch (Exception e) {
                            respond(ctx, reqSeq, req, HttpResponseStatus.INTERNAL_SERVER_ERROR, e);
                        }
                    });
                }
                break;
            }
            case FAILURE: {
                // Could not create an invocation context.
                final Object errorResponse = decodeResult.errorResponse();
                if (errorResponse instanceof FullHttpResponse) {
                    FullHttpResponse httpResponse = (FullHttpResponse) errorResponse;
                    promise.tryFailure(new RequestDecodeException(
                            decodeResult.cause(), httpResponse.content().readableBytes()));
                    respond(ctx, reqSeq, req, (FullHttpResponse) errorResponse);
                } else {
                    ReferenceCountUtil.safeRelease(errorResponse);
                    promise.tryFailure(new RequestDecodeException(decodeResult.cause(), 0));
                    respond(ctx, reqSeq, req, HttpResponseStatus.BAD_REQUEST, decodeResult.cause());
                }
                break;
            }
            case NOT_FOUND:
                // Turned out that the request wasn't accepted by the service.
                promise.tryFailure(SERVICE_NOT_FOUND);
                respond(ctx, reqSeq, req, HttpResponseStatus.NOT_FOUND);
                break;
            }
        } finally {
            // If invocation has been started successfully, handleInvocationResult() will call
            // ReferenceCountUtil.safeRelease() when the invocation is done.
            if (!invoked) {
                ReferenceCountUtil.safeRelease(req);
            }
        }
    }

    private static String hostname(FullHttpRequest req) {
        final String hostname = req.headers().getAsString(HttpHeaderNames.HOST);
        if (hostname == null) {
            return "";
        }

        final int hostnameColonIdx = hostname.lastIndexOf(':');
        if (hostnameColonIdx < 0) {
            return hostname;
        }

        return hostname.substring(0, hostnameColonIdx);
    }

    private static String stripQuery(String uri) {
        final int queryStart = uri.indexOf('?');
        return queryStart < 0 ? uri : uri.substring(0, queryStart);
    }

    private void handleInvocationResult(
            ChannelHandlerContext ctx, int reqSeq, FullHttpRequest req,
            ServiceInvocationContext iCtx, ServiceCodec codec, Future<Object> future,
            ScheduledFuture<?> timeoutFuture) throws Exception {

        // Release the original request which was retained before the invocation.
        ReferenceCountUtil.safeRelease(req);

        // Cancel the associated timeout, if any.
        if (timeoutFuture != null && !timeoutFuture.isDone()) {
            timeoutFuture.cancel(true);
        }

        if (future.isSuccess()) {
            final Object res = future.getNow();
            if (res instanceof FullHttpResponse) {
                respond(ctx, reqSeq, req, (FullHttpResponse) res);
            } else {
                final ByteBuf encoded = codec.encodeResponse(iCtx, res);
                respond(ctx, reqSeq, req, encoded);
            }
        } else {
            final Throwable cause = future.cause();
            final ByteBuf encoded = codec.encodeFailureResponse(iCtx, cause);
            if (codec.failureResponseFailsSession(iCtx)) {
                respond(ctx, reqSeq, req, toHttpResponseStatus(cause), encoded);
            } else {
                respond(ctx, reqSeq, req, encoded);
            }
        }
    }

    private static HttpResponseStatus toHttpResponseStatus(Throwable cause) {
        if (cause instanceof RequestTimeoutException) {
            return HttpResponseStatus.SERVICE_UNAVAILABLE;
        }

        return HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }

    private void respond(ChannelHandlerContext ctx, int reqSeq, FullHttpRequest req, ByteBuf content) {
        respond(ctx, reqSeq, req, HttpResponseStatus.OK, content);
    }

    private void respond(ChannelHandlerContext ctx, int reqSeq, FullHttpRequest req,
                         HttpResponseStatus status, ByteBuf content) {

        if (content == null) {
            content = Unpooled.EMPTY_BUFFER;
        }
        respond(ctx, reqSeq, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content));
    }

    private void respond(ChannelHandlerContext ctx, int reqSeq, FullHttpRequest req, HttpResponseStatus status) {
        if (status.code() < 400) {
            respond(ctx, reqSeq, req, status, Unpooled.EMPTY_BUFFER);
        } else {
            respond(ctx, reqSeq, req, status, (Throwable) null);
        }
    }

    private void respond(ChannelHandlerContext ctx, int reqSeq, FullHttpRequest req,
                         HttpResponseStatus status, Throwable cause) {

        assert status.code() >= 400;

        final String msg = errorMessage(status);
        if (cause != null) {
            logger.warn("{} Unexpected failure: {}", ctx.channel(), msg, cause);
        }

        final DefaultFullHttpResponse res = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(msg, StandardCharsets.UTF_8));
        res.headers().set(HttpHeaderNames.CONTENT_TYPE, ERROR_CONTENT_TYPE);

        respond(ctx, reqSeq, req, res);
    }

    private static String errorMessage(HttpResponseStatus status) {
        String reasonPhrase = status.reasonPhrase();
        StringBuilder buf = new StringBuilder(reasonPhrase.length() + 4);

        buf.append(status.code());
        buf.append(' ');
        buf.append(reasonPhrase);
        return buf.toString();
    }

    private void respond(ChannelHandlerContext ctx, int reqSeq, FullHttpRequest req, FullHttpResponse res) {
        String streamId = req.headers().getAsString(STREAM_ID);
        if (streamId != null) {
            // HTTP/2
            res.headers().set(STREAM_ID, streamId);
        }

        if (useHeadOfLineBlocking && !handlePendingResponses(ctx, reqSeq, res)) {
            return;
        }

        if (!handledLastRequest) {
            addKeepAliveHeaders(res);
            ctx.write(res).addListener(CLOSE_ON_FAILURE);
        } else {
            ctx.write(res).addListener(CLOSE);
        }

        if (!isReading) {
            ctx.flush();
        }
    }

    private boolean handlePendingResponses(ChannelHandlerContext ctx, int reqSeq, FullHttpResponse res) {
        final IntObjectMap<FullHttpResponse> pendingResponses = this.pendingResponses;
        while (reqSeq != resSeq) {
            FullHttpResponse pendingRes = pendingResponses.remove(resSeq);
            if (pendingRes == null) {
                // Stuck by head-of-line blocking; try again later.
                FullHttpResponse oldPendingRes = pendingResponses.put(reqSeq, res);
                if (oldPendingRes != null) {
                    // It is impossible to reach here as long as there are 2G+ pending responses.
                    logger.error("{} Orphaned pending response ({}): {}", reqSeq, oldPendingRes);
                    ReferenceCountUtil.safeRelease(oldPendingRes.release());
                }
                return false;
            }

            addKeepAliveHeaders(pendingRes);
            ctx.write(pendingRes);
            resSeq++;
        }

        // At this point, we have cleared all the pending responses. i.e. reqSeq = resSeq
        // Increment resSeq in preparation of the next request.
        resSeq++;
        return true;
    }

    private static void addKeepAliveHeaders(FullHttpResponse res) {
        // Add 'Content-Length' header only for a keep-alive connection.
        res.headers().set(HttpHeaderNames.CONTENT_LENGTH, res.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        res.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        isReading = false;
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logUnexpectedException(ctx.channel(), cause);
        ctx.close();
    }

    private static void logUnexpectedException(Channel ch, Throwable cause) {
        if (!logger.isWarnEnabled()) {
            return;
        }

        if (IGNORABLE_ERROR_MESSAGE.matcher(cause.getMessage()).find()) {
            return;
        }

        logger.warn("{} Unexpected exception:", ch, cause);
    }
}