text:
import inspect
import warnings
from functools import wraps

POSITIONAL_OR_KEYWORD = inspect.Parameter.POSITIONAL_OR_KEYWORD
KEYWORD_ONLY = inspect.Parameter.KEYWORD_ONLY
POSITIONAL_ONLY = inspect.Parameter.POSITIONAL_ONLY
EMPTY = inspect.Parameter.empty

def _deprecate_positional_args(version):
    """Decorator for methods that issues warnings for positional arguments

    Using the keyword-only argument syntax in pep 3102, arguments after the
    ``*`` will issue a warning when passed as a positional argument.

    Parameters
    ----------
    version : str
        version of the library when the positional arguments were deprecated

    Examples
    --------
    Deprecate passing `b` as positional argument:

    def func(a, b=1):
        pass

    @_deprecate_positional_args("v0.1.0")
    def func(a, *, b=2):
        pass

    func(1, 2)

    Notes
    -----
    This function is adapted from scikit-learn under the terms of its license. See
    licences/SCIKIT_LEARN_LICENSE
    """

    def _decorator(func):

        signature = inspect.signature(func)

        pos_or_kw_args = []
        kwonly_args = []
        for name, param in signature.parameters.items():
            if param.kind in (POSITIONAL_OR_KEYWORD, POSITIONAL_ONLY):
                pos_or_kw_args.append(name)
            elif param.kind == KEYWORD_ONLY:
                kwonly_args.append(name)
                if param.default is EMPTY:
                    # IMHO `def f(a, *, b):` does not make sense -> disallow it
                    # if removing this constraint -> need to add these to kwargs as well
                    raise TypeError("Keyword-only param without default disallowed.")

        @wraps(func)
        def inner(*args, **kwargs):

            name = func.__name__
            n_extra_args = len(args) - len(pos_or_kw_args)
            if n_extra_args > 0:

                extra_args = ", ".join(kwonly_args[:n_extra_args])

                warnings.warn(
                    f"Passing '{extra_args}' as positional argument(s) to {name} "
                    f"was deprecated in version {version} and will raise an error two "
                    "releases later. Please pass them as keyword arguments."
                    "",
                    FutureWarning,
                    stacklevel=2,
                )

                zip_args = zip(kwonly_args[:n_extra_args], args[-n_extra_args:])
                kwargs.update({name: arg for name, arg in zip_args})

                return func(*args[:-n_extra_args], **kwargs)

            return func(*args, **kwargs)

        return inner

    return _decorator


text:
Chat with websocket in Spring Boot Java and MongoDB

------

![diagrama_classes](Doc/ChatEado.0.0.1.jpg)

------

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
>
	<bean id="com.liferay.portal.portletcontainer.PortletWindowContextFactoryUtil" class="com.liferay.portal.portletcontainer.PortletWindowContextFactoryUtil">
		<property name="portletWindowContextFactory">
			<bean class="com.liferay.portal.portletcontainer.PortletWindowContextFactoryImpl" />
		</property>
	</bean>
	<bean id="com.liferay.portlet.PortletInstanceFactoryUtil" class="com.liferay.portlet.PortletInstanceFactoryUtil">
		<property name="portletInstanceFactory">
			<bean class="com.liferay.portlet.PortletInstanceFactoryImpl">
				<property name="internalInvokerPortletPrototype">
					<bean class="com.liferay.portlet.InvokerPortletImpl" />
				</property>
				<property name="sunInvokerPortletPrototype">
					<bean class="com.liferay.portal.portletcontainer.WindowInvoker" />
				</property>
			</bean>
		</property>
	</bean>
	<bean id="com.liferay.portlet.PortletPreferencesFactoryUtil" class="com.liferay.portlet.PortletPreferencesFactoryUtil">
		<property name="portletPreferencesFactory">
			<bean class="com.liferay.portlet.PortletPreferencesFactoryImpl" />
		</property>
	</bean>
	<bean id="com.liferay.portlet.PortletQNameUtil" class="com.liferay.portlet.PortletQNameUtil">
		<property name="portletQName">
			<bean class="com.liferay.portlet.PortletQNameImpl" />
		</property>
	</bean>
	<bean id="com.liferay.portlet.PortletURLFactoryUtil" class="com.liferay.portlet.PortletURLFactoryUtil">
		<property name="portletURLFactory">
			<bean class="com.liferay.portlet.PortletURLFactoryImpl" />
		</property>
	</bean>
</beans>


text:
import ply.lex as lex
from ply.lex import TOKEN

class STFLexer:
    def __init__(self):
        self.filename = ''
        # Keeps track of the last token returned from self.token()
        self.last_token = None
        self.errors_cnt = 0
        self.lexer = None

    def reset_lineno(self):
        """ Resets the internal line number counter of the lexer.
        """
        self.lexer.lineno = 1
        self.lexer.colno = 1

    def get_lineno(self):
        return self.lexer.lineno

    def get_colno(self):
        return self.lexer.colno

    # input() and token() are required when building parser from this lexer
    def input(self, text):
        self.lexer.input(text)

    def token(self):
        self.last_token = self.lexer.token()
        self.lexer.colno += 1
        # print self.last_token
        return self.last_token

    def find_tok_column(self, token):
        """ Find the column of the token in its line.
        """
        last_cr = self.lexer.lexdata.rfind('\n', 0, token.lexpos)
        return token.lexpos - last_cr

    # Build the lexer
    def build(self,**kwargs):
        self.lexer = lex.lex(module=self, **kwargs)
        # start the lexer looking for keywords
        self.lexer.begin('keyword')

    def _error(self, s, token):
        print(s, "in file", self.filename, "at line", self.get_lineno())
        self.errors_cnt += 1

    states = (
        # add a state to lex only keywords. By default, all keywords
        # are IDs. Fortunately, in the current grammar all keywords
        # are commands at the beginning of a line (except for packets and bytes!).
        ('keyword', 'inclusive'),
        # lex only packet data
        ('packetdata', 'exclusive'),
    )

    keywords = (
        'ADD',
        'ALL',
        'BYTES',
        'CHECK_COUNTER',
        'EXPECT',
        'NO_PACKET',
        'PACKET',
        'PACKETS',
        'REMOVE',
        'SETDEFAULT',
        'WAIT'
    )

    keywords_map = {}
    for keyword in keywords:
        if keyword == 'P4_PARSING_DONE':
            keywords_map[keyword] = keyword
        else:
            keywords_map[keyword.lower()] = keyword

    tokens = (
        'COLON',
        'COMMA',
        'DATA_DEC',
        'DATA_HEX',
        'DATA_TERN',
        'DOT',
        'ID',
        'INT_CONST_BIN',
        'INT_CONST_DEC',
        'TERN_CONST_HEX',
        'INT_CONST_HEX',
        'LBRACKET',
        'RBRACKET',
        'LPAREN',
        'RPAREN',
        'SLASH',
        'EQUAL',
        'EQEQ',
        'LE',
        'LEQ',
        'GT',
        'GEQ',
        'NEQ'
    ) + keywords

    t_ignore_COMMENT = r'\#.*'
    t_COLON     = r':'
    t_COMMA     = r','
    t_DOT       = r'\.'
    t_LBRACKET  = r'\['
    t_RBRACKET  = r'\]'
    t_LPAREN    = r'\('
    t_RPAREN    = r'\)'
    t_EQUAL     = r'='
    t_EQEQ      = r'=='
    t_NEQ       = r'!='
    t_LE        = r'<'
    t_LEQ       = r'<='
    t_GT        = r'>'
    t_GEQ       = r'>='
    t_SLASH     = r'/'

    # binary constants with ternary (don't care) bits
    binary_constant     = r'(0[bB][*01]+)'

    hex_prefix          = r'0[xX]'
    hex_digits          = r'[0-9a-fA-F]'
    hex_constant_body   = r'(' + hex_digits + r'+)'
    hex_constant        = r'(' + hex_prefix + hex_constant_body + r')'

    hex_tern            = r'([0-9a-fA-F\*]+)'
    hex_tern_constant   = r'(' + hex_prefix + hex_tern + r')'

    dec_constant        = r'([0-9]+)'

    identifier          = r'([a-z$A-Z_][a-z$A-Z_0-9]*)'

    @TOKEN(hex_tern_constant)
    def t_TERN_CONST_HEX(self, t):
        return t

    @TOKEN(hex_constant)
    def t_INT_CONST_HEX(self, t):
        return t

    @TOKEN(binary_constant)
    def t_INT_CONST_BIN(self, t):
        return t

    @TOKEN(dec_constant)
    def t_INT_CONST_DEC(self, t):
        return t

    # Identifiers in the keyword state should be checked against keywords.
    # In fact, it should be an error not to find a keyword!!
    # Throwing that as an error is left as an exercise for next time
    # when we read the ply manual.
    @TOKEN(identifier)
    def t_keyword_ID(self, t):
        typ = self.keywords_map.get(t.value.lower(), "ID")
        t.type = typ
        if typ == 'EXPECT' or typ == 'PACKET':
            t.lexer.begin('packetdata')
        else:
            t.lexer.begin('INITIAL')
        # print t, "pos:", t.lexpos, "col:", self.lexer.colno
        return t

    # All identifiers, including keywords are returned as ID outside
    # the keyword state, except for PACKETS and BYTES (counter types)
    @TOKEN(identifier)
    def t_ID(self, t):
        typ = self.keywords_map.get(t.value.lower(), "ID")
        if typ == 'BYTES' or typ == 'PACKETS':
            t.type = typ
        # print t, "pos:", t.lexpos, "col:", self.lexer.colno
        return t

    # Discard comments.
    def t_COMMENT(self, t):
        r'\#.*$'
        pass

    # Track line numbers.
    def t_newline(self, t):
        r'\n+'
        t.lexer.lineno += len(t.value)
        t.lexer.colno = 0
        t.lexer.begin('keyword')

    # Ignore spaces and tabs.
    t_ignore = ' \t'

    # Error handling.
    def t_error(self, t):
        self._error("Illegal character '%s'" % t.value[0], t)

    # PACKET DATA ------------------------------------------------------------

    @TOKEN(dec_constant)
    def t_packetdata_DATA_DEC(self, t):
        return t

    @TOKEN(hex_constant_body)
    def t_packetdata_DATA_HEX(self, t):
        return t

    def t_packetdata_DATA_TERN(self, t):
        r'\*'
        return t

    def t_packetdata_newline(self, t):
        r'\n+'
        t.lexer.lineno += len(t.value)
        t.lexer.begin('keyword')

    # Ignore spaces and tabs.
    t_packetdata_ignore = ' \t'

    # Error handling.
    def t_packetdata_error(self, t):
        self._error('invalid packet data', t)


text:
/*
 * This file is part of the Linalg project, a C++ interface to BLAS and LAPACK.
 *
 * The source-code is licensed under the terms of the MIT license, read LICENSE for more details.
 *
 * (c) 2011, 2012 Hannes Matuschek <hmatuschek at gmail dot com>
 */

#ifndef GEMVTEST_HH
#define GEMVTEST_HH

#include "unittest.hh"

class GEMVTest : public UnitTest::TestCase
{
public:
  void testSquareRowMajor();
  void testSquareColMajor();
  void testSquareTransposedRowMajor();
  void testSquareTransposedColMajor();

  void testRectRowMajor();
  void testRectTransposedRowMajor();
  void testRectColMajor();
  void testRectTransposedColMajor();

public:
  static UnitTest::TestSuite *suite();
};

#endif // GEMVTEST_HH


text:
/**
 * The approach here owes a LOT to https://github.com/substack/html-tokenize.
 */

var Transform = require('readable-stream').Transform;
var inherits = require('inherits');

inherits(Tokenize, Transform);
module.exports = Tokenize;

var codes = {
  fslash: '/'.charCodeAt(0),
  bslash: '\\'.charCodeAt(0),
  lparen: '('.charCodeAt(0),
  rparen: ')'.charCodeAt(0),
  lbrace: '{'.charCodeAt(0),
  rbrace: '}'.charCodeAt(0),
  lbrack: '['.charCodeAt(0),
  rbrack: ']'.charCodeAt(0),
  squote: '\''.charCodeAt(0),
  dquote: '"'.charCodeAt(0),
  at: '@'.charCodeAt(0),
  semi: ';'.charCodeAt(0),
  asterisk: '*'.charCodeAt(0)
}

var sequences = {
  comment_start: '/*',
  comment_end: '*/'
}

function charCodes(s) { return s.split('').map(function(c){return c.charCodeAt(0)}) }
var sets = {
  space: charCodes(' \t\n\r\f'),
  open_brackets: [codes.lparen, codes.lbrace, codes.lbrack],
  newline: charCodes('\n\r\f')
}

function Tokenize() {
  if (!(this instanceof Tokenize)) return new Tokenize;
  Transform.call(this);
  this._readableState.objectMode = true;
  this.state = [['root']];
  this._input = null; // buffer the input for read-ahead
  this._position = 0; // current position in this._input
  this.buffers = []; // collect data for current token
}

Tokenize.prototype._transform = function(buf, enc, next) {
  var input = this._input = this._input ? Buffer.concat([ this._input, buf ]) : buf;

  for(var i = this._position; i < input.length; i++) {
    var c = input[i];
    var state = this.state[this.state.length - 1][0],
      stateData = this.state[this.state.length - 1][1],
      end = null;

    // console.log(i, c, this.state);

    /* comments */
    if(i === input.length - 1
    && (('comment' === state && c === codes.asterisk)
        || c === codes.fslash)) {
      // need more data: save unprocessed input and bail out.
      this._input = this._input.slice(this._position);
      break;
    }
    else if('comment' !== state
    && c === codes.fslash && input[i+1] === codes.asterisk) {
      if('root' !== state) end = [].concat(state);
      i--; //backup to save the '/*' for the comment token.
      this.state.push(['comment'])
    }
    else if('comment' === state
    && c === codes.asterisk && input[i+1] === codes.fslash) {
      i++;
      end = this.state.pop();
    }
    /* strings */
    else if('string' === state
    && c === stateData) {
      this.state.pop();
    }
    else if('string' !== state
    && codes.squote === c || codes.dquote === c) {
      this.state.push(['string', c]);
    }
    /* brackets */
    // else if(codes.lparen === c) {
    //   this.state.push(['brackets', codes.rparen]);
    // }
    // else if(codes.lbrack === c) {
    //   this.state.push(['brackets', codes.rbrack]);
    // }
    // else if('brackets' === state
    // && c === stateData) {
    //   this.state.pop();
    // }
    /* rules */
    else if('rule_start' === state
    && c === codes.lbrace) {
      end = this.state.pop();
      this.state.push(['rule']);
    }
    else if('atrule_start' === state
    && c === codes.lbrace) {
      end = this.state.pop();
      this.state.push(['atrule']);
    }
    else if(('rule' === state || 'atrule' === state)
    && c === codes.rbrace) {
      end = this.state.pop();
      i--; // backup to save the ending curly brace for the rule_end token.
      this.state.push([ state + '_end' ]);
    }
    else if(('rule_end' === state || 'atrule_end' === state)
    && c === codes.rbrace) {
      end = this.state.pop();
    }
    else if('root' === state
    && c === codes.at) {
      end = ['space'];
      i--;
      this.state.push(['atrule_start'])
    }
    // rules can start from the root or nested within at-rules.
    else if(sets.space.indexOf(c) < 0)
    {
      if('root' === state) {
        end = ['root'];
        i--;
        this.state.push(['rule_start'])
      }
      else if('atrule' === state) {
        end = ['atrule'];
        i--;
        this.state.push(['rule_start']);
      }
    }

    if(end && i >= this._position) {
      var out;
      this.push(out = [end[0], input.slice(this._position, i+1)]);
      this._position = i+1;
      end = null;
    }
  }

  if(this._position < this._input.length) {
    this._input = this._input.slice(this._position);
    this._position = 0;
  }
  else {
    this._input = null;
    this._position = 0;
  }
  next();
}

Tokenize.prototype._flush = function (next) {
  if(this._input)
    this.push([this.state.pop()[0], this._input.slice(this._position)]);
  if(this.state.length !== 0 && this.state[0][0] === 'root') {
    console.warn("[css-tokenize] unfinished business", this.state);
  }
  this.push(null);
  next();
};


text:
<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Composer\Autoload\ClassLoader;

/**
 * @var ClassLoader $loader
 */
$loader = require __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/../src/DC3/InstawallBundle/utils/Instagram.class.php';

AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

/* $loader->add('NSM', __DIR__.'/../vendor/bundles'); */

return $loader;


text:
module.exports = function(RED) {
	function averageValues(that, values, keys) {
		//console.log("AVV: ", that.topicSuffix, values, keys, that.avgCount)
		if(that.avgCount == that.max-1) {
			that.avgCount=0;
			//Clone the last message as a template for the cascade.
			ret = JSON.parse(JSON.stringify(that.lastMsg));
			//Are we storing objects or simple values?
			if(keys) {
				for(k in keys) {
					for(var v=0; v<values.length; v++) {
						if(!values[v]) {
							console.log("Null values!!!", values);
							break;
						}
						that.averages[keys[k]] += values[v][keys[k]];
					}
					ret.payload[keys[k]] = parseFloat((that.averages[keys[k]] / values.length).toFixed(2));
					that.averages[keys[k]] = 0;
				}
				that.send([null, ret])
			} else {
				var sum  = values.reduce(function(a, b) {
					return a + b}, 0);
				var average  = parseFloat((sum /  values.length).toFixed(2));
				that.send([null, {payload: average, topic: that.lastMsg.topic}])
			}
		} else {
			that.avgCount++;
		}
	}
    function Journal(config) {
	var Fifo = require('fifo-array');
	var storage = require('node-persist');
        RED.nodes.createNode(this,config);
		this.max = config.max;
		this.name = config.name;
		this.storeName = config.storeName;
		this.persist = config.persist;
		this.persistInterval  = config.persistInterval;
		this.clocked = config.clocked;
		this.clockInterval = config.clockInterval;
		this.keysToAverage = config.keysToAverage ? config.keysToAverage.split(",") : null;
		this.topicSuffix = config.topicSuffix;
		this.lastMsg = {payload: null};
		this.avgCount = 0;
		if(this.keysToAverage) {
			this.averages = {}
			for(k in this.keysToAverage) {
				this.averages[this.keysToAverage[k]] = 0;
			}
		} else {
			this.averages = 0;
		}
        var node = this;
		storage.initSync({
			interval: 1000 * this.persistInterval
		});
		//Set up the clocked journalling if applicable
		if(this.clocked) {
			function journalClock(){
				//console.log("Clock!!!: ", new Date())
				if(this.lastMsg) {
					fifo.push(this.lastMsg.payload);
					node.send([{payload: fifo, topic: this.lastMsg.topic + this.topicSuffix}, null]);
					storage.setItem(this.storeName, fifo);
					that = this;
					averageValues(that, fifo, this.keysToAverage);
				}
			}
			this.clock = setInterval(journalClock.bind(this), this.clockInterval * 1000);
		}
		// Initialise the fifo with values from the persisted one.
        var fifo  = new Fifo(parseInt(node.max));
		//fifo.journalName = this.name;
		var oldFifo = storage.getItem(this.storeName);
		if(oldFifo) {
			oldFifo.map(function(obj){
				fifo.push(obj);
			})
		}
		var cnt = 0;
		this.on('close', function(){
			node.warn("Shutting down journal: ", this.name);
			clearInterval(this.clock);
		});
        this.on('input', function(msg) {
			this.lastMsg = msg;
			//console.log("MSG: ", msg)
			// If clocked, just store the last value.
			if(!this.clocked) {
				// Push the value on to the fifo
	            fifo.push(msg.payload);
				//output the fifo as a message.
				node.send([{payload: fifo, topic: msg.topic + this.topicSuffix}, null]);
				storage.setItem(this.storeName, fifo);
				averageValues(this, fifo, this.keysToAverage);
			}

        });
    }
    RED.nodes.registerType("journal",Journal);
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.ResourceManager.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Linq;
using Microsoft.Azure.Commands.Profile.Properties;

namespace Microsoft.Azure.Commands.Profile.AzureRmAlias
{
    /// <summary>
    /// Cmdlet to clear default options.
    /// </summary>
    [Cmdlet("Enable","AzureRmAlias", SupportsShouldProcess = true)]
    [OutputType(typeof(string))]
    public class EnableAzureRmAlias : AzureRMCmdlet
    {
        [Parameter(Mandatory = false, HelpMessage = "Indicates what scope aliases should be enabled for.  Default is 'Process'")]
        [ValidateSet("Process", "CurrentUser", "LocalMachine")]
        public string Scope { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "Indicates which modules to enable aliases for. If none are specified, default is all modules.")]
        public string[] Module { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "If specified, cmdlet will return all aliases enabled")]
        public SwitchParameter PassThru { get; set; }

        public override void ExecuteCmdlet()
        {
            Dictionary<string, object> mapping = Mappings.GetCaseInsensitiveMapping();

            // If no modules are specified, enable all aliases
            if (Module == null)
            {
                EnableLocalAliases(mapping.Keys.ToArray(), mapping);
            }
            else
            {
                EnableLocalAliases(Module, mapping);
            }

            // Set path to user profile based on the Scope
            string userprofile = AliasHelper.GetProfilePath(Scope, SessionState);

            if (Scope != null && (Scope.Equals("CurrentUser") || Scope.Equals("LocalMachine")))
            {
                var helper = new AliasHelper();
                helper.AddAliasesToProfile(userprofile, Module, mapping);
            }
        }

        public void EnableLocalAliases(string[] modulesToEnable, Dictionary<string, object> mapping)
        {
            foreach (var module in modulesToEnable)
            {
                if (ShouldProcess(module, Resources.AddAlias))
                {
                    if (mapping.ContainsKey(module))
                    {
                        Dictionary<string, string> modulemapping =
                            (Dictionary<string, string>)JsonConvert.DeserializeObject(mapping[module].ToString(), typeof(Dictionary<string, string>));
                        foreach (var name in modulemapping.Keys)
                        {
                            // For every alias, add a pairing in the Alias provider
                            SessionState.PSVariable.Set("Alias:" + modulemapping[name], name);
                            if (PassThru)
                            {
                                WriteObject(modulemapping[name] + " : " + name);
                            }
                        }
                    }
                    else
                    {
                        WriteWarning("Module '" + module + "' is not a valid Az module.");
                    }
                }
            }
        }
    }
}


text:
#include "GrVkGpuCommandBuffer.h"

#include "GrBackendDrawableInfo.h"
#include "GrContextPriv.h"
#include "GrFixedClip.h"
#include "GrMesh.h"
#include "GrOpFlushState.h"
#include "GrPipeline.h"
#include "GrRenderTargetPriv.h"
#include "GrTexturePriv.h"
#include "GrVkCommandBuffer.h"
#include "GrVkCommandPool.h"
#include "GrVkGpu.h"
#include "GrVkPipeline.h"
#include "GrVkRenderPass.h"
#include "GrVkRenderTarget.h"
#include "GrVkResourceProvider.h"
#include "GrVkSemaphore.h"
#include "GrVkTexture.h"
#include "SkDrawable.h"
#include "SkRect.h"

void GrVkGpuTextureCommandBuffer::copy(GrSurface* src, GrSurfaceOrigin srcOrigin,
                                       const SkIRect& srcRect, const SkIPoint& dstPoint) {
    fCopies.emplace_back(src, srcOrigin, srcRect, dstPoint);
}

void GrVkGpuTextureCommandBuffer::insertEventMarker(const char* msg) {
    // TODO: does Vulkan have a correlate?
}

void GrVkGpuTextureCommandBuffer::submit() {
    for (int i = 0; i < fCopies.count(); ++i) {
        CopyInfo& copyInfo = fCopies[i];
        fGpu->copySurface(fTexture, fOrigin, copyInfo.fSrc.get(), copyInfo.fSrcOrigin,
                          copyInfo.fSrcRect, copyInfo.fDstPoint);
    }
}

GrVkGpuTextureCommandBuffer::~GrVkGpuTextureCommandBuffer() {}

////////////////////////////////////////////////////////////////////////////////

void get_vk_load_store_ops(GrLoadOp loadOpIn, GrStoreOp storeOpIn,
                           VkAttachmentLoadOp* loadOp, VkAttachmentStoreOp* storeOp) {
    switch (loadOpIn) {
        case GrLoadOp::kLoad:
            *loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
            break;
        case GrLoadOp::kClear:
            *loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
            break;
        case GrLoadOp::kDiscard:
            *loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
            break;
        default:
            SK_ABORT("Invalid LoadOp");
            *loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
    }

    switch (storeOpIn) {
        case GrStoreOp::kStore:
            *storeOp = VK_ATTACHMENT_STORE_OP_STORE;
            break;
        case GrStoreOp::kDiscard:
            *storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
            break;
        default:
            SK_ABORT("Invalid StoreOp");
            *storeOp = VK_ATTACHMENT_STORE_OP_STORE;
    }
}

GrVkGpuRTCommandBuffer::GrVkGpuRTCommandBuffer(GrVkGpu* gpu)
        : fCurrentCmdInfo(-1)
        , fGpu(gpu)
        , fLastPipelineState(nullptr) {
}

void GrVkGpuRTCommandBuffer::init() {
    GrVkRenderPass::LoadStoreOps vkColorOps(fVkColorLoadOp, fVkColorStoreOp);
    GrVkRenderPass::LoadStoreOps vkStencilOps(fVkStencilLoadOp, fVkStencilStoreOp);

    CommandBufferInfo& cbInfo = fCommandBufferInfos.push_back();
    SkASSERT(fCommandBufferInfos.count() == 1);
    fCurrentCmdInfo = 0;

    GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(fRenderTarget);
    const GrVkResourceProvider::CompatibleRPHandle& rpHandle = vkRT->compatibleRenderPassHandle();
    if (rpHandle.isValid()) {
        cbInfo.fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle,
                                                                     vkColorOps,
                                                                     vkStencilOps);
    } else {
        cbInfo.fRenderPass = fGpu->resourceProvider().findRenderPass(*vkRT,
                                                                     vkColorOps,
                                                                     vkStencilOps);
    }

    cbInfo.fColorClearValue.color.float32[0] = fClearColor[0];
    cbInfo.fColorClearValue.color.float32[1] = fClearColor[1];
    cbInfo.fColorClearValue.color.float32[2] = fClearColor[2];
    cbInfo.fColorClearValue.color.float32[3] = fClearColor[3];

    if (VK_ATTACHMENT_LOAD_OP_CLEAR == fVkColorLoadOp) {
        cbInfo.fBounds = SkRect::MakeWH(vkRT->width(), vkRT->height());
    } else {
        cbInfo.fBounds.setEmpty();
    }

    if (VK_ATTACHMENT_LOAD_OP_CLEAR == fVkColorLoadOp) {
        cbInfo.fLoadStoreState = LoadStoreState::kStartsWithClear;
    } else if (VK_ATTACHMENT_LOAD_OP_LOAD == fVkColorLoadOp &&
               VK_ATTACHMENT_STORE_OP_STORE == fVkColorStoreOp) {
        cbInfo.fLoadStoreState = LoadStoreState::kLoadAndStore;
    } else if (VK_ATTACHMENT_LOAD_OP_DONT_CARE == fVkColorLoadOp) {
        cbInfo.fLoadStoreState = LoadStoreState::kStartsWithDiscard;
    }

    cbInfo.fCommandBuffers.push_back(fGpu->cmdPool()->findOrCreateSecondaryCommandBuffer(fGpu));
    cbInfo.currentCmdBuf()->begin(fGpu, vkRT->framebuffer(), cbInfo.fRenderPass);
}

void GrVkGpuRTCommandBuffer::initWrapped() {
    CommandBufferInfo& cbInfo = fCommandBufferInfos.push_back();
    SkASSERT(fCommandBufferInfos.count() == 1);
    fCurrentCmdInfo = 0;

    GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(fRenderTarget);
    SkASSERT(vkRT->wrapsSecondaryCommandBuffer());
    cbInfo.fRenderPass = vkRT->externalRenderPass();
    cbInfo.fRenderPass->ref();

    cbInfo.fBounds.setEmpty();
    cbInfo.fCommandBuffers.push_back(vkRT->getExternalSecondaryCommandBuffer());
    cbInfo.fCommandBuffers[0]->ref();
    cbInfo.currentCmdBuf()->begin(fGpu, nullptr, cbInfo.fRenderPass);
}

GrVkGpuRTCommandBuffer::~GrVkGpuRTCommandBuffer() {
    this->reset();
}

GrGpu* GrVkGpuRTCommandBuffer::gpu() { return fGpu; }

void GrVkGpuRTCommandBuffer::end() {
    if (fCurrentCmdInfo >= 0) {
        fCommandBufferInfos[fCurrentCmdInfo].currentCmdBuf()->end(fGpu);
    }
}

void GrVkGpuRTCommandBuffer::submit() {
    if (!fRenderTarget) {
        return;
    }

    GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(fRenderTarget);
    GrVkImage* targetImage = vkRT->msaaImage() ? vkRT->msaaImage() : vkRT;
    GrStencilAttachment* stencil = fRenderTarget->renderTargetPriv().getStencilAttachment();

    for (int i = 0; i < fCommandBufferInfos.count(); ++i) {
        CommandBufferInfo& cbInfo = fCommandBufferInfos[i];

        for (int j = 0; j < cbInfo.fPreDrawUploads.count(); ++j) {
            InlineUploadInfo& iuInfo = cbInfo.fPreDrawUploads[j];
            iuInfo.fFlushState->doUpload(iuInfo.fUpload);
        }

        for (int j = 0; j < cbInfo.fPreCopies.count(); ++j) {
            CopyInfo& copyInfo = cbInfo.fPreCopies[j];
            fGpu->copySurface(fRenderTarget, fOrigin, copyInfo.fSrc.get(), copyInfo.fSrcOrigin,
                              copyInfo.fSrcRect, copyInfo.fDstPoint, copyInfo.fShouldDiscardDst);
        }

        // TODO: Many things create a scratch texture which adds the discard immediately, but then
        // don't draw to it right away. This causes the discard to be ignored and we get yelled at
        // for loading uninitialized data. However, once MDB lands with reordering, the discard will
        // get reordered with the rest of the draw commands and we can remove the discard check.
        if (cbInfo.fIsEmpty &&
            cbInfo.fLoadStoreState != LoadStoreState::kStartsWithClear &&
            cbInfo.fLoadStoreState != LoadStoreState::kStartsWithDiscard) {
            // We have sumbitted no actual draw commands to the command buffer and we are not using
            // the render pass to do a clear so there is no need to submit anything.
            continue;
        }

        // We don't want to actually submit the secondary command buffer if it is wrapped.
        if (this->wrapsSecondaryCommandBuffer()) {
            // If we have any sampled images set their layout now.
            for (int j = 0; j < cbInfo.fSampledTextures.count(); ++j) {
                cbInfo.fSampledTextures[j]->setImageLayout(
                        fGpu, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT,
                        VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, false);
            }

            // There should have only been one secondary command buffer in the wrapped case so it is
            // safe to just return here.
            SkASSERT(fCommandBufferInfos.count() == 1);
            return;
        }

        // Make sure if we only have a discard load that we execute the discard on the whole image.
        // TODO: Once we improve our tracking of discards so that we never end up flushing a discard
        // call with no actually ops, remove this.
        if (cbInfo.fIsEmpty && cbInfo.fLoadStoreState == LoadStoreState::kStartsWithDiscard) {
            cbInfo.fBounds = SkRect::MakeWH(vkRT->width(), vkRT->height());
        }

        if (cbInfo.fBounds.intersect(0, 0,
                                     SkIntToScalar(fRenderTarget->width()),
                                     SkIntToScalar(fRenderTarget->height()))) {
            // Make sure we do the following layout changes after all copies, uploads, or any other
            // pre-work is done since we may change the layouts in the pre-work. Also since the
            // draws will be submitted in different render passes, we need to guard againts write
            // and write issues.

            // Change layout of our render target so it can be used as the color attachment.
            // TODO: If we know that we will never be blending or loading the attachment we could
            // drop the VK_ACCESS_COLOR_ATTACHMENT_READ_BIT.
            targetImage->setImageLayout(fGpu,
                                        VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
                                        VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |
                                        VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
                                        VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
                                        false);

            // If we are using a stencil attachment we also need to update its layout
            if (stencil) {
                GrVkStencilAttachment* vkStencil = (GrVkStencilAttachment*)stencil;
                // We need the write and read access bits since we may load and store the stencil.
                // The initial load happens in the VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT so we
                // wait there.
                vkStencil->setImageLayout(fGpu,
                                          VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
                                          VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
                                          VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT,
                                          VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
                                          false);
            }

            // If we have any sampled images set their layout now.
            for (int j = 0; j < cbInfo.fSampledTextures.count(); ++j) {
                cbInfo.fSampledTextures[j]->setImageLayout(
                        fGpu, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT,
                        VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, false);
            }

            SkIRect iBounds;
            cbInfo.fBounds.roundOut(&iBounds);

            fGpu->submitSecondaryCommandBuffer(cbInfo.fCommandBuffers, cbInfo.fRenderPass,
                                               &cbInfo.fColorClearValue, vkRT, fOrigin, iBounds);
        }
    }
}

void GrVkGpuRTCommandBuffer::set(GrRenderTarget* rt, GrSurfaceOrigin origin,
                                 const GrGpuRTCommandBuffer::LoadAndStoreInfo& colorInfo,
                                 const GrGpuRTCommandBuffer::StencilLoadAndStoreInfo& stencilInfo) {
    SkASSERT(!fRenderTarget);
    SkASSERT(fCommandBufferInfos.empty());
    SkASSERT(-1 == fCurrentCmdInfo);
    SkASSERT(fGpu == rt->getContext()->priv().getGpu());
    SkASSERT(!fLastPipelineState);

    this->INHERITED::set(rt, origin);

    if (this->wrapsSecondaryCommandBuffer()) {
        this->initWrapped();
        return;
    }

    fClearColor = colorInfo.fClearColor;

    get_vk_load_store_ops(colorInfo.fLoadOp, colorInfo.fStoreOp,
                          &fVkColorLoadOp, &fVkColorStoreOp);

    get_vk_load_store_ops(stencilInfo.fLoadOp, stencilInfo.fStoreOp,
                          &fVkStencilLoadOp, &fVkStencilStoreOp);

    this->init();
}

void GrVkGpuRTCommandBuffer::reset() {
    for (int i = 0; i < fCommandBufferInfos.count(); ++i) {
        CommandBufferInfo& cbInfo = fCommandBufferInfos[i];
        for (int j = 0; j < cbInfo.fCommandBuffers.count(); ++j) {
            cbInfo.fCommandBuffers[j]->unref(fGpu);
        }
        cbInfo.fRenderPass->unref(fGpu);
    }
    fCommandBufferInfos.reset();

    fCurrentCmdInfo = -1;

    fLastPipelineState = nullptr;
    fRenderTarget = nullptr;
}

bool GrVkGpuRTCommandBuffer::wrapsSecondaryCommandBuffer() const {
    GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(fRenderTarget);
    return vkRT->wrapsSecondaryCommandBuffer();
}

////////////////////////////////////////////////////////////////////////////////

void GrVkGpuRTCommandBuffer::discard() {
    GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(fRenderTarget);

    CommandBufferInfo& cbInfo = fCommandBufferInfos[fCurrentCmdInfo];
    if (cbInfo.fIsEmpty) {
        // Change the render pass to do a don't-care load for both color & stencil
        GrVkRenderPass::LoadStoreOps vkColorOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE,
                                                VK_ATTACHMENT_STORE_OP_STORE);
        GrVkRenderPass::LoadStoreOps vkStencilOps(VK_ATTACHMENT_LOAD_OP_DONT_CARE,
                                                  VK_ATTACHMENT_STORE_OP_STORE);

        const GrVkRenderPass* oldRP = cbInfo.fRenderPass;

        const GrVkResourceProvider::CompatibleRPHandle& rpHandle =
            vkRT->compatibleRenderPassHandle();
        if (rpHandle.isValid()) {
            cbInfo.fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle,
                                                                         vkColorOps,
                                                                         vkStencilOps);
        } else {
            cbInfo.fRenderPass = fGpu->resourceProvider().findRenderPass(*vkRT,
                                                                         vkColorOps,
                                                                         vkStencilOps);
        }

        SkASSERT(cbInfo.fRenderPass->isCompatible(*oldRP));
        oldRP->unref(fGpu);
        cbInfo.fBounds.join(fRenderTarget->getBoundsRect());
        cbInfo.fLoadStoreState = LoadStoreState::kStartsWithDiscard;
        // If we are going to discard the whole render target then the results of any copies we did
        // immediately before to the target won't matter, so just drop them.
        cbInfo.fPreCopies.reset();
    }
}

void GrVkGpuRTCommandBuffer::insertEventMarker(const char* msg) {
    // TODO: does Vulkan have a correlate?
}

void GrVkGpuRTCommandBuffer::onClearStencilClip(const GrFixedClip& clip, bool insideStencilMask) {
    SkASSERT(!clip.hasWindowRectangles());

    CommandBufferInfo& cbInfo = fCommandBufferInfos[fCurrentCmdInfo];

    GrStencilAttachment* sb = fRenderTarget->renderTargetPriv().getStencilAttachment();
    // this should only be called internally when we know we have a
    // stencil buffer.
    SkASSERT(sb);
    int stencilBitCount = sb->bits();

    // The contract with the callers does not guarantee that we preserve all bits in the stencil
    // during this clear. Thus we will clear the entire stencil to the desired value.

    VkClearDepthStencilValue vkStencilColor;
    memset(&vkStencilColor, 0, sizeof(VkClearDepthStencilValue));
    if (insideStencilMask) {
        vkStencilColor.stencil = (1 << (stencilBitCount - 1));
    } else {
        vkStencilColor.stencil = 0;
    }

    VkClearRect clearRect;
    // Flip rect if necessary
    SkIRect vkRect;
    if (!clip.scissorEnabled()) {
        vkRect.setXYWH(0, 0, fRenderTarget->width(), fRenderTarget->height());
    } else if (kBottomLeft_GrSurfaceOrigin != fOrigin) {
        vkRect = clip.scissorRect();
    } else {
        const SkIRect& scissor = clip.scissorRect();
        vkRect.setLTRB(scissor.fLeft, fRenderTarget->height() - scissor.fBottom,
                       scissor.fRight, fRenderTarget->height() - scissor.fTop);
    }

    clearRect.rect.offset = { vkRect.fLeft, vkRect.fTop };
    clearRect.rect.extent = { (uint32_t)vkRect.width(), (uint32_t)vkRect.height() };

    clearRect.baseArrayLayer = 0;
    clearRect.layerCount = 1;

    uint32_t stencilIndex;
    SkAssertResult(cbInfo.fRenderPass->stencilAttachmentIndex(&stencilIndex));

    VkClearAttachment attachment;
    attachment.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
    attachment.colorAttachment = 0; // this value shouldn't matter
    attachment.clearValue.depthStencil = vkStencilColor;

    cbInfo.currentCmdBuf()->clearAttachments(fGpu, 1, &attachment, 1, &clearRect);
    cbInfo.fIsEmpty = false;

    // Update command buffer bounds
    if (!clip.scissorEnabled()) {
        cbInfo.fBounds.join(fRenderTarget->getBoundsRect());
    } else {
        cbInfo.fBounds.join(SkRect::Make(clip.scissorRect()));
    }
}

void GrVkGpuRTCommandBuffer::onClear(const GrFixedClip& clip, const SkPMColor4f& color) {
    GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(fRenderTarget);

    // parent class should never let us get here with no RT
    SkASSERT(!clip.hasWindowRectangles());

    CommandBufferInfo& cbInfo = fCommandBufferInfos[fCurrentCmdInfo];

    VkClearColorValue vkColor = {{color.fR, color.fG, color.fB, color.fA}};

    if (cbInfo.fIsEmpty && !clip.scissorEnabled()) {
        // Change the render pass to do a clear load
        GrVkRenderPass::LoadStoreOps vkColorOps(VK_ATTACHMENT_LOAD_OP_CLEAR,
                                                VK_ATTACHMENT_STORE_OP_STORE);
        // Preserve the stencil buffer's load & store settings
        GrVkRenderPass::LoadStoreOps vkStencilOps(fVkStencilLoadOp, fVkStencilStoreOp);

        const GrVkRenderPass* oldRP = cbInfo.fRenderPass;

        const GrVkResourceProvider::CompatibleRPHandle& rpHandle =
            vkRT->compatibleRenderPassHandle();
        if (rpHandle.isValid()) {
            cbInfo.fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle,
                                                                         vkColorOps,
                                                                         vkStencilOps);
        } else {
            cbInfo.fRenderPass = fGpu->resourceProvider().findRenderPass(*vkRT,
                                                                         vkColorOps,
                                                                         vkStencilOps);
        }

        SkASSERT(cbInfo.fRenderPass->isCompatible(*oldRP));
        oldRP->unref(fGpu);

        cbInfo.fColorClearValue.color = {{color.fR, color.fG, color.fB, color.fA}};
        cbInfo.fLoadStoreState = LoadStoreState::kStartsWithClear;
        // If we are going to clear the whole render target then the results of any copies we did
        // immediately before to the target won't matter, so just drop them.
        cbInfo.fPreCopies.reset();

        // Update command buffer bounds
        cbInfo.fBounds.join(fRenderTarget->getBoundsRect());
        return;
    }

    // We always do a sub rect clear with clearAttachments since we are inside a render pass
    VkClearRect clearRect;
    // Flip rect if necessary
    SkIRect vkRect;
    if (!clip.scissorEnabled()) {
        vkRect.setXYWH(0, 0, fRenderTarget->width(), fRenderTarget->height());
    } else if (kBottomLeft_GrSurfaceOrigin != fOrigin) {
        vkRect = clip.scissorRect();
    } else {
        const SkIRect& scissor = clip.scissorRect();
        vkRect.setLTRB(scissor.fLeft, fRenderTarget->height() - scissor.fBottom,
                       scissor.fRight, fRenderTarget->height() - scissor.fTop);
    }
    clearRect.rect.offset = { vkRect.fLeft, vkRect.fTop };
    clearRect.rect.extent = { (uint32_t)vkRect.width(), (uint32_t)vkRect.height() };
    clearRect.baseArrayLayer = 0;
    clearRect.layerCount = 1;

    uint32_t colorIndex;
    SkAssertResult(cbInfo.fRenderPass->colorAttachmentIndex(&colorIndex));

    VkClearAttachment attachment;
    attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
    attachment.colorAttachment = colorIndex;
    attachment.clearValue.color = vkColor;

    cbInfo.currentCmdBuf()->clearAttachments(fGpu, 1, &attachment, 1, &clearRect);
    cbInfo.fIsEmpty = false;

    // Update command buffer bounds
    if (!clip.scissorEnabled()) {
        cbInfo.fBounds.join(fRenderTarget->getBoundsRect());
    } else {
        cbInfo.fBounds.join(SkRect::Make(clip.scissorRect()));
    }
    return;
}

////////////////////////////////////////////////////////////////////////////////

void GrVkGpuRTCommandBuffer::addAdditionalCommandBuffer() {
    GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(fRenderTarget);

    CommandBufferInfo& cbInfo = fCommandBufferInfos[fCurrentCmdInfo];
    cbInfo.currentCmdBuf()->end(fGpu);
    cbInfo.fCommandBuffers.push_back(fGpu->cmdPool()->findOrCreateSecondaryCommandBuffer(fGpu));
    cbInfo.currentCmdBuf()->begin(fGpu, vkRT->framebuffer(), cbInfo.fRenderPass);
}

void GrVkGpuRTCommandBuffer::addAdditionalRenderPass() {
    GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(fRenderTarget);

    fCommandBufferInfos[fCurrentCmdInfo].currentCmdBuf()->end(fGpu);

    CommandBufferInfo& cbInfo = fCommandBufferInfos.push_back();
    fCurrentCmdInfo++;

    GrVkRenderPass::LoadStoreOps vkColorOps(VK_ATTACHMENT_LOAD_OP_LOAD,
                                            VK_ATTACHMENT_STORE_OP_STORE);
    GrVkRenderPass::LoadStoreOps vkStencilOps(VK_ATTACHMENT_LOAD_OP_LOAD,
                                              VK_ATTACHMENT_STORE_OP_STORE);

    const GrVkResourceProvider::CompatibleRPHandle& rpHandle =
            vkRT->compatibleRenderPassHandle();
    if (rpHandle.isValid()) {
        cbInfo.fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle,
                                                                     vkColorOps,
                                                                     vkStencilOps);
    } else {
        cbInfo.fRenderPass = fGpu->resourceProvider().findRenderPass(*vkRT,
                                                                     vkColorOps,
                                                                     vkStencilOps);
    }
    cbInfo.fLoadStoreState = LoadStoreState::kLoadAndStore;

    cbInfo.fCommandBuffers.push_back(fGpu->cmdPool()->findOrCreateSecondaryCommandBuffer(fGpu));
    // It shouldn't matter what we set the clear color to here since we will assume loading of the
    // attachment.
    memset(&cbInfo.fColorClearValue, 0, sizeof(VkClearValue));
    cbInfo.fBounds.setEmpty();

    cbInfo.currentCmdBuf()->begin(fGpu, vkRT->framebuffer(), cbInfo.fRenderPass);
}

void GrVkGpuRTCommandBuffer::inlineUpload(GrOpFlushState* state,
                                          GrDeferredTextureUploadFn& upload) {
    if (!fCommandBufferInfos[fCurrentCmdInfo].fIsEmpty) {
        this->addAdditionalRenderPass();
    }
    fCommandBufferInfos[fCurrentCmdInfo].fPreDrawUploads.emplace_back(state, upload);
}

void GrVkGpuRTCommandBuffer::copy(GrSurface* src, GrSurfaceOrigin srcOrigin, const SkIRect& srcRect,
                                  const SkIPoint& dstPoint) {
    CommandBufferInfo& cbInfo = fCommandBufferInfos[fCurrentCmdInfo];
    if (!cbInfo.fIsEmpty || LoadStoreState::kStartsWithClear == cbInfo.fLoadStoreState) {
        this->addAdditionalRenderPass();
    }

    fCommandBufferInfos[fCurrentCmdInfo].fPreCopies.emplace_back(
            src, srcOrigin, srcRect, dstPoint,
            LoadStoreState::kStartsWithDiscard == cbInfo.fLoadStoreState);

    if (LoadStoreState::kLoadAndStore != cbInfo.fLoadStoreState) {
        // Change the render pass to do a load and store so we don't lose the results of our copy
        GrVkRenderPass::LoadStoreOps vkColorOps(VK_ATTACHMENT_LOAD_OP_LOAD,
                                                VK_ATTACHMENT_STORE_OP_STORE);
        GrVkRenderPass::LoadStoreOps vkStencilOps(VK_ATTACHMENT_LOAD_OP_LOAD,
                                                  VK_ATTACHMENT_STORE_OP_STORE);

        const GrVkRenderPass* oldRP = cbInfo.fRenderPass;

        GrVkRenderTarget* vkRT = static_cast<GrVkRenderTarget*>(fRenderTarget);
        const GrVkResourceProvider::CompatibleRPHandle& rpHandle =
                vkRT->compatibleRenderPassHandle();
        if (rpHandle.isValid()) {
            cbInfo.fRenderPass = fGpu->resourceProvider().findRenderPass(rpHandle,
                                                                         vkColorOps,
                                                                         vkStencilOps);
        } else {
            cbInfo.fRenderPass = fGpu->resourceProvider().findRenderPass(*vkRT,
                                                                         vkColorOps,
                                                                         vkStencilOps);
        }
        SkASSERT(cbInfo.fRenderPass->isCompatible(*oldRP));
        oldRP->unref(fGpu);

        cbInfo.fLoadStoreState = LoadStoreState::kLoadAndStore;

    }
}

////////////////////////////////////////////////////////////////////////////////

void GrVkGpuRTCommandBuffer::bindGeometry(const GrGpuBuffer* indexBuffer,
                                          const GrGpuBuffer* vertexBuffer,
                                          const GrGpuBuffer* instanceBuffer) {
    GrVkSecondaryCommandBuffer* currCmdBuf = fCommandBufferInfos[fCurrentCmdInfo].currentCmdBuf();
    // There is no need to put any memory barriers to make sure host writes have finished here.
    // When a command buffer is submitted to a queue, there is an implicit memory barrier that
    // occurs for all host writes. Additionally, BufferMemoryBarriers are not allowed inside of
    // an active RenderPass.

    // Here our vertex and instance inputs need to match the same 0-based bindings they were
    // assigned in GrVkPipeline. That is, vertex first (if any) followed by instance.
    uint32_t binding = 0;

    if (vertexBuffer) {
        SkASSERT(vertexBuffer);
        SkASSERT(!vertexBuffer->isMapped());

        currCmdBuf->bindInputBuffer(fGpu, binding++,
                                    static_cast<const GrVkVertexBuffer*>(vertexBuffer));
    }

    if (instanceBuffer) {
        SkASSERT(instanceBuffer);
        SkASSERT(!instanceBuffer->isMapped());

        currCmdBuf->bindInputBuffer(fGpu, binding++,
                                    static_cast<const GrVkVertexBuffer*>(instanceBuffer));
    }
    if (indexBuffer) {
        SkASSERT(indexBuffer);
        SkASSERT(!indexBuffer->isMapped());

        currCmdBuf->bindIndexBuffer(fGpu, static_cast<const GrVkIndexBuffer*>(indexBuffer));
    }
}

GrVkPipelineState* GrVkGpuRTCommandBuffer::prepareDrawState(
        const GrPrimitiveProcessor& primProc,
        const GrPipeline& pipeline,
        const GrPipeline::FixedDynamicState* fixedDynamicState,
        const GrPipeline::DynamicStateArrays* dynamicStateArrays,
        GrPrimitiveType primitiveType) {
    CommandBufferInfo& cbInfo = fCommandBufferInfos[fCurrentCmdInfo];
    SkASSERT(cbInfo.fRenderPass);

    VkRenderPass compatibleRenderPass = cbInfo.fRenderPass->vkRenderPass();

    const GrTextureProxy* const* primProcProxies = nullptr;
    if (dynamicStateArrays && dynamicStateArrays->fPrimitiveProcessorTextures) {
        primProcProxies = dynamicStateArrays->fPrimitiveProcessorTextures;
    } else if (fixedDynamicState) {
        primProcProxies = fixedDynamicState->fPrimitiveProcessorTextures;
    }

    SkASSERT(SkToBool(primProcProxies) == SkToBool(primProc.numTextureSamplers()));

    GrVkPipelineState* pipelineState =
        fGpu->resourceProvider().findOrCreateCompatiblePipelineState(fRenderTarget, fOrigin,
                                                                     pipeline,
                                                                     primProc,
                                                                     primProcProxies,
                                                                     primitiveType,
                                                                     compatibleRenderPass);
    if (!pipelineState) {
        return pipelineState;
    }

    if (!cbInfo.fIsEmpty &&
        fLastPipelineState && fLastPipelineState != pipelineState &&
        fGpu->vkCaps().newCBOnPipelineChange()) {
        this->addAdditionalCommandBuffer();
    }
    fLastPipelineState = pipelineState;

    pipelineState->bindPipeline(fGpu, cbInfo.currentCmdBuf());

    pipelineState->setAndBindUniforms(fGpu, fRenderTarget, fOrigin,
                                      primProc, pipeline, cbInfo.currentCmdBuf());

    // Check whether we need to bind textures between each GrMesh. If not we can bind them all now.
    bool setTextures = !(dynamicStateArrays && dynamicStateArrays->fPrimitiveProcessorTextures);
    if (setTextures) {
        pipelineState->setAndBindTextures(fGpu, primProc, pipeline, primProcProxies,
                                          cbInfo.currentCmdBuf());
    }

    if (!pipeline.isScissorEnabled()) {
        GrVkPipeline::SetDynamicScissorRectState(fGpu, cbInfo.currentCmdBuf(),
                                                 fRenderTarget, fOrigin,
                                                 SkIRect::MakeWH(fRenderTarget->width(),
                                                                 fRenderTarget->height()));
    } else if (!dynamicStateArrays || !dynamicStateArrays->fScissorRects) {
        SkASSERT(fixedDynamicState);
        GrVkPipeline::SetDynamicScissorRectState(fGpu, cbInfo.currentCmdBuf(), fRenderTarget,
                                                 fOrigin,
                                                 fixedDynamicState->fScissorRect);
    }
    GrVkPipeline::SetDynamicViewportState(fGpu, cbInfo.currentCmdBuf(), fRenderTarget);
    GrVkPipeline::SetDynamicBlendConstantState(fGpu, cbInfo.currentCmdBuf(),
                                               fRenderTarget->config(),
                                               pipeline.getXferProcessor());

    return pipelineState;
}

void GrVkGpuRTCommandBuffer::onDraw(const GrPrimitiveProcessor& primProc,
                                    const GrPipeline& pipeline,
                                    const GrPipeline::FixedDynamicState* fixedDynamicState,
                                    const GrPipeline::DynamicStateArrays* dynamicStateArrays,
                                    const GrMesh meshes[],
                                    int meshCount,
                                    const SkRect& bounds) {
    if (!meshCount) {
        return;
    }

    CommandBufferInfo& cbInfo = fCommandBufferInfos[fCurrentCmdInfo];

    auto prepareSampledImage = [&](GrTexture* texture, GrSamplerState::Filter filter) {
        GrVkTexture* vkTexture = static_cast<GrVkTexture*>(texture);
        // We may need to resolve the texture first if it is also a render target
        GrVkRenderTarget* texRT = static_cast<GrVkRenderTarget*>(vkTexture->asRenderTarget());
        if (texRT) {
            fGpu->resolveRenderTargetNoFlush(texRT);
        }

        // Check if we need to regenerate any mip maps
        if (GrSamplerState::Filter::kMipMap == filter &&
            (vkTexture->width() != 1 || vkTexture->height() != 1)) {
            SkASSERT(vkTexture->texturePriv().mipMapped() == GrMipMapped::kYes);
            if (vkTexture->texturePriv().mipMapsAreDirty()) {
                fGpu->regenerateMipMapLevels(vkTexture);
            }
        }
        cbInfo.fSampledTextures.push_back(vkTexture);
    };

    if (dynamicStateArrays && dynamicStateArrays->fPrimitiveProcessorTextures) {
        for (int m = 0, i = 0; m < meshCount; ++m) {
            for (int s = 0; s < primProc.numTextureSamplers(); ++s, ++i) {
                auto texture = dynamicStateArrays->fPrimitiveProcessorTextures[i]->peekTexture();
                prepareSampledImage(texture, primProc.textureSampler(s).samplerState().filter());
            }
        }
    } else {
        for (int i = 0; i < primProc.numTextureSamplers(); ++i) {
            auto texture = fixedDynamicState->fPrimitiveProcessorTextures[i]->peekTexture();
            prepareSampledImage(texture, primProc.textureSampler(i).samplerState().filter());
        }
    }
    GrFragmentProcessor::Iter iter(pipeline);
    while (const GrFragmentProcessor* fp = iter.next()) {
        for (int i = 0; i < fp->numTextureSamplers(); ++i) {
            const GrFragmentProcessor::TextureSampler& sampler = fp->textureSampler(i);
            prepareSampledImage(sampler.peekTexture(), sampler.samplerState().filter());
        }
    }
    if (GrTexture* dstTexture = pipeline.peekDstTexture()) {
        cbInfo.fSampledTextures.push_back(sk_ref_sp(static_cast<GrVkTexture*>(dstTexture)));
    }

    GrPrimitiveType primitiveType = meshes[0].primitiveType();
    GrVkPipelineState* pipelineState = this->prepareDrawState(primProc, pipeline, fixedDynamicState,
                                                              dynamicStateArrays, primitiveType);
    if (!pipelineState) {
        return;
    }

    bool dynamicScissor =
            pipeline.isScissorEnabled() && dynamicStateArrays && dynamicStateArrays->fScissorRects;
    bool dynamicTextures = dynamicStateArrays && dynamicStateArrays->fPrimitiveProcessorTextures;

    for (int i = 0; i < meshCount; ++i) {
        const GrMesh& mesh = meshes[i];
        if (mesh.primitiveType() != primitiveType) {
            SkDEBUGCODE(pipelineState = nullptr);
            primitiveType = mesh.primitiveType();
            pipelineState = this->prepareDrawState(primProc, pipeline, fixedDynamicState,
                                                   dynamicStateArrays, primitiveType);
            if (!pipelineState) {
                return;
            }
        }

        if (dynamicScissor) {
            GrVkPipeline::SetDynamicScissorRectState(fGpu, cbInfo.currentCmdBuf(), fRenderTarget,
                                                     fOrigin,
                                                     dynamicStateArrays->fScissorRects[i]);
        }
        if (dynamicTextures) {
            GrTextureProxy* const* meshProxies = dynamicStateArrays->fPrimitiveProcessorTextures +
                                                 primProc.numTextureSamplers() * i;
            pipelineState->setAndBindTextures(fGpu, primProc, pipeline, meshProxies,
                                              cbInfo.currentCmdBuf());
        }
        SkASSERT(pipelineState);
        mesh.sendToGpu(this);
    }

    cbInfo.fBounds.join(bounds);
    cbInfo.fIsEmpty = false;
}

void GrVkGpuRTCommandBuffer::sendInstancedMeshToGpu(GrPrimitiveType,
                                                    const GrBuffer* vertexBuffer,
                                                    int vertexCount,
                                                    int baseVertex,
                                                    const GrBuffer* instanceBuffer,
                                                    int instanceCount,
                                                    int baseInstance) {
    CommandBufferInfo& cbInfo = fCommandBufferInfos[fCurrentCmdInfo];
    SkASSERT(!vertexBuffer || !vertexBuffer->isCpuBuffer());
    SkASSERT(!instanceBuffer || !instanceBuffer->isCpuBuffer());
    auto gpuVertexBuffer = static_cast<const GrGpuBuffer*>(vertexBuffer);
    auto gpuInstanceBuffer = static_cast<const GrGpuBuffer*>(instanceBuffer);
    this->bindGeometry(nullptr, gpuVertexBuffer, gpuInstanceBuffer);
    cbInfo.currentCmdBuf()->draw(fGpu, vertexCount, instanceCount, baseVertex, baseInstance);
    fGpu->stats()->incNumDraws();
}

void GrVkGpuRTCommandBuffer::sendIndexedInstancedMeshToGpu(GrPrimitiveType,
                                                           const GrBuffer* indexBuffer,
                                                           int indexCount,
                                                           int baseIndex,
                                                           const GrBuffer* vertexBuffer,
                                                           int baseVertex,
                                                           const GrBuffer* instanceBuffer,
                                                           int instanceCount,
                                                           int baseInstance,
                                                           GrPrimitiveRestart restart) {
    SkASSERT(restart == GrPrimitiveRestart::kNo);
    CommandBufferInfo& cbInfo = fCommandBufferInfos[fCurrentCmdInfo];
    SkASSERT(!vertexBuffer || !vertexBuffer->isCpuBuffer());
    SkASSERT(!instanceBuffer || !instanceBuffer->isCpuBuffer());
    SkASSERT(!indexBuffer->isCpuBuffer());
    auto gpuIndexxBuffer = static_cast<const GrGpuBuffer*>(indexBuffer);
    auto gpuVertexBuffer = static_cast<const GrGpuBuffer*>(vertexBuffer);
    auto gpuInstanceBuffer = static_cast<const GrGpuBuffer*>(instanceBuffer);
    this->bindGeometry(gpuIndexxBuffer, gpuVertexBuffer, gpuInstanceBuffer);
    cbInfo.currentCmdBuf()->drawIndexed(fGpu, indexCount, instanceCount,
                                        baseIndex, baseVertex, baseInstance);
    fGpu->stats()->incNumDraws();
}

////////////////////////////////////////////////////////////////////////////////

void GrVkGpuRTCommandBuffer::executeDrawable(std::unique_ptr<SkDrawable::GpuDrawHandler> drawable) {
    GrVkRenderTarget* target = static_cast<GrVkRenderTarget*>(fRenderTarget);

    GrVkImage* targetImage = target->msaaImage() ? target->msaaImage() : target;

    CommandBufferInfo& cbInfo = fCommandBufferInfos[fCurrentCmdInfo];
    VkRect2D bounds;
    bounds.offset = { 0, 0 };
    bounds.extent = { 0, 0 };

    GrVkDrawableInfo vkInfo;
    vkInfo.fSecondaryCommandBuffer = cbInfo.currentCmdBuf()->vkCommandBuffer();
    vkInfo.fCompatibleRenderPass = cbInfo.fRenderPass->vkRenderPass();
    SkAssertResult(cbInfo.fRenderPass->colorAttachmentIndex(&vkInfo.fColorAttachmentIndex));
    vkInfo.fFormat = targetImage->imageFormat();
    vkInfo.fDrawBounds = &bounds;
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
    vkInfo.fImage = targetImage->image();
#else
    vkInfo.fImage = VK_NULL_HANDLE;
#endif //SK_BUILD_FOR_ANDROID_FRAMEWORK

    GrBackendDrawableInfo info(vkInfo);

    // After we draw into the command buffer via the drawable, cached state we have may be invalid.
    cbInfo.currentCmdBuf()->invalidateState();
    // Also assume that the drawable produced output.
    cbInfo.fIsEmpty = false;

    drawable->draw(info);
    fGpu->addDrawable(std::move(drawable));

    if (bounds.extent.width == 0 || bounds.extent.height == 0) {
        cbInfo.fBounds.join(target->getBoundsRect());
    } else {
        cbInfo.fBounds.join(SkRect::MakeXYWH(bounds.offset.x, bounds.offset.y,
                                             bounds.extent.width, bounds.extent.height));
    }
}


text:
namespace SoundCatcher
{
    partial class FormOptionsDialog
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.label2 = new System.Windows.Forms.Label();
            this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
            this.trackBar1 = new System.Windows.Forms.TrackBar();
            this.label1 = new System.Windows.Forms.Label();
            this.checkBox1 = new System.Windows.Forms.CheckBox();
            this.checkBox2 = new System.Windows.Forms.CheckBox();
            this.button2 = new System.Windows.Forms.Button();
            this.label3 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button3 = new System.Windows.Forms.Button();
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.button1.Location = new System.Drawing.Point(281, 193);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 10;
            this.button1.Text = "OK";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // label2
            //
            this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(198, 30);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(99, 13);
            this.label2.TabIndex = 12;
            this.label2.Text = "Amplitude threshold";
            //
            // numericUpDown1
            //
            this.numericUpDown1.Location = new System.Drawing.Point(118, 81);
            this.numericUpDown1.Maximum = new decimal(new int[] {
            15,
            0,
            0,
            0});
            this.numericUpDown1.Name = "numericUpDown1";
            this.numericUpDown1.Size = new System.Drawing.Size(46, 20);
            this.numericUpDown1.TabIndex = 13;
            this.numericUpDown1.Value = new decimal(new int[] {
            5,
            0,
            0,
            0});
            this.numericUpDown1.ValueChanged += new System.EventHandler(this.numericUpDown1_ValueChanged);
            //
            // trackBar1
            //
            this.trackBar1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.trackBar1.BackColor = System.Drawing.SystemColors.Control;
            this.trackBar1.LargeChange = 100;
            this.trackBar1.Location = new System.Drawing.Point(303, 10);
            this.trackBar1.Maximum = 32767;
            this.trackBar1.Name = "trackBar1";
            this.trackBar1.Orientation = System.Windows.Forms.Orientation.Vertical;
            this.trackBar1.Size = new System.Drawing.Size(45, 170);
            this.trackBar1.TabIndex = 14;
            this.trackBar1.Tag = "Amplitude";
            this.trackBar1.TickFrequency = 1000;
            this.trackBar1.TickStyle = System.Windows.Forms.TickStyle.Both;
            this.trackBar1.Value = 15000;
            this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(22, 83);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(90, 13);
            this.label1.TabIndex = 15;
            this.label1.Text = "Seconds to save:";
            //
            // checkBox1
            //
            this.checkBox1.AutoSize = true;
            this.checkBox1.Location = new System.Drawing.Point(10, 19);
            this.checkBox1.Name = "checkBox1";
            this.checkBox1.Size = new System.Drawing.Size(141, 17);
            this.checkBox1.TabIndex = 16;
            this.checkBox1.Text = "Detect amplitude events";
            this.checkBox1.UseVisualStyleBackColor = true;
            this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
            //
            // checkBox2
            //
            this.checkBox2.AutoSize = true;
            this.checkBox2.Location = new System.Drawing.Point(6, 19);
            this.checkBox2.Name = "checkBox2";
            this.checkBox2.Size = new System.Drawing.Size(105, 17);
            this.checkBox2.TabIndex = 17;
            this.checkBox2.Text = "Save event data";
            this.checkBox2.UseVisualStyleBackColor = true;
            this.checkBox2.CheckedChanged += new System.EventHandler(this.checkBox2_CheckedChanged);
            //
            // button2
            //
            this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.button2.Location = new System.Drawing.Point(199, 193);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 18;
            this.button2.Text = "Cancel";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(22, 39);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(66, 13);
            this.label3.TabIndex = 19;
            this.label3.Text = "Output path:";
            //
            // textBox1
            //
            this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox1.Location = new System.Drawing.Point(25, 57);
            this.textBox1.Name = "textBox1";
            this.textBox1.ReadOnly = true;
            this.textBox1.Size = new System.Drawing.Size(202, 20);
            this.textBox1.TabIndex = 20;
            //
            // button3
            //
            this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button3.Location = new System.Drawing.Point(233, 55);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(54, 23);
            this.button3.TabIndex = 21;
            this.button3.Text = "Change";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.checkBox2);
            this.groupBox1.Controls.Add(this.button3);
            this.groupBox1.Controls.Add(this.textBox1);
            this.groupBox1.Controls.Add(this.label1);
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Controls.Add(this.numericUpDown1);
            this.groupBox1.Location = new System.Drawing.Point(6, 72);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(293, 107);
            this.groupBox1.TabIndex = 22;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Output";
            //
            // groupBox2
            //
            this.groupBox2.Controls.Add(this.textBox2);
            this.groupBox2.Controls.Add(this.checkBox1);
            this.groupBox2.Controls.Add(this.groupBox1);
            this.groupBox2.Controls.Add(this.trackBar1);
            this.groupBox2.Controls.Add(this.label2);
            this.groupBox2.Location = new System.Drawing.Point(2, 2);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(354, 185);
            this.groupBox2.TabIndex = 23;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Events";
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(201, 46);
            this.textBox2.Name = "textBox2";
            this.textBox2.ReadOnly = true;
            this.textBox2.Size = new System.Drawing.Size(92, 20);
            this.textBox2.TabIndex = 23;
            //
            // FormOptionsDialog
            //
            this.AcceptButton = this.button1;
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(359, 218);
            this.ControlBox = false;
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.MaximizeBox = false;
            this.Name = "FormOptionsDialog";
            this.ShowIcon = false;
            this.Text = "Options";
            this.Load += new System.EventHandler(this.FormOptionsDialog_Load);
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.NumericUpDown numericUpDown1;
        private System.Windows.Forms.TrackBar trackBar1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.CheckBox checkBox1;
        private System.Windows.Forms.CheckBox checkBox2;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.TextBox textBox2;
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Closure Unit Tests - goog.dom.annotate</title>

Tom & Jerry

    This little piggy
    That little piggy

    This little piggy
    That little piggy

<object classid="clsid:SAMPLE-UNRECOGNIZED-ID" width="100" height="50">
  <param name="BorderStyle" value="1" />
  <param name="MousePointer" value="0" />
  <param name="Enabled" value="1" />
  <param name="Min" value="0" />
  <param name="Max" value="10" />
  Your browser cannot display this object.
</object>


text:
package org.apache.camel.component.graphql.server;

public class Book {
    private String id;
    private String name;
    private String authorId;

    public Book(String id, String name, String authorId) {
        this.id = id;
        this.name = name;
        this.authorId = authorId;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthorId() {
        return authorId;
    }

    public void setAuthorId(String authorId) {
        this.authorId = authorId;
    }
}


text:
#include "tensorflow/contrib/lite/java/src/main/native/nativeinterpreterwrapper_jni.h"

namespace {

const int kByteBufferValue = 999;
const int kBufferSize = 256;

tflite::Interpreter* convertLongToInterpreter(JNIEnv* env, jlong handle) {
  if (handle == 0) {
    throwException(env, kIllegalArgumentException,
                   "Invalid handle to Interpreter.");
    return nullptr;
  }
  return reinterpret_cast<tflite::Interpreter*>(handle);
}

tflite::FlatBufferModel* convertLongToModel(JNIEnv* env, jlong handle) {
  if (handle == 0) {
    throwException(env, kIllegalArgumentException, "Invalid handle to model.");
    return nullptr;
  }
  return reinterpret_cast<tflite::FlatBufferModel*>(handle);
}

BufferErrorReporter* convertLongToErrorReporter(JNIEnv* env, jlong handle) {
  if (handle == 0) {
    throwException(env, kIllegalArgumentException,
                   "Invalid handle to ErrorReporter.");
    return nullptr;
  }
  return reinterpret_cast<BufferErrorReporter*>(handle);
}

std::vector<int> convertJIntArrayToVector(JNIEnv* env, jintArray inputs) {
  int size = static_cast<int>(env->GetArrayLength(inputs));
  std::vector<int> outputs(size, 0);
  jint* ptr = env->GetIntArrayElements(inputs, nullptr);
  if (ptr == nullptr) {
    throwException(env, kIllegalArgumentException,
                   "Empty dimensions of input array.");
    return {};
  }
  for (int i = 0; i < size; ++i) {
    outputs[i] = ptr[i];
  }
  env->ReleaseIntArrayElements(inputs, ptr, JNI_ABORT);
  return outputs;
}

bool isByteBuffer(jint data_type) { return data_type == kByteBufferValue; }

TfLiteType resolveDataType(jint data_type) {
  switch (data_type) {
    case 1:
      return kTfLiteFloat32;
    case 2:
      return kTfLiteInt32;
    case 3:
      return kTfLiteUInt8;
    case 4:
      return kTfLiteInt64;
    default:
      return kTfLiteNoType;
  }
}

void printDims(char* buffer, int max_size, int* dims, int num_dims) {
  if (max_size <= 0) return;
  buffer[0] = '?';
  int size = 1;
  for (int i = 1; i < num_dims; ++i) {
    if (max_size > size) {
      int written_size =
          snprintf(buffer + size, max_size - size, ",%d", dims[i]);
      if (written_size < 0) return;
      size += written_size;
    }
  }
}

TfLiteStatus checkInputs(JNIEnv* env, tflite::Interpreter* interpreter,
                         const int input_size, jintArray data_types,
                         jintArray nums_of_bytes, jobjectArray values,
                         jobjectArray sizes) {
  if (input_size != interpreter->inputs().size()) {
    throwException(env, kIllegalArgumentException,
                   "Expected num of inputs is %d but got %d",
                   interpreter->inputs().size(), input_size);
    return kTfLiteError;
  }
  if (input_size != env->GetArrayLength(data_types) ||
      input_size != env->GetArrayLength(nums_of_bytes) ||
      input_size != env->GetArrayLength(values)) {
    throwException(env, kIllegalArgumentException,
                   "Arrays in arguments should be of the same length, but got "
                   "%d sizes, %d data_types, %d nums_of_bytes, and %d values",
                   input_size, env->GetArrayLength(data_types),
                   env->GetArrayLength(nums_of_bytes),
                   env->GetArrayLength(values));
    return kTfLiteError;
  }
  for (int i = 0; i < input_size; ++i) {
    int input_idx = interpreter->inputs()[i];
    TfLiteTensor* target = interpreter->tensor(input_idx);
    jintArray dims =
        static_cast<jintArray>(env->GetObjectArrayElement(sizes, i));
    int num_dims = static_cast<int>(env->GetArrayLength(dims));
    if (target->dims->size != num_dims) {
      throwException(env, kIllegalArgumentException,
                     "%d-th input should have %d dimensions, but found %d "
                     "dimensions",
                     i, target->dims->size, num_dims);
      return kTfLiteError;
    }
    jint* ptr = env->GetIntArrayElements(dims, nullptr);
    for (int j = 1; j < num_dims; ++j) {
      if (target->dims->data[j] != ptr[j]) {
        std::unique_ptr<char[]> expected_dims(new char[kBufferSize]);
        std::unique_ptr<char[]> obtained_dims(new char[kBufferSize]);
        printDims(expected_dims.get(), kBufferSize, target->dims->data,
                  num_dims);
        printDims(obtained_dims.get(), kBufferSize, ptr, num_dims);
        throwException(env, kIllegalArgumentException,
                       "%d-th input dimension should be [%s], but found [%s]",
                       i, expected_dims.get(), obtained_dims.get());
        env->ReleaseIntArrayElements(dims, ptr, JNI_ABORT);
        return kTfLiteError;
      }
    }
    env->ReleaseIntArrayElements(dims, ptr, JNI_ABORT);
    env->DeleteLocalRef(dims);
    if (env->ExceptionCheck()) return kTfLiteError;
  }
  return kTfLiteOk;
}

TfLiteStatus resizeInputs(JNIEnv* env, tflite::Interpreter* interpreter,
                          int input_size, jobjectArray sizes) {
  for (int i = 0; i < input_size; ++i) {
    int input_idx = interpreter->inputs()[i];
    jintArray dims =
        static_cast<jintArray>(env->GetObjectArrayElement(sizes, i));
    TfLiteStatus status = interpreter->ResizeInputTensor(
        input_idx, convertJIntArrayToVector(env, dims));
    if (status != kTfLiteOk) {
      return status;
    }
    env->DeleteLocalRef(dims);
    if (env->ExceptionCheck()) return kTfLiteError;
  }
  return kTfLiteOk;
}

TfLiteStatus setInputs(JNIEnv* env, tflite::Interpreter* interpreter,
                       int input_size, jintArray data_types,
                       jintArray nums_of_bytes, jobjectArray values) {
  jint* data_type = env->GetIntArrayElements(data_types, nullptr);
  jint* num_bytes = env->GetIntArrayElements(nums_of_bytes, nullptr);
  for (int i = 0; i < input_size; ++i) {
    int input_idx = interpreter->inputs()[i];
    TfLiteTensor* target = interpreter->tensor(input_idx);
    jobject value = env->GetObjectArrayElement(values, i);
    bool is_byte_buffer = isByteBuffer(data_type[i]);
    if (is_byte_buffer) {
      writeByteBuffer(env, value, &(target->data.raw),
                      static_cast<int>(num_bytes[i]));
    } else {
      TfLiteType type = resolveDataType(data_type[i]);
      if (type != target->type) {
        throwException(env, kIllegalArgumentException,
                       "DataType (%d) of input data does not match with the "
                       "DataType (%d) of model inputs.",
                       type, target->type);
        return kTfLiteError;
      }
      writeMultiDimensionalArray(env, value, target->type, target->dims->size,
                                 &(target->data.raw),
                                 static_cast<int>(num_bytes[i]));
    }
    env->DeleteLocalRef(value);
    if (env->ExceptionCheck()) return kTfLiteError;
  }
  env->ReleaseIntArrayElements(data_types, data_type, JNI_ABORT);
  env->ReleaseIntArrayElements(nums_of_bytes, num_bytes, JNI_ABORT);
  return kTfLiteOk;
}

}  // namespace

JNIEXPORT jobjectArray JNICALL
Java_org_tensorflow_lite_NativeInterpreterWrapper_getInputNames(JNIEnv* env,
                                                                jclass clazz,
                                                                jlong handle) {
  tflite::Interpreter* interpreter = convertLongToInterpreter(env, handle);
  if (interpreter == nullptr) return nullptr;
  jclass string_class = env->FindClass("java/lang/String");
  if (string_class == nullptr) {
    throwException(env, kUnsupportedOperationException,
                   "Can not find java/lang/String class to get input names.");
    return nullptr;
  }
  size_t size = interpreter->inputs().size();
  jobjectArray names = static_cast<jobjectArray>(
      env->NewObjectArray(size, string_class, env->NewStringUTF("")));
  for (int i = 0; i < size; ++i) {
    env->SetObjectArrayElement(names, i,
                               env->NewStringUTF(interpreter->GetInputName(i)));
  }
  return names;
}

JNIEXPORT jobjectArray JNICALL
Java_org_tensorflow_lite_NativeInterpreterWrapper_getOutputNames(JNIEnv* env,
                                                                 jclass clazz,
                                                                 jlong handle) {
  tflite::Interpreter* interpreter = convertLongToInterpreter(env, handle);
  if (interpreter == nullptr) return nullptr;
  jclass string_class = env->FindClass("java/lang/String");
  if (string_class == nullptr) {
    throwException(env, kUnsupportedOperationException,
                   "Can not find java/lang/String class to get output names.");
    return nullptr;
  }
  size_t size = interpreter->outputs().size();
  jobjectArray names = static_cast<jobjectArray>(
      env->NewObjectArray(size, string_class, env->NewStringUTF("")));
  for (int i = 0; i < size; ++i) {
    env->SetObjectArrayElement(
        names, i, env->NewStringUTF(interpreter->GetOutputName(i)));
  }
  return names;
}

JNIEXPORT void JNICALL
Java_org_tensorflow_lite_NativeInterpreterWrapper_useNNAPI(JNIEnv* env,
                                                           jclass clazz,
                                                           jlong handle,
                                                           jboolean state) {
  tflite::Interpreter* interpreter = convertLongToInterpreter(env, handle);
  if (interpreter == nullptr) return;
  interpreter->UseNNAPI(static_cast<bool>(state));
}

JNIEXPORT jlong JNICALL
Java_org_tensorflow_lite_NativeInterpreterWrapper_createErrorReporter(
    JNIEnv* env, jclass clazz, jint size) {
  BufferErrorReporter* error_reporter =
      new BufferErrorReporter(env, static_cast<int>(size));
  return reinterpret_cast<jlong>(error_reporter);
}

JNIEXPORT jlong JNICALL
Java_org_tensorflow_lite_NativeInterpreterWrapper_createModel(
    JNIEnv* env, jclass clazz, jstring model_file, jlong error_handle) {
  BufferErrorReporter* error_reporter =
      convertLongToErrorReporter(env, error_handle);
  if (error_reporter == nullptr) return 0;
  const char* path = env->GetStringUTFChars(model_file, nullptr);
  auto model = tflite::FlatBufferModel::BuildFromFile(path, error_reporter);
  if (!model) {
    throwException(env, kIllegalArgumentException,
                   "Contents of %s does not encode a valid TensorFlowLite "
                   "model: %s",
                   path, error_reporter->CachedErrorMessage());
    env->ReleaseStringUTFChars(model_file, path);
    return 0;
  }
  env->ReleaseStringUTFChars(model_file, path);
  return reinterpret_cast<jlong>(model.release());
}

JNIEXPORT jlong JNICALL
Java_org_tensorflow_lite_NativeInterpreterWrapper_createModelWithBuffer(
    JNIEnv* env, jclass /*clazz*/, jobject model_buffer, jlong error_handle) {
  BufferErrorReporter* error_reporter =
      convertLongToErrorReporter(env, error_handle);
  if (error_reporter == nullptr) return 0;
  const char* buf =
      static_cast<char*>(env->GetDirectBufferAddress(model_buffer));
  jlong capacity = env->GetDirectBufferCapacity(model_buffer);
  auto model = tflite::FlatBufferModel::BuildFromBuffer(
      buf, static_cast<size_t>(capacity), error_reporter);
  if (!model) {
    throwException(env, kIllegalArgumentException,
                   "MappedByteBuffer does not encode a valid TensorFlowLite "
                   "model: %s",
                   error_reporter->CachedErrorMessage());
    return 0;
  }
  return reinterpret_cast<jlong>(model.release());
}

JNIEXPORT jlong JNICALL
Java_org_tensorflow_lite_NativeInterpreterWrapper_createInterpreter(
    JNIEnv* env, jclass clazz, jlong model_handle, jlong error_handle) {
  tflite::FlatBufferModel* model = convertLongToModel(env, model_handle);
  if (model == nullptr) return 0;
  BufferErrorReporter* error_reporter =
      convertLongToErrorReporter(env, error_handle);
  if (error_reporter == nullptr) return 0;
  auto resolver = ::tflite::CreateOpResolver();
  std::unique_ptr<tflite::Interpreter> interpreter;
  TfLiteStatus status =
      tflite::InterpreterBuilder(*model, *(resolver.get()))(&interpreter);
  if (status != kTfLiteOk) {
    throwException(env, kIllegalArgumentException,
                   "Cannot create interpreter: %s",
                   error_reporter->CachedErrorMessage());
  }
  return reinterpret_cast<jlong>(interpreter.release());
}

// Sets inputs, runs inference, and returns outputs as long handles.
JNIEXPORT jlongArray JNICALL
Java_org_tensorflow_lite_NativeInterpreterWrapper_run(
    JNIEnv* env, jclass clazz, jlong interpreter_handle, jlong error_handle,
    jobjectArray sizes, jintArray data_types, jintArray nums_of_bytes,
    jobjectArray values) {
  tflite::Interpreter* interpreter =
      convertLongToInterpreter(env, interpreter_handle);
  if (interpreter == nullptr) return nullptr;
  BufferErrorReporter* error_reporter =
      convertLongToErrorReporter(env, error_handle);
  if (error_reporter == nullptr) return nullptr;
  const int input_size = env->GetArrayLength(sizes);
  // validates inputs
  TfLiteStatus status = checkInputs(env, interpreter, input_size, data_types,
                                    nums_of_bytes, values, sizes);
  if (status != kTfLiteOk) return nullptr;
  // resizes inputs
  status = resizeInputs(env, interpreter, input_size, sizes);
  if (status != kTfLiteOk) {
    throwException(env, kNullPointerException, "Can not resize the input: %s",
                   error_reporter->CachedErrorMessage());
    return nullptr;
  }
  // allocates memory
  status = interpreter->AllocateTensors();
  if (status != kTfLiteOk) {
    throwException(env, kNullPointerException,
                   "Can not allocate memory for the given inputs: %s",
                   error_reporter->CachedErrorMessage());
    return nullptr;
  }
  // sets inputs
  status = setInputs(env, interpreter, input_size, data_types, nums_of_bytes,
                     values);
  if (status != kTfLiteOk) return nullptr;
  // runs inference
  if (interpreter->Invoke() != kTfLiteOk) {
    throwException(env, kIllegalArgumentException,
                   "Failed to run on the given Interpreter: %s",
                   error_reporter->CachedErrorMessage());
    return nullptr;
  }
  // returns outputs
  const std::vector<int>& results = interpreter->outputs();
  if (results.empty()) {
    throwException(env, kIllegalArgumentException,
                   "The Interpreter does not have any outputs.");
    return nullptr;
  }
  jlongArray outputs = env->NewLongArray(results.size());
  size_t size = results.size();
  for (int i = 0; i < size; ++i) {
    TfLiteTensor* source = interpreter->tensor(results[i]);
    jlong output = reinterpret_cast<jlong>(source);
    env->SetLongArrayRegion(outputs, i, 1, &output);
  }
  return outputs;
}

JNIEXPORT jintArray JNICALL
Java_org_tensorflow_lite_NativeInterpreterWrapper_getInputDims(
    JNIEnv* env, jclass clazz, jlong handle, jint input_idx, jint num_bytes) {
  tflite::Interpreter* interpreter = convertLongToInterpreter(env, handle);
  if (interpreter == nullptr) return nullptr;
  const int idx = static_cast<int>(input_idx);
  if (input_idx >= interpreter->inputs().size()) {
    throwException(env, kIllegalArgumentException,
                   "Out of range: Failed to get %d-th input out of %d inputs",
                   input_idx, interpreter->inputs().size());
    return nullptr;
  }
  TfLiteTensor* target = interpreter->tensor(interpreter->inputs()[idx]);
  int size = target->dims->size;
  int expected_num_bytes = elementByteSize(target->type);
  for (int i = 0; i < size; ++i) {
    expected_num_bytes *= target->dims->data[i];
  }
  if (num_bytes != expected_num_bytes) {
    throwException(env, kIllegalArgumentException,
                   "Failed to get input dimensions. %d-th input should have"
                   " %d bytes, but found %d bytes.",
                   idx, expected_num_bytes, num_bytes);
    return nullptr;
  }
  jintArray outputs = env->NewIntArray(size);
  env->SetIntArrayRegion(outputs, 0, size, &(target->dims->data[0]));
  return outputs;
}

JNIEXPORT void JNICALL
Java_org_tensorflow_lite_NativeInterpreterWrapper_resizeInput(
    JNIEnv* env, jclass clazz, jlong interpreter_handle, jlong error_handle,
    jint input_idx, jintArray dims) {
  BufferErrorReporter* error_reporter =
      convertLongToErrorReporter(env, error_handle);
  if (error_reporter == nullptr) return;
  tflite::Interpreter* interpreter =
      convertLongToInterpreter(env, interpreter_handle);
  if (interpreter == nullptr) return;
  const int idx = static_cast<int>(input_idx);
  if (idx < 0 || idx >= interpreter->inputs().size()) {
    throwException(env, kIllegalArgumentException,
                   "Can not resize %d-th input for a model having %d inputs.",
                   idx, interpreter->inputs().size());
  }
  TfLiteStatus status = interpreter->ResizeInputTensor(
      interpreter->inputs()[idx], convertJIntArrayToVector(env, dims));
  if (status != kTfLiteOk) {
    throwException(env, kIllegalArgumentException,
                   "Failed to resize %d-th input: %s", idx,
                   error_reporter->CachedErrorMessage());
  }
}

JNIEXPORT void JNICALL Java_org_tensorflow_lite_NativeInterpreterWrapper_delete(
    JNIEnv* env, jclass clazz, jlong error_handle, jlong model_handle,
    jlong interpreter_handle) {
  if (interpreter_handle != 0) {
    delete convertLongToInterpreter(env, interpreter_handle);
  }
  if (model_handle != 0) {
    delete convertLongToModel(env, model_handle);
  }
  if (error_handle != 0) {
    delete convertLongToErrorReporter(env, error_handle);
  }
}


text:
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var gutil = require('gulp-util');
var istanbul = require('gulp-istanbul');

gulp.task('mocha', function() {
    return gulp.src(['test/*.js'], { read: false })
        .pipe(mocha({ reporter: 'list' }))
        .on('error', gutil.log);
});

gulp.task('watch-mocha', function() {
    gulp.watch(['index.js', 'test/**'], ['mocha']);
});

gulp.task('test', function (cb) {
    gulp.src(['index.js'])
        .pipe(istanbul()) // Covering files
        .pipe(istanbul.hookRequire()) // Force `require` to return covered files
        .on('finish', function () {
            gulp.src(['test/*.js'])
                .pipe(mocha())
                .pipe(istanbul.writeReports()) // Creating the reports after tests ran
                .pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } })) // Enforce a coverage of at least 90%
                .on('end', cb);
        });
});


text:
package org.directwebremoting.servlet;

import org.directwebremoting.extend.NamedConverter;
import org.directwebremoting.util.LocalUtil;

/**
 * A handler for dtoall generation requests in the Dojo module format
 * @author Mike Wilson [mikewse at hotmail dot com]
 */
public class DojoDtoAllHandler extends BaseDtoAllHandler
{
    /**
     * Generates the full dtoall script by decorating the DTO classes returned by the Remoter.
     * @return string containing dtoall script
     */
    @Override
    public String generateDtoAllScript(String contextPath, String servletPath)
    {
        DojoModule mod = new DojoModule(contextPath, servletPath, dojoDwrBaseModulePath, "dtoall");
        mod.addRequire(dojoDwrBaseModulePath, "engine");
        String engineModule = mod.expandModulePath(dojoDwrBaseModulePath, "engine");

        mod.addContent("(function() {\n");
        mod.addContent("  var c;\n");
        mod.addContent("  var addedNow = [];\n");

        // DTO class definitions
        for (String jsClassName : converterManager.getNamedConverterJavaScriptNames())
        {
            String dtoModule = mod.expandModulePath(dojoDtoBaseModulePath, jsClassName);
            mod.addContent("\n");
            mod.addContent("  dojo.provide(\"" + dtoModule + "\");\n");
            mod.addContent("  if (!" + engineModule + "._mappedClasses[\"" + jsClassName + "\"]) {\n");
            mod.addContent(remoter.generateDtoJavaScript(jsClassName, "    ", "c"));
            mod.addContent("    " + engineModule + "._mappedClasses[\"" + jsClassName + "\"] = c;\n");
            mod.addContent("    addedNow[\"" + jsClassName + "\"] = true;\n");
            mod.addContent("  }\n");
            mod.addContent("  dojo.setObject(\"" + dtoModule + "\", " + engineModule + "._mappedClasses[\"" + jsClassName + "\"]);\n");
        }

        // DTO inheritance definitions
        for (String jsClassName : converterManager.getNamedConverterJavaScriptNames())
        {
            NamedConverter namedConv = converterManager.getNamedConverter(jsClassName);
            String jsSuperClassName = namedConv.getJavascriptSuperClass();
            if (LocalUtil.hasLength(jsSuperClassName))
            {
                String classExpression = engineModule + "._mappedClasses[\"" + jsClassName + "\"]";
                String superClassExpression = engineModule + "._mappedClasses[\"" + jsSuperClassName + "\"]";
                mod.addContent("\n");
                mod.addContent("  if (addedNow[\"" + jsClassName + "\"]) {\n");
                mod.addContent(remoter.generateDtoInheritanceJavaScript("    ", classExpression, superClassExpression, engineModule + "._delegate"));
                mod.addContent("  }\n");
            }
        }

        mod.addContent("})();\n");

        return mod.toString();
    }

    /**
     * Setter for the module path that dtoall is on
     * @param modulePath the modulePath to set
     */
    public void setDojoDwrBaseModulePath(final String modulePath)
    {
        dojoDwrBaseModulePath = modulePath;
    }

    /**
     * Setter for the module path that DTO is on
     * @param modulePath the modulePath to set
     */
    public void setDojoDtoBaseModulePath(final String modulePath)
    {
        dojoDtoBaseModulePath = modulePath;
    }

    /**
     * What module path is dtoall on?
     */
    protected String dojoDwrBaseModulePath;

    /**
     * What module path are DTOs on?
     */
    protected String dojoDtoBaseModulePath;
}


text:
@interface MOBProjectionEPSG6065 : MOBProjection

@end


text:
package org.springframework.social.facebook.api.impl.json;

import org.springframework.social.facebook.api.FacebookObject;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Annotated mixin to add Jackson annotations to UserInvitableFriend.
 * @author Craig Walls
 */
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class UserInvitableFriendMixin extends FacebookObject {

	@JsonCreator
	UserInvitableFriendMixin(
			@JsonProperty("id") String id,
			@JsonProperty("name") String name,
			@JsonProperty("first_name") String firstName,
			@JsonProperty("middle_name") String middleName,
			@JsonProperty("last_name") String lastName) {}

}


text:
import unittest

from example import main_1

class TestExample(unittest.TestCase):

    def test_example_read_file(self):
        self.assertEqual(main_1(), ['1', '2', '3'])

if __name__ == '__main__':
    unittest.main()