text:
//@tag dom,core
//@define Ext.DomHelper
//@require Ext.dom.Query

/**
 * @class Ext.DomHelper
 * @alternateClassName Ext.dom.Helper
 *
 * The DomHelper class provides a layer of abstraction from DOM and transparently supports creating elements via DOM or
 * using HTML fragments. It also has the ability to create HTML fragment templates from your DOM building code.
 *
 * ## DomHelper element specification object
 *
 * A specification object is used when creating elements. Attributes of this object are assumed to be element
 * attributes, except for 4 special attributes:
 *
 * * **tag**: The tag name of the element
 * * **children (or cn)**: An array of the same kind of element definition objects to be created and appended. These
 * can be nested as deep as you want.
 * * **cls**: The class attribute of the element. This will end up being either the "class" attribute on a HTML
 * fragment or className for a DOM node, depending on whether DomHelper is using fragments or DOM.
 * * **html**: The innerHTML for the element
 *
 * ## Insertion methods
 *
 * Commonly used insertion methods:
 *
 * * {@link #append}
 * * {@link #insertBefore}
 * * {@link #insertAfter}
 * * {@link #overwrite}
 * * {@link #insertHtml}
 *
 * ## Example
 *
 * This is an example, where an unordered list with 3 children items is appended to an existing element with id
 * 'my-div':
 *
 *     var dh = Ext.DomHelper; // create shorthand alias
 *     // specification object
 *     var spec = {
 *         id: 'my-ul',
 *         tag: 'ul',
 *         cls: 'my-list',
 *         // append children after creating
 *         children: [     // may also specify 'cn' instead of 'children'
 *             {tag: 'li', id: 'item0', html: 'List Item 0'},
 *             {tag: 'li', id: 'item1', html: 'List Item 1'},
 *             {tag: 'li', id: 'item2', html: 'List Item 2'}
 *         ]
 *     };
 *     var list = dh.append(
 *         'my-div', // the context element 'my-div' can either be the id or the actual node
 *         spec      // the specification object
 *     );
 *
 * Element creation specification parameters in this class may also be passed as an Array of specification objects.
 * This can be used to insert multiple sibling nodes into an existing container very efficiently. For example, to add
 * more list items to the example above:
 *
 *     dh.append('my-ul', [
 *         {tag: 'li', id: 'item3', html: 'List Item 3'},
 *         {tag: 'li', id: 'item4', html: 'List Item 4'}
 *     ]);
 *
 * ## Templating
 *
 * The real power is in the built-in templating. Instead of creating or appending any elements, createTemplate returns
 * a Template object which can be used over and over to insert new elements. Revisiting the example above, we could
 * utilize templating this time:
 *
 *     // create the node
 *     var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
 *     // get template
 *     var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
 *
 *     for(var i = 0; i < 5; i++){
 *         tpl.append(list, i); // use template to append to the actual node
 *     }
 *
 * An example using a template:
 *
 *     var html = '"{0}" href="{1}" class="nav">{2}';
 *
 *     var tpl = new Ext.DomHelper.createTemplate(html);
 *     tpl.append('blog-roll', ['link1', 'http://www.tommymaintz.com/', "Tommy's Site"]);
 *     tpl.append('blog-roll', ['link2', 'http://www.avins.org/', "Jamie's Site"]);
 *
 * The same example using named parameters:
 *
 *     var html = '"{id}" href="{url}" class="nav">{text}';
 *
 *     var tpl = new Ext.DomHelper.createTemplate(html);
 *     tpl.append('blog-roll', {
 *         id: 'link1',
 *         url: 'http://www.tommymaintz.com/',
 *         text: "Tommy's Site"
 *     });
 *     tpl.append('blog-roll', {
 *         id: 'link2',
 *         url: 'http://www.avins.org/',
 *         text: "Jamie's Site"
 *     });
 *
 * ## Compiling Templates
 *
 * Templates are applied using regular expressions. The performance is great, but if you are adding a bunch of DOM
 * elements using the same template, you can increase performance even further by "compiling" the template. The way
 * "compile()" works is the template is parsed and broken up at the different variable points and a dynamic function is
 * created and eval'ed. The generated function performs string concatenation of these parts and the passed variables
 * instead of using regular expressions.
 *
 *     var html = '"{id}" href="{url}" class="nav">{text}';
 *
 *     var tpl = new Ext.DomHelper.createTemplate(html);
 *     tpl.compile();
 *
 *     // ... use template like normal
 *
 * ## Performance Boost
 *
 * DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead of DOM can
 * significantly boost performance.
 *
 * Element creation specification parameters may also be strings. If useDom is false, then the string is used as
 * innerHTML. If useDom is true, a string specification results in the creation of a text node. Usage:
 *
 *     Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance
 *
 */
Ext.define('Ext.dom.Helper', {
    emptyTags: /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
    confRe: /tag|children|cn|html|tpl|tplData$/i,
    endRe: /end/i,
    attribXlat: {cls: 'class', htmlFor: 'for'},
    closeTags: {},
    decamelizeName: function() {
        var camelCaseRe = /([a-z])([A-Z])/g,
                cache = {};

        function decamel(match, p1, p2) {
            return p1 + '-' + p2.toLowerCase();
        }

        return function(s) {
            return cache[s] || (cache[s] = s.replace(camelCaseRe, decamel));
        };
    }(),
    generateMarkup: function(spec, buffer) {
        var me = this,
                attr, val, tag, i, closeTags;

        if (typeof spec == "string") {
            buffer.push(spec);
        } else if (Ext.isArray(spec)) {
            for (i = 0; i < spec.length; i++) {
                if (spec[i]) {
                    me.generateMarkup(spec[i], buffer);
                }
            }
        } else {
            tag = spec.tag || 'div';
            buffer.push('<', tag);

            for (attr in spec) {
                if (spec.hasOwnProperty(attr)) {
                    val = spec[attr];
                    if (!me.confRe.test(attr)) {
                        if (typeof val == "object") {
                            buffer.push(' ', attr, '="');
                            me.generateStyles(val, buffer).push('"');
                        } else {
                            buffer.push(' ', me.attribXlat[attr] || attr, '="', val, '"');
                        }
                    }
                }
            }

            // Now either just close the tag or try to add children and close the tag.
            if (me.emptyTags.test(tag)) {
                buffer.push('/>');
            } else {
                buffer.push('>');

                // Apply the tpl html, and cn specifications
                if ((val = spec.tpl)) {
                    val.applyOut(spec.tplData, buffer);
                }
                if ((val = spec.html)) {
                    buffer.push(val);
                }
                if ((val = spec.cn || spec.children)) {
                    me.generateMarkup(val, buffer);
                }

                // we generate a lot of close tags, so cache them rather than push 3 parts
                closeTags = me.closeTags;
                buffer.push(closeTags[tag] || (closeTags[tag] = '</' + tag + '>'));
            }
        }

        return buffer;
    },
    /**
     * Converts the styles from the given object to text. The styles are CSS style names
     * with their associated value.
     *
     * The basic form of this method returns a string:
     *
     *      var s = Ext.DomHelper.generateStyles({
     *          backgroundColor: 'red'
     *      });
     *
     *      // s = 'background-color:red;'
     *
     * Alternatively, this method can append to an output array.
     *
     *      var buf = [];
     *
     *      // ...
     *
     *      Ext.DomHelper.generateStyles({
     *          backgroundColor: 'red'
     *      }, buf);
     *
     * In this case, the style text is pushed on to the array and the array is returned.
     *
     * @param {Object} styles The object describing the styles.
     * @param {String[]} [buffer] The output buffer.
     * @return {String/String[]} If buffer is passed, it is returned. Otherwise the style
     * string is returned.
     */
    generateStyles: function(styles, buffer) {
        var a = buffer || [],
                name;

        for (name in styles) {
            if (styles.hasOwnProperty(name)) {
                a.push(this.decamelizeName(name), ':', styles[name], ';');
            }
        }

        return buffer || a.join('');
    },
    /**
     * Returns the markup for the passed Element(s) config.
     * @param {Object} spec The DOM object spec (and children).
     * @return {String}
     */
    markup: function(spec) {
        if (typeof spec == "string") {
            return spec;
        }

        var buf = this.generateMarkup(spec, []);
        return buf.join('');
    },
    /**
     * Applies a style specification to an element.
     * @param {String/HTMLElement} el The element to apply styles to
     * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
     * a function which returns such a specification.
     */
    applyStyles: function(el, styles) {
        Ext.fly(el).applyStyles(styles);
    },
    /**
     * @private
     * Fix for browsers which no longer support createContextualFragment
     */
    createContextualFragment: function(html) {
        var div = document.createElement("div"),
                fragment = document.createDocumentFragment(),
                i = 0,
                length, childNodes;

        div.innerHTML = html;
        childNodes = div.childNodes;
        length = childNodes.length;

        for (; i < length; i++) {
            fragment.appendChild(childNodes[i].cloneNode(true));
        }

        return fragment;
    },
    /**
     * Inserts an HTML fragment into the DOM.
     * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
     *
     * For example take the following HTML: `<div>Contents</div>`
     *
     * Using different `where` values inserts element to the following places:
     *
     * - beforeBegin: `<HERE><div>Contents</div>`
     * - afterBegin: `<div><HERE>Contents</div>`
     * - beforeEnd: `<div>Contents<HERE></div>`
     * - afterEnd: `<div>Contents</div><HERE>`
     *
     * @param {HTMLElement/TextNode} el The context element
     * @param {String} html The HTML fragment
     * @return {HTMLElement} The new node
     */
    insertHtml: function(where, el, html) {
        var setStart, range, frag, rangeEl, isBeforeBegin, isAfterBegin;

        where = where.toLowerCase();

        if (Ext.isTextNode(el)) {
            if (where == 'afterbegin') {
                where = 'beforebegin';
            }
            else if (where == 'beforeend') {
                where = 'afterend';
            }
        }

        isBeforeBegin = where == 'beforebegin';
        isAfterBegin = where == 'afterbegin';

        range = Ext.feature.has.CreateContextualFragment ? el.ownerDocument.createRange() : undefined;
        setStart = 'setStart' + (this.endRe.test(where) ? 'After' : 'Before');

        if (isBeforeBegin || where == 'afterend') {
            if (range) {
                range[setStart](el);
                frag = range.createContextualFragment(html);
            }
            else {
                frag = this.createContextualFragment(html);
            }
            el.parentNode.insertBefore(frag, isBeforeBegin ? el : el.nextSibling);
            return el[(isBeforeBegin ? 'previous' : 'next') + 'Sibling'];
        }
        else {
            rangeEl = (isAfterBegin ? 'first' : 'last') + 'Child';
            if (el.firstChild) {
                if (range) {
                    // Creating ranges on a hidden element throws an error, checking for the element being painted is
                    // VERY expensive, so we'll catch the error and fall back to using the full fragment
                    try {
                        range[setStart](el[rangeEl]);
                        frag = range.createContextualFragment(html);
                    }
                    catch (e) {
                        frag = this.createContextualFragment(html);
                    }
                } else {
                    frag = this.createContextualFragment(html);
                }

                if (isAfterBegin) {
                    el.insertBefore(frag, el.firstChild);
                } else {
                    el.appendChild(frag);
                }
            } else {
                el.innerHTML = html;
            }
            return el[rangeEl];
        }
    },
    /**
     * Creates new DOM element(s) and inserts them before el.
     * @param {String/HTMLElement/Ext.Element} el The context element
     * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
     * @param {Boolean} [returnElement] true to return a Ext.Element
     * @return {HTMLElement/Ext.Element} The new node
     */
    insertBefore: function(el, o, returnElement) {
        return this.doInsert(el, o, returnElement, 'beforebegin');
    },
    /**
     * Creates new DOM element(s) and inserts them after el.
     * @param {String/HTMLElement/Ext.Element} el The context element
     * @param {Object} o The DOM object spec (and children)
     * @param {Boolean} [returnElement] true to return a Ext.Element
     * @return {HTMLElement/Ext.Element} The new node
     */
    insertAfter: function(el, o, returnElement) {
        return this.doInsert(el, o, returnElement, 'afterend');
    },
    /**
     * Creates new DOM element(s) and inserts them as the first child of el.
     * @param {String/HTMLElement/Ext.Element} el The context element
     * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
     * @param {Boolean} [returnElement] true to return a Ext.Element
     * @return {HTMLElement/Ext.Element} The new node
     */
    insertFirst: function(el, o, returnElement) {
        return this.doInsert(el, o, returnElement, 'afterbegin');
    },
    /**
     * Creates new DOM element(s) and appends them to el.
     * @param {String/HTMLElement/Ext.Element} el The context element
     * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
     * @param {Boolean} [returnElement] true to return a Ext.Element
     * @return {HTMLElement/Ext.Element} The new node
     */
    append: function(el, o, returnElement) {
        return this.doInsert(el, o, returnElement, 'beforeend');
    },
    /**
     * Creates new DOM element(s) and overwrites the contents of el with them.
     * @param {String/HTMLElement/Ext.Element} el The context element
     * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
     * @param {Boolean} [returnElement] true to return a Ext.Element
     * @return {HTMLElement/Ext.Element} The new node
     */
    overwrite: function(el, o, returnElement) {
        el = Ext.getDom(el);
        el.innerHTML = this.markup(o);
        return returnElement ? Ext.get(el.firstChild) : el.firstChild;
    },
    doInsert: function(el, o, returnElement, pos) {
        var newNode = this.insertHtml(pos, Ext.getDom(el), this.markup(o));
        return returnElement ? Ext.get(newNode, true) : newNode;
    },
    /**
     * Creates a new Ext.Template from the DOM object spec.
     * @param {Object} o The DOM object spec (and children)
     * @return {Ext.Template} The new template
     */
    createTemplate: function(o) {
        var html = this.markup(o);
        return new Ext.Template(html);
    }
}, function() {
    Ext.ns('Ext.core');
    Ext.core.DomHelper = Ext.DomHelper = new this;
});


text:
package com.gemstone.gemfire.management.internal.cli.commands;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Properties;

import javax.management.ObjectName;

import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionFactory;
import com.gemstone.gemfire.cache.RegionShortcut;
import com.gemstone.gemfire.cache.server.CacheServer;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.internal.AvailablePortHelper;
import com.gemstone.gemfire.management.CacheServerMXBean;
import com.gemstone.gemfire.management.DistributedRegionMXBean;
import com.gemstone.gemfire.management.DistributedSystemMXBean;
import com.gemstone.gemfire.management.ManagementService;
import com.gemstone.gemfire.management.MemberMXBean;
import com.gemstone.gemfire.management.RegionMXBean;
import com.gemstone.gemfire.management.cli.Result;
import com.gemstone.gemfire.management.cli.Result.Status;
import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
import com.gemstone.gemfire.management.internal.cli.remote.CommandProcessor;
import com.gemstone.gemfire.management.internal.cli.result.CommandResult;

import dunit.Host;
import dunit.SerializableCallable;
import dunit.SerializableRunnable;
import dunit.VM;

/****
 *
 * @author bansods
 *
 */
public class ShowMetricsDUnitTest extends CliCommandTestBase {

  /**
   *
   */
  private static final long serialVersionUID = 1L;

  public ShowMetricsDUnitTest(String name) {
    super(name);
    // TODO Auto-generated constructor stub
  }

  private void createLocalSetUp() {
    Properties localProps = new Properties();
    localProps.setProperty(DistributionConfig.NAME_NAME, "Controller");
    getSystem(localProps);
    Cache cache = getCache();
    RegionFactory<Integer, Integer> dataRegionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
    Region region1 = dataRegionFactory.create("REGION1");
    Region region2 = dataRegionFactory.create("REGION2");
  }

  /***
   * tests the default version of "show metrics"
   */

  public void testShowMetricsDefault() {
    createDefaultSetup(null);
    createLocalSetUp();
    final VM vm1 = Host.getHost(0).getVM(1);
    final String vm1Name = "VM" + vm1.getPid();

    vm1.invoke(new SerializableRunnable() {
      public void run() {
        Properties localProps = new Properties();
        localProps.setProperty(DistributionConfig.NAME_NAME, vm1Name);
        getSystem(localProps);

        Cache cache = getCache();
        RegionFactory<Integer, Integer> dataRegionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
        Region region = dataRegionFactory.create("REGION1");
      }
    });

    SerializableCallable showMetricCmd = new SerializableCallable() {

      @Override
      public Object call() throws Exception {
        WaitCriterion wc = createMBeanWaitCriterion(1, "", null, 0);
        waitForCriterion(wc, 5000, 500, true);
        CommandProcessor commandProcessor = new CommandProcessor();
        Result result = commandProcessor.createCommandStatement("show metrics", Collections.EMPTY_MAP).process();
        String resultStr = commandResultToString((CommandResult)result);
        getLogWriter().info(resultStr);
        assertEquals(resultStr, true, result.getStatus().equals(Status.OK));
        return resultStr;
      }
    };

    //Invoke the command in the Manager VM
    final VM managerVm = Host.getHost(0).getVM(0);
    Object managerResultObj = managerVm.invoke(showMetricCmd);

    String managerResult = (String) managerResultObj;

    getLogWriter().info("#SB Manager");
    getLogWriter().info(managerResult);
  }

  public void systemSetUp() {
    createDefaultSetup(null);
    createLocalSetUp();
    final VM vm1 = Host.getHost(0).getVM(1);
    final String vm1Name = "VM" + vm1.getPid();

    vm1.invoke(new SerializableRunnable() {
      public void run() {
        Properties localProps = new Properties();
        localProps.setProperty(DistributionConfig.NAME_NAME, vm1Name);
        getSystem(localProps);

        Cache cache = getCache();
        RegionFactory<Integer, Integer> dataRegionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
        Region region = dataRegionFactory.create("REGION1");
      }
    });
  }

  public void testShowMetricsRegion() throws InterruptedException {
   systemSetUp();
   final String regionName = "REGION1";
    SerializableCallable showMetricCmd = new SerializableCallable() {

      @Override
      public Object call() throws Exception {
        WaitCriterion wc = createMBeanWaitCriterion(2, regionName, null, 0);
        waitForCriterion(wc, 5000, 500, true);
        CommandProcessor commandProcessor = new CommandProcessor();
        Result result = commandProcessor.createCommandStatement("show metrics --region=REGION1", Collections.EMPTY_MAP).process();
        String resultAsString = commandResultToString((CommandResult)result);
        assertEquals(resultAsString, true, result.getStatus().equals(Status.OK));
        return resultAsString;
      }
    };

    //Invoke the command in the Manager VM
    final VM managerVm = Host.getHost(0).getVM(0);
    Object managerResultObj = managerVm.invoke(showMetricCmd);

    String managerResult = (String) managerResultObj;

    getLogWriter().info("#SB Manager");
    getLogWriter().info(managerResult);
  }

  /***
   * Creates WaitCriterion based on creation of different types of MBeans
   * @param beanType
   * @param regionName
   * @param memberName
   * @return
   */
  private WaitCriterion createMBeanWaitCriterion(final int beanType, final String regionName, final DistributedMember distributedMember, final int cacheServerPort) {

    WaitCriterion waitCriterion = new WaitCriterion() {

      @Override
      public boolean done() {
        boolean done = false;
        Cache cache = getCache();
        ManagementService mgmtService = ManagementService
            .getManagementService(cache);
        if (beanType == 1) {
          DistributedSystemMXBean dsMxBean = mgmtService.getDistributedSystemMXBean();
          if (dsMxBean != null)
            done = true;
        } else if (beanType == 2) {
          DistributedRegionMXBean dsRegionMxBean = mgmtService.getDistributedRegionMXBean("/"+regionName);
          if (dsRegionMxBean != null)
            done = true;
        } else if (beanType == 3) {
          ObjectName memberMBeanName = mgmtService.getMemberMBeanName(distributedMember);
          MemberMXBean memberMxBean = mgmtService.getMBeanInstance(memberMBeanName, MemberMXBean.class);

          if (memberMxBean != null)
            done = true;
        } else if (beanType == 4) {
          ObjectName regionMBeanName = mgmtService.getRegionMBeanName(distributedMember, "/"+regionName);
          RegionMXBean regionMxBean = mgmtService.getMBeanInstance(regionMBeanName, RegionMXBean.class);

          if (regionMxBean != null)
            done = true;
        } else if (beanType == 5) {
          ObjectName csMxBeanName = mgmtService.getCacheServerMBeanName(cacheServerPort, distributedMember);
          CacheServerMXBean csMxBean = mgmtService.getMBeanInstance(csMxBeanName, CacheServerMXBean.class);

          if (csMxBean != null) {
            done = true;
          }
        }

        return done;
      }

      @Override
      public String description() {
        return "Waiting for the mbean to be created";
      }

    };

    return waitCriterion;

  }

  public void testShowMetricsMember() throws ClassNotFoundException, IOException, InterruptedException {
    systemSetUp();
    Cache cache = getCache();
    final DistributedMember distributedMember = cache.getDistributedSystem().getDistributedMember();
    final String exportFileName = "memberMetricReport.csv";

    int ports [] = AvailablePortHelper.getRandomAvailableTCPPorts(1);
    CacheServer cs = getCache().addCacheServer();
    cs.setPort(ports[0]);
    cs.start();
    final int cacheServerPort = cs.getPort();

    SerializableCallable showMetricCmd = new SerializableCallable() {
      @Override
      public Object call() throws Exception {

        WaitCriterion wc = createMBeanWaitCriterion(3, "", distributedMember, 0);
        waitForCriterion(wc, 5000, 500, true);
        wc = createMBeanWaitCriterion(5, "", distributedMember, cacheServerPort);
        waitForCriterion(wc, 10000, 500, true);

        final String command = CliStrings.SHOW_METRICS + " --" + CliStrings.SHOW_METRICS__MEMBER + "=" + distributedMember.getId()
            + " --" + CliStrings.SHOW_METRICS__CACHESERVER__PORT + "=" + cacheServerPort
            + " --" + CliStrings.SHOW_METRICS__FILE + "=" + exportFileName;

        CommandProcessor commandProcessor = new CommandProcessor();
        Result result = commandProcessor.createCommandStatement(command, Collections.EMPTY_MAP).process();
        String resultAsString = commandResultToString((CommandResult)result);
        assertEquals(resultAsString, true, result.getStatus().equals(Status.OK));
        assertTrue(result.hasIncomingFiles());
        result.saveIncomingFiles(null);
        File file = new File(exportFileName);
        file.deleteOnExit();
        assertTrue(file.exists());
        file.delete();
        return resultAsString;

      }
    };

    //Invoke the command in the Manager VM
    final VM managerVm = Host.getHost(0).getVM(0);
    Object managerResultObj = managerVm.invoke(showMetricCmd);

    String managerResult = (String) managerResultObj;

    getLogWriter().info("#SB Manager");
    getLogWriter().info(managerResult);
    cs.stop();
  }

  public void testShowMetricsRegionFromMember() throws ClassNotFoundException, IOException, InterruptedException {
    systemSetUp();
    Cache cache = getCache();
    final DistributedMember distributedMember = cache.getDistributedSystem().getDistributedMember();
    final String exportFileName = "regionOnAMemberReport.csv";
    final String regionName = "REGION1";

    SerializableCallable showMetricCmd = new SerializableCallable() {

      @Override
      public Object call() throws Exception {

        WaitCriterion wc = createMBeanWaitCriterion(4, regionName, distributedMember, 0);
        waitForCriterion(wc, 5000, 500, true);
        CommandProcessor commandProcessor = new CommandProcessor();
        Result result = commandProcessor.createCommandStatement("show metrics --region="+ regionName + " --member=" + distributedMember.getName()
                                          + " --file="+exportFileName, Collections.EMPTY_MAP).process();
        String resultAsString = commandResultToString((CommandResult)result);
        assertEquals(resultAsString, true, result.getStatus().equals(Status.OK));
        assertTrue(result.hasIncomingFiles());
        result.saveIncomingFiles(null);
        File file = new File(exportFileName);
        file.deleteOnExit();
        assertTrue(file.exists());
        file.delete();
        return resultAsString;
      }
    };

    //Invoke the command in the Manager VM
    final VM managerVm = Host.getHost(0).getVM(0);
    Object managerResultObj = managerVm.invoke(showMetricCmd);

    String managerResult = (String) managerResultObj;

    getLogWriter().info("#SB Manager");
    getLogWriter().info(managerResult);
  }

  public void testShowMetricsRegionFromMemberWithCategories() throws ClassNotFoundException, IOException, InterruptedException {
    systemSetUp();
    Cache cache = getCache();
    final DistributedMember distributedMember = cache.getDistributedSystem().getDistributedMember();
    final String exportFileName = "regionOnAMemberReport.csv";
    final String regionName = "REGION1";

    SerializableCallable showMetricCmd = new SerializableCallable() {

      @Override
      public Object call() throws Exception {

        WaitCriterion wc = createMBeanWaitCriterion(4, regionName, distributedMember, 0);
        waitForCriterion(wc, 5000, 500, true);
        CommandProcessor commandProcessor = new CommandProcessor();
        Result result = commandProcessor.createCommandStatement("show metrics --region="+ regionName + " --member=" + distributedMember.getName()
                                          + " --file="+exportFileName
                                          + " --categories=region,eviction", Collections.EMPTY_MAP).process();
        String resultAsString = commandResultToString((CommandResult)result);
        assertEquals(resultAsString, true, result.getStatus().equals(Status.OK));
        assertTrue(result.hasIncomingFiles());
        result.saveIncomingFiles(null);
        File file = new File(exportFileName);
        file.deleteOnExit();
        assertTrue(file.exists());
        file.delete();
        return resultAsString;
      }
    };

    //Invoke the command in the Manager VM
    final VM managerVm = Host.getHost(0).getVM(0);
    Object managerResultObj = managerVm.invoke(showMetricCmd);

    String managerResult = (String) managerResultObj;

    getLogWriter().info("#SB Manager");
    getLogWriter().info(managerResult);
  }
}

redpajama_set_name: RedPajamaGithub


text:
<query id="getDocumentListWithinTag" action="select">
    <tables>

    </tables>
    <columns>
        <column name="documents.document_srl" />
        <column name="documents.list_order" />
    </columns>
    <conditions>
        <condition operation="in" column="documents.module_srl" var="module_srl" filter="number" />
        <condition operation="notin" column="documents.module_srl" var="exclude_module_srl" filter="number" pipe="and" />
        <condition operation="equal" column="documents.document_srl" default="tags.document_srl" notnull="notnull" pipe="and" />
        <condition operation="in" column="documents.category_srl" var="category_srl" filter="number" pipe="and" />
        <condition operation="equal" column="documents.member_srl" var="member_srl" filter="number" pipe="and" />
        <condition operation="like" column="tags.tag" var="s_tags" notnull="notnull" pipe="and" />
        <condition operation="in" column="documents.status" var="statusList" pipe="and" />
    </conditions>
    <navigation>
        <index var="sort_index" default="documents.list_order" order="order_type" />
        <list_count var="list_count" default="20" />
        <page_count var="page_count" default="10" />
        <page var="page" default="1" />
    </navigation>
    <groups>
        <group column="documents.document_srl" />
    </groups>
</query>


text:
public class SecondBean {
}


text:
package common

import (
	"context"
	"testing"
)

func TestRandomCorrectCreation(t *testing.T) {
	tests := []struct {
		max int64
		min int64
	}{
		{min: 0, max: 1},
		{min: 5, max: 10},
		{min: 98, max: 99},
		{min: 1234, max: 12345},
		{min: 0, max: 999999999999999999},
	}

	for _, test := range tests {
		ops := map[string]interface{}{
			maxLimitOpt: test.max,
			minLimitOpt: test.min,
		}

		r, err := NewRandom(ops)

		if err != nil {
			t.Errorf("\n- %+v\n  Creation shouldn't give error: %v", test, err)
		}

		if r.MaxLimit != test.max || r.MinLimit != test.min {
			t.Errorf("\n- %+v\n  Wrong parameters loaded on object, want: %v; got %v", test, []int64{test.min, test.max}, []int64{r.MinLimit, r.MaxLimit})
		}
	}

}

func TestRandomWrongParameterCreation(t *testing.T) {
	tests := []struct {
		opts map[string]interface{}
	}{
		{opts: map[string]interface{}{maxLimitOpt: 10}},
		{opts: map[string]interface{}{minLimitOpt: 10}},
		{opts: map[string]interface{}{minLimitOpt: 11, maxLimitOpt: 10}},
		{opts: map[string]interface{}{minLimitOpt: 10, maxLimitOpt: 10}},
		{opts: map[string]interface{}{minLimitOpt: 0.1, maxLimitOpt: 10}},
		{opts: map[string]interface{}{minLimitOpt: -4, maxLimitOpt: -1}},
		{opts: map[string]interface{}{minLimitOpt: -4, maxLimitOpt: 10}},
		{opts: map[string]interface{}{minLimitOpt: "wrong", maxLimitOpt: 10}},
		{opts: map[string]interface{}{minLimitOpt: 10, maxLimitOpt: true}},
		{opts: map[string]interface{}{minLimitOpt: 10, maxLimitOpt: []int64{1}}},
	}

	for _, test := range tests {

		_, err := NewRandom(test.opts)

		if err == nil {
			t.Errorf("\n- %+v\n  Creation should give error", test)
		}
	}
}

func TestRandomGather(t *testing.T) {
	ops := map[string]interface{}{
		minLimitOpt: 0,
		maxLimitOpt: 99999999999999999,
	}

	r, err := NewRandom(ops)
	if err != nil {
		t.Fatalf("\n- Creation shouldn't give error: %v", err)
	}

	n1, err := r.Gather(context.TODO())
	if err != nil {
		t.Errorf("\n- Gather shouldn't give error: %v", err)
	}

	n2, err := r.Gather(context.TODO())
	if err != nil {
		t.Errorf("\n- Gather shouldn't give error: %v", err)
	}

	if n2.Q == n1.Q {
		t.Errorf("\n- %+v\n- 2 random sequential numbers should be different", []int64{n1.Q, n2.Q})
	}
}


text:
'''
 Copyright (c) 2015 Yichi Zhang
 https://github.com/yichizhang
 zhang-yi-chi@hotmail.com

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

import os
import sys
import argparse

C_SINGLE_LINE_COMMENT = "//"
C_MULTI_LINE_COMMENT_BEGIN = "/*"
C_MULTI_LINE_COMMENT_END = "*/"

def newstringbychangingheader (originalstring, newheader):
	newstring = ""

	loc1 = originalstring.find(C_SINGLE_LINE_COMMENT)
	loc2 = originalstring.find(C_MULTI_LINE_COMMENT_BEGIN)

	if (loc1 == 0):
		words = originalstring.split('\n')

		newstring = newheader
		firstblockofcomments = True

		for word in words:
			if (word.startswith(C_SINGLE_LINE_COMMENT) == True and (firstblockofcomments == True)):
				# First few lines of single line comments;
				# Original comments; no need to copy.
				# Therefore, pass;
				pass
			else:
				# Copy all the rest of lines;
				firstblockofcomments = False
				newstring = newstring + word + "\n"

			# First line that do not start with //
			if (word.startswith(C_SINGLE_LINE_COMMENT) == False):
				firstblockofcomments = False

	elif (loc2 == 0):
		endlocation = originalstring.find(C_MULTI_LINE_COMMENT_END)
		trimlocation = endlocation + len(C_MULTI_LINE_COMMENT_END)
		newstring = newheader + originalstring[trimlocation:]
	else:
		newstring = newheader + originalstring

	return newstring

def processfile (filepath, newheader):
	outputpath = filepath
	newstring = ""

	fin = open(filepath, 'r')
	originalstring = fin.read()
	fin.close()

	newstring = newstringbychangingheader(originalstring, newheader)

	fout = open(outputpath, 'w')
	fout.write(newstring)
	fout.close()

	return

def shouldprocessfile (filename):
	flag = False
	if filename.startswith('._'):
		flag = False
	else:
		if (filename.endswith('.swift') or filename.endswith('.h') or filename.endswith('.m')):
			flag = True

	return flag

# Main program

def main (rootdir, newheaderpath):

	k = raw_input("\n--------------------------------------------\n                  WARNING\n--------------------------------------------\nYour files will be modified; YOU MIGHT LOSE IMPORTANT INFORMATION.\nYou should backup or commit your files before continuing.\n\nPress ENTER to continue\nIf you wish to abort, press Control + C")

	f = open(newheaderpath, 'r')
	newheader = f.read()
	f.close()

	for subdir, dirs, files in os.walk(rootdir):
		for file in files:
			if shouldprocessfile (file):
				filepath = os.path.join(subdir, file)
				processfile(filepath, newheader)
	return

if __name__ == "__main__":
	parser = argparse.ArgumentParser()

	#parser.add_argument('dir', help="directory of the files to be changed")
	#parser.add_argument('newheaderfile', help="path of the new header file to be added to the files in the directory")
	parser.add_argument('-d', '--dir', help="directory of the files to be changed")
	parser.add_argument('-f', '--newheaderfile', help="path of the new header file to be added to the files in the directory")

	args = parser.parse_args()

	if args.dir is None:
		rootdir = os.path.dirname(os.path.realpath(__file__))
		print "No directory specified; using: " + rootdir
	else:
		rootdir = args.dir

	if args.newheaderfile is None:
		newheaderpath = "newheader.txt"
		print "No new header file specified; looking for: " + newheaderpath
	else:
		newheaderpath = args.newheaderfile

	main(rootdir, newheaderpath)


text:
EmployeesController = MeteorisController.extend({
    /* get subscribtion from server with parameter criteria, and sort/limit */
    subscriptions: function() {
        var sort = MeteorisGridView.getSorting();
        sort.limit = this.limit();

        this.subs.subscribe('jobs', {});

        this.subscription = this.subs.subscribe('employees', this.getCriteria(), sort);
    },
    /* event searching data by user input with parameter */
    search: function(t) {
        Router.go(Router.current().route.getName(), {limit: this.limit()}, {query: "q=" + t.find('#search').value});
    },
    /* @override getCriteria */
    getCriteria: function() {
        var search = this.params.query.q ? this.params.query.q : "";
        return {
            $or: [
                {name: {$regex: search, $options: 'i'}},
{jobId: {$regex: search, $options: 'i'}},
{birthDate: {$regex: search, $options: 'i'}},

            ]
        };
    },
    index: function() {
        var sort = MeteorisGridView.getSorting();
        sort.limit = this.limit();
        var models = Employees.find(this.getCriteria(), sort);

        return this.render('employeesIndex', {
            data: {
                ready: this.subscription.ready,
                isEmpty: models.count() === 0 ? true : false,
                models: models,
                hasMore: this.limit() == models.fetch().length ? this.route.path({limit: this.limit() + this.increment}) : null,
            }
        });
    },
    view: function() {
        return this.render('employeesView', {
            data: {
                model: this._loadModel(this.getId()),
            }
        });
    },
    /* private get user input docs */
    _getDoc: function(t) {
        return {
            name: t.find('#name').value,
jobId: t.find('#jobId').value,
birthDate: t.find('#birthDate').value? new Date(t.find('#birthDate').value):null,

        };
    },
    /* uploading file using cfs:fileSystem package + cfs:ejson */
    _uploadImage: function() {
        var imageId = null;
        var file = $('#image').get(0).files[0];
        if (file) {
            var image = Images.insert(file, function(err) {
                if (err) {
                    MeteorisFlash.set('danger', err.message);
                    throw new Meteor.Error(err);
                }
            });
            imageId = image._id;
        }

        return imageId;
    },
    /* event inserting data */
    insert: function(t) {
        if (this._post) {
            //uploading file using cfs:fileSystem package + cfs:ejson
            //var imageId = this._uploadImage();

            //set inserted doc
            var doc = this._getDoc(t);
            //doc.imageId = imageId;

            Employees.insert(doc, function(err, _id) {
                if (err) {
                    MeteorisFlash.set('danger', err.message);
                    throw new Meteor.Error(err);
                }
                MeteorisFlash.set('success', "Success Inserting Employees");
                Router.go('employeesView', {_id: _id});
            });
        }
        return this.render('employeesInsert', {});
    },
    /* event updating data */
    update: function(t) {
        var _id = this.getId();
        var model = this._loadModel(_id);

        if (this._post) {
            //uploading file using cfs:fileSystem package + cfs:ejson
            //var imageId = this._uploadImage();

            //remove old image if user inputting new image
            //if (imageId && model.imageId)
            //Images.remove(model.imageId);

            //set updated doc
            var doc = this._getDoc(t);
            //doc.imageId = imageId ? imageId : model.imageId;

            Employees.update(_id, {$set: doc}, function(err) {
                if (err) {
                    MeteorisFlash.set('danger', err.message);
                    throw new Meteor.Error(err);
                }
                MeteorisFlash.set('success', "Success Updating Employees");
            });
            Router.go('employeesView', {_id: _id});
        }
        return this.render('employeesUpdate', {
            data: {
                model: model,
            }
        });
    },
    /* event removing data by id */
    remove: function(_id) {
        Employees.remove(_id, function(err) {
            if (err) {
                MeteorisFlash.set('danger', err.message);
                throw new Meteor.Error(err);
            }
            MeteorisFlash.set('success', "Success Removing Employees");
        });
    },
    _loadModel: function(_id) {
        return Employees.findOne(_id);
    },
});


text:
class CreateOptions < ActiveRecord::Migration[5.1]
  def change
    create_table :options do |t|
      t.string :name
      t.string :unit

      t.timestamps
    end

    add_index :options, :name
  end
end


text:
@class NSString;

@interface PayReq : BaseReq
{
    unsigned int timeStamp;
    NSString *nonceStr;
    NSString *package;
    NSString *partnerId;
    NSString *prepayId;
    NSString *sign;
}

@property(retain, nonatomic) NSString *sign; // @synthesize sign;
@property(nonatomic) unsigned int timeStamp; // @synthesize timeStamp;
@property(retain, nonatomic) NSString *prepayId; // @synthesize prepayId;
@property(retain, nonatomic) NSString *partnerId; // @synthesize partnerId;
@property(retain, nonatomic) NSString *package; // @synthesize package;
@property(retain, nonatomic) NSString *nonceStr; // @synthesize nonceStr;
- (void).cxx_destruct;

@end


text:
package iconvg

import (
	"image/color"
)

func validAlphaPremulColor(c color.RGBA) bool {
	return c.R <= c.A && c.G <= c.A && c.B <= c.A
}

// ColorType distinguishes types of Colors.
type ColorType uint8

const (
	// ColorTypeRGBA is a direct RGBA color.
	ColorTypeRGBA ColorType = iota

	// ColorTypePaletteIndex is an indirect color, indexing the custom palette.
	ColorTypePaletteIndex

	// ColorTypeCReg is an indirect color, indexing the CREG color registers.
	ColorTypeCReg

	// ColorTypeBlend is an indirect color, blending two other colors.
	ColorTypeBlend
)

// Color is an IconVG color, whose RGBA values can depend on context. Some
// Colors are direct RGBA values. Other Colors are indirect, referring to an
// index of the custom palette, a color register of the decoder virtual
// machine, or a blend of two other Colors.
//
// See the "Colors" section in the package documentation for details.
type Color struct {
	typ  ColorType
	data color.RGBA
}

func (c Color) rgba() color.RGBA         { return c.data }
func (c Color) paletteIndex() uint8      { return c.data.R }
func (c Color) cReg() uint8              { return c.data.R }
func (c Color) blend() (t, c0, c1 uint8) { return c.data.R, c.data.G, c.data.B }

// Resolve resolves the Color's RGBA value, given its context: the custom
// palette and the color registers of the decoder virtual machine.
func (c Color) Resolve(pal *Palette, cReg *[64]color.RGBA) color.RGBA {
	switch c.typ {
	case ColorTypeRGBA:
		return c.rgba()
	case ColorTypePaletteIndex:
		return pal[c.paletteIndex()&0x3f]
	case ColorTypeCReg:
		return cReg[c.cReg()&0x3f]
	}
	t, c0, c1 := c.blend()
	p, q := uint32(255-t), uint32(t)
	rgba0 := decodeColor1(c0).Resolve(pal, cReg)
	rgba1 := decodeColor1(c1).Resolve(pal, cReg)
	return color.RGBA{
		uint8(((p * uint32(rgba0.R)) + q*uint32(rgba1.R) + 128) / 255),
		uint8(((p * uint32(rgba0.G)) + q*uint32(rgba1.G) + 128) / 255),
		uint8(((p * uint32(rgba0.B)) + q*uint32(rgba1.B) + 128) / 255),
		uint8(((p * uint32(rgba0.A)) + q*uint32(rgba1.A) + 128) / 255),
	}
}

// RGBAColor returns a direct Color.
func RGBAColor(c color.RGBA) Color { return Color{ColorTypeRGBA, c} }

// PaletteIndexColor returns an indirect Color referring to an index of the
// custom palette.
func PaletteIndexColor(i uint8) Color { return Color{ColorTypePaletteIndex, color.RGBA{R: i & 0x3f}} }

// CRegColor returns an indirect Color referring to a color register of the
// decoder virtual machine.
func CRegColor(i uint8) Color { return Color{ColorTypeCReg, color.RGBA{R: i & 0x3f}} }

// BlendColor returns an indirect Color that blends two other Colors. Those two
// other Colors must both be encodable as a 1 byte color.
//
// To blend a Color that is not encodable as a 1 byte color, first load that
// Color into a CREG color register, then call CRegColor to produce a Color
// that is encodable as a 1 byte color. See testdata/favicon.ivg for an
// example.
//
// See the "Colors" section in the package documentation for details.
func BlendColor(t, c0, c1 uint8) Color { return Color{ColorTypeBlend, color.RGBA{R: t, G: c0, B: c1}} }

func decodeColor1(x byte) Color {
	if x >= 0x80 {
		if x >= 0xc0 {
			return CRegColor(x)
		} else {
			return PaletteIndexColor(x)
		}
	}
	if x >= 125 {
		switch x - 125 {
		case 0:
			return RGBAColor(color.RGBA{0xc0, 0xc0, 0xc0, 0xc0})
		case 1:
			return RGBAColor(color.RGBA{0x80, 0x80, 0x80, 0x80})
		case 2:
			return RGBAColor(color.RGBA{0x00, 0x00, 0x00, 0x00})
		}
	}
	blue := dc1Table[x%5]
	x = x / 5
	green := dc1Table[x%5]
	x = x / 5
	red := dc1Table[x]
	return RGBAColor(color.RGBA{red, green, blue, 0xff})
}

var dc1Table = [5]byte{0x00, 0x40, 0x80, 0xc0, 0xff}

func is1(u uint8) bool { return u&0x3f == 0 || u == 0xff }

func encodeColor1(c Color) (x byte, ok bool) {
	switch c.typ {
	case ColorTypeRGBA:
		if c.data.A != 0xff {
			switch c.data {
			case color.RGBA{0x00, 0x00, 0x00, 0x00}:
				return 127, true
			case color.RGBA{0x80, 0x80, 0x80, 0x80}:
				return 126, true
			case color.RGBA{0xc0, 0xc0, 0xc0, 0xc0}:
				return 125, true
			}
		} else if is1(c.data.R) && is1(c.data.G) && is1(c.data.B) && is1(c.data.A) {
			r := c.data.R / 0x3f
			g := c.data.G / 0x3f
			b := c.data.B / 0x3f
			return 25*r + 5*g + b, true
		}
	case ColorTypePaletteIndex:
		return c.data.R | 0x80, true
	case ColorTypeCReg:
		return c.data.R | 0xc0, true
	}
	return 0, false
}

func is2(u uint8) bool { return u%0x11 == 0 }

func encodeColor2(c Color) (x [2]byte, ok bool) {
	if c.typ == ColorTypeRGBA && is2(c.data.R) && is2(c.data.G) && is2(c.data.B) && is2(c.data.A) {
		return [2]byte{
			(c.data.R/0x11)<<4 | (c.data.G / 0x11),
			(c.data.B/0x11)<<4 | (c.data.A / 0x11),
		}, true
	}
	return [2]byte{}, false
}

func encodeColor3Direct(c Color) (x [3]byte, ok bool) {
	if c.typ == ColorTypeRGBA && c.data.A == 0xff {
		return [3]byte{c.data.R, c.data.G, c.data.B}, true
	}
	return [3]byte{}, false
}

func encodeColor4(c Color) (x [4]byte, ok bool) {
	if c.typ == ColorTypeRGBA {
		return [4]byte{c.data.R, c.data.G, c.data.B, c.data.A}, true
	}
	return [4]byte{}, false
}

func encodeColor3Indirect(c Color) (x [3]byte, ok bool) {
	if c.typ == ColorTypeBlend {
		return [3]byte{c.data.R, c.data.G, c.data.B}, true
	}
	return [3]byte{}, false
}


text:
<?php

namespace Oro\Bundle\EntityConfigBundle\Translation;

use Symfony\Component\Translation\TranslatorInterface;

use Oro\Bundle\TranslationBundle\Entity\Translation;
use Oro\Bundle\TranslationBundle\Manager\TranslationManager;

class ConfigTranslationHelper
{
    /** @var TranslationManager */
    protected $translationManager;

    /** @var TranslatorInterface */
    protected $translator;

    /**
     * @param TranslationManager $translationManager
     * @param TranslatorInterface $translator
     */
    public function __construct(TranslationManager $translationManager, TranslatorInterface $translator)
    {
        $this->translationManager = $translationManager;
        $this->translator = $translator;
    }

    /**
     * @param string $key
     * @param string $value
     * @return bool
     */
    public function isTranslationEqual($key, $value)
    {
        return $value === $this->translator->trans($key);
    }

    /**
     * @return string
     */
    public function getLocale()
    {
        return $this->translator->getLocale();
    }

    /**
     * @param string|null $locale
     */
    public function invalidateCache($locale = null)
    {
        $this->translationManager->invalidateCache($locale);
    }

    /**
     * @param array $translations
     */
    public function saveTranslations(array $translations)
    {
        if (!$translations) {
            return;
        }

        $locale = $this->translator->getLocale();

        foreach ($translations as $key => $value) {
            $this->translationManager->saveTranslation(
                $key,
                $value,
                $locale,
                TranslationManager::DEFAULT_DOMAIN,
                Translation::SCOPE_UI
            );
        }

        // mark translation cache dirty
        $this->translationManager->invalidateCache($locale);

        $this->translationManager->flush();
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DocAsCode.MarkdownLite.Tests
{
    using Microsoft.DocAsCode.MarkdownLite.Matchers;

    using Xunit;

    public class MatcherTest
    {
        [Fact]
        public void TestCharMatcher()
        {
            var m = Matcher.Char('a');
            Assert.Equal(1, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(1, m.Match(new MatchContent("aabc", 1, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("aabc", 1, MatchDirection.Backward)));
            Assert.Equal(1, m.Match(new MatchContent("cba", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cbb", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cbb", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cbb", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cbb", 3, MatchDirection.Backward)));
        }

        [Fact]
        public void TestAnyCharMatcher()
        {
            var m = Matcher.AnyChar;
            Assert.Equal(1, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
        }

        [Fact]
        public void TestAnyCharInMatcher()
        {
            var m = Matcher.AnyCharIn('a', 'b');
            Assert.Equal(1, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
        }

        [Fact]
        public void TestAnyCharInRangeMatcher()
        {
            var m = Matcher.AnyCharInRange('a', 'z');
            Assert.Equal(1, m.Match(new MatchContent("azX", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("azX", 0, MatchDirection.Backward)));
            Assert.Equal(1, m.Match(new MatchContent("azX", 1, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("azX", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("azX", 2, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("azX", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("azX", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("azX", 3, MatchDirection.Backward)));
        }

        [Fact]
        public void TestAnyCharNotInMatcher()
        {
            var m = Matcher.AnyCharNotIn('a', 'b');
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
        }

        [Fact]
        public void TestStringMatcher()
        {
            var m = Matcher.String("abc");
            Assert.Equal(3, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(3, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
            Assert.Equal(3, m.Match(new MatchContent("aabc", 1, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("aabc", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("bbc", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("bbc", 3, MatchDirection.Backward)));
        }

        [Fact]
        public void TestCaseInsensitiveStringMatcher()
        {
            var m = Matcher.CaseInsensitiveString("aBc");
            Assert.Equal(3, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(3, m.Match(new MatchContent("aBc", 0, MatchDirection.Forward)));
            Assert.Equal(3, m.Match(new MatchContent("ABC", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(3, m.Match(new MatchContent("aabc", 1, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("aabc", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(3, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
            Assert.Equal(3, m.Match(new MatchContent("Cba", 3, MatchDirection.Backward)));
            Assert.Equal(3, m.Match(new MatchContent("cbA", 3, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cbb", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cbb", 3, MatchDirection.Backward)));
        }

        [Fact]
        public void TestEndOfStringMatcher()
        {
            var m = Matcher.EndOfString;
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
        }

        [Fact]
        public void TestMaybeMatcher()
        {
            var m = Matcher.Maybe(Matcher.String("abc"));
            Assert.Equal(3, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(3, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
            Assert.Equal(3, m.Match(new MatchContent("aabc", 1, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("aabc", 1, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
        }

        [Fact]
        public void TestRepeatMatcher()
        {
            var m = Matcher.Repeat(Matcher.AnyCharInRange('a', 'b'), 1);
            Assert.Equal(2, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(2, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(2, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
        }

        [Fact]
        public void TestAnyMatcher()
        {
            var m = Matcher.Any(Matcher.Char('a'), Matcher.String("bc"));
            Assert.Equal(1, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(2, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(2, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(1, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
            Assert.Equal(1, m.Match(new MatchContent("cba", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Backward)));
        }

        [Fact]
        public void TestSequenceMatcher()
        {
            var m = Matcher.Sequence(Matcher.Char('a'), Matcher.EndOfString);
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
            Assert.Equal(1, m.Match(new MatchContent("cba", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Backward)));
        }

        [Fact]
        public void TestTestMatcher()
        {
            var m = Matcher.Test(Matcher.Char('a'));
            Assert.Equal(0, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("cba", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Backward)));
        }

        [Fact]
        public void TestNegativeTestMatcher()
        {
            var m = Matcher.NegativeTest(Matcher.Char('a'));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("cba", 2, MatchDirection.Backward)));
        }

        [Fact]
        public void TestReverseTestMatcher()
        {
            var m = Matcher.ReverseTest(Matcher.Char('a'));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("cba", 2, MatchDirection.Backward)));
        }

        [Fact]
        public void TestReverseNegativeTestMatcher()
        {
            var m = Matcher.ReverseNegativeTest(Matcher.Char('a'));
            Assert.Equal(0, m.Match(new MatchContent("abc", 0, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 0, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("abc", 1, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 1, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 2, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 2, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 3, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("abc", 3, MatchDirection.Backward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 3, MatchDirection.Forward)));
            Assert.Equal(0, m.Match(new MatchContent("cba", 3, MatchDirection.Backward)));
            Assert.Equal(0, m.Match(new MatchContent("cba", 2, MatchDirection.Forward)));
            Assert.Equal(Matcher.NotMatch, m.Match(new MatchContent("cba", 2, MatchDirection.Backward)));
        }

        [Fact]
        public void TestCaptureGroupMatcher()
        {
            var m = Matcher.CaptureGroup("g", Matcher.Repeat(Matcher.Char('a'), 1));
            {
                var c = new MatchContent("abc", 0, MatchDirection.Forward);
                Assert.Equal(1, m.Match(c));
                var g = c.GetGroup("g");
                Assert.NotNull(g);
                Assert.Equal(0, g.Value.StartIndex);
                Assert.Equal(1, g.Value.Count);
                Assert.Equal("a", g.Value.GetValue());
            }
            {
                var c = new MatchContent("abc", 0, MatchDirection.Backward);
                Assert.Equal(Matcher.NotMatch, m.Match(c));
                var g = c.GetGroup("g");
                Assert.Null(g);
            }
            {
                var c = new MatchContent("abc", 1, MatchDirection.Forward);
                Assert.Equal(Matcher.NotMatch, m.Match(c));
                var g = c.GetGroup("g");
                Assert.Null(g);
            }
            {
                var c = new MatchContent("abc", 1, MatchDirection.Backward);
                Assert.Equal(1, m.Match(c));
                var g = c.GetGroup("g");
                Assert.NotNull(g);
                Assert.Equal(0, g.Value.StartIndex);
                Assert.Equal(1, g.Value.Count);
                Assert.Equal("a", g.Value.GetValue());
            }
            {
                var c = new MatchContent("aaa", 0, MatchDirection.Forward);
                Assert.Equal(3, m.Match(c));
                var g = c.GetGroup("g");
                Assert.NotNull(g);
                Assert.Equal(0, g.Value.StartIndex);
                Assert.Equal(3, g.Value.Count);
                Assert.Equal("aaa", g.Value.GetValue());
            }
            {
                var c = new MatchContent("aaa", 3, MatchDirection.Backward);
                Assert.Equal(3, m.Match(c));
                var g = c.GetGroup("g");
                Assert.NotNull(g);
                Assert.Equal(0, g.Value.StartIndex);
                Assert.Equal(3, g.Value.Count);
                Assert.Equal("aaa", g.Value.GetValue());
            }
        }

        [Fact]
        public void TestBackReferenceMatcher()
        {
            var m = Matcher.Sequence(
                Matcher.CaptureGroup(
                    "g",
                    Matcher.Repeat(
                        Matcher.Char('a'),
                        1
                    )
                ),
                Matcher.Char('b'),
                Matcher.BackReference("g")
            );
            {
                var c = new MatchContent("abc", 0, MatchDirection.Forward);
                Assert.Equal(Matcher.NotMatch, m.Match(c));
                var g = c.GetGroup("g");
                Assert.NotNull(g);
                Assert.Equal(0, g.Value.StartIndex);
                Assert.Equal(1, g.Value.Count);
                Assert.Equal("a", g.Value.GetValue());
            }
            {
                var c = new MatchContent("abc", 0, MatchDirection.Backward);
                Assert.Equal(Matcher.NotMatch, m.Match(c));
                var g = c.GetGroup("g");
                Assert.Null(g);
            }
            {
                var c = new MatchContent("abc", 1, MatchDirection.Forward);
                Assert.Equal(Matcher.NotMatch, m.Match(c));
                var g = c.GetGroup("g");
                Assert.Null(g);
            }
            {
                var c = new MatchContent("abc", 1, MatchDirection.Backward);
                Assert.Equal(Matcher.NotMatch, m.Match(c));
                var g = c.GetGroup("g");
                Assert.Null(g);
            }
            {
                var c = new MatchContent("aba", 0, MatchDirection.Forward);
                Assert.Equal(3, m.Match(c));
                var g = c.GetGroup("g");
                Assert.NotNull(g);
                Assert.Equal(0, g.Value.StartIndex);
                Assert.Equal(1, g.Value.Count);
                Assert.Equal("a", g.Value.GetValue());
            }
            {
                var c = new MatchContent("aabaa", 0, MatchDirection.Forward);
                Assert.Equal(5, m.Match(c));
                var g = c.GetGroup("g");
                Assert.NotNull(g);
                Assert.Equal(0, g.Value.StartIndex);
                Assert.Equal(2, g.Value.Count);
                Assert.Equal("aa", g.Value.GetValue());
            }
            {
                var c = new MatchContent("aaba", 0, MatchDirection.Forward);
                Assert.Equal(Matcher.NotMatch, m.Match(c));
                var g = c.GetGroup("g");
                Assert.NotNull(g);
                Assert.Equal(0, g.Value.StartIndex);
                Assert.Equal(2, g.Value.Count);
                Assert.Equal("aa", g.Value.GetValue());
            }
            {
                var c = new MatchContent("aababb", 0, MatchDirection.Forward);
                Assert.Equal(Matcher.NotMatch, m.Match(c));
                var g = c.GetGroup("g");
                Assert.NotNull(g);
                Assert.Equal(0, g.Value.StartIndex);
                Assert.Equal(2, g.Value.Count);
                Assert.Equal("aa", g.Value.GetValue());
            }
        }

        [Fact]
        public void TestComplexMatcher()
        {
            var m = ((Matcher)"abc").Repeat(1, 2).ToGroup("g") + (Matcher.NewLine | Matcher.EndOfString).ToTest();
            {
                var result = m.Match("abc");
                Assert.NotNull(result);
                Assert.Equal(3, result.Length);
                Assert.NotNull(result["g"]);
                Assert.Equal(0, result["g"].StartIndex);
                Assert.Equal(3, result["g"].Count);
                Assert.Equal("abc", result["g"].GetValue());
            }
            {
                var result = m.Match("abcd");
                Assert.Null(result);
            }
            {
                var result = m.Match("abcabc");
                Assert.NotNull(result);
                Assert.Equal(6, result.Length);
                Assert.NotNull(result["g"]);
                Assert.Equal(0, result["g"].StartIndex);
                Assert.Equal(6, result["g"].Count);
                Assert.Equal("abcabc", result["g"].GetValue());
            }
            {
                var result = m.Match("abc\nd");
                Assert.NotNull(result);
                Assert.Equal(3, result.Length);
                Assert.NotNull(result["g"]);
                Assert.Equal(0, result["g"].StartIndex);
                Assert.Equal(3, result["g"].Count);
                Assert.Equal("abc", result["g"].GetValue());
            }
            {
                var result = m.Match("abcabcabc");
                Assert.Null(result);
            }
            {
                var result = m.Match("abc\nabcabc");
                Assert.NotNull(result);
                Assert.Equal(3, result.Length);
                Assert.NotNull(result["g"]);
                Assert.Equal(0, result["g"].StartIndex);
                Assert.Equal(3, result["g"].Count);
                Assert.Equal("abc", result["g"].GetValue());
            }
        }
    }
}


text:
<?php
namespace Application\Factory\Table;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Application\Model\Entity\KhachHang;
use Application\Model\KhachHangTable;

class KhachHangTableFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $servicelocator)
    {
        $adapter = $servicelocator->get('Zend\Db\Adapter\Adapter');
        $resultSetPrototype = new ResultSet();
        $resultSetPrototype->setArrayObjectPrototype(new KhachHang());
        $tableGateway = new TableGateway('khach_hang', $adapter, null, $resultSetPrototype);
        return new KhachHangTable($tableGateway);
    }
}


text:
"""Random number interface of MXNet."""
from __future__ import absolute_import

import ctypes
from .base import _LIB, check_call
from .ndarray.random import *
from .context import Context

def seed(seed_state, ctx="all"):
    """Seeds the random number generators in MXNet.

    This affects the behavior of modules in MXNet that uses random number generators,
    like the dropout operator and `NDArray`'s random sampling operators.

    Parameters
    ----------
    seed_state : int
        The random number seed.

    ctx : Context
        The device context of the generator. The default is "all" which means seeding random
        number generators of all devices.

    Notes
    -----
    Random number generators in MXNet are device specific.
    `mx.random.seed(seed_state)` sets the state of each generator using `seed_state` and the
    device id. Therefore, random numbers generated from different devices can be different
    even if they are seeded using the same seed.

    To produce identical random number sequences independent of the device id,
    set optional `ctx` argument. This produces the same sequence of random numbers independent
    of the device id, but the sequence can be different on different kind of devices as MXNet's
    random number generators for CPU and GPU use different algorithms.

    Example
    -------
    >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy())
    [[ 1.36481571 -0.62203991]
     [-1.4962182  -0.08511394]]
    >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy())
    [[ 1.09544981 -0.20014545]
     [-0.20808885  0.2527658 ]]
    # Same results on the same device with the same seed
    >>> mx.random.seed(128)
    >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy())
    [[ 0.47400656 -0.75213492]
     [ 0.20251541  0.95352972]]
    >>> mx.random.seed(128)
    >>> print(mx.nd.random.normal(shape=(2,2)).asnumpy())
    [[ 0.47400656 -0.75213492]
     [ 0.20251541  0.95352972]]
    # Different results on gpu(0) and gpu(1) with the same seed
    >>> mx.random.seed(128)
    >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy())
    [[ 2.5020072 -1.6884501]
     [-0.7931333 -1.4218881]]
    >>> mx.random.seed(128)
    >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy())
    [[ 0.24336822 -1.664805  ]
     [-1.0223296   1.253198  ]]
    # Seeding with `ctx` argument produces identical results on gpu(0) and gpu(1)
    >>> mx.random.seed(128, ctx=mx.gpu(0))
    >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(0)).asnumpy())
    [[ 2.5020072 -1.6884501]
     [-0.7931333 -1.4218881]]
    >>> mx.random.seed(128, ctx=mx.gpu(1))
    >>> print(mx.nd.random.normal(shape=(2,2), ctx=mx.gpu(1)).asnumpy())
    [[ 2.5020072 -1.6884501]
     [-0.7931333 -1.4218881]]
    """
    if not isinstance(seed_state, int):
        raise ValueError('seed_state must be int')
    seed_state = ctypes.c_int(seed_state)
    if ctx == "all":
        check_call(_LIB.MXRandomSeed(seed_state))
    else:
        ctx = Context(ctx)
        check_call(_LIB.MXRandomSeedContext(seed_state, ctx.device_typeid, ctx.device_id))


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var nodeAcl = require('acl');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
const paginate = require('express-paginate');

var index = require('./routes/index');
var users = require('./routes/users');
var sku = require('./routes/sku');
var color = require('./routes/color');
var gender = require('./routes/gender');
var size = require('./routes/size');
var item = require('./routes/item');
var innerreport = require('./routes/innerreport')
var report = require('./routes/report');
var output = require('./routes/output');
var category = require('./routes/category')
var profile = require('./routes/profile')
var retur = require('./routes/retur')
var auth = require('./routes/auth');
var deliveryOrder = require('./routes/deliveryorder');
var inner = require('./routes/inner');
var innerDeliveryOrder = require('./routes/innerDeliveryOrder');
var warehouse = require('./routes/warehouse');
var carton = require('./routes/carton');
var innerGrade = require('./routes/innergrade');
var innerSource = require('./routes/innersource');
var config = require('./config/config');
var cors = require('cors')

require('dotenv').config()

mongoose.connect(process.env.MONGO_URL, { useMongoClient: true }, err=>{
  var acl = new nodeAcl(new nodeAcl.mongodbBackend(mongoose.connection.db, ''));
  app.set('acl', acl)
  app.set('mongo', mongoose.connection.db)
  // sementara tak taruh sini seeder acl-nya :D (mnirfan)
  acl.allow('admin', 'item', ['GET', 'POST', 'DELETE'])
  acl.allow('admin', 'category', ['GET', 'POST', 'DELETE'])
  acl.allow('admin', 'user', ['GET', 'POST', 'DELETE'])
  acl.allow('basic', 'item', ['GET'])
  acl.addUserRoles('1', 'admin') // irfan
  acl.addUserRoles('9', 'admin') // irfan
  acl.addUserRoles('21', 'basic') //arnaz
})

var app = express();
var router = express.Router()

// view engine setup

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.set('superSecret',config.secret)

// acl.whatResources('lolaa', (err, res)=>{
//   console.log("debuggg");
//   console.log(res);
//   console.log(err);
// })

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

console.log('pada NODE_ENV : ', process.env.NODE_ENV);

//use cors
app.use(cors())

//body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(paginate.middleware(10,50))
app.use(function(req, res, next) {
  // set default or minimum is 10 (as it was prior to v0.2.0)
  if (req.query.limit <= 10) req.query.limit = 10;
  next();
});

//verify token
router.use(function(req, res, next){
  if (req.query.accessToken) {
    var head = ['Bearer', req.query.accessToken]
  }
  else {
    var head = req.headers.authorization ? req.headers.authorization.split(' ') : ''
  }
  var token = null

  if(head.length == 2){
    var scheme = head[0]
    if(/^Bearer$/i.test(scheme)){
      token = head[1]
      jwt.verify(token, app.get('superSecret'), function (err, decoded) {
        if(err){
          res.status(403).json({
            success: false,
            message: 'Failed to authenticate token.'
          })
        }else {
          req.decoded = decoded;
          next();
        }
      })}
  }else {
    return res.status(403).send({
       success: false,
       message: 'No token provided.'
   })
  }
})

app.use('/api',router);
app.use('/', index);
app.use('/api/user', users);
app.use('/api/item', item);
app.use('/api/sku', sku);
app.use('/api/color', color);
app.use('/api/gender', gender);
app.use('/api/size', size);
app.use('/api/report', report);
app.use('/api/category', category);
app.use('/api/profile', profile);
app.use('/api/inner', inner);
app.use('/api/innergrade', innerGrade);
app.use('/api/innersource', innerSource);
app.use('/api/innerreport',innerreport)
app.use('/api/report',report)
app.use('/api/warehouse', warehouse);
app.use('/api/innerDeliveryOrder', innerDeliveryOrder);
app.use('/api/carton', carton);
app.use('/api/retur', retur);
app.use('/api/output', output);
app.use('/api/deliveryorder', deliveryOrder);
app.use('/auth', auth);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


text:
//  This file is part of gen-mdl - A Source code generator for model definitions.
//  Copyright (c) angrifel

//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to
//  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
//  of the Software, and to permit persons to whom the Software is furnished to do
//  so, subject to the following conditions:

//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.

//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.

namespace ModelGenerator.TypeScript.Builders
{
  public class TypeScriptExportStatementBuilder
  {
    private readonly TypeScriptExportStatement _result = new TypeScriptExportStatement();

    private TypeScriptExportStatementBuilder() { }

    public static TypeScriptExportStatementBuilder Start() => new TypeScriptExportStatementBuilder();

    public TypeScriptExportStatementBuilder DefaultExport(TypeScriptTypeDeclaration typeDeclaration)
    {
      _result.IsDefault = true;
      _result.TypeDeclaration = typeDeclaration;
      return this;
    }

    public TypeScriptExportStatement Build() => _result;
  }
}


text:
import pathlib

import pytest
from pytestshellutils.utils.ports import get_unused_localhost_port

import salt.config
import tests.support.netapi as netapi

@pytest.fixture
def netapi_port():
    return get_unused_localhost_port()

@pytest.fixture
def client_config(salt_master_factory):
    # Make sure we have the tokens directory writable
    tokens_dir = pathlib.Path(salt_master_factory.config["cachedir"]) / "tokens"
    if not tokens_dir.is_dir():
        tokens_dir.mkdir()
    config = salt.config.client_config(
        salt_master_factory.config["conf_file"],
        defaults=salt_master_factory.config.copy(),
    )
    return config

@pytest.fixture
def minion_config(salt_minion_factory):
    return salt_minion_factory.config.copy()

@pytest.fixture
def load_auth(client_config):
    return netapi.load_auth(client_config)

@pytest.fixture(scope="package")
def salt_netapi_account(salt_netapi_account_factory):
    with salt_netapi_account_factory as account:
        yield account

@pytest.fixture
def auth_creds(salt_netapi_account):
    return {
        "username": salt_netapi_account.username,
        "password": salt_netapi_account.password,
        "eauth": "auto",
    }

@pytest.fixture
def auth_token(load_auth, auth_creds):
    """
    Mint and return a valid token for auth_creds
    """
    return netapi.auth_token(load_auth, auth_creds)

@pytest.fixture
def content_type_map():
    return netapi.content_type_map()