text:
<?php

/**
 * HighchartsAsset class file.
 *
 * @author Milo Schuman <miloschuman@gmail.com>
 * @link https://github.com/miloschuman/yii2-highcharts/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace miloschuman\highcharts;

use yii\web\AssetBundle;

/**
 * Asset bundle for Highcharts, Highstock, and Highmaps widgets.
 */
class HighchartsAsset extends AssetBundle
{
    public $sourcePath = '@bower/highcharts';
    public $depends = ['yii\web\JqueryAsset'];

    /**
     * Registers additional JavaScript files required by the widget.
     *
     * @param array $scripts list of additional JavaScript files to register.
     * @return $this
     */
    public function withScripts($scripts = ['highcharts'])
    {
        // use unminified files when in debug mode
        $ext = YII_DEBUG ? 'src.js' : 'js';

        // add files
        foreach ($scripts as $script) {
            // theme files are not packaged with a .src.js version
            $this->js[] = "$script." . ((strpos($script, 'themes/') === 0) ? 'js' : $ext);
        }

        // make sure that either highcharts or highstock base file is included.
        array_unshift($this->js, "highcharts.$ext");
        $hasHighstock = in_array("highstock.$ext", $this->js);
        if ($hasHighstock) {
            array_unshift($this->js, "highstock.$ext");
            // remove highcharts if highstock is used on page
            $this->js = array_diff($this->js, ["highcharts.$ext"]);
        }

        return $this;
    }
}


text:
/*
 * @test
 * @bug 4469866
 * @summary Connecting to a link-local IPv6 address should not
 *          causes a SocketException to be thrown.
 */
import java.net.*;
import java.util.Enumeration;

public class LinkLocal {

    static int testCount = 0;
    static int failed = 0;

    static void TcpTest(InetAddress ia) throws Exception {
        System.out.println("**************************************");
        testCount++;
        System.out.println("Test " + testCount + ": TCP connect to " + ia);

        /*
         * Create ServerSocket on wildcard address and then
         * try to connect Socket to link-local address.
         */
        ServerSocket ss = new ServerSocket(0);

        Socket s = new Socket();
        try {
            s.connect(new InetSocketAddress(ia, ss.getLocalPort()));

            System.out.println("Test passed - connection established.");

            // connection was established so accept it
            Socket s2 = ss.accept();
            s2.close();
        } catch (SocketException e) {
            failed++;
            System.out.println("Test failed: " + e);
        }

        // clean up
        s.close();
        ss.close();
    }

    static void UdpTest(InetAddress ia, boolean connected) throws Exception {

        System.out.println("**************************************");
        testCount++;

        if (connected) {
            System.out.println("Test " + testCount + ": UDP connect to " + ia);
        } else {
            System.out.println("Test " + testCount + ": UDP send to " + ia);
        }

        DatagramSocket ds1 = new DatagramSocket();
        DatagramSocket ds2 = new DatagramSocket();

        try {
            byte b[] = "Hello".getBytes();
            DatagramPacket p = new DatagramPacket(b, b.length);

            if (connected) {
                ds1.connect( new InetSocketAddress(ia, ds2.getLocalPort()) );
                System.out.println("DatagramSocket connected.");
            } else {
                p.setAddress(ia);
                p.setPort(ds2.getLocalPort());
            }
            ds1.send(p);
            System.out.println("Packet has been sent.");

            ds2.setSoTimeout(1000);
            ds2.receive(p);
            System.out.println("Test passed - packet received.");
        } catch (SocketException e) {
            failed++;
            System.out.println("Test failed: " + e);
        }

        ds1.close();
        ds2.close();
    }

    static void TestAddress(InetAddress ia) throws Exception {
        TcpTest(ia);
        UdpTest(ia, true);      /* unconnected */
        UdpTest(ia, false);     /* connected */
    }

    public static void main(String args[]) throws Exception {

        /*
         * If an argument is provided ensure that it's
         * a link-local IPv6 address.
         */
        if (args.length > 0) {
            InetAddress ia = InetAddress.getByName(args[0]);

            if ( !(ia instanceof Inet6Address) ||
                !ia.isLinkLocalAddress()) {
                throw new Exception(ia +
                        " is not a link-local IPv6 address");
            }

            TestAddress(ia);
        }

        /*
         * If no argument is provided then enumerate the
         * local addresses and run the test on each link-local
         * IPv6 address.
         */
        if (args.length == 0) {
            Enumeration nifs = NetworkInterface.getNetworkInterfaces();
            while (nifs.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface)nifs.nextElement();
                Enumeration addrs = ni.getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress addr = (InetAddress)addrs.nextElement();

                    if (addr instanceof Inet6Address &&
                        addr.isLinkLocalAddress()) {

                        TestAddress(addr);
                    }
                }
            }
        }

        /*
         * Print results
         */
        if (testCount == 0) {
            System.out.println("No link-local IPv6 addresses - test skipped!");
        } else {
            System.out.println("**************************************");
            System.out.println(testCount + " test(s) executed, " +
                failed + " failed.");
            if (failed > 0) {
                throw new Exception( failed + " test(s) failed.");
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


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

/*=============================================================================
**
**
**
** Purpose: The exception class for type loading failures.
**
**
=============================================================================*/

using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security;
using System.Diagnostics.Contracts;

namespace System
{
    [Serializable]
    public class TypeLoadException : SystemException
    {
        public TypeLoadException()
            : base(SR.Arg_TypeLoadException)
        {
            HResult = __HResults.COR_E_TYPELOAD;
        }

        public TypeLoadException(String message)
            : base(message)
        {
            HResult = __HResults.COR_E_TYPELOAD;
        }

        public TypeLoadException(String message, Exception inner)
            : base(message, inner)
        {
            HResult = __HResults.COR_E_TYPELOAD;
        }

        internal TypeLoadException(String message, String typeName)
            : base(message)
        {
            HResult = __HResults.COR_E_TYPELOAD;
            _typeName = typeName;
        }

        protected TypeLoadException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        public override String Message
        {
            get
            {
                SetMessageField();
                return _message;
            }
        }

        private void SetMessageField()
        {
            if (_message == null)
                _message = SR.Arg_TypeLoadException;
        }

        public String TypeName
        {
            get
            {
                if (_typeName == null)
                    return String.Empty;
                return _typeName;
            }
        }

        private String _typeName;
    }
}


text:
import React, { Component } from 'react'

export default class QuantityList extends Component {
  getGroupRows(map, groupName) {
    var groupRows = [];

    map.forEach( function (value, k, m){
      var sizes = k.split('*');
      groupRows.push(

            {map.get(k)}
            {sizes[0]}
            {sizes[1]}
            {groupName.toUpperCase()}

      );
    })

    return groupRows;
  }
  getGroupDiv(group, groupName) {

    var qtyAggregatedMap = new Map();
    for (const p of group) {
      var key = `${p.cutHt}*${p.cutWd}`;
      if (qtyAggregatedMap.has(key)) {
        qtyAggregatedMap.set(key, qtyAggregatedMap.get(key) + p.qty);
      } else {
        qtyAggregatedMap.set(key, p.qty);
      }
    }
    return (

          {groupName.toUpperCase()}

                      Qty
                      CutHt
                      CutWd
                      Material

                  {this.getGroupRows(qtyAggregatedMap, groupName)}

    );
  }
  sortPieces(piece1, piece2) {
    var diff;
    var cutHtDiff = piece1.cutHt - piece2.cutHt;
    if (cutHtDiff == 0) {
      diff = piece1.cutWd - piece2.cutWd;
    } else {
      diff = cutHtDiff;
    }

    return diff;
  }
  getGroupDivs(calcResult) {
    var groupDivs = [];
    var groups = {
      white16: [],
      colorBoard: []
    };
    for (const cab of calcResult) {
      for (const piece of cab.pieces) {
        if (piece.material == 'WHITE16') {
          groups.white16.push(piece);
        } else {
          groups.colorBoard.push(piece);
        }
      }
    }
    groupDivs.push(this.getGroupDiv(groups.white16.sort(this.sortPieces), 'white16'));
    groupDivs.push(this.getGroupDiv(groups.colorBoard.sort(this.sortPieces), 'colorBoard'));
    return groupDivs;
  }
  render () {
    return (

          {this.getGroupDivs(this.props.calcResult)}

    )
  }
}


text:
files = {}

try:
    import htcondor
    import classad
except ImportError:
    import imp
    local_path = ['/usr/lib64/python2.6/site-packages/']
    def _get_module(name):
        global files
        found = imp.find_module(name,local_path)
        files[name] = found[0]
        return imp.load_module(name,*found)
    classad = _get_module('classad')
    htcondor = _get_module('htcondor')

def _close_files():
    global files
    for k,v in files.iteritems():
        v.close()

import atexit
atexit.register(_close_files)


text:
import logging

import telemetry
from telemetry import util

def _WaitForLoginFormToLoad(backend, login_form_id, tab):
  def IsFormLoadedOrAlreadyLoggedIn():
    return tab.EvaluateJavaScript(
        'document.querySelector("#%s")!== null' % login_form_id) or \
            backend.IsAlreadyLoggedIn(tab)

  # Wait until the form is submitted and the page completes loading.
  util.WaitFor(lambda: IsFormLoadedOrAlreadyLoggedIn(), # pylint: disable=W0108
               60)

def _SubmitFormAndWait(form_id, tab):
  js = 'document.getElementById("%s").submit();' % form_id
  tab.ExecuteJavaScript(js)

  def IsLoginStillHappening():
    return tab.EvaluateJavaScript(
        'document.querySelector("#%s")!== null' % form_id)

  # Wait until the form is submitted and the page completes loading.
  util.WaitFor(lambda: not IsLoginStillHappening(), 60)

class FormBasedCredentialsBackend(object):
  def __init__(self):
    self._logged_in = False

  def IsAlreadyLoggedIn(self, tab):
    raise NotImplementedError()

  @property
  def credentials_type(self):
    raise NotImplementedError()

  @property
  def url(self):
    raise NotImplementedError()

  @property
  def login_form_id(self):
    raise NotImplementedError()

  @property
  def login_input_id(self):
    raise NotImplementedError()

  @property
  def password_input_id(self):
    raise NotImplementedError()

  def IsLoggedIn(self):
    return self._logged_in

  def _ResetLoggedInState(self):
    """Makes the backend think we're not logged in even though we are.
    Should only be used in unit tests to simulate --dont-override-profile.
    """
    self._logged_in = False

  def LoginNeeded(self, tab, config):
    """Logs in to a test account.

    Raises:
      RuntimeError: if could not get credential information.
    """
    if self._logged_in:
      return True

    if 'username' not in config or 'password' not in config:
      message = ('Credentials for "%s" must include username and password.' %
                 self.credentials_type)
      raise RuntimeError(message)

    logging.debug('Logging into %s account...' % self.credentials_type)

    try:
      logging.info('Loading %s...', self.url)
      tab.Navigate(self.url)
      _WaitForLoginFormToLoad(self, self.login_form_id, tab)

      if self.IsAlreadyLoggedIn(tab):
        self._logged_in = True
        return True

      tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
      logging.info('Loaded page: %s', self.url)

      email_id = 'document.querySelector("#%s").%s.value = "%s"; ' % (
          self.login_form_id, self.login_input_id, config['username'])
      password = 'document.querySelector("#%s").%s.value = "%s"; ' % (
          self.login_form_id, self.password_input_id, config['password'])
      tab.ExecuteJavaScript(email_id)
      tab.ExecuteJavaScript(password)

      _SubmitFormAndWait(self.login_form_id, tab)

      self._logged_in = True
      return True
    except telemetry.TimeoutException:
      logging.warning('Timed out while loading: %s', self.url)
      return False

  def LoginNoLongerNeeded(self, tab): # pylint: disable=W0613
    assert self._logged_in


text:
	<li <?php echo $this->uri->segment(4) == '' ? 'class="active"' : '' ?>>
		<a href="<?php echo site_url(SITE_AREA .'/content/project') ?>" id="list"><?php echo lang('project_list'); ?>

	<?php if ($this->auth->has_permission('Project.Content.Create')) : ?>
	<li <?php echo $this->uri->segment(4) == 'create' ? 'class="active"' : '' ?> >
		<a href="<?php echo site_url(SITE_AREA .'/content/project/create') ?>" id="create_new"><?php echo lang('project_new'); ?>

	<?php endif; ?>


text:
"""
    Qc API

    Qc API  # noqa: E501

    The version of the OpenAPI document: 3.0.0
    Contact: cloudsupport@telestream.net
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from telestream_cloud_qc.configuration import Configuration

class VideoSubDescriptorTest(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'sub_descriptor_type': 'VideoSubDescriptorType',
        'reject_on_error': 'bool',
        'checked': 'bool'
    }

    attribute_map = {
        'sub_descriptor_type': 'sub_descriptor_type',
        'reject_on_error': 'reject_on_error',
        'checked': 'checked'
    }

    def __init__(self, sub_descriptor_type=None, reject_on_error=None, checked=None, local_vars_configuration=None):  # noqa: E501
        """VideoSubDescriptorTest - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._sub_descriptor_type = None
        self._reject_on_error = None
        self._checked = None
        self.discriminator = None

        if sub_descriptor_type is not None:
            self.sub_descriptor_type = sub_descriptor_type
        if reject_on_error is not None:
            self.reject_on_error = reject_on_error
        if checked is not None:
            self.checked = checked

    @property
    def sub_descriptor_type(self):
        """Gets the sub_descriptor_type of this VideoSubDescriptorTest.  # noqa: E501

        :return: The sub_descriptor_type of this VideoSubDescriptorTest.  # noqa: E501
        :rtype: VideoSubDescriptorType
        """
        return self._sub_descriptor_type

    @sub_descriptor_type.setter
    def sub_descriptor_type(self, sub_descriptor_type):
        """Sets the sub_descriptor_type of this VideoSubDescriptorTest.

        :param sub_descriptor_type: The sub_descriptor_type of this VideoSubDescriptorTest.  # noqa: E501
        :type: VideoSubDescriptorType
        """

        self._sub_descriptor_type = sub_descriptor_type

    @property
    def reject_on_error(self):
        """Gets the reject_on_error of this VideoSubDescriptorTest.  # noqa: E501

        :return: The reject_on_error of this VideoSubDescriptorTest.  # noqa: E501
        :rtype: bool
        """
        return self._reject_on_error

    @reject_on_error.setter
    def reject_on_error(self, reject_on_error):
        """Sets the reject_on_error of this VideoSubDescriptorTest.

        :param reject_on_error: The reject_on_error of this VideoSubDescriptorTest.  # noqa: E501
        :type: bool
        """

        self._reject_on_error = reject_on_error

    @property
    def checked(self):
        """Gets the checked of this VideoSubDescriptorTest.  # noqa: E501

        :return: The checked of this VideoSubDescriptorTest.  # noqa: E501
        :rtype: bool
        """
        return self._checked

    @checked.setter
    def checked(self, checked):
        """Sets the checked of this VideoSubDescriptorTest.

        :param checked: The checked of this VideoSubDescriptorTest.  # noqa: E501
        :type: bool
        """

        self._checked = checked

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, VideoSubDescriptorTest):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, VideoSubDescriptorTest):
            return True

        return self.to_dict() != other.to_dict()


text:
from flask import Flask
# from flask_sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO
import docassemble.webapp.db_object  # noqa: F401 # pylint: disable=unused-import
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref

def create_app():
    the_app = Flask(__name__)
    the_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    from docassemble.base.config import daconfig  # pylint: disable=import-outside-toplevel
    import docassemble.webapp.database  # pylint: disable=import-outside-toplevel,redefined-outer-name
    alchemy_connect_string = docassemble.webapp.database.alchemy_connection_string()
    # the_app.config['SQLALCHEMY_DATABASE_URI'] = alchemy_connect_string
    the_app.secret_key = daconfig.get('secretkey', '38ihfiFehfoU34mcq_4clirglw3g4o87')
    # the_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # the_db = SQLAlchemy(the_app)
    if alchemy_connect_string.startswith('postgresql'):
        connect_args = docassemble.webapp.database.connect_args()
        the_db = sqlalchemy.create_engine(alchemy_connect_string, connect_args=connect_args, pool_pre_ping=docassemble.webapp.database.pool_pre_ping)
    else:
        the_db = sqlalchemy.create_engine(alchemy_connect_string, pool_pre_ping=docassemble.webapp.database.pool_pre_ping)
    Base = declarative_base()
    Base.metadata.bind = the_db
    # the_app.wsgi_app = ProxyFix(the_app.wsgi_app)
    the_db.Model = Base
    the_db.Column = sqlalchemy.Column
    the_db.Integer = sqlalchemy.Integer
    the_db.String = sqlalchemy.String
    the_db.Index = sqlalchemy.Index
    the_db.Boolean = sqlalchemy.Boolean
    the_db.Text = sqlalchemy.Text
    the_db.DateTime = sqlalchemy.DateTime
    the_db.func = sqlalchemy.func
    the_db.relationship = relationship
    the_db.backref = backref
    the_db.ForeignKey = sqlalchemy.ForeignKey
    docassemble.webapp.db_object.db = the_db
    # import flask_login
    docassemble.webapp.db_object.UserMixin = object
    if 'cross site domains' in daconfig and isinstance(daconfig['cross site domains'], list) and len(daconfig['cross site domains']) > 0:
        origins = daconfig['cross site domains']
    else:
        origins = [daconfig.get('url root', '*')]
    the_socketio = SocketIO(the_app, async_mode='eventlet', verify=False, logger=True, engineio_logger=True, cors_allowed_origins=origins)
    return the_app, the_db, the_socketio

app, db, socketio = create_app()


text:
<form id="{v#id}loginform" role="form" action="/user/login/" method="post">

        Имя пользователя или email
        <input id="{v#id}in-username" type="text"
               name="username" class="form-control field-required"
               placeholder="Имя пользователя или email">

        Пароль
        <input id="{v#id}in-pass" type="password"
               name="password" class="form-control field-required"
               placeholder="Пароль">

             <input type="checkbox" name="autologin" checked="checked"
                           data-form="autologin"> Запомнить меня

        <button type="submit" class="btn btn-primary" data-wait="disable">Войти</button>

</form>


text:
package org.apache.sshd;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.ServerSocket;

import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.future.OpenFuture;
import org.apache.sshd.common.SshException;
import org.apache.sshd.common.future.CloseFuture;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.apache.sshd.common.util.BufferUtils;
import org.apache.sshd.util.BogusPasswordAuthenticator;
import org.apache.sshd.util.EchoShellFactory;
import org.apache.sshd.util.TeePipedOutputStream;
import org.junit.After;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;

/**
 * TODO Add javadoc
 *
 * @author Apache MINA SSHD Project
 */
public class ClientTest {

    private SshServer sshd;
    private int port;

    @Before
    public void setUp() throws Exception {
        ServerSocket s = new ServerSocket(0);
        port = s.getLocalPort();
        s.close();

        sshd = SshServer.setUpDefaultServer();
        sshd.setPort(port);
        sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/test/resources/hostkey.pem" }));
        sshd.setShellFactory(new EchoShellFactory());
        sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
        sshd.start();
    }

    @After
    public void tearDown() throws Exception {
        if (sshd != null) {
            sshd.stop();
            Thread.sleep(50);
        }
    }

    @Test
    public void testClient() throws Exception {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();
        ClientSession session = client.connect("localhost", port).await().getSession();
        session.authPassword("smx", "smx").await().isSuccess();
        ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);

        ByteArrayOutputStream sent = new ByteArrayOutputStream();
        PipedOutputStream pipedIn = new TeePipedOutputStream(sent);
        channel.setIn(new PipedInputStream(pipedIn));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        channel.setOut(out);
        channel.setErr(err);
        channel.open();

        pipedIn.write("this is my command\n".getBytes());
        pipedIn.flush();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 1000; i++) {
            sb.append("0123456789");
        }
        sb.append("\n");
        pipedIn.write(sb.toString().getBytes());

        pipedIn.write("exit\n".getBytes());
        pipedIn.flush();

        channel.waitFor(ClientChannel.CLOSED, 0);

        channel.close(false);
        client.stop();

        assertArrayEquals(sent.toByteArray(), out.toByteArray());
    }

    @Test
    public void testClientWithLengthyDialog() throws Exception {
        SshClient client = SshClient.setUpDefaultClient();
        // Reduce window size and packet size
//        client.getProperties().put(SshClient.WINDOW_SIZE, Integer.toString(0x20000));
//        client.getProperties().put(SshClient.MAX_PACKET_SIZE, Integer.toString(0x1000));
//        sshd.getProperties().put(SshServer.WINDOW_SIZE, Integer.toString(0x20000));
//        sshd.getProperties().put(SshServer.MAX_PACKET_SIZE, Integer.toString(0x1000));
        client.start();
        ClientSession session = client.connect("localhost", port).await().getSession();
        session.authPassword("smx", "smx");
        ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
        ByteArrayOutputStream sent = new ByteArrayOutputStream();
        PipedOutputStream pipedIn = new TeePipedOutputStream(sent);
        channel.setIn(new PipedInputStream(pipedIn));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        channel.setOut(out);
        channel.setErr(err);
        channel.open().await();

        long t0 = System.currentTimeMillis();

        int bytes = 0;
        for (int i = 0; i < 10000; i++) {
            byte[] data = "01234567890123456789012345678901234567890123456789\n".getBytes();
            pipedIn.write(data);
            pipedIn.flush();
            bytes += data.length;
            if ((bytes & 0xFFF00000) != ((bytes - data.length) & 0xFFF00000)) {
                System.out.println("Bytes written: " + bytes);
            }
        }
        pipedIn.write("exit\n".getBytes());
        pipedIn.flush();

        long t1 = System.currentTimeMillis();

        System.out.println("Sent " + (bytes / 1024) + " Kb in " + (t1 - t0) + " ms");

        System.out.println("Waiting for channel to be closed");

        channel.waitFor(ClientChannel.CLOSED, 0);

        channel.close(false);
        client.stop();

        assertTrue(BufferUtils.equals(sent.toByteArray(), out.toByteArray()));
        //assertArrayEquals(sent.toByteArray(), out.toByteArray());
    }

    @Test(expected = SshException.class)
    public void testOpenChannelOnClosedSession() throws Exception {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();
        ClientSession session = client.connect("localhost", port).await().getSession();
        session.authPassword("smx", "smx").await().isSuccess();
        ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
        session.close(false);

        ByteArrayOutputStream sent = new ByteArrayOutputStream();
        PipedOutputStream pipedIn = new TeePipedOutputStream(sent);
        channel.setIn(new PipedInputStream(pipedIn));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        channel.setOut(out);
        channel.setErr(err);
        channel.open();
    }

    @Test
    public void testCloseBeforeAuthSucceed() throws Exception {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();
        ClientSession session = client.connect("localhost", port).await().getSession();
        AuthFuture authFuture = session.authPassword("smx", "smx");
        CloseFuture closeFuture = session.close(false);
        authFuture.await();
        closeFuture.await();
        assertNotNull(authFuture.getException());

    }

    @Test
    public void testCloseCleanBeforeChannelOpened() throws Exception {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();
        ClientSession session = client.connect("localhost", port).await().getSession();
        session.authPassword("smx", "smx").await();
        ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
        channel.setIn(new ByteArrayInputStream(new byte[0]));
        channel.setOut(new ByteArrayOutputStream());
        channel.setErr(new ByteArrayOutputStream());
        OpenFuture openFuture = channel.open();
        CloseFuture closeFuture = session.close(false);
        openFuture.await();
        closeFuture.await();
        assertNotNull(openFuture.isOpened());
        assertNotNull(closeFuture.isClosed());
    }

    @Test
    public void testCloseImmediateBeforeChannelOpened() throws Exception {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();
        ClientSession session = client.connect("localhost", port).await().getSession();
        session.authPassword("smx", "smx").await();
        ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
        channel.setIn(new ByteArrayInputStream(new byte[0]));
        channel.setOut(new ByteArrayOutputStream());
        channel.setErr(new ByteArrayOutputStream());
        OpenFuture openFuture = channel.open();
        CloseFuture closeFuture = session.close(true);
        openFuture.await();
        closeFuture.await();
        assertNotNull(openFuture.getException());
        assertNotNull(closeFuture.isClosed());
    }

    public static void main(String[] args) throws Exception {
        SshClient.main(args);
    }
}


text:
package com.newnius.mobileJLU.jwc;

import java.util.List;

/**
 * Created by newnius on 15-12-18.
 */
public class JwcAnnouncement {
    private int id;
    private String title;
    private String content;
    private String date;
    private String department;
    private List<String> attachments;
    private List<String> attachmentNames;

    public JwcAnnouncement(int id, String title, String date, String department) {
        this.id = id;
        this.title = title;
        this.date = date;
        this.department = department;
    }

    public JwcAnnouncement(int id, String title, String content, String date, String department, List<String> attachments, List<String> attachmentNames) {
        this.id = id;
        this.title = title;
        this.content = content;
        this.date = date;
        this.department = department;
        this.attachments = attachments;
        this.attachmentNames = attachmentNames;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getContent() {
        return content;
    }

    public String getDate() {
        return date;
    }

    public String getDepartment() {
        return department;
    }
}


text:
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include <string.h> /* for strerror */
#include <pthread.h>
#include <signal.h>
#include "libcgo.h"

static void* threadentry(void*);
static pthread_key_t k1;

#define magic1 (0x23581321345589ULL)

static void
inittls(void)
{
	uint64 x;
	pthread_key_t tofree[128], k;
	int i, ntofree;

	/*
	 * Same logic, code as gcc_darwin_386.c:/inittls.
	 * Note that this is a temporary hack that should be fixed soon.
	 * Android-L and M bionic's pthread implementation differ
	 * significantly, and can change any time.
	 * https://android-review.googlesource.com/#/c/134202
	 *
	 * We chose %fs:0x1d0 which seems to work in testing with Android
	 * emulators (API22, API23) but it may break any time.
	 *
	 * TODO: fix this.
	 *
	 * The linker and runtime hard-code this constant offset
	 * from %fs where we expect to find g. Disgusting.
	 *
	 * Known to src/cmd/link/internal/ld/sym.go:/0x1d0
	 * and to src/runtime/sys_linux_amd64.s:/0x1d0 or /GOOS_android.
	 *
	 * As disgusting as on the darwin/386, darwin/amd64.
	 */
	ntofree = 0;
	for(;;) {
		if(pthread_key_create(&k, nil) != 0) {
			fprintf(stderr, "runtime/cgo: pthread_key_create failed\n");
			abort();
		}
		pthread_setspecific(k, (void*)magic1);
		asm volatile("movq %%fs:0x1d0, %0" : "=r"(x));
		pthread_setspecific(k, 0);
		if(x == magic1) {
			k1 = k;
			break;
		}
		if(ntofree >= nelem(tofree)) {
			fprintf(stderr, "runtime/cgo: could not obtain pthread_keys\n");
			fprintf(stderr, "\ttried");
			for(i=0; i<ntofree; i++)
				fprintf(stderr, " %#x", (unsigned)tofree[i]);
			fprintf(stderr, "\n");
			abort();
		}
		tofree[ntofree++] = k;
	}
	// TODO: output to stderr is not useful for apps.
	// Can we fall back to Android's log library?

	/*
	 * We got the key we wanted.  Free the others.
	 */
	for(i=0; i<ntofree; i++) {
		pthread_key_delete(tofree[i]);
	}
}

static void*
threadentry(void *v)
{
	ThreadStart ts;

	ts = *(ThreadStart*)v;
	free(v);

	if (pthread_setspecific(k1, (void*)ts.g) != 0) {
		fprintf(stderr, "runtime/cgo: pthread_setspecific failed\n");
		abort();
	}

	crosscall_amd64(ts.fn);
	return nil;
}

void (*x_cgo_inittls)(void) = inittls;
void* (*x_cgo_threadentry)(void*) = threadentry;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.pattern.data;

import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;

/**
 * Central lookup.
 *
 * @author palas
 */
public class CentralLookup extends AbstractLookup {

    private InstanceContent content = null;
    private static CentralLookup def = new CentralLookup();

    public CentralLookup(InstanceContent content) {
        super(content);
        this.content = content;
    }

    public CentralLookup() {
        this(new InstanceContent());
    }

    public void add(Object instance) {
        content.add(instance);
    }

    public void remove(Object instance) {
        content.remove(instance);
    }

    public static CentralLookup getDefault() {
        return def;
    }
}


text:
package multipletlsgateway

import (
	"testing"
	"time"

	"istio.io/istio/pkg/test/framework"
	"istio.io/istio/pkg/test/framework/components/environment"
	"istio.io/istio/pkg/test/framework/components/ingress"
	ingressutil "istio.io/istio/tests/integration/security/sds_ingress/util"
)

var (
	credNames = []string{"bookinfo-credential-1", "bookinfo-credential-2", "bookinfo-credential-3",
		"bookinfo-credential-4", "bookinfo-credential-5"}
	hosts = []string{"bookinfo1.example.com", "bookinfo2.example.com", "bookinfo3.example.com",
		"bookinfo4.example.com", "bookinfo5.example.com"}
)

// testMultiTlsGateways deploys multiple TLS gateways with SDS enabled, and creates kubernetes that store
// private key and server certificate for each TLS gateway. Verifies that all gateways are able to terminate
// SSL connections successfully.
func testMultiTLSGateways(t *testing.T, ctx framework.TestContext) { // nolint:interfacer
	t.Helper()

	ingressutil.CreateIngressKubeSecret(t, ctx, credNames, ingress.TLS, ingressutil.IngressCredentialA)
	ingressutil.DeployBookinfo(t, ctx, g, ingressutil.MultiTLSGateway)

	ing := ingress.NewOrFail(t, ctx, ingress.Config{Istio: inst})
	err := ingressutil.WaitUntilGatewaySdsStatsGE(t, ing, len(credNames), 30*time.Second)
	if err != nil {
		t.Errorf("sds update stats does not match: %v", err)
	}
	// Expect two active listeners, one listens on 443 and the other listens on 15090
	err = ingressutil.WaitUntilGatewayActiveListenerStatsGE(t, ing, 2, 60*time.Second)
	if err != nil {
		t.Errorf("total active listener stats does not match: %v", err)
	}
	tlsContext := ingressutil.TLSContext{
		CaCert: ingressutil.CaCertA,
	}
	callType := ingress.TLS

	for _, h := range hosts {
		err := ingressutil.VisitProductPage(ing, h, callType, tlsContext, 30*time.Second,
			ingressutil.ExpectedResponse{ResponseCode: 200, ErrorMessage: ""}, t)
		if err != nil {
			t.Errorf("unable to retrieve 200 from product page at host %s: %v", h, err)
		}
	}
}

func TestTlsGateways(t *testing.T) {
	framework.
		NewTest(t).
		RequiresEnvironment(environment.Kube).
		Run(func(ctx framework.TestContext) {
			testMultiTLSGateways(t, ctx)
		})
}


text:
.class public Landroid/support/v4/widget/EdgeEffectCompat;
.super Ljava/lang/Object;
.source "EdgeEffectCompat.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectIcsImpl;,
        Landroid/support/v4/widget/EdgeEffectCompat$BaseEdgeEffectImpl;,
        Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;
    }
.end annotation

# static fields
.field private static final IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

# instance fields
.field private mEdgeEffect:Ljava/lang/Object;

# direct methods
.method static constructor <clinit>()V
    .locals 2

    .prologue
    .line 37
    sget v0, Landroid/os/Build$VERSION;->SDK_INT:I

    const/16 v1, 0xe

    if-lt v0, v1, :cond_0

    .line 38
    new-instance v0, Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectIcsImpl;

    invoke-direct {v0}, Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectIcsImpl;-><init>()V

    sput-object v0, Landroid/support/v4/widget/EdgeEffectCompat;->IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

    .line 42
    :goto_0
    return-void

    .line 40
    :cond_0
    new-instance v0, Landroid/support/v4/widget/EdgeEffectCompat$BaseEdgeEffectImpl;

    invoke-direct {v0}, Landroid/support/v4/widget/EdgeEffectCompat$BaseEdgeEffectImpl;-><init>()V

    sput-object v0, Landroid/support/v4/widget/EdgeEffectCompat;->IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

    goto :goto_0
.end method

.method public constructor <init>(Landroid/content/Context;)V
    .locals 1
    .param p1, "context"    # Landroid/content/Context;

    .prologue
    .line 132
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 133
    sget-object v0, Landroid/support/v4/widget/EdgeEffectCompat;->IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

    invoke-interface {v0, p1}, Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;->newEdgeEffect(Landroid/content/Context;)Ljava/lang/Object;

    move-result-object v0

    iput-object v0, p0, Landroid/support/v4/widget/EdgeEffectCompat;->mEdgeEffect:Ljava/lang/Object;

    .line 134
    return-void
.end method

# virtual methods
.method public draw(Landroid/graphics/Canvas;)Z
    .locals 2
    .param p1, "canvas"    # Landroid/graphics/Canvas;

    .prologue
    .line 218
    sget-object v0, Landroid/support/v4/widget/EdgeEffectCompat;->IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

    iget-object v1, p0, Landroid/support/v4/widget/EdgeEffectCompat;->mEdgeEffect:Ljava/lang/Object;

    invoke-interface {v0, v1, p1}, Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;->draw(Ljava/lang/Object;Landroid/graphics/Canvas;)Z

    move-result v0

    return v0
.end method

.method public finish()V
    .locals 2

    .prologue
    .line 162
    sget-object v0, Landroid/support/v4/widget/EdgeEffectCompat;->IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

    iget-object v1, p0, Landroid/support/v4/widget/EdgeEffectCompat;->mEdgeEffect:Ljava/lang/Object;

    invoke-interface {v0, v1}, Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;->finish(Ljava/lang/Object;)V

    .line 163
    return-void
.end method

.method public isFinished()Z
    .locals 2

    .prologue
    .line 154
    sget-object v0, Landroid/support/v4/widget/EdgeEffectCompat;->IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

    iget-object v1, p0, Landroid/support/v4/widget/EdgeEffectCompat;->mEdgeEffect:Ljava/lang/Object;

    invoke-interface {v0, v1}, Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;->isFinished(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public onAbsorb(I)Z
    .locals 2
    .param p1, "velocity"    # I

    .prologue
    .line 204
    sget-object v0, Landroid/support/v4/widget/EdgeEffectCompat;->IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

    iget-object v1, p0, Landroid/support/v4/widget/EdgeEffectCompat;->mEdgeEffect:Ljava/lang/Object;

    invoke-interface {v0, v1, p1}, Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;->onAbsorb(Ljava/lang/Object;I)Z

    move-result v0

    return v0
.end method

.method public onPull(F)Z
    .locals 2
    .param p1, "deltaDistance"    # F

    .prologue
    .line 177
    sget-object v0, Landroid/support/v4/widget/EdgeEffectCompat;->IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

    iget-object v1, p0, Landroid/support/v4/widget/EdgeEffectCompat;->mEdgeEffect:Ljava/lang/Object;

    invoke-interface {v0, v1, p1}, Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;->onPull(Ljava/lang/Object;F)Z

    move-result v0

    return v0
.end method

.method public onRelease()Z
    .locals 2

    .prologue
    .line 189
    sget-object v0, Landroid/support/v4/widget/EdgeEffectCompat;->IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

    iget-object v1, p0, Landroid/support/v4/widget/EdgeEffectCompat;->mEdgeEffect:Ljava/lang/Object;

    invoke-interface {v0, v1}, Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;->onRelease(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public setSize(II)V
    .locals 2
    .param p1, "width"    # I
    .param p2, "height"    # I

    .prologue
    .line 143
    sget-object v0, Landroid/support/v4/widget/EdgeEffectCompat;->IMPL:Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;

    iget-object v1, p0, Landroid/support/v4/widget/EdgeEffectCompat;->mEdgeEffect:Ljava/lang/Object;

    invoke-interface {v0, v1, p1, p2}, Landroid/support/v4/widget/EdgeEffectCompat$EdgeEffectImpl;->setSize(Ljava/lang/Object;II)V

    .line 144
    return-void
.end method


text:
#include "semihost_api.h"
#include "mbed_interface.h"
#if DEVICE_STDIO_MESSAGES
#include <stdio.h>
#endif

#ifdef TOOLCHAIN_GCC_CW
// TODO: Ideally, we would like to define directly "_ExitProcess"
void mbed_exit(int return_code) {
#else
void exit(int return_code) {
#endif

#if DEVICE_STDIO_MESSAGES
    fflush(stdout);
    fflush(stderr);
#endif

#if DEVICE_SEMIHOST
    if (mbed_interface_connected()) {
        semihost_exit();
    }
#endif
    if (return_code) {
        mbed_die();
    }

    while (1);
}


text:
class CommisionedClassification : public PaymentClassification
{
public:
	CommisionedClassification(double salary, double rate)
		: mSalary(salary), mCommisionRate(rate) {}
	~CommisionedClassification();

	double getSalary() { return mSalary; }
	double getRate() { return mCommisionRate; }
private:
	double mSalary;
	double mCommisionRate;
};


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dev.yjtsai.minesweeper.commend.event;

/**
 *
 * @author yjtsai
 */
public class Help {
    public Help(){
        System.out.println("\"init\" : Start a new game.");
        System.out.println("\"flip\" : Flip the blank space. Use \"flip x,y\" => \"flip 0,1\" : Open the blank for (0,1).");
        System.out.println("\"flag\" : Flag the blank space the bomb you think where is. Use \"flag x,y\" => \"flag 0,1\" : Mark the blank to flag for (0,1).");
        System.out.println("\"unknown\" : Mark the blank space that you don't know what is it. Use \"unknown x,y\" => \"unknown 0,1\" : Mark the blank to unknown for (0,1).");
        System.out.println("\"quit\" : Quit game.");
    }
}


text:
package com.usermodule.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class RequestMonitor {
	private static final Logger logger = LoggerFactory.getLogger(RequestMonitor.class);

	/*Advice method, runs either before, after or surrounding business function*/
	/*Surrounding advice, add a PointCut as parameter*/
	@Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
	public Object wrap(ProceedingJoinPoint pjp) throws Throwable{
		logger.info("Before controller method "+pjp.getSignature().getName() + ". Thread "+Thread.currentThread().getName());
		Object retVal=pjp.proceed();
		logger.info("Controller method "+ pjp.getSignature().getName()+" execution successful");
		return retVal;
	}

}


text:
<?php
namespace PayPal\EBLBaseComponents;
use PayPal\Core\PPXmlMessage;
/**
 * Type of the Payment is it Instant or Echeck or Any.
 */
class PaymentDirectivesType
   extends PPXmlMessage{

	/**
	 * Type of the Payment is it Instant or Echeck or Any.
	 * @access public

	 * @namespace ebl

	 * @var string
	 */
	public $PaymentType;

}


text:
function DebugMessage($message){
    [System.Diagnostics.Debug]::WriteLine("PoshDnvm:$message")
}
function DnvmTabExpansion($lastBlock) {

    $cmd = $lastBlock -replace "^dnvm\s*", ""
    switch -Regex ($cmd)  {

        ##########################################
        #
        # dnvm <cmd>

        # Handle dnvm <cmd>
        "^(?<cmd>\S*)$" {
            DebugMessage -message "DnvmExpansion: <cmd>; cmd=$($matches['cmd'])"
            $commands | filterMatches $matches['cmd']
        }

        ##########################################
        #
        # dnvm alias

        # Handle dnvm alias <name>
        "^alias (?<name>\S*)$" {
            DebugMessage -message "DnvmExpansion: alias <name>; name=$($matches['name'])"
            getAliases | filterMatches $matches['name']
        }
        # Handle dnvm alias -d <name>
        "^alias -d (?<name>\S*)$" {
            DebugMessage -message "DnvmExpansion: alias -d <name>; name=$($matches['name'])"
            getAliases | filterMatches $matches['name']
        }
        # Handle dnvm alias <name> <version>
        "^alias (?<name>[^-]\S*)\s+(?<version>\S*)$" {
            DebugMessage -message "DnvmExpansion: alias <name> <version>; name=$($matches['name']); version=$($matches['version'])"
            getVersions | filterMatches $matches['version']
        }
        # Handle dnvm alias <name> <version> [switches...] -<switch>
        "^alias (?<name>\S*)\s+(?<version>\S*)\s+.*(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: alias <name> <name> -<switch>; name=$($matches['name']); version=$($matches['version']); switch=$($matches['switch'])"
            @('-a', '-arch', '-os', '-r') | filterMatches $matches['switch']
        }

        # Handle dnvm alias <name> <version> -a <arch>
        "^alias (?<name>\S*)\s+(?<version>\S*)\s+.*-a\s+(?<arch>\S*)$" {
           DebugMessage -message "DnvmExpansion: alias <name> <version> -a <arch>; name=$($matches['name']); version=$($matches['version']); arch=$($matches['arch'])"
           getArchitectures | filterMatches $matches['arch']
        }
        # Handle dnvm alias <name> <version> -arch <arch>
        "^alias (?<name>\S*)\s+(?<version>\S*)\s+.*-arch\s+(?<arch>\S*)$" {
           DebugMessage -message "DnvmExpansion: alias <name> <version> -arch <arch>; name=$($matches['name']); version=$($matches['version']); arch=$($matches['arch'])"
           getArchitectures | filterMatches $matches['arch']
        }

        # Handle dnvm alias <name> <version> -os <os>
        "^alias (?<name>\S*)\s+(?<version>\S*)\s+.*-os\s+(?<os>\S*)$" {
           DebugMessage -message "DnvmExpansion: alias <name> <version> -os <os>; name=$($matches['name']); version=$($matches['version']); os=$($matches['os'])"
           getOSes | filterMatches $matches['os']
        }

        # Handle dnvm alias <name> <version> -r <runtime>
        "^alias (?<name>\S*)\s+(?<version>\S*)\s+.*-r\s+(?<runtime>\S*)$" {
            DebugMessage -message "DnvmExpansion: alias <name> <version> -r <runtime>; name=$($matches['name']); version=$($matches['version']); runtime=$($matches['runtime'])"
            getRuntimes | filterMatches $matches['runtime']
        }

        ##########################################
        #
        # dnvm exec

        # Handle dnvm exec <VersionOrAlias>
        "^exec (?<name>\S*)$" {
            DebugMessage -message "DnvmExpansion: exec <VersionOrAlias>; name=$($matches['name'])"
            getAliasesAndVersions | filterMatches $matches['name']
        }
        # Handle dnvm exec <cmd> <version> [switches...] -<switch>
        "^exec (?<name>\S*)\s+(?<version>\S*).*\s(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: exec <name> <version> -<switch>; name=$($matches['name']); version=$($matches['version']); switch=$($matches['switch'])"
            @('-a', '-arch', '-r') | filterMatches $matches['switch']
        }
        # Handle dnvm exec <name> <version> [switches...] -a <arch>
        "^exec (?<name>\S*)\s+(?<version>\S*).*\s-a\s+(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: exec <name> <version> -arch <arch>; name=$($matches['name']); version=$($matches['version']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm exec <name> <version> [switches...] -arch <arch>
        "^exec (?<name>\S*)\s+(?<version>\S*).*\s-arch\s*(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: exec <name> <version> -arch <arch>; name=$($matches['name']); version=$($matches['version']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm exec <name> <version> [switches...] -r <runtime>
        "^exec (?<name>\S*)\s+(?<version>\S*).*\s-r\s*(?<runtime>\S*)$" {
            DebugMessage -message "DnvmExpansion: exec <name> <version> -r <runtime>; name=$($matches['name']); version=$($matches['version']); runtime=$($matches['runtime'])"
            getRuntimes | filterMatches $matches['runtime']
        }

        ##########################################
        #
        # dnvm help <cmd>

        # Handle dnvm help <cmd>
        "^help (?<cmd>\S*)$" {
            DebugMessage -message "DnvmExpansion: help <cmd>; cmd=$($matches['cmd'])"
            $commands | filterMatches $matches['cmd'] | ?{$_ -ne 'help'}
        }
        # Handle dnvm help -<switch>
        "^help.*\s(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: help -<switch>; switch=$($matches['switch'])"
            @('-PassThru') | filterMatches $matches['switch']
        }
        # Handle dnvm help cmd -<switch>
        "^help\s+(?<switch>-\S*)\s+(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: help <cmd> -<switch>; cmd=$($matches['cmd']); switch=$($matches['switch'])"
            @('-PassThru') | filterMatches $matches['switch']
        }

        ##########################################
        #
        # dnvm install

        # Handle dnvm install <name>
        "^install (?<name>\S*)$" {
            DebugMessage -message "DnvmExpansion: install <name>; name=$($matches['name'])"
            # TODO - name can be path to .nupkg, 'latest', or a version!
            # for now, just disable tab expansion?!
            ''
        }
        # Handle dnvm install <name> [switches...] -<switch>
        "^install (?<name>\S*).*\s(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: install <name> -<switch>; name=$($matches['name']); switch=$($matches['switch'])"
            @('-a', '-alias', '-arch', '-r', '-f', '-g', '-Proxy', '-NoNative', '-Ngen', '-Persistent', '-Unstable') | filterMatches $matches['switch']
        }
        # Handle dnvm install <name> [switches...] -a <arch>
        "^install (?<name>\S*).*\s-a\s*(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: install <name> -arch <arch>; name=$($matches['name']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm install <name> [switches...] -arch <arch>
        "^install (?<name>\S*).*\s-arch\s*(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: install <name> -arch <arch>; name=$($matches['name']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm install <name> [switches...] -r <runtime>
        "^install (?<name>\S*).*\s-r\s*(?<runtime>\S*)$" {
            DebugMessage -message "DnvmExpansion: install <name> -r <runtime>; name=$($matches['name']); runtime=$($matches['runtime'])"
            getRuntimes | filterMatches $matches['runtime']
        }
        # Handle dnvm install <name> [switches...] -os <os>
        "^install (?<name>\S*).*\s-os\s*(?<os>\S*)$" {
            DebugMessage -message "DnvmExpansion: install <name> -os <os>; name=$($matches['name']); os=$($matches['os'])"
            getOSes | filterMatches $matches['os']
        }
        # Handle dnvm install <name> [switches...] -alias <alias>
        "^install (?<name>\S*).*\s-alias\s*(?<alias>\S*)$" {
            DebugMessage -message "DnvmExpansion: install <name> -alias <alias>; name=$($matches['name']); alias=$($matches['alias'])"
            getAliases | filterMatches $matches['alias']
        }

        ##########################################
        #
        # dnvm list

        # Handle dnvm list -<switch>
        "^list.*\s(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: list -<switch>; switch=$($matches['switch'])"
            @('-Detailed', '-PassThru') | filterMatches $matches['switch']
        }

        ##########################################
        #
        # dnvm name

        # Handle dnvm name <name>
        "^name (?<name>\S*)$" {
            DebugMessage -message "DnvmExpansion: name <name>; name=$($matches['name'])"
            getAliasesAndVersions | filterMatches $matches['name']
        }
        # Handle dnvm name <name> [switches...] -<switch>
        "^name (?<name>\S*).*\s(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: name <name> -<switch>; name=$($matches['name']); switch=$($matches['switch'])"
            @('-arch', '-r') | filterMatches $matches['switch']
        }
        # Handle dnvm name <name> [switches...] -arch <arch>
        "^name (?<name>\S*).*\s-arch\s*(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: name <name> -arch <arch>; name=$($matches['name']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm name <name> [switches...] -r <runtime>
        "^name (?<name>\S*).*\s-r\s*(?<runtime>\S*)$" {
            DebugMessage -message "DnvmExpansion: name <name> -r <runtime>; name=$($matches['name']); runtime=$($matches['runtime'])"
            getRuntimes | filterMatches $matches['runtime']
        }

        ##########################################
        #
        # dnvm run

        # Handle dnvm run <VersionOrAlias>
        "^run (?<name>\S*)$" {
            DebugMessage -message "DnvmExpansion: run <VersionOrAlias>; name=$($matches['name'])"
            getAliasesAndVersions | filterMatches $matches['name']
        }
        # Handle dnvm run <cmd> <version> [switches...] -<switch>
        "^run (?<name>\S*)\s+(?<version>\S*).*\s(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: run <name> <version> -<switch>; name=$($matches['name']); version=$($matches['version']); switch=$($matches['switch'])"
            @('-a', '-arch', '-r') | filterMatches $matches['switch']
        }
        # Handle dnvm run <name> <version> [switches...] -a <arch>
        "^run (?<name>\S*)\s+(?<version>\S*).*\s-a\s+(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: run <name> <version> -a <arch>; name=$($matches['name']); version=$($matches['version']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm run <name> <version> [switches...] -arch <arch>
        "^run (?<name>\S*)\s+(?<version>\S*).*\s-arch\s+(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: run <name> <version> -arch <arch>; name=$($matches['name']); version=$($matches['version']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm run <name> <version> [switches...] -r <runtime>
        "^run (?<name>\S*)\s+(?<version>\S*).*\s-r\s*(?<runtime>\S*)$" {
            DebugMessage -message "DnvmExpansion: run <name> <version> -r <runtime>; name=$($matches['name']); version=$($matches['version']); runtime=$($matches['runtime'])"
            getRuntimes | filterMatches $matches['runtime']
        }

        ##########################################
        #
        # dnvm setup

        # Handle dnvm setup -<switch>
        "^setup.*\s(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: setup -<switch>; switch=$($matches['switch'])"
            @('-SkipUserEnvironmentInstall') | filterMatches $matches['switch']
        }

        ##########################################
        #
        # dnvm uninstall

        # Handle dnvm uninstall <VersionOrAlias>
        "^uninstall (?<name>\S*)$" {
            DebugMessage -message "DnvmExpansion: uninstall <name>; name=$($matches['name'])"
            getAliasesAndVersions | filterMatches $matches['name']
        }
        # Handle dnvm uninstall <name> [switches...] -<switch>
        "^uninstall (?<name>\S*).*\s(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: uninstall <name> -<switch>; name=$($matches['name']); switch=$($matches['switch'])"
            @('-a', '-arch', '-r', '-os') | filterMatches $matches['switch']
        }
        # Handle dnvm install <name> [switches...] -a <arch>
        "^uninstall (?<name>\S*).*\s-a\s+(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: uninstall <name> -arch <arch>; name=$($matches['name']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm install <name> [switches...] -arch <arch>
        "^uninstall (?<name>\S*).*\s-arch\s+(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: uninstall <name> -arch <arch>; name=$($matches['name']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm install <name> [switches...] -r <runtime>
        "^uninstall (?<name>\S*).*\s-r\s+(?<runtime>\S*)$" {
            DebugMessage -message "DnvmExpansion: uninstall <name> -r <runtime>; name=$($matches['name']); runtime=$($matches['runtime'])"
            getRuntimes | filterMatches $matches['runtime']
        }
        # Handle dnvm install <name> [switches...] -os <os>
        "^uninstall (?<name>\S*).*\s-os\s+(?<os>\S*)$" {
            DebugMessage -message "DnvmExpansion: uninstall <name> -os <os>; name=$($matches['name']); os=$($matches['os'])"
            getOSes | filterMatches $matches['os']
        }

        ##########################################
        #
        # dnvm upgrade

        # Handle dnvm upgrade <alias>
        "^upgrade (?<alias>\S*)$" {
            DebugMessage -message "DnvmExpansion: upgrade <alias>; alias=$($matches['alias'])"
            getAliases | filterMatches $matches['alias']
        }
        # Handle dnvm upgrade <alias> [switches...] -<switch>
        "^upgrade ((?<alias>\S*)?.*\s)?(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: upgrade <alias> -<switch>; alias=$($matches['alias']); switch=$($matches['switch'])"
            @('-a', '-arch', '-r', '-f', '-g', '-Proxy', '-NoNative', '-Ngen', '-Unstable') | filterMatches $matches['switch']
        }
        # Handle dnvm upgrade <alias> [switches...] -arch <arch>
        "^upgrade ((?<alias>\S*)?.*\s)?-a\s*(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: upgrade <alias> -a <arch>; alias=$($matches['alias']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm upgrade <alias> [switches...] -arch <arch>
        "^upgrade ((?<alias>\S*)?.*\s)?-arch\s*(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: upgrade <alias> -arch <arch>; alias=$($matches['alias']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm upgrade <alias> [switches...] -os <os>
        "^upgrade ((?<alias>\S*)?.*\s)?-os\s*(?<os>\S*)$" {
            DebugMessage -message "DnvmExpansion: upgrade <alias> -a <os>; alias=$($matches['alias']); os=$($matches['os'])"
            getOSes | filterMatches $matches['os'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm upgrade <alias> [switches...] -r <runtime>
        "^upgrade ((?<alias>\S*)?.*\s)?-r\s*(?<runtime>\S*)$" {
            DebugMessage -message "DnvmExpansion: upgrade <alias> -r <runtime>; alias=$($matches['alias']); runtime=$($matches['runtime'])"
            getRuntimes | filterMatches $matches['runtime']
        }

        ##########################################
        #
        # dnvm use

        # Handle dnvm use <VersionOrAlias>
        "^use (?<name>\S*)$" {
            DebugMessage -message "DnvmExpansion: use <name>; name=$($matches['name'])"
            getAliasesAndVersions | filterMatches $matches['name']
        }
        # Handle dnvm use <VersionOrAlias> [switches...] -<switch>
        "^use (?<name>\S*).*\s(?<switch>-\S*)$" {
            DebugMessage -message "DnvmExpansion: use <name> -<switch>; name=$($matches['name']); switch=$($matches['switch'])"
            @('-a', '-arch', '-r', '-p') | filterMatches $matches['switch']
        }
        # Handle dnvm use <VersionOrAlias> [switches...] -a <arch>
        "^use (?<name>\S*).*\s-a\s+(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: use <name> -a <arch>; name=$($matches['name']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm use <VersionOrAlias> [switches...] -arch <arch>
        "^use (?<name>\S*).*\s-arch\s+(?<arch>\S*)$" {
            DebugMessage -message "DnvmExpansion: use <name> -arch <arch>; name=$($matches['name']); arch=$($matches['arch'])"
            getArchitectures | filterMatches $matches['arch'] # values taken from inspecting dnvm.ps1 (look for ValidateSet on $architecture parameters)
        }
        # Handle dnvm use <VersionOrAlias> [switches...] -r <runtime>
        "^use (?<name>\S*).*\s-r\s+(?<runtime>\S*)$" {
            DebugMessage -message "DnvmExpansion: use <name> -r <runtime>; name=$($matches['name']); runtime=$($matches['runtime'])"
            getRuntimes | filterMatches $matches['runtime']
        }

        default {
            DebugMessage -message "DnvmExpansion - not handled: $cmd"
        }
    }
}

$commands = @('alias', 'exec', 'help', 'install', 'list', 'run', 'setup', 'uninstall', 'update-self', 'upgrade', 'use');

function filterMatches($filter = $null){
  if($filter) {
     $input| ? { $_.StartsWith($filter, "InvariantCultureIgnoreCase") } | sort
  }
  else {
    $input | % { $_.Trim() } | sort
  }
}

function getAliasesAndVersions(){
    $aliases = getAliases
    $versions = getVersions
    $aliases + $versions
}
function getAliases(){
    dnvm list -PassThru | ?{$_.Alias -ne ""} | %{$_.Alias}
}

function getVersions(){
    dnvm list -PassThru | select -Unique -ExpandProperty Version
}
function getRuntimes(){
    @('clr', 'coreclr') # values taken from inspecting dnvm.ps1 (look for ValidateSet on $runtime parameters)
}
function getArchitectures(){
    @('x64', 'x86', 'arm') # values taken from inspecting dnvm.ps1 (look for ValidateSet on $runtime parameters)
}
function getOSes(){
    @('darwin', 'linux', 'osx', 'win') # values taken from inspecting dnvm.ps1 (look for ValidateSet on $OS parameters)
}

# TODO - look at posh-git/posh-hg to link with powertab
DebugMessage -message "Installing: Test DnvmTabExpansionBackup function"
if(-not (Test-Path Function:\DnvmTabExpansionBackup)){

    if (Test-Path Function:\TabExpansion) {
        DebugMessage -message "Installing: Backup TabExpansion function"
        Rename-Item Function:\TabExpansion DnvmTabExpansionBackup
    }

    function TabExpansion($line="", $lastWord="") {
       $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()

       switch -Regex ($lastBlock) {
            "^dnvm (.*)" { DnvmTabExpansion $lastBlock }

            # Fall back on existing tab expansion
            default { if (Test-Path Function:\DnvmTabExpansionBackup) { DnvmTabExpansionBackup $line $lastWord } }
       }
    }
}


text:
module ChatbotHelper
  module Telegram
    # A base resource class for Telegram bot API resources.
    class BaseResource
      class << self
        # Returns an array of words which represent the required fields
        # for this resource
        #
        # Fields are primitive data types like +String+, +Integer+, +Boolean+
        # and +Float+ or arrays of primitive data types.
        # If you have more complex types like +Object+ or arrays of +Object+s,
        # see {required_objects}, {optional_objects}, {required_arrays} and
        # {optional_arrays}.
        #
        # @return [Array<String>] The required fields for this resource
        def required_fields
          %w[]
        end

        # Returns an array of words which represent the optional fields
        # for this resource
        #
        # Fields are primitive data types like +String+, +Integer+, +Boolean+
        # and +Float+ or arrays of primitive data types.
        # If you have more complex types like +Object+ or arrays of +Object+s,
        # see {required_objects}, {optional_objects}, {required_arrays} and
        # {optional_arrays}.
        #
        # @return [Array<String>] The optional fields for this resource
        def optional_fields
          %w[]
        end

        # Returns an array of hashes which represent the required objects
        # for this resource
        #
        # The hashes must follow the following structure:
        #
        # +{ name: 'field_name', type: 'ChatbotHelper::Telegram::FieldType' }+
        #
        # where +type+ represents the type of the resulting object which must
        # be a subclass of +ChatbotHelper::Telegram::BaseResource+
        #
        # @return [Array<Hash>] The required objects for this resource
        def required_objects
          []
        end

        # Returns an array of hashes which represent the optional objects
        # for this resource
        #
        # The hashes must follow the following structure:
        #
        # +{ name: 'field_name', type: 'ChatbotHelper::Telegram::FieldType' }+
        #
        # where +type+ represents the type of the resulting object which must
        # be a subclass of +ChatbotHelper::Telegram::BaseResource+
        #
        # @return [Array<Hash>] The optional objects for this resource
        def optional_objects
          []
        end

        # Returns an array of hashes which represent the required arrays
        # for this resource
        #
        # The hashes must follow the following structure:
        #
        # +{ name: 'field_name', type: 'ChatbotHelper::Telegram::FieldType' }+
        #
        # where +type+ represents the type of the resulting objects in the
        # array, which must be a subclass of
        # +ChatbotHelper::Telegram::BaseResource+
        #
        # Arrays are arrays of complex objects. If you have arrays of primitive
        # data types see {required_fields} and {optional_fields}.
        #
        # @return [Array<Hash>] The required arrays for this resource
        def required_arrays
          []
        end

        # Returns an array of hashes which represent the optional arrays
        # for this resource
        #
        # The hashes must follow the following structure:
        #
        # +{ name: 'field_name', type: 'ChatbotHelper::Telegram::FieldType' }+
        #
        # where +type+ represents the type of the resulting objects in the
        # array, which must be a subclass of
        # +ChatbotHelper::Telegram::BaseResource+
        #
        # Arrays are arrays of complex objects. If you have arrays of primitive
        # data types see {required_fields} and {optional_fields}.
        #
        # @return [Array<Hash>] The optional arrays for this resource
        def optional_arrays
          []
        end

        # Checks a given Hash and returns true iff it is a valid bot Resource as
        # defined in the Telegram bot documentation. Returns false otherwise.
        #
        # See https://core.telegram.org/bots/api for more information
        # about the resource structures.
        #
        # @param resource [Hash] The resource representing the Telegram bot API resource as a hash with stringified keys
        # @return [Boolean] True iff the given resource represents this resource as described in the Telegram bot API.
        # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
        # rubocop:disable Metrics/CyclomaticComplexity
        def valid_resource?(resource)
          return false if resource.nil? || !resource.respond_to?('[]')

          required_fields.each do |f|
            return false if resource[f].nil?
          end

          required_objects.each do |o|
            return false unless o[:type].valid_resource?(resource[o[:name]])
          end

          required_arrays.each do |a|
            arr = resource[a[:name]]
            return false unless arr.respond_to?('each')
            arr.each do |el|
              return false unless a[:type].valid_resource?(el)
            end
          end

          # All tests passed. Return true...
          true
        end

        # Checks a given Hash and returns true iff it is a valid bot Resource as
        # defined in the Telegram bot documentation. Raises an exception
        # otherwise.
        #
        # See https://core.telegram.org/bots/api for more information
        # about the resource structures.
        #
        # @param resource [Hash] The resource representing the Telegram bot API resource as a hash with stringified keys
        # @return [Boolean] True iff the given resource represents this resource as described in the Telegram bot API.
        def valid_resource!(resource)
          if valid_resource?(resource)
            true
          else
            m = 'The given resource is not valid or does not follow its '\
                'specification from the Telegram bot API'
            raise ChatbotHelper::Exceptions::InvalidResource.new(m), m
          end
        end
      end

      attr_reader :hash

      # Initializes a new resource object with the given json String or hash.
      #
      # Either +hash+ or +string+ should be set but not both. It is recommended
      # to pass +string+ instead of an already deserialized hash (+hash+) to the
      # initializer.
      #
      # @param hash [Hash] A hash which represents this resource as described in the telegram bot api. Defaults to nil.
      # @param string [String] A json String which represents this resource as described in the telegram bot api. Defaults to nil.
      def initialize(hash: nil, string: nil)
        @toolbox = ChatbotHelper::Telegram::Toolbox
        @hash = hash.nil? ? @toolbox.parse_json(string) : @toolbox.parse_json(@toolbox.generate_json(hash))

        # Validate resource
        self.class.valid_resource!(@hash)

        # Implement getters
        implement_field_accessors
        implement_object_accessors
        implement_array_accessors
      end

      def to_s
        @toolbox.generate_json(@hash)
      end

      alias to_json to_s

      def ==(other)
        other.is_a?(ChatbotHelper::Telegram::BaseResource) ?
          @hash == other.hash :
          @hash == other
      end

      alias eql? ==

      protected

      def implement_field_accessors
        self.class.required_fields.each do |f|
          define_singleton_method(f) do
            return @hash[f]
          end
        end

        self.class.optional_fields.each do |f|
          define_singleton_method(f) do
            return @hash[f]
          end
        end
      end

      def implement_object_accessors
        self.class.required_objects.each do |o|
          res = o[:type].new(hash: @hash[o[:name]])
          define_singleton_method(o[:name]) do
            return res
          end
        end

        # Optional objects mus be either nil or a valid resource
        self.class.optional_objects.each do |o|
          res = nil
          res_val = @hash[o[:name]]
          res = o[:type].new(hash: res_val) unless res_val.nil?
          define_singleton_method(o[:name]) do
            return res
          end
        end
      end

      def implement_array_accessors
        self.class.required_arrays.each do |a|
          elements = []
          @hash[a[:name]].each do |el|
            elements << a[:type].new(hash: el)
          end
          define_singleton_method(a[:name]) do
            return elements
          end
        end

        # Optional arrays must be either nil or arrays of valid resources
        self.class.optional_arrays.each do |a|
          elements = []
          arr_val = @hash[a[:name]]
          unless arr_val.nil?
            arr_val.each do |el|
              elements << a[:type].new(hash: el)
            end
          end
          define_singleton_method(a[:name]) do
            return elements
          end
        end
      end
    end
  end
end


text:
module CompassIconFonts
  VERSION = "0.0.6"
end


text:
// Imports the Google Cloud client library
const Logging = require('@google-cloud/logging');

// Your Google Cloud Platform project ID
const projectId = process.env.GCLOUD_PROJECT;

// Instantiates a client
const loggingClient = Logging({
  projectId: projectId
});

// Convert a callstack to a multi-line text string in standard C# exception print-out format
function callStackToText (callStack)
{
	callStackLines = callStack.map(function(callStackEntry) {
		// Example:  at MyClass.MyMethod(type args) in c:\\project\\source.cs:line 27\n
		return "        at " + callStackEntry['function'] + " in " + callStackEntry['file'] + ":line " + callStackEntry['line'] + "\n";
	});

	callStackLine = callStackLines.join("");

	return callStackLine;
}

function regularEntryToStackdriverEntry (log, entry)
{
	// The metadata associated with the entry
	const metadata = { resource: { type: 'cloud_function', labels: { project_id: projectId, region: '', function_name: 'uberlogger-stackdriver-client'} }, sourceLocation: entry['sourceLocation'], severity: entry['severity'] };

	var messageWithCallStack = entry['message'];

	if (('callStack' in entry) && entry['callStack'] && (entry['callStack'].length > 0))
		messageWithCallStack += "\n" + callStackToText(entry['callStack']);

	const stackdriverEntry = log.entry(metadata, messageWithCallStack);

	return stackdriverEntry;
}

function regularEntriesToStackdriverEntries (log, entries)
{
	return entries.map(function(entry) {
			return regularEntryToStackdriverEntry(log, entry);
		});
}

/**
* HTTP Cloud Function.
*
* @param {Object} req Cloud Function request context.
* @param {Object} res Cloud Function response context.
*/
exports.appendToLog = function helloHttp (req, res) {
	if (req.method == 'POST')
	{
		try
		{
			//console.log("Input: ", req.body);

			// The name of the log to write to
			const logName = req.body.logName;
			// Selects the log to write to
			var log = loggingClient.log(logName);

			// Convert input json data to Stackdriver data structures
			var stackdriverEntries = regularEntriesToStackdriverEntries(log, req.body.entries);

			// Submit log entries to Stackdriver
			log.write(stackdriverEntries)
				.then(() => {
					console.log("Logged ", stackdriverEntries.length, " entries");
					res.status(200).send();
				})
				.catch((err) => {
					console.error('Internal error: ', err);
					res.status(500).send({ error: err });
				});
		}
		catch (err)
		{
			console.error('User error: ', err);
			res.status(400).send({ error: 'Malformed input'});
		}

	}
	else
		res.status(405).send({ error: 'appendToLog only supports POST' });
};


text:
package com.tiarebalbi.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.stereotype.Repository;

import com.tiarebalbi.entity.Chat;

/**
 * Repository da entidade {@link Chat}
 *
 * @author Tiarê Balbi Bonamini
 */
@Repository
public interface ChatRepository extends JpaRepository<Chat, Long>, QueryDslPredicateExecutor<Chat> {

}


text:
namespace Prolog
{
    internal interface IPrologVariableListContainer
    {
    }
}


text:
=begin

Copyright 2012-2013 inBloom, Inc. and its affiliates.

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.

=end

require 'rubygems'
require 'fileutils'

def parseGitb(out)
  branchName=""
  out.each_line do |line|
    if line.include? "*"
      branchName = line.split(" ")[1]
    end
  end

  branchName
end

gitb_out = `git branch`
branch = parseGitb(gitb_out)
if __FILE__ == $0
  if ARGV.length == 0
    branch = branch
  elsif ARGV.length == 1
    branch = ARGV[0]
  else
    puts "Usage: prompt>ruby #{$0} branchName"
    puts "Example: ruby #{$0} alpha.1"
    puts "If no branchName is specified, it defaults to what is determine from git"
    exit(1)
  end
end

puts "*******NOTE******** Ingestion must have been built prior to running this script so that the ingestion/ingestion-validation/target directory exists!!!!"

curTime = Time.new
dirString = ""

dirs_to_zip = ["acceptance-tests", "opstools", "admin-tools/approval", "ingestion/ingestion-validation/target/", "api/src/main/resources/wadl/"]

`cd ..;zip -r testBundle_#{curTime.strftime("%m%d%Y_%H%M%S")}_#{branch}.zip #{dirs_to_zip.join(" ")}`


text:
package org.apache.camel.component.file.remote.sftp;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

/**
 * @version
 */
public class SftpSimpleConsumeAbsoluteTest extends SftpServerTestSupport {

    @Override
    protected boolean canTest() {
        // cannot test on windows
        return super.canTest() && !isPlatform("windows");
    }

    protected static String createAbsolutePath() {
        String answer = System.getProperty("user.dir") + "/" + FTP_ROOT_DIR + "/tmp/mytemp";
        return answer;
    }

    @Test
    public void testSftpSimpleConsumeAbsolute() throws Exception {
        if (!canTest()) {
            return;
        }

        String expected = "Hello World";

        template.sendBodyAndHeader("file:" + createAbsolutePath(), expected, Exchange.FILE_NAME, "hello.txt");

        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(1);
        mock.expectedBodiesReceived(expected);
        mock.expectedHeaderReceived(Exchange.FILE_NAME_ONLY, "hello.txt");

        context.startRoute("foo");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                // we must remember to use // slash because of the url separator
                from("sftp://localhost:" + getPort() + "//" + createAbsolutePath()  + "?username=admin&password=admin&delay=10s&disconnect=true")
                    .routeId("foo").noAutoStartup()
                    .to("mock:result");
            }
        };
    }
}


text:
TestIt('TestLocalStoragePersistent', {

  'before all': function (test) {
    this.store = new LocalStoragePersistent();

    var task1 = new Task('', 'First Task');
    task1.id = Util.uuid();
    localStorage.setItem(JSON.stringify(task1.id), JSON.stringify(task1));

    var task2 = new Task('', 'Second Task');
    task2.id = Util.uuid();
    localStorage.setItem(JSON.stringify(task2.id), JSON.stringify(task2));

    var task3 = new Task('', 'Third Task');
    task3.id = Util.uuid();
    localStorage.setItem(JSON.stringify(task3.id), JSON.stringify(task3));

    this.fixtures = [ task1.id, task2.id, task3.id ];

  },

  'after all': function (test) {
    localStorage.clear();
  },

  'testSaveNewTask': function(test) {

    var task = new Task('', 'Sample Task +book +llun');
    this.store.save(task);
    test.assert(task.id, 'Task must have an ID after save to persistent');

    var expect = JSON.parse(localStorage.getItem(JSON.stringify(task.id)));

    test.assertEqual(task.detail, expect.detail, 'Prototype and stored task' +
      ' should have same detail');
    test.assertEqual(task.id, expect.id, 'Prototype and stored task should' +
      ' have same id');
    test.assertEqual(task.status, expect.status, 'Prototype and stored ' +
      'task should have same status');

  },

  'testSaveOldTask': function(test) {

    var fixtures = this.fixtures;

    var task = new Task('', 'Hello, World');
    task.id = fixtures[0];
    this.store.save(task);

    var expect = JSON.parse(localStorage.getItem(JSON.stringify(fixtures[0])));

    test.assertEqual(task.detail, expect.detail, 'Prototype and stored task' +
      ' should have same detail');
    test.assertEqual(task.id, expect.id, 'Prototype and stored task should' +
      ' have same id');
    test.assertEqual(task.status, expect.status, 'Prototype and stored ' +
      'task should have same status');

  },

  'testGetTask': function(test) {

    var fixtures = this.fixtures;

    var task = this.store.get(fixtures[1]);
    test.assert(task.id, 'Task should have ID');
    test.assertEqual(fixtures[1], task.id,
      'Task ID must equal to fixture (' + task.id + ')');
    test.assertEqual('Second Task', task.detail,
      'Task get from store must have "Second Task" in detail. (' +
      task.detail + ')');

  },

  'testGetInvalidTask': function(test) {

    var task = this.store.get('noid');
    test.assert(!task, 'Task should be null or undefined');

  },

  'testRemove': function(test) {

    var fixtures = this.fixtures;

    this.store.remove(fixtures[2]);
    var task = localStorage.getItem(fixtures[2]);

    test.assert(!task, 'Store should be null or undefined')

  }

});