text:
import sys

import tornkts.utils as utils
from tornado import httputil
from tornado.log import gen_log
from tornado.web import HTTPError, Finish, app_log, MissingArgumentError
from tornkts.base.server_response import ServerResponseStatus, ServerError
from tornkts.mixins.arguments_mixin import ArgumentsMixin
from .session_handler import SessionHandler

class BaseHandler(SessionHandler, ArgumentsMixin):
    def __init__(self, application, request, **kwargs):
        super(BaseHandler, self).__init__(application, request, **kwargs)

    def get_argument(self, name, default=SessionHandler._ARG_DEFAULT, strip=True):
        try:
            value = super(BaseHandler, self).get_argument(name, default, strip)
        except MissingArgumentError:
            raise ServerError(ServerError.BAD_REQUEST, field=name, field_problem=ServerError.FIELD_SKIPPED)
        return value

    def data_received(self, chunk):
        pass

    @property
    def client_version(self):
        return self.get_float_argument('v', default=1)

    @property
    def default_get_method(self):
        return None

    @property
    def default_post_method(self):
        return None

    @property
    def get_methods(self):
        return {}

    @property
    def post_methods(self):
        return {}

    def get(self, *args, **kwargs):
        action_title = args[0] if len(args) > 0 else ''

        if not (action_title in self.get_methods.keys()):
            action_title = self.default_get_method
        if action_title in self.get_methods.keys():
            return self.get_methods.get(action_title)()

        if action_title in self.post_methods:
            raise ServerError(ServerError.NOT_IMPLEMENTED)
        else:
            raise ServerError(ServerError.NOT_FOUND)

    def post(self, *args, **kwargs):
        action_title = args[0] if len(args) > 0 else ''

        if not (action_title in self.post_methods.keys()):
            action_title = self.default_post_method
        if action_title in self.post_methods.keys():
            return self.post_methods.get(action_title)()

        if action_title in self.get_methods:
            raise ServerError(ServerError.NOT_IMPLEMENTED)
        else:
            raise ServerError(ServerError.NOT_FOUND)

    def head(self, *args, **kwargs):
        raise ServerError(ServerError.NOT_IMPLEMENTED)

    def delete(self, *args, **kwargs):
        raise ServerError(ServerError.NOT_IMPLEMENTED)

    def patch(self, *args, **kwargs):
        raise ServerError(ServerError.NOT_IMPLEMENTED)

    def put(self, *args, **kwargs):
        raise ServerError(ServerError.NOT_IMPLEMENTED)

    def options(self, *args, **kwargs):
        raise ServerError(ServerError.NOT_IMPLEMENTED)

    @property
    def current_user_id(self):
        if self.current_user is not None:
            return self.current_user.get_id()
        else:
            return None

    @property
    def current_user_role(self):
        if self.current_user is not None:
            return self.current_user.role
        else:
            return None

    def _handle_request_exception(self, e):
        if isinstance(e, Finish):
            if not self._finished:
                self.finish()
            return
        self.log_exception(*sys.exc_info())
        if self._finished:
            return
        if isinstance(e, HTTPError):
            if e.status_code not in httputil.responses and not e.reason:
                gen_log.error("Bad HTTP status code: %d", e.status_code)
                self.send_error(ServerError.INTERNAL_SERVER_ERROR, exc_info=sys.exc_info())
            else:
                self.send_error(ServerResponseStatus('http_error', e.reason, e.status_code), exc_info=sys.exc_info())
        elif isinstance(e, ServerError):
            self.send_error(e.status, exc_info=sys.exc_info())
        else:
            self.send_error(exc_info=sys.exc_info())

    def send_error(self, status=ServerError.INTERNAL_SERVER_ERROR, **kwargs):
        if not isinstance(status, ServerResponseStatus):
            status = ServerError.UNKNOWN

        if self._headers_written:
            gen_log.error("Cannot send error response after headers written")
            if not self._finished:
                self.finish()
            return
        self.clear()

        reason = None
        if 'exc_info' in kwargs:
            exception = kwargs['exc_info'][1]
            if isinstance(exception, HTTPError) and exception.reason:
                reason = exception.reason

        self.set_status(status_code=status.http_code, reason=reason)
        try:
            self.write_error(status, **kwargs)
        except Exception:
            app_log.error("Uncaught exception in write_error", exc_info=True)
        if not self._finished:
            self.finish()

    def write_error(self, status=ServerError.INTERNAL_SERVER_ERROR, **kwargs):
        if not isinstance(status, ServerResponseStatus):
            status = ServerError.UNKNOWN

        exception = kwargs['exc_info'][1]
        data = None
        field = None
        field_problem = None

        if isinstance(exception, HTTPError) and exception.log_message is not None:
            message = exception.log_message
        elif isinstance(exception, ServerError):
            message = exception.get_description()
            data = exception.get_data()
            field = exception.get_field()
            field_problem = exception.get_field_problem()
        else:
            message = self._reason
        self.send_response(status=status, message=message, data=data, field=field, field_problem=field_problem)

    def set_content_type_json(self):
        self.set_header("Content-Type", "application/json; charset=UTF-8")

    def set_content_type_plain(self):
        self.set_header("Content-Type", "text/plain; charset=UTF-8")

    def send_success_response(self, message=None, data=None):
        self.send_response(status=ServerError.OK, message=message, data=data)

    def send_response(self, status=ServerError.OK, message=None, data=None, field=None, field_problem=None):
        if not isinstance(status, ServerResponseStatus):
            status = ServerError.UNKNOWN

        if data is None:
            data = {}

        self.set_status(status.http_code)

        response = {
            'status': status.alias,
            'data': data
        }

        if message is not None:
            response['message'] = message

        if field is not None:
            response['field'] = field
        if field_problem is not None:
            response['field_problem'] = field_problem

        self.write(utils.json_dumps(response))

    def log_exception(self, typ, value, tb):
        if not isinstance(value, ServerError):
            super(BaseHandler, self).log_exception(typ, value, tb)

    def write_raw(self, chunk):
        self.write(chunk, plain=True)

    def write(self, chunk, plain=False, nocontenttype=False):
        if not nocontenttype:
            if plain:
                self.set_content_type_plain()
            else:
                self.set_content_type_json()
        self.set_header('Cache-control', 'no-cache,no-store,must-revalidate')
        super(BaseHandler, self).write(chunk)


text:
package com.example.safetysitter.safetysitter;

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

import static com.example.safetysitter.safetysitter.RegistrationActivity.TAG;
import static com.example.safetysitter.safetysitter.RegistrationActivity.TOKEN_KEY;
import static com.example.safetysitter.safetysitter.RegistrationActivity.deviceId;
import static com.example.safetysitter.safetysitter.RegistrationActivity.editorPreferencesPhoneNumber;
import static com.example.safetysitter.safetysitter.RegistrationActivity.sendTokenToServer;
import static com.example.safetysitter.safetysitter.RegistrationActivity.token;
import static com.example.safetysitter.safetysitter.RegistrationService.REFRESH_TOKEN;

/**
 * Created by omeredut on 17/11/2016.
 */

public class SafetySitterFirebaseInstanceIDService extends FirebaseInstanceIdService{

    private String newToken;

    @Override
    public void onTokenRefresh() {
        super.onTokenRefresh();
        newToken = FirebaseInstanceId.getInstance().getToken();
        token = newToken;
        Log.d(TAG, "token: " + newToken);
        editorPreferencesPhoneNumber.putString(TOKEN_KEY + deviceId, token);
        editorPreferencesPhoneNumber.commit();
        sendTokenToServer(getApplicationContext(), REFRESH_TOKEN);

    }

}

redpajama_set_name: RedPajamaGithub


text:
class Users::SessionsController < Devise::SessionsController
  layout 'openportal'
end


text:
package com.henry.hh.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.henry.hh.R;
import com.henry.library.activity.TitleActivity;

public class RegisterActivity extends TitleActivity
        implements View.OnClickListener, TextView.OnEditorActionListener {
    private static String charOrNum = "^[A-Za-z0-9]+$";
    //账号
    private EditText mAccount;
    //昵称
    private EditText mNickName;
    //密码
    private EditText mPassword;
    //确认密码
    private EditText mPasswordComform;
    //错误提示--账号
    private TextView mErrAccount;
    //错误提示--昵称
    private TextView mErrNick;
    //错误提示--密码
    private TextView mErrPassword;
    //错误提示--确认密码
    private TextView mErrPwdComform;
    //注册按钮
    private Button mRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initViews();
    }

    /**
     * 初始化控件
     */
    private void initViews() {
        //设置标题
        setTitle(R.string.login_register_account);
        //返回
        showBackwardView(R.string.register_back, true);
        mAccount = getViewById(R.id.et_account_register);
        mNickName = getViewById(R.id.et_nickname_register);
        mPassword = getViewById(R.id.et_pwd_register);
        mPasswordComform = getViewById(R.id.et_pwd_conform_register);
        mPasswordComform.setOnEditorActionListener(this);
        mErrAccount = getViewById(R.id.tv_error_account);
        mErrNick = getViewById(R.id.tv_error_nick);
        mErrPassword = getViewById(R.id.tv_error_password);
        mErrPwdComform = getViewById(R.id.tv_error_password_comform);
        mRegister = getViewById(R.id.btn_register);
        mRegister.setOnClickListener(this);
    }

    /**
     * 执行登录操作
     */
    private void doRegister() {
        clearErrText();
        String account = mAccount.getText().toString();
        String nickName = mNickName.getText().toString();
        String passwd = mPassword.getText().toString();
        String pwdComform = mPasswordComform.getText().toString();
        if (TextUtils.isEmpty(account)) {
            mErrAccount.setVisibility(View.VISIBLE);
            mErrAccount.setText(R.string.register_account_not_null);
        } else if (!account.matches(charOrNum)) {
            mErrAccount.setVisibility(View.VISIBLE);
            mErrAccount.setText(R.string.register_account_only_num_or_char);
        } else if (TextUtils.isEmpty(nickName)) {
            mErrNick.setVisibility(View.VISIBLE);
            mErrNick.setText(R.string.register_nick_not_null);
        } else if (!isPwdSuit(passwd)) {
            mErrPassword.setVisibility(View.VISIBLE);
            mErrPassword.setText(R.string.register_password_length_not_true);
        } else if (TextUtils.isEmpty(pwdComform) || !passwd.equals(pwdComform)) {
            mErrPwdComform.setVisibility(View.VISIBLE);
            mErrPwdComform.setText(R.string.register_password_not_same);
        } else {
            showToast("register");
        }
    }

    /***
     * 判断密码是否适合仅有数字、密码的要求
     *
     * @param password
     * @return
     */
    private boolean isPwdSuit(String password) {
        if (password.length() < 6 || password.length() > 16)
            return false;
        if (!password.matches(charOrNum))
            return false;
        return true;
    }

    /**
     * 清除错误记录
     */
    private void clearErrText() {
        mErrAccount.setVisibility(View.GONE);
        mErrNick.setVisibility(View.GONE);
        mErrPassword.setVisibility(View.GONE);
        mErrPwdComform.setVisibility(View.GONE);
    }

    /**
     * 返回
     *
     * @param backwardView
     */
    @Override
    protected void onBackward(View backwardView) {
        super.onBackward(backwardView);
        finish();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        //点击软键盘的GO
        if (actionId == EditorInfo.IME_ACTION_GO) {
            doRegister();
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v == mRegister) {
            doRegister();
        }
        super.onClick(v);
    }

}


text:
  Rework declaration visitor for plugins (and rework core).

# License

  MIT


text:
package com.arckenver.nations.cmdexecutor.zone;

import java.math.BigDecimal;

import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;

import com.arckenver.nations.DataHandler;
import com.arckenver.nations.LanguageHandler;
import com.arckenver.nations.Utils;
import com.arckenver.nations.object.Nation;
import com.arckenver.nations.object.Zone;

public class ZoneSellExecutor implements CommandExecutor
{
	public static void create(CommandSpec.Builder cmd) {
		cmd.child(CommandSpec.builder()
				.description(Text.of(""))
				.permission("nations.command.zone.sell")
				.arguments(GenericArguments.optional(GenericArguments.doubleNum(Text.of("price"))))
				.executor(new ZoneSellExecutor())
				.build(), "sell", "forsale", "fs");
	}

	public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
	{
		if (src instanceof Player)
		{
			Player player = (Player) src;
			Nation nation = DataHandler.getNation(player.getLocation());
			if (nation == null)
			{
				src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NEEDSTANDNATION));
				return CommandResult.success();
			}
			Zone zone = nation.getZone(player.getLocation());
			if (zone == null)
			{
				src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NEEDSTANDZONESELF));
				return CommandResult.success();
			}
			if ((!zone.isOwner(player.getUniqueId()) || nation.isAdmin()) && !nation.isStaff(player.getUniqueId()))
			{
				src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOOWNER));
				return CommandResult.success();
			}
			if (!ctx.<Double>getOne("price").isPresent())
			{
				src.sendMessage(Text.of(TextColors.YELLOW, "/z sell <price>"));
				return CommandResult.success();
			}
			BigDecimal price = BigDecimal.valueOf(ctx.<Double>getOne("price").get());
			if (price.compareTo(BigDecimal.ZERO) == -1)
			{
				src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_BADARG_P));
				return CommandResult.success();
			}
			zone.setPrice(price);
			DataHandler.saveNation(nation.getUUID());
			nation.getCitizens().forEach(
				uuid -> Sponge.getServer().getPlayer(uuid).ifPresent(
						p -> {
							String str = LanguageHandler.INFO_ZONEFORSALE.replaceAll("\\{PLAYER\\}",  player.getName()).replaceAll("\\{ZONE\\}", zone.getName());
							String[] splited = str.split("\\{AMOUNT\\}");
							src.sendMessage(Text.builder()
									.append(Text.of(TextColors.AQUA, (splited.length > 0) ? splited[0] : ""))
									.append(Utils.formatPrice(TextColors.AQUA, price))
									.append(Text.of(TextColors.AQUA, (splited.length > 1) ? splited[1] : "")).build());
						}));
		}
		else
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
		}
		return CommandResult.success();
	}
}


text:
<?php

namespace ProdaCom\FilterBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Class FilterCompilerPass
 * @package ProdaCom\FilterBundle\DependencyInjection\Compiler
 */
class FilterCompilerPass implements CompilerPassInterface {

    /**
     * @param ContainerBuilder $container
     * @return void
     */
    public function process(ContainerBuilder $container) {
        if (!$container->has('prodacom_filter.registry')) {
            return;
        }

        $registry = $container->findDefinition('prodacom_filter.registry');

        $taggedFilters = $container->findTaggedServiceIds('filter.type');
        foreach ($taggedFilters as $id => $taggedFilter) {
            $registry->addMethodCall('addType', [new Reference($id)]);
        }
    }

}


text:
/**
 * ReplyOptions.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.onset.onpage.hubapi.client;

public class ReplyOptions  implements java.io.Serializable {
    private boolean allowFreeText;

    private java.lang.String[] requested;

    public ReplyOptions() {
    }

    public ReplyOptions(
           boolean allowFreeText,
           java.lang.String[] requested) {
           this.allowFreeText = allowFreeText;
           this.requested = requested;
    }

    /**
     * Gets the allowFreeText value for this ReplyOptions.
     *
     * @return allowFreeText
     */
    public boolean isAllowFreeText() {
        return allowFreeText;
    }

    /**
     * Sets the allowFreeText value for this ReplyOptions.
     *
     * @param allowFreeText
     */
    public void setAllowFreeText(boolean allowFreeText) {
        this.allowFreeText = allowFreeText;
    }

    /**
     * Gets the requested value for this ReplyOptions.
     *
     * @return requested
     */
    public java.lang.String[] getRequested() {
        return requested;
    }

    /**
     * Sets the requested value for this ReplyOptions.
     *
     * @param requested
     */
    public void setRequested(java.lang.String[] requested) {
        this.requested = requested;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof ReplyOptions)) return false;
        ReplyOptions other = (ReplyOptions) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            this.allowFreeText == other.isAllowFreeText() &&
            ((this.requested==null && other.getRequested()==null) ||
             (this.requested!=null &&
              java.util.Arrays.equals(this.requested, other.getRequested())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        _hashCode += (isAllowFreeText() ? Boolean.TRUE : Boolean.FALSE).hashCode();
        if (getRequested() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getRequested());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getRequested(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(ReplyOptions.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://onsetinc.com/OnPage/HUB/08/2011", "ReplyOptions"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("allowFreeText");
        elemField.setXmlName(new javax.xml.namespace.QName("http://onsetinc.com/OnPage/HUB/08/2011", "AllowFreeText"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("requested");
        elemField.setXmlName(new javax.xml.namespace.QName("http://onsetinc.com/OnPage/HUB/08/2011", "Requested"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setNillable(true);
        elemField.setItemQName(new javax.xml.namespace.QName("http://onsetinc.com/OnPage/HUB/08/2011", "Option"));
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
var MemoryStorageAdapter = module.exports = function() {
    this.store = {};
};

MemoryStorageAdapter.prototype = {

    /**
     * Instance-based storage
     */
    store: null,

    /**
     * Saves a value to the store.  Persist is not supported for the memory store, so don't use it.
     *
     * @param key
     * @param value
     * @param persist
     */
    setValue: function(key, value, persist) {
        this.store[key] = value;
    },

    /**
     * Saves a value to the store.  Persist is not supported for the memory store, so don't use it.
     *
     * @param key
     */
    getValue: function(key) {
        return this.store[key];
    },

    /**
     * Deletes a value from the store
     *
     * @param key
     */
    unsetValue: function(key) {
        delete this.store[key];
    }
};


text:
{-# LANGUAGE CPP #-}
{-# OPTIONS -fno-warn-unused-binds   #-}
{-# OPTIONS -fno-warn-unused-imports #-}
-- |
-- Module      : Data.Array.Accelerate.CUDA.Debug
-- Copyright   : [2008..2014] Manuel M T Chakravarty, Gabriele Keller
--               [2009..2014] Trevor L. McDonell
-- License     : BSD3
--
-- Maintainer  : Trevor L. McDonell <tmcdonell@cse.unsw.edu.au>
-- Stability   : experimental
-- Portability : non-portable (GHC extensions)
--
-- Hijack some command line arguments to pass runtime debugging options. This
-- might cause problems for users of the library...
--

module Data.Array.Accelerate.CUDA.Debug (

  module Data.Array.Accelerate.Debug,
  module Data.Array.Accelerate.CUDA.Debug,

) where

import Data.Array.Accelerate.Debug                      hiding ( timed, elapsed )

import Control.Concurrent                               ( forkIO )
import Control.Monad                                    ( void )
import Control.Monad.IO.Class                           ( liftIO, MonadIO )
import GHC.Float                                        ( float2Double )
import System.CPUTime
import System.IO.Unsafe

import Foreign.CUDA.Driver.Stream                       ( Stream )
import qualified Foreign.CUDA.Driver.Event              as Event

-- | Execute an action and time the results. The second argument specifies how
-- to format the output string given elapsed GPU and CPU time respectively
--
timed :: Mode -> (Double -> Double -> String) -> Maybe Stream -> IO () -> IO ()
#ifdef ACCELERATE_DEBUG
{-# NOINLINE timed #-}
timed f fmt stream action = do
  enabled <- queryFlag f
  if enabled
    then do
      gpuBegin  <- Event.create []
      gpuEnd    <- Event.create []
      cpuBegin  <- getCPUTime
      Event.record gpuBegin stream
      action
      Event.record gpuEnd stream
      cpuEnd    <- getCPUTime

      -- Wait for the GPU to finish executing then display the timing execution
      -- message. Do this in a separate thread so that the remaining kernels can
      -- be queued asynchronously.
      --
      void . forkIO $ do
        Event.block gpuEnd
        diff    <- Event.elapsedTime gpuBegin gpuEnd
        let gpuTime = float2Double $ diff * 1E-3                         -- milliseconds
            cpuTime = fromIntegral (cpuEnd - cpuBegin) * 1E-12 :: Double -- picoseconds

        Event.destroy gpuBegin
        Event.destroy gpuEnd
        --
        traceIO f (fmt gpuTime cpuTime)

    else
      action
#else
{-# INLINE timed #-}
timed _ _ _ action = action
#endif

{-# INLINE elapsed #-}
elapsed :: Double -> Double -> String
elapsed gpuTime cpuTime
  = "gpu: " ++ showFFloatSIBase (Just 3) 1000 gpuTime "s, " ++
    "cpu: " ++ showFFloatSIBase (Just 3) 1000 cpuTime "s"


text:
package picocli;

import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import picocli.CommandLine.*;
import picocli.CommandLine.Model.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import static org.junit.Assert.*;
import static picocli.TestUtil.usageString;

public class MixinTest {

    // allows tests to set any kind of properties they like, without having to individually roll them back
    @Rule
    public final TestRule restoreSystemProperties = new RestoreSystemProperties();

    @Rule
    public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false");

    @Test
    public void testMixinAnnotationMustBeValidCommand_CommandAnnotation() {
        @Command class ValidMixin {} // valid command because it has @Command annotation

        class Receiver { // valid command because it has @Mixin annotated field
            @Mixin ValidMixin mixMeIn;
        }
        new CommandLine(new Receiver(), new InnerClassFactory(this)); // no exception
    }

    @Test
    public void testMixinAnnotationMustBeValidCommand_OptionAnnotatedField() {
        class ValidMixin { // valid command because it has @Option annotation
            @Option(names = "-a") int a;
        }

        class Receiver { // valid command because it has @Mixin annotated field
            @Mixin ValidMixin mixMeIn;
        }
        new CommandLine(new Receiver(), new InnerClassFactory(this)); // no exception
    }

    @Test
    public void testMixinAnnotationMustBeValidCommand_ParametersAnnotatedField() {
        class ValidMixin { // valid command because it has @Parameters annotation
            @Parameters int a;
        }

        class Receiver { // valid command because it has @Mixin annotated field
            @Mixin ValidMixin mixMeIn;
        }
        new CommandLine(new Receiver(), new InnerClassFactory(this)); // no exception
    }

    @Test
    public void testAddMixinMustBeValidCommand_CommandAnnotation() {
        @Command class ValidMixin {} // valid command because it has @Command annotation
        @Command class Receiver {}
        CommandLine commandLine = new CommandLine(new Receiver());
        commandLine.addMixin("valid", new ValidMixin()); // no exception
    }

    @Test
    public void testAddMixinMustBeValidCommand_OptionAnnotatedField() {
        class ValidMixin { // valid command because it has @Option annotation
            @Option(names = "-a") int a;
        }
        @Command class Receiver {}
        CommandLine commandLine = new CommandLine(new Receiver());
        commandLine.addMixin("valid", new ValidMixin()); // no exception
    }

    @Test
    public void testAddMixinMustBeValidCommand_ParametersAnnotatedField() {
        class ValidMixin { // valid command because it has @Parameters annotation
            @Parameters int a;
        }
        @Command class Receiver {}
        CommandLine commandLine = new CommandLine(new Receiver());
        commandLine.addMixin("valid", new ValidMixin()); // no exception
    }

    @Test
    public void testAddMixinMustBeValidCommand_SubCommandMethod() {
        @Command class ValidMixin {  // valid command because it has @Command annotation
        }
        @Command class Receiver {
            @Command void sub(@Mixin ValidMixin mixin) {
            }
        }
        CommandLine commandLine = new CommandLine(new Receiver(), new InnerClassFactory(this));
        CommandSpec commandSpec = commandLine.getCommandSpec().subcommands().get("sub").getCommandSpec().mixins().get("arg0");
        assertEquals(ValidMixin.class, commandSpec.userObject().getClass());
        commandLine.addMixin("valid", new ValidMixin()); // no exception
    }

    @Test
    public void testMixinIn_SubCommandMethod() {
        @Command class ValidMixin {
            @Option(names = "-x") int x;
        }
        @Command class Mixee {
            @Command int sub(@Mixin ValidMixin mixin) {
                return mixin.x;
            }
        }
        IFactory fact = new InnerClassFactory(this);
        assertEquals(3, new CommandLine(new Mixee(), fact).execute("sub", "-x=3"));
        assertEquals(4, new CommandLine(new Mixee(), fact).execute("sub", "-x=4"));
    }

    @Test
    public void testMixinMixeeIn_SubCommandMethod() {
        @Command class ValidMixin {
            @Spec CommandSpec spec;
            @Spec(Spec.Target.MIXEE) CommandSpec mixee;
            @Option(names = "-x") int x;
        }
        @Command class Mixee {
            @Command int sub(@Mixin ValidMixin mixin) throws NoSuchMethodException {
                assertNotSame  (mixin.mixee, mixin.spec);
                assertNotEquals(mixin.mixee, mixin.spec);
                assertEquals(ValidMixin.class.getName(), mixin.spec.userObject().getClass().getName());
                assertEquals(Mixee.class.getDeclaredMethod("sub", ValidMixin.class).toString(),
                        mixin.mixee.userObject().toString());
                return mixin.x;
            }
        }
        IFactory fact = new InnerClassFactory(this);
        assertEquals(3, new CommandLine(new Mixee(), fact).execute("sub", "-x=3"));
    }

    @Test
    public void testMixeeWithoutMixin() {
        @Command class SomeMixin {
            @Spec CommandSpec spec;
            @Spec(Spec.Target.MIXEE) CommandSpec mixee;
            @Option(names = "-x") int x;
        }
        SomeMixin mixin = new SomeMixin();
        new CommandLine(mixin).parseArgs();
        assertNull("Not mixed into anything: no mixee", mixin.mixee);
        assertNotNull(mixin.spec);
    }

    @Test
    public void testMixinAnnotationRejectedIfNotAValidCommand() {
        class Invalid {}
        class Receiver {
            @Mixin Invalid mixMeIn;
        }
        Receiver userObject = new Receiver();
        try {
            new CommandLine(userObject, new InnerClassFactory(this));
        } catch (InitializationException ex) {
            assertEquals(userObject.mixMeIn + " is not a command: it has no @Command, @Option, @Parameters or @Unmatched annotations", ex.getMessage());
        }
    }

    @Test
    public void testAddMixinRejectedIfNotAValidCommand() {
        class Invalid {}
        @Command class Receiver {}

        Invalid mixin = new Invalid();
        CommandLine commandLine = new CommandLine(new Receiver());
        try {
            commandLine.addMixin("invalid", mixin);
        } catch (InitializationException ex) {
            assertEquals(mixin + " is not a command: it has no @Command, @Option, @Parameters or @Unmatched annotations", ex.getMessage());
        }
    }

    static class CommandAttributes {
        @Command(name = "mixmein",
                version = "Mixin 1.0",
                separator = ":",
                description = "description from mixin",
                descriptionHeading = "Mixin Description Heading%n",
                header = "Mixin Header",
                headerHeading = "Mixin Header Heading%n",
                footer = "Mixin Footer",
                footerHeading = "Mixin Footer Heading%n",
                optionListHeading = "Mixin Option List Heading%n",
                parameterListHeading = "Mixin Parameter List Heading%n",
                commandListHeading = "Mixin Command List Heading%n",
                requiredOptionMarker = '%',
                synopsisHeading = "Mixin Synopsis Heading%n",
                abbreviateSynopsis = true,
                customSynopsis = "Mixin custom synopsis",
                showDefaultValues = true,
                sortOptions = false)
        static class MixMeIn {}
    }

    @Test
    public void testMixinAnnotationCommandAttributes() throws Exception {
        class Receiver {
            @Mixin
            CommandAttributes.MixMeIn mixMeIn;
        }

        CommandLine commandLine = new CommandLine(new Receiver());
        verifyMixinCommandAttributes(commandLine);
    }

    @Test
    public void testAddMixinCommandAttributes() throws Exception {
        @Command class Receiver {}

        CommandLine commandLine = new CommandLine(new Receiver());
        commandLine.addMixin("mixmein", new CommandAttributes.MixMeIn());
        verifyMixinCommandAttributes(commandLine);
    }

    private void verifyMixinCommandAttributes(CommandLine commandLine) throws UnsupportedEncodingException {
        CommandSpec commandSpec = commandLine.getCommandSpec();
        assertEquals("mixmein", commandSpec.name());
        assertArrayEquals(new String[] {"Mixin 1.0"}, commandSpec.version());
        assertEquals(":", commandSpec.parser().separator());
        assertArrayEquals(new String[] {"description from mixin"}, commandSpec.usageMessage().description());
        assertEquals("Mixin Description Heading%n", commandSpec.usageMessage().descriptionHeading());
        assertArrayEquals(new String[] {"Mixin Header"}, commandSpec.usageMessage().header());
        assertEquals("Mixin Header Heading%n", commandSpec.usageMessage().headerHeading());
        assertArrayEquals(new String[] {"Mixin Footer"}, commandSpec.usageMessage().footer());
        assertEquals("Mixin Footer Heading%n", commandSpec.usageMessage().footerHeading());
        assertEquals("Mixin Option List Heading%n", commandSpec.usageMessage().optionListHeading());
        assertEquals("Mixin Parameter List Heading%n", commandSpec.usageMessage().parameterListHeading());
        assertEquals("Mixin Command List Heading%n", commandSpec.usageMessage().commandListHeading());
        assertEquals('%', commandSpec.usageMessage().requiredOptionMarker());
        assertEquals("Mixin Synopsis Heading%n", commandSpec.usageMessage().synopsisHeading());
        assertTrue("abbreviateSynopsis", commandSpec.usageMessage().abbreviateSynopsis());
        assertArrayEquals(new String[] {"Mixin custom synopsis"}, commandSpec.usageMessage().customSynopsis());
        assertTrue("showDefaultValues", commandSpec.usageMessage().showDefaultValues());
        assertFalse("sortOptions", commandSpec.usageMessage().sortOptions());

        String expected = String.format("" +
                "Mixin Header Heading%n" +
                "Mixin Header%n" +
                "Mixin Synopsis Heading%n" +
                "Mixin custom synopsis%n" +
                "Mixin Description Heading%n" +
                "description from mixin%n" +
                "Mixin Footer Heading%n" +
                "Mixin Footer%n");
        assertEquals(expected, usageString(commandLine, Help.Ansi.OFF));
    }

    static class CommandAttributesDontOverwriteReceiverAttributes {
        @Command(name = "mixmein",
                version = "Mixin 1.0",
                separator = ":",
                description = "description from mixin",
                descriptionHeading = "Mixin Description Heading%n",
                header = "Mixin Header",
                headerHeading = "Mixin Header Heading%n",
                footer = "Mixin Footer",
                footerHeading = "Mixin Footer Heading%n",
                optionListHeading = "Mixin Option List Heading%n",
                parameterListHeading = "Mixin Parameter List Heading%n",
                commandListHeading = "Mixin Command List Heading%n",
                requiredOptionMarker = '%',
                synopsisHeading = "Mixin Synopsis Heading%n",
                abbreviateSynopsis = true,
                customSynopsis = "Mixin custom synopsis",
                showDefaultValues = true,
                sortOptions = false)
        static class MixMeIn {}
    }

    @Test
    public void testMixinAnnotationCommandAttributesDontOverwriteReceiverAttributes() throws Exception {

        @Command(name = "receiver",
                version = "Receiver 1.0",
                separator = "~",
                description = "Receiver description",
                descriptionHeading = "Receiver Description Heading%n",
                header = "Receiver Header",
                headerHeading = "Receiver Header Heading%n",
                footer = "Receiver Footer",
                footerHeading = "Receiver Footer Heading%n",
                optionListHeading = "Receiver Option List Heading%n",
                parameterListHeading = "Receiver Parameter List Heading%n",
                commandListHeading = "Receiver Command List Heading%n",
                requiredOptionMarker = '#',
                synopsisHeading = "Receiver Synopsis Heading%n",
                customSynopsis = "Receiver custom synopsis")
        class Receiver {
            @Mixin
            CommandAttributesDontOverwriteReceiverAttributes.MixMeIn mixMeIn;
        }

        CommandLine commandLine = new CommandLine(new Receiver());
        verifyMixinCommandAttributesDontOverwriteReceiverAttributes(commandLine);
    }

    @Test
    public void testAddMixinCommandAttributesDontOverwriteReceiverAttributes() throws Exception {
        @Command(name = "receiver",
                version = "Receiver 1.0",
                separator = "~",
                description = "Receiver description",
                descriptionHeading = "Receiver Description Heading%n",
                header = "Receiver Header",
                headerHeading = "Receiver Header Heading%n",
                footer = "Receiver Footer",
                footerHeading = "Receiver Footer Heading%n",
                optionListHeading = "Receiver Option List Heading%n",
                parameterListHeading = "Receiver Parameter List Heading%n",
                commandListHeading = "Receiver Command List Heading%n",
                requiredOptionMarker = '#',
                synopsisHeading = "Receiver Synopsis Heading%n",
                customSynopsis = "Receiver custom synopsis")
        class Receiver {}

        CommandLine commandLine = new CommandLine(new Receiver(), new InnerClassFactory(this));
        commandLine.addMixin("mixMeIn", new CommandAttributesDontOverwriteReceiverAttributes.MixMeIn());
        verifyMixinCommandAttributesDontOverwriteReceiverAttributes(commandLine);
    }

    private void verifyMixinCommandAttributesDontOverwriteReceiverAttributes(CommandLine commandLine) throws UnsupportedEncodingException {
        CommandSpec commandSpec = commandLine.getCommandSpec();
        assertEquals("receiver", commandSpec.name());
        assertArrayEquals(new String[] {"Receiver 1.0"}, commandSpec.version());
        assertEquals("~", commandSpec.parser().separator());
        assertArrayEquals(new String[] {"Receiver description"}, commandSpec.usageMessage().description());
        assertEquals("Receiver Description Heading%n", commandSpec.usageMessage().descriptionHeading());
        assertArrayEquals(new String[] {"Receiver Header"}, commandSpec.usageMessage().header());
        assertEquals("Receiver Header Heading%n", commandSpec.usageMessage().headerHeading());
        assertArrayEquals(new String[] {"Receiver Footer"}, commandSpec.usageMessage().footer());
        assertEquals("Receiver Footer Heading%n", commandSpec.usageMessage().footerHeading());
        assertEquals("Receiver Option List Heading%n", commandSpec.usageMessage().optionListHeading());
        assertEquals("Receiver Parameter List Heading%n", commandSpec.usageMessage().parameterListHeading());
        assertEquals("Receiver Command List Heading%n", commandSpec.usageMessage().commandListHeading());
        assertEquals('#', commandSpec.usageMessage().requiredOptionMarker());
        assertEquals("Receiver Synopsis Heading%n", commandSpec.usageMessage().synopsisHeading());
        assertArrayEquals(new String[] {"Receiver custom synopsis"}, commandSpec.usageMessage().customSynopsis());

        String expected = String.format("" +
                "Receiver Header Heading%n" +
                "Receiver Header%n" +
                "Receiver Synopsis Heading%n" +
                "Receiver custom synopsis%n" +
                "Receiver Description Heading%n" +
                "Receiver description%n" +
                "Receiver Footer Heading%n" +
                "Receiver Footer%n");
        assertEquals(expected, usageString(commandLine, Help.Ansi.OFF));
    }

    static class SuperClassCommandAttributesDontOverwriteSubclassAttributes {
        @Command(name = "mixmein",
                version = "Mixin 1.0",
                separator = ":",
                description = "description from mixin",
                descriptionHeading = "Mixin Description Heading%n",
                header = "Mixin Header",
                headerHeading = "Mixin Header Heading%n",
                footer = "Mixin Footer",
                footerHeading = "Mixin Footer Heading%n",
                optionListHeading = "Mixin Option List Heading%n",
                parameterListHeading = "Mixin Parameter List Heading%n",
                commandListHeading = "Mixin Command List Heading%n",
                requiredOptionMarker = '%',
                synopsisHeading = "Mixin Synopsis Heading%n",
                abbreviateSynopsis = true,
                customSynopsis = "Mixin custom synopsis",
                showDefaultValues = true,
                sortOptions = false)
        static class MixMeInSuper {}

        @Command(name = "mixmeinSub",
                version = "MixinSub 1.0",
                separator = "~",
                description = "description from mixinSub",
                descriptionHeading = "MixinSub Description Heading%n",
                header = "MixinSub Header",
                headerHeading = "MixinSub Header Heading%n",
                footer = "MixinSub Footer",
                footerHeading = "MixinSub Footer Heading%n",
                optionListHeading = "MixinSub Option List Heading%n",
                parameterListHeading = "MixinSub Parameter List Heading%n",
                commandListHeading = "MixinSub Command List Heading%n",
                requiredOptionMarker = '#',
                synopsisHeading = "MixinSub Synopsis Heading%n",
                abbreviateSynopsis = true,
                customSynopsis = "MixinSub custom synopsis",
                showDefaultValues = true,
                sortOptions = false)
        static class MixMeInSub extends MixMeInSuper {}
    }

    @Test
    public void testMixinAnnotationSuperClassCommandAttributesDontOverwriteSubclassAttributes() throws Exception {
        class Receiver {
            @Mixin SuperClassCommandAttributesDontOverwriteSubclassAttributes.MixMeInSub mixMeIn;
        }

        CommandLine commandLine = new CommandLine(new Receiver());
        verifyMixinSuperClassCommandAttributesDontOverwriteSubclassAttributes(commandLine);
    }

    @Test
    public void testAddMixinSuperClassCommandAttributesDontOverwriteSubclassAttributes() throws Exception {
        @Command class Receiver {}

        CommandLine commandLine = new CommandLine(new Receiver());
        commandLine.addMixin("mixMeIn", new SuperClassCommandAttributesDontOverwriteSubclassAttributes.MixMeInSub());
        verifyMixinSuperClassCommandAttributesDontOverwriteSubclassAttributes(commandLine);
    }

    private void verifyMixinSuperClassCommandAttributesDontOverwriteSubclassAttributes(CommandLine commandLine) throws UnsupportedEncodingException {
        CommandSpec commandSpec = commandLine.getCommandSpec();
        assertEquals("mixmeinSub", commandSpec.name());
        assertArrayEquals(new String[] {"MixinSub 1.0"}, commandSpec.version());
        assertEquals("~", commandSpec.parser().separator());
        assertArrayEquals(new String[] {"description from mixinSub"}, commandSpec.usageMessage().description());
        assertEquals("MixinSub Description Heading%n", commandSpec.usageMessage().descriptionHeading());
        assertArrayEquals(new String[] {"MixinSub Header"}, commandSpec.usageMessage().header());
        assertEquals("MixinSub Header Heading%n", commandSpec.usageMessage().headerHeading());
        assertArrayEquals(new String[] {"MixinSub Footer"}, commandSpec.usageMessage().footer());
        assertEquals("MixinSub Footer Heading%n", commandSpec.usageMessage().footerHeading());
        assertEquals("MixinSub Option List Heading%n", commandSpec.usageMessage().optionListHeading());
        assertEquals("MixinSub Parameter List Heading%n", commandSpec.usageMessage().parameterListHeading());
        assertEquals("MixinSub Command List Heading%n", commandSpec.usageMessage().commandListHeading());
        assertEquals('#', commandSpec.usageMessage().requiredOptionMarker());
        assertEquals("MixinSub Synopsis Heading%n", commandSpec.usageMessage().synopsisHeading());
        assertArrayEquals(new String[] {"MixinSub custom synopsis"}, commandSpec.usageMessage().customSynopsis());

        String expected = String.format("" +
                "MixinSub Header Heading%n" +
                "MixinSub Header%n" +
                "MixinSub Synopsis Heading%n" +
                "MixinSub custom synopsis%n" +
                "MixinSub Description Heading%n" +
                "description from mixinSub%n" +
                "MixinSub Footer Heading%n" +
                "MixinSub Footer%n");
        assertEquals(expected, usageString(commandLine, Help.Ansi.OFF));
    }

    static class CombinesAttributes {
        @Command(name = "superName",
                version = "MixMeInSuper 1.0",
                separator = "$",
                description = "33",
                descriptionHeading = "333",
                header = "3333",
                headerHeading = "33333",
                //footer = "333 3",
                //footerHeading = "333 33",
                //optionListHeading = "333 333",
                parameterListHeading = "333 333 3",
                commandListHeading = "333 333 33",
                requiredOptionMarker = '3',
                synopsisHeading = "3333 3")
        static class MixMeInSuper {}

        @Command(description = "description from mixinSub",
                descriptionHeading = "MixinSub Description Heading%n",
                header = "MixinSub Header",
                headerHeading = "MixinSub Header Heading%n",
                //footer = "222",
                //footerHeading = "222 222",
                //optionListHeading = "222 222 222",
                parameterListHeading = "2 22",
                commandListHeading = "222 2",
                requiredOptionMarker = '2',
                synopsisHeading = "22222")
        static class MixMeInSub extends MixMeInSuper {}

        @Command(
                //name = "000 - set by MixinMeInSuper",
                //version = "0.0 - set by MixinMeInSuper",
                //separator = "0 - set by MixinMeInSuper",
                //description = "00 - set by MixMeInSub",
                //descriptionHeading = "000 - set by MixMeInSub",
                //header = "0000 - set by MixMeInSub",
                //headerHeading = "00000 - set by MixMeInSub",

                footer = "ReceiverSuper Footer",
                footerHeading = "ReceiverSuper Footer Heading%n",
                optionListHeading = "ReceiverSuper Option List Heading%n",
                parameterListHeading = "-1-1-1",
                commandListHeading = "--1--1--1",
                requiredOptionMarker = '1',
                synopsisHeading = "---1---1---1")
        static class ReceiverSuper {}
    }

    @Test
    public void testMixinAnnotationCombinesAttributes() throws Exception {
        @Command(parameterListHeading = "Receiver Parameter List Heading%n",
                commandListHeading = "Receiver Command List Heading%n",
                requiredOptionMarker = '#',
                synopsisHeading = "Receiver Synopsis Heading%n",
                //customSynopsis = "Receiver custom synopsis", // use standard generated synopsis
                showDefaultValues = true,
                sortOptions = false)
        class Receiver extends CombinesAttributes.ReceiverSuper {
            @Mixin CombinesAttributes.MixMeInSub mixMeIn;
            @Parameters(description = "some files") File[] files;
        }

        CommandLine commandLine = new CommandLine(new Receiver());
        verifyMixinCombinesAttributes(commandLine);
    }

    @Test
    public void testAddMixinCombinesAttributes() throws Exception {
        @Command(parameterListHeading = "Receiver Parameter List Heading%n",
                commandListHeading = "Receiver Command List Heading%n",
                requiredOptionMarker = '#',
                synopsisHeading = "Receiver Synopsis Heading%n",
                //customSynopsis = "Receiver custom synopsis", // use standard generated synopsis
                showDefaultValues = true,
                sortOptions = false)
        class Receiver extends CombinesAttributes.ReceiverSuper {
            @Parameters(description = "some files") File[] files;
        }

        CommandLine commandLine = new CommandLine(new Receiver());
        commandLine.addMixin("mixMeIn", new CombinesAttributes.MixMeInSub());

        verifyMixinCombinesAttributes(commandLine);
    }

    private void verifyMixinCombinesAttributes(CommandLine commandLine) throws UnsupportedEncodingException {
        CommandSpec commandSpec = commandLine.getCommandSpec();
        assertEquals("superName", commandSpec.name());
        assertArrayEquals(new String[] {"MixMeInSuper 1.0"}, commandSpec.version());
        assertEquals("$", commandSpec.parser().separator());

        UsageMessageSpec usage = commandSpec.usageMessage();
        assertArrayEquals(new String[] {"description from mixinSub"}, usage.description());
        assertEquals("MixinSub Description Heading%n", usage.descriptionHeading());
        assertArrayEquals(new String[] {"MixinSub Header"}, usage.header());
        assertEquals("MixinSub Header Heading%n", usage.headerHeading());

        assertArrayEquals(new String[] {"ReceiverSuper Footer"}, usage.footer());
        assertEquals("ReceiverSuper Footer Heading%n", usage.footerHeading());
        assertEquals("ReceiverSuper Option List Heading%n", usage.optionListHeading());

        assertEquals("Receiver Parameter List Heading%n", usage.parameterListHeading());
        assertEquals("Receiver Command List Heading%n", usage.commandListHeading());
        assertEquals('#', usage.requiredOptionMarker());
        assertEquals("Receiver Synopsis Heading%n", usage.synopsisHeading());
        assertArrayEquals(new String[0], usage.customSynopsis());

        String expected = String.format("" +
                "MixinSub Header Heading%n" +
                "MixinSub Header%n" +
                "Receiver Synopsis Heading%n" +
                "superName [<files>...]%n" +
                "MixinSub Description Heading%n" +
                "description from mixinSub%n" +
                "Receiver Parameter List Heading%n" +
                "      [<files>...]   some files%n" +
                "ReceiverSuper Footer Heading%n" +
                "ReceiverSuper Footer%n");
        assertEquals(expected, usageString(commandLine, Help.Ansi.OFF));
    }

    static class InjectsOptionsAndParameters {
        static class MixMeIn {
            @Option(names = {"-a", "--alpha"}, description = "option from mixin")
            private int alpha;

            @Parameters(description = "parameters from mixin")
            File[] files;
        }
    }
    @Test
    public void testMixinAnnotationInjectsOptionsAndParameters() throws UnsupportedEncodingException {
        @Command(sortOptions = false)
        class Receiver {
            @Option(names = {"-b", "--beta"}, description = "Receiver option")
            private int beta;

            @Parameters(description = "parameters from receiver")
            File[] receiverFiles;

            @Mixin
            InjectsOptionsAndParameters.MixMeIn mixMeIn;
        }
        CommandLine commandLine = new CommandLine(new Receiver());
        verifyMixinInjectsOptionsAndParameters(commandLine);
    }

    @Test
    public void testAddMixinInjectsOptionsAndParameters() throws UnsupportedEncodingException {
        @Command(sortOptions = false)
        class Receiver {
            @Option(names = {"-b", "--beta"}, description = "Receiver option")
            private int beta;

            @Parameters(description = "parameters from receiver")
            File[] receiverFiles;
        }
        CommandLine commandLine = new CommandLine(new Receiver());
        commandLine.addMixin("mixMeIn", new InjectsOptionsAndParameters.MixMeIn());
        verifyMixinInjectsOptionsAndParameters(commandLine);
    }

    private void verifyMixinInjectsOptionsAndParameters(CommandLine commandLine) throws UnsupportedEncodingException {
        CommandSpec commandSpec = commandLine.getCommandSpec();
        assertEquals(2, commandSpec.options().size());
        assertArrayEquals(new String[]{"-b", "--beta"},  commandSpec.options().get(0).names());
        assertArrayEquals(new String[]{"-a", "--alpha"}, commandSpec.options().get(1).names());

        assertTrue(commandSpec.optionsMap().containsKey("--alpha"));
        assertTrue(commandSpec.optionsMap().containsKey("--beta"));
        assertTrue(commandSpec.optionsMap().containsKey("-a"));
        assertTrue(commandSpec.optionsMap().containsKey("-b"));

        assertTrue(commandSpec.posixOptionsMap().containsKey('a'));
        assertTrue(commandSpec.posixOptionsMap().containsKey('b'));

        assertEquals(2, commandSpec.positionalParameters().size());
        assertEquals("<receiverFiles>", commandSpec.positionalParameters().get(0).paramLabel());
        assertEquals("<files>",         commandSpec.positionalParameters().get(1).paramLabel());

        String expects = String.format("" +
                "Usage: <main class> [-a=<alpha>] [-b=<beta>] [<receiverFiles>...] [<files>...]%n" +
                "      [<receiverFiles>...]   parameters from receiver%n" +
                "      [<files>...]           parameters from mixin%n" +
                "  -b, --beta=<beta>          Receiver option%n" +
                "  -a, --alpha=<alpha>        option from mixin%n");
        assertEquals(expects, usageString(commandLine, Help.Ansi.OFF));
    }
    @Test
    public void testMixinAnnotationParsesOptionsAndParameters() throws UnsupportedEncodingException {
        @Command(sortOptions = false)
        class Receiver {
            @Option(names = {"-b", "--beta"}, description = "Receiver option")
            private int beta;

            @Parameters(description = "parameters from receiver")
            File[] receiverFiles;

            @Mixin
            InjectsOptionsAndParameters.MixMeIn mixMeIn;
        }
        CommandLine commandLine = new CommandLine(new Receiver());
        commandLine.parseArgs("-a", "111", "-b", "222", "a", "b");
        Receiver receiver = commandLine.getCommand();
        assertEquals(222, receiver.beta);
        assertEquals(111, receiver.mixMeIn.alpha);
        assertArrayEquals(new File[] {new File("a"), new File("b")}, receiver.receiverFiles);
        assertArrayEquals(new File[] {new File("a"), new File("b")}, receiver.mixMeIn.files);
    }

    @Test
    public void testAddMixinParsesOptionsAndParameters() throws UnsupportedEncodingException {
        @Command(sortOptions = false)
        class Receiver {
            @Option(names = {"-b", "--beta"}, description = "Receiver option")
            private int beta;

            @Parameters(description = "parameters from receiver")
            File[] receiverFiles;
        }
        CommandLine commandLine = new CommandLine(new Receiver());
        InjectsOptionsAndParameters.MixMeIn mixin = new InjectsOptionsAndParameters.MixMeIn();
        commandLine.addMixin("mixin", mixin);

        commandLine.parseArgs("-a", "111", "-b", "222", "a", "b");
        Receiver receiver = commandLine.getCommand();
        assertEquals(222, receiver.beta);
        assertEquals(111, mixin.alpha);
        assertArrayEquals(new File[] {new File("a"), new File("b")}, receiver.receiverFiles);
        assertArrayEquals(new File[] {new File("a"), new File("b")}, mixin.files);

        assertSame(mixin, commandLine.getMixins().get("mixin"));
        assertSame(mixin, commandLine.getCommandSpec().mixins().get("mixin").userObject());
    }

    @Test
    public void testMixinAnnotationInjectsOptionsAndParametersInDeclarationOrder() throws Exception {
        @Command(sortOptions = false)
        class Receiver {
            @Mixin
            InjectsOptionsAndParameters.MixMeIn mixMeIn;

            @Option(names = {"-b", "--beta"}, description = "Receiver option")
            private int beta;

            @Parameters(description = "parameters from receiver")
            File[] receiverFiles;
        }
        CommandLine commandLine = new CommandLine(new Receiver());
        CommandSpec commandSpec = commandLine.getCommandSpec();
        assertEquals(2, commandSpec.options().size());
        assertArrayEquals(new String[]{"-a", "--alpha"}, commandSpec.options().get(0).names());
        assertArrayEquals(new String[]{"-b", "--beta"},  commandSpec.options().get(1).names());

        assertEquals(2, commandSpec.positionalParameters().size());
        assertEquals("<files>",         commandSpec.positionalParameters().get(0).paramLabel());
        assertEquals("<receiverFiles>", commandSpec.positionalParameters().get(1).paramLabel());

        String expects = String.format("" +
                "Usage: <main class> [-a=<alpha>] [-b=<beta>] [<files>...] [<receiverFiles>...]%n" +
                "      [<files>...]           parameters from mixin%n" +
                "      [<receiverFiles>...]   parameters from receiver%n" +
                "  -a, --alpha=<alpha>        option from mixin%n" +
                "  -b, --beta=<beta>          Receiver option%n");
        assertEquals(expects, usageString(commandLine, Help.Ansi.OFF));
    }

    @Test
    public void testMixinAnnotationRejectsDuplicateOptions() {
        class MixMeInDuplicate {
            @Option(names = {"-a", "--alpha"}, description = "option from mixin")
            private int alpha;
        }

        class ReceiverDuplicate {
            @Option(names = {"-a"}, description = "Receiver option")
            private int beta;

            @Mixin
            MixMeInDuplicate mixMeIn;
        }
        try {
            new CommandLine(new ReceiverDuplicate(), new InnerClassFactory(this));
            fail("Expected exception");
        } catch (DuplicateOptionAnnotationsException ex) {
            assertEquals("Option name '-a' is used by both field int picocli.MixinTest$1MixMeInDuplicate.alpha and field int picocli.MixinTest$1ReceiverDuplicate.beta", ex.getMessage());
        }
    }

    @Test
    public void testMixinAnnotationWithSubcommands() {
        @Command(name = "mixinsub")
        class MixedInSubCommand {}

        @Command(subcommands = MixedInSubCommand.class)
        class MixMeIn {}

        class Receiver {
            @Mixin
            MixMeIn mixMeIn;
        }
        CommandLine commandLine = new CommandLine(new Receiver(), new InnerClassFactory(this));
        CommandSpec commandSpec = commandLine.getCommandSpec();

        assertEquals(1, commandLine.getSubcommands().size());
        assertEquals(1, commandSpec.subcommands().size());
        CommandLine subcommandLine = commandSpec.subcommands().get("mixinsub");
        assertSame(subcommandLine, commandLine.getSubcommands().get("mixinsub"));
        assertTrue(((Object) subcommandLine.getCommand()) instanceof MixedInSubCommand);
    }

    @Test
    public void testMixinAnnotationCanBeRetrievedByAnnotationName() {
        @Command class MixMeIn {}

        @Command class Receiver {
            @Mixin(name = "aMixin") MixMeIn mixMeIn;
        }
        CommandLine commandLine = new CommandLine(new Receiver(), new InnerClassFactory(this));
        assertFalse("mixin was registered", commandLine.getMixins().isEmpty());
        assertTrue(commandLine.getMixins().get("aMixin") instanceof MixMeIn);

        Receiver receiver = commandLine.getCommand();
        assertNotNull(receiver.mixMeIn);
        assertSame(receiver.mixMeIn, commandLine.getMixins().get("aMixin"));
        assertSame(receiver.mixMeIn, commandLine.getCommandSpec().mixins().get("aMixin").userObject());
    }

    @Test
    public void testMixinAnnotationCanBeRetrievedByFieldName() {
        @Command class MixMeIn {}

        @Command class Receiver {
            @Mixin MixMeIn mixMeIn;
        }
        CommandLine commandLine = new CommandLine(new Receiver(), new InnerClassFactory(this));
        assertFalse("mixin was registered", commandLine.getMixins().isEmpty());
        assertTrue(commandLine.getMixins().get("mixMeIn") instanceof MixMeIn);

        Receiver receiver = commandLine.getCommand();
        assertNotNull(receiver.mixMeIn);
        assertSame(receiver.mixMeIn, commandLine.getMixins().get("mixMeIn"));
        assertSame(receiver.mixMeIn, commandLine.getCommandSpec().mixins().get("mixMeIn").userObject());
    }

    @Test
    public void testAddMixin_CanBeRetrievedByFieldName() {
        @Command class MixMeIn {}
        @Command class Receiver {}

        CommandLine commandLine = new CommandLine(new Receiver(), new InnerClassFactory(this));
        commandLine.addMixin("mixin", new MixMeIn());
        assertFalse("mixin was registered", commandLine.getMixins().isEmpty());
        assertTrue(commandLine.getMixins().get("mixin") instanceof MixMeIn);
    }

    @Test
    public void testMixinStandardHelpOptions_AreAddedLast() {
        @Command(mixinStandardHelpOptions = true, sortOptions = false) class App {
            @Option(names = "-a", description = "a option") boolean aOpt;
            @Option(names = "-z", description = "z option") boolean zOpt;
        }
        CommandLine commandLine = new CommandLine(new App(), new InnerClassFactory(this));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        commandLine.usage(new PrintStream(baos));

        String expected = String.format("" +
                "Usage: <main class> [-ahVz]%n" +
                "  -a              a option%n" +
                "  -z              z option%n" +
                "  -h, --help      Show this help message and exit.%n" +
                "  -V, --version   Print version information and exit.%n"
        );
        assertEquals(expected, baos.toString());
    }

    static class Issue439Mixin {
        @Spec CommandSpec spec;

        @Option(names = "--trex")
        void setTRexFences(final String value) {
            throw new ParameterException(spec.commandLine(), "TREX error");
        }
    }

    static class Issue439Command {
        @Mixin Issue439Mixin mixin;
        @Spec CommandSpec spec;

        @Option(names = "--raptor")
        void setRaptorFences(final String value) {
            throw new ParameterException(spec.commandLine(), "RAPTOR error");
        }
    }

    @Test
    public void testIssue439InjectedSpecInMixinHasNullCommandLineAnnotations() {
        CommandLine cmd = new CommandLine(new Issue439Command());
        assertExceptionThrownFromSetter(cmd);
    }

    @Test
    public void testIssue439InjectedSpecInMixinHasNullCommandLineProgrammatic() {
        final CommandSpec mixinSpec = CommandSpec.create();
        ISetter trexSetter = new ISetter() {
            public <T> T set(T value) {
                throw new ParameterException(mixinSpec.commandLine(), "TREX error");
            }
        };
        mixinSpec.addOption(OptionSpec.builder("--trex").
                type(String.class).setter(trexSetter).build());

        final CommandSpec commandSpec = CommandSpec.create();
        commandSpec.addMixin("mixin", mixinSpec);
        ISetter raptorSetter = new ISetter() {
            public <T> T set(T value) {
                throw new ParameterException(commandSpec.commandLine(), "RAPTOR error");
            }
        };
        commandSpec.addOption(OptionSpec.builder("--raptor").
                type(String.class).setter(raptorSetter).build());

        CommandLine cmd = new CommandLine(commandSpec);
        assertExceptionThrownFromSetter(cmd);
    }

    private void assertExceptionThrownFromSetter(CommandLine cmd) {
        try {
            cmd.parseArgs("--trex", "abc");
            fail("expected ParameterException");
        } catch (ParameterException ex) {
            assertEquals("TREX error", ex.getMessage());
        }
        try {
            cmd.parseArgs("--raptor", "xyz");
            fail("expected ParameterException");
        } catch (ParameterException ex) {
            assertEquals("RAPTOR error", ex.getMessage());
        }
    }

    @Command(name="super")
    static class SuperClass {
    }

    @Command(name="sub")
    static class SubClass extends SuperClass {
        @Command(name="method")
        public void method() {}
    }
    @Command(name="main", subcommands= {SuperClass.class, SubClass.class})
    static class Main {
    }

    @Test
    public void testIssue619MethodSubcommandInSubclassAddedTwice() {
        //setTraceLevel(CommandLine.TraceLevel.DEBUG);
        CommandLine commandLine = new CommandLine(new Main());
        assertEquals(2, commandLine.getSubcommands().size());

        CommandLine zuper = commandLine.getSubcommands().get("super");
        assertEquals(0, zuper.getSubcommands().size());

        CommandLine sub = commandLine.getSubcommands().get("sub");
        assertEquals(1, sub.getSubcommands().size());

        CommandLine method = sub.getSubcommands().get("method");
        assertEquals(0, method.getSubcommands().size());
    }

    @Command
    static class Issue924 {
        @Mixin Issue924Mixin myMixin;

        Issue924Mixin methodMixin;

        @Command
        void subcommand(@Mixin(name = "blah") Issue924Mixin myMixin) {
            methodMixin = myMixin;
        }
    }
    static class Issue924Mixin {
        @Option(names = "-v") boolean verbose;
    }
    @Test
    public void testIssue924mixinAnnotatedElement() {
        Issue924 userObject = new Issue924();
        CommandLine commandLine = new CommandLine(userObject);
        assertNotNull(userObject.myMixin);

        Map<String, IAnnotatedElement> mixinElements = commandLine.getCommandSpec().mixinAnnotatedElements();
        assertEquals(1, mixinElements.size());
        IAnnotatedElement element = mixinElements.get("myMixin");
        assertNotNull(element);
        assertEquals("myMixin", element.getName());
        assertEquals(Issue924Mixin.class, element.getTypeInfo().getType());
        assertTrue(String.valueOf(element.getter()), element.getter() instanceof FieldBinding);

        CommandLine subcommand = commandLine.getSubcommands().get("subcommand");
        Map<String, IAnnotatedElement> mixinMethodElements = subcommand.getCommandSpec().mixinAnnotatedElements();
        assertEquals(1, mixinMethodElements.size());
        IAnnotatedElement methodElement = mixinMethodElements.get("blah");
        assertNotNull(methodElement);
        assertEquals("arg0", methodElement.getName());
        assertEquals(Issue924Mixin.class, methodElement.getTypeInfo().getType());
    }

    @Command(subcommands = Issue925Sub.class)
    static class Issue925Top {
        boolean verbose;

        @Option(names = "-v")
        public void setVerbose(boolean verbose) {
            this.verbose = verbose;
        }
    }

    // Define a mixin that delegates to the parent command.
    static class Issue925MyMixin {
        @ParentCommand Issue925Top top;

        @Option(names = "-v")
        public void setVerbose(boolean verbose) {
            top.setVerbose(verbose);
        }
    }

    // Now subcommands just need to mix in the `MyMixin`
    // to get a `-v` option that delegates to the parent command.
    @Command(name = "sub")
    static class Issue925Sub {
        @Mixin Issue925MyMixin mymixin;

        // This works for @Command-annotated methods also.
        // But needs to have the correct parent!
        @Command(name = "subsub")
        void subsub(@Mixin(name = "key") Issue925SubMixin mymixin) {
            // business logic for the subsub command...
        }
    }
    static class Issue925SubMixin {
        @ParentCommand Issue925Sub sub;

        @Option(names = "-v")
        public void setVerbose(boolean verbose) {
            sub.mymixin.setVerbose(verbose);
        }
    }

    @Test
    public void testIssue925ParentCommandAnnotationInMixins() {
        Issue925Top top = new Issue925Top();
        CommandLine commandLine = new CommandLine(top);

        Issue925Sub subCmdObject = commandLine.getSubcommands().get("sub").getCommand();
        assertNotNull(subCmdObject.mymixin);
        assertNotNull(subCmdObject.mymixin.top);
        assertSame(top, subCmdObject.mymixin.top);

        CommandSpec subsub = commandLine.getSubcommands().get("sub").getSubcommands().get("subsub").getCommandSpec();
        assertEquals(1, subsub.mixins().size());
        CommandSpec mixin = subsub.mixins().get("key");
        Issue925SubMixin mixinInstance = (Issue925SubMixin) mixin.userObject();
        assertNotNull(mixinInstance.sub);
        assertSame(subCmdObject, mixinInstance.sub);
    }

    static class VerbosityMixin {
        @Spec CommandSpec mySpec;
        @Spec(Spec.Target.MIXEE) CommandSpec commandSpec;

        @Option(names = "-v") boolean verbose;
    }

    @Test
    public void testMixinSpecTarget() {
        class MyApp {
            @Mixin VerbosityMixin verbosityMixin;
        }

        MyApp myApp = new MyApp();
        new CommandLine(myApp).parseArgs("-v");
        assertNotNull(myApp.verbosityMixin.mySpec);
        assertNotNull(myApp.verbosityMixin.commandSpec);

        assertNotSame(myApp.verbosityMixin.commandSpec, myApp.verbosityMixin.mySpec);
        assertTrue(myApp.verbosityMixin.mySpec.userObject() instanceof VerbosityMixin);

        assertSame(myApp, myApp.verbosityMixin.commandSpec.userObject());
    }

    @Command(usageHelpWidth = 123 )
    static class MixinWidth {}

    @Test
    public void testMixinWidth() {
        class MyApp {
            @Mixin
            MixinWidth mixin;
        }
        CommandLine cmd = new CommandLine(new MyApp());
        assertEquals(123, cmd.getCommandSpec().usageMessage().width());
    }

    @Test
    public void testMixinLongOptionsMaxWidth() {
        CommandSpec spec = CommandSpec.create();
        assertNotEquals(43, spec.usageMessage().longOptionsMaxWidth());
        spec.usageMessage().longOptionsMaxWidth(43);

        CommandSpec another = CommandSpec.create();
        another.addMixin("a", spec);

        assertEquals(43, another.usageMessage().longOptionsMaxWidth());
    }

    @Command(aliases = {"ls"} )
    public static class ListAliasMixin {
    }

    @Command(name="list")
    public static class MyListCommand {
        @Mixin() public ListAliasMixin aliasMixin;
    }

    @Command(subcommands = {MyListCommand.class})
    public static class App_Issue1836 {
    }

    @Test
    public void testIssue1836CommandAliasOnMixin() {
        Help help = new Help(new App_Issue1836());
        assertEquals("list, ls", help.commandList().trim());
    }
}


text:
define([
    'application',
		'modules/TestingTesting123Module'
		],
		function( app, TestingTesting123Module ) {

			describe('TestingTesting123Module Module', function () {

				it('should equal TestingTesting123Module Module', function () {
					var testingtesting123module = app.TestingTesting123Module;
					expect( testingtesting123module ).to.equal( TestingTesting123Module );
				});

				it('should have more test written', function(){
					expect( false ).to.be.ok;
				});
			});

		});


text:
using System;
using System.Diagnostics.Contracts;

namespace EventStore.Core.Data
{
    public struct TFPos : IEquatable<TFPos>, IComparable<TFPos>
    {
        public static readonly TFPos Invalid = new TFPos(-1, -1);
        public static readonly TFPos HeadOfTf = new TFPos(-1, -1);

        public readonly long CommitPosition;
        public readonly long PreparePosition;

        public TFPos(long commitPosition, long preparePosition)
        {
            CommitPosition = commitPosition;
            PreparePosition = preparePosition;
        }

        [Pure]
        public string AsString()
        {
            return string.Format("{0:X16}{1:X16}", CommitPosition, PreparePosition);
        }

        public static bool TryParse(string s, out TFPos pos)
        {
            pos = Invalid;
            if (s == null || s.Length != 32)
                return false;

            long commitPos;
            long preparePos;
            if (!long.TryParse(s.Substring(0, 16), System.Globalization.NumberStyles.HexNumber, null, out commitPos))
                return false;
            if (!long.TryParse(s.Substring(16, 16), System.Globalization.NumberStyles.HexNumber, null, out preparePos))
                return false;
            pos = new TFPos(commitPos, preparePos);
            return true;
        }

        public int CompareTo(TFPos other)
        {
            if (CommitPosition < other.CommitPosition)
                return -1;
            if (CommitPosition > other.CommitPosition)
                return 1;
            return PreparePosition.CompareTo(other.PreparePosition);
        }

        public bool Equals(TFPos other)
        {
            return this == other;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            return obj is TFPos && Equals((TFPos) obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return (CommitPosition.GetHashCode()*397) ^ PreparePosition.GetHashCode();
            }
        }

        public static bool operator ==(TFPos left, TFPos right)
        {
            return left.CommitPosition == right.CommitPosition && left.PreparePosition == right.PreparePosition;
        }

        public static bool operator !=(TFPos left, TFPos right)
        {
            return !(left == right);
        }

        public static bool operator <=(TFPos left, TFPos right)
        {
            return !(left > right);
        }

        public static bool operator >=(TFPos left, TFPos right)
        {
            return !(left < right);
        }

        public static bool operator <(TFPos left, TFPos right)
        {
            return left.CommitPosition < right.CommitPosition
                   || (left.CommitPosition == right.CommitPosition && left.PreparePosition < right.PreparePosition);
        }

        public static bool operator >(TFPos left, TFPos right)
        {
            return left.CommitPosition > right.CommitPosition
                   || (left.CommitPosition == right.CommitPosition && left.PreparePosition > right.PreparePosition);
        }

        public override string ToString()
        {
            return string.Format("C:{0}/P:{1}", CommitPosition, PreparePosition);
        }
    }
}


text:
/* @flow */

const output = (content, target, atBeginning) => {
  switch (typeof target) {
    case 'string':
      switch (atBeginning) {
        case true:
          return `${content}${target}`;
        default:
          return `${target}${content}`;
      }
    case 'number':
      if (typeof content === 'number') {
        switch (atBeginning) {
          case true:
            return Number(`${content}${target}`);
          default:
            return Number(`${target}${content}`);
        }
      }
      break;
    default:
      break;
  }
  return target;
};

const add = (content: string, target: ?string, atBeginning: boolean = true) => {
  if (Object.prototype.toString.call(target) === '[object Array]') {
    const list = target || [];
    const result = [];
    for (let i = 0; i <= list.length - 1; i++) {
      const item = output(content, list[i], atBeginning);
      result.push(item);
    }
    return result;
  }
  return output(content, target, atBeginning);
};

export default add;


text:
angular-grecaptcha
==================

Angular implementation of Google recaptcha: https://developers.google.com/recaptcha/

bower
-----
`bower install angular-recaptcha --save`

npm
-----
`npm install angular-recaptcha --save-dev`

configuration
-----

>grecaptchaProvider.setLanguage(languageCode)

list of ***languageCode*** : https://developers.google.com/recaptcha/docs/language

>grecaptchaProvider.setParameters(parameters);

parameters = {
	***sitekey***: 'yoursitekey',
	theme: '***light***|dark',
	type: 'audio|***image***,
})

runtime configuration
-----
>grecaptcha.updateParameters(parameters);

##inline configuration

```HTML
<div grecaptcha ng-model="captcha" grecaptcha-params="{theme:'dark'}"></div>
```

example
-----

```HTML
<!doctype html>
<html class="no-js" ng-app="myModule">
<head>
    <meta charset="utf-8">
    <title>angular-grecaptcha</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1>angular-grecaptcha example</h1>
        <form role="form" name="myForm" ng-controller="FormCtrl" ng-submit="submit()">
            <div class="form-group">
                <div grecaptcha ng-model="captcha"></div>
                <button type="submit" class="btn btn-primary">submit</button>
            </div>
        </fieldset>
    </form>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<script src="grecaptcha.js"></script>
<script type="text/javascript">
    angular
    .module('myModule', ['grecaptcha'])
    .config(function(grecaptchaProvider) {
        grecaptchaProvider.setParameters({
            sitekey: 'your key here',
            theme: 'light'
        });
    })
    .controller('FormCtrl', function($scope) {
        $scope.submit = function() {
            console.log("submit : ", $scope.captcha);
        };
    });
</script>
</body>
</html>
````


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="BPMNEditorStateService">
    <stateFile url="file://$PROJECT_DIR$/src/main/resources/sayLeave.bpmn">
      <view grid="false" />
    </stateFile>
    <stateFile url="file://$PROJECT_DIR$/src/main/resources/leave.bpmn">
      <view grid="false" />
    </stateFile>
  </component>
</project>


text:
package academic.cookSalad;

public enum Dish {
	CEASERS,RUSSIAN;
}


text:
When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the SingularityNET development team before making a change.

Please note we have a SingularityNET [Code of Conduct](https://github.com/singnet/singnet/blob/master/CODE_OF_CONDUCT.md), please
read it and follow it in all your interactions with the project.

## Pull Request Process

1. Ensure any install or build dependencies are removed before the end of the layer when doing a
   build.
2. Make sure that the code meets high quality standards, is well commented and conforms to the
   same style as the code it amends or augments.
3. Update the README.md with details of changes to the interface, this includes new environment
   variables, exposed ports, useful file locations and container parameters.
4. Where applicable, increase the version numbers in any examples files and the README.md to the
   new version that this Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/).
5. If you have commit privileges, you may merge the Pull Request in once you have the sign-off
   of two other developers, or if you do not have permission to do that, you may request another
   second reviewer to merge it for you. Check the merge commit history to see who has permissions
   to merge code for the area covered by your pull request.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1" name="viewport">
    <meta content="Website for a university project" name="description">
    <meta content="Slytaria" name="author">
    <title>Gochuumon wa Usagi Desu ka?</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

Chargement en cours...

                    <button class="navbar-toggle" data-target="#bs-example-navbar-collapse-1" data-toggle="collapse" type="button">Toggle navigation

                        </button> Gochuumon wa Usagi Desu ka?

                            histoire

                            staff

                            personnages

                            épisodes

                            musique

                            galerie

Gochuumon wa Usagi Desu ka?

 Copyright © Aurélien Thorel 2017. All right reserved.


text:
import { ClinicalSummaryVisualizationService } from './clinical-summary-visualization.service';

describe('Service : ClinicalSummaryVisualizationService', () => {
  let service: ClinicalSummaryVisualizationService;
  const expectedCols = {
    'clinical-hiv-comparative-overview': {
      reporting_month: 'Reporting Month',
      currently_in_care_total: 'Patients In Care',
      on_art_total: 'Patients On ART',
      not_on_art_total: 'Patients Not On ART',
      patients_requiring_vl: 'Patients Qualified For VL',
      tested_appropriately: 'On ART with VL',
      not_tested_appropriately: 'On ART without VL',
      due_for_annual_vl: 'Due For Annual VL',
      pending_vl_orders: 'Ordered & Pending VL Result',
      missing_vl_order: 'Missing VL Order',
      virally_suppressed: 'Virally Suppressed',
      perc_virally_suppressed: '% Virally Suppressed',
      perc_tested_appropriately: '% on ART with VL',
      not_virally_suppressed: 'Not Virally Suppressed'
    },
    'clinical-art-overview': {
      not_on_arv: 'Not On Any ARV Drugs',
      on_nevirapine: 'Nevirapine',
      on_efavirenz: 'Efavirenz',
      on_lopinavir: 'Lopinavir',
      on_atazanavir: 'Atazanavir',
      on_raltegravir: 'Raltegravir',
      on_other_arv_drugs: 'Others'
    },
    'clinical-patient-care-status-overview': {
      patients_continuing_care: 'Patients In Care',
      transferred_out_patients: 'Transferred Out Patients',
      deceased_patients: 'Deceased Patients',
      untraceable_patients: 'Untraceable Patients',
      hiv_negative_patients: 'HIV Negative Patients',
      self_disengaged_from_care: 'Self Disengaged From Care',
      defaulters: 'Defaulters',
      other_patient_care_status: 'Others'
    }
  };

  const tableData = [{ t: 1 }];

  beforeEach(() => {
    service = new ClinicalSummaryVisualizationService();
  });

  it('should generate the correct columns when translateColumns is called', (done) => {
    expect(service.translateColumns).toEqual(expectedCols);
    done();
  });

  it('should return table data when generateTableData is called', (done) => {
    expect(service.generateTableData(tableData)).toEqual(tableData);
    done();
  });

  it('should be able to flip table columns when flipTranlateColumns is called', (done) => {
    const flippedCols = service.flipTranlateColumns;
    expect(flippedCols['clinical-art-overview']['Raltegravir']).toEqual(
      'on_raltegravir'
    );
    done();
  });

  it(
    'should be able to add onCellClicked and cellRenderer when generateTabularViewColumns' +
      ' is called',
    (done) => {
      const tableCols = service.generateTabularViewColumns;
      expect(tableCols[0].onCellClicked).toBeDefined();
      done();
    }
  );
});


text:
@class SCNNode;

@interface SKEDocumentAddNodeAttributeEdition : SKEDocumentEdition
{
    SCNNode *_node;
    Class _nodeAttributeClass;
}

- (void).cxx_destruct;
- (BOOL)revert;
- (BOOL)apply;
- (BOOL)_edit:(BOOL)arg1;
- (id)initWithDocument:(id)arg1 node:(id)arg2 nodeAttributeClass:(Class)arg3;

@end


text:
package com.flipkart.foxtrot.core.querystore.actions;

import com.flipkart.foxtrot.common.Period;
import com.google.common.collect.Maps;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogram;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityBuilder;
import org.elasticsearch.search.aggregations.metrics.percentiles.InternalPercentiles;
import org.elasticsearch.search.aggregations.metrics.percentiles.Percentile;
import org.elasticsearch.search.aggregations.metrics.stats.extended.InternalExtendedStats;

import java.util.Map;

/**
 * Created by rishabh.goyal on 24/08/14.
 */
public class Utils {

    public static AbstractAggregationBuilder buildExtendedStatsAggregation(String field) {
        String metricKey = getExtendedStatsAggregationKey(field);
        return AggregationBuilders.extendedStats(metricKey).field(field);
    }

    public static AbstractAggregationBuilder buildPercentileAggregation(String field) {
        String metricKey = getPercentileAggregationKey(field);
        return AggregationBuilders.percentiles(metricKey).field(field);
    }

    public static DateHistogramBuilder buildDateHistogramAggregation(String field, DateHistogram.Interval interval) {
        String metricKey = getDateHistogramKey(field);
        return AggregationBuilders.dateHistogram(metricKey)
                .minDocCount(0)
                .field(field)
                .interval(interval);
    }

    public static CardinalityBuilder buildCardinalityAggregation(String field) {
        return AggregationBuilders
                .cardinality(Utils.sanitizeFieldForAggregation(field))
                .precisionThreshold(40000)
                .field(field);
    }

    public static String sanitizeFieldForAggregation(String field) {
        return field.replaceAll(Constants.FIELD_REPLACEMENT_REGEX, Constants.FIELD_REPLACEMENT_VALUE);
    }

    public static DateHistogram.Interval getHistogramInterval(Period period) {
        DateHistogram.Interval interval;
        switch (period) {
            case seconds:
                interval = DateHistogram.Interval.SECOND;
                break;
            case minutes:
                interval = DateHistogram.Interval.MINUTE;
                break;
            case hours:
                interval = DateHistogram.Interval.HOUR;
                break;
            case days:
                interval = DateHistogram.Interval.DAY;
                break;
            default:
                interval = DateHistogram.Interval.HOUR;
                break;
        }
        return interval;
    }

    public static String getExtendedStatsAggregationKey(String field) {
        return sanitizeFieldForAggregation(field) + "_extended_stats";
    }

    public static String getPercentileAggregationKey(String field) {
        return sanitizeFieldForAggregation(field) + "_percentile";
    }

    public static String getDateHistogramKey(String field) {
        return sanitizeFieldForAggregation(field) + "_date_histogram";
    }

    public static IndicesOptions indicesOptions() {
        return IndicesOptions.lenientExpandOpen();
    }

    public static Map<String, Number> createExtendedStatsResponse(InternalExtendedStats extendedStats) {
        Map<String, Number> stats = Maps.newHashMap();
        stats.put("avg", extendedStats.getAvg());
        stats.put("sum", extendedStats.getSum());
        stats.put("count", extendedStats.getCount());
        stats.put("min", extendedStats.getMin());
        stats.put("max", extendedStats.getMax());
        stats.put("sum_of_squares", extendedStats.getSumOfSquares());
        stats.put("variance", extendedStats.getVariance());
        stats.put("std_deviation", extendedStats.getStdDeviation());
        return stats;
    }

    public static Map<Number, Number> createPercentilesResponse(InternalPercentiles internalPercentiles) {
        Map<Number, Number> percentiles = Maps.newHashMap();
        for (Percentile percentile : internalPercentiles) {
            percentiles.put(percentile.getPercent(), percentile.getValue());
        }
        return percentiles;
    }

}


text: SoftLayer Slack Bot


text:
package io.vertx.codegen.testmodel;

import io.vertx.codegen.annotations.Nullable;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

import java.util.*;

@VertxGen
public interface ConstantTCK {

  /**
   * Some doc.
   */
  byte BYTE = (byte) 123;
  Byte BOXED_BYTE = BYTE;
  short SHORT = (short)12345;
  Short BOXED_SHORT = SHORT;
  int INT = 12345464;
  Integer BOXED_INT = INT;
  long LONG = 65675123L;
  Long BOXED_LONG = LONG;
  float FLOAT = 1.23f;
  Float BOXED_FLOAT = FLOAT;
  double DOUBLE = 3.34535d;
  Double BOXED_DOUBLE = DOUBLE;
  boolean BOOLEAN = true;
  Boolean BOXED_BOOLEAN = BOOLEAN;
  char CHAR = 'Y';
  Character BOXED_CHAR = CHAR;
  String STRING = "orangutan";
  RefedInterface1 VERTX_GEN = new RefedInterface1Impl().setString("chaffinch");
  TestDataObject DATA_OBJECT = new TestDataObject().setFoo("foo").setBar(123);
  JsonObject JSON_OBJECT = new JsonObject().put("cheese", "stilton");
  JsonArray JSON_ARRAY = new JsonArray().add("socks").add("shoes");
  TestEnum ENUM = TestEnum.JULIEN;
  Throwable THROWABLE = new Exception("test");
  Object OBJECT = 4;

  @Nullable  RefedInterface1 NULLABLE_NON_NULL = VERTX_GEN;
  @Nullable RefedInterface1 NULLABLE_NULL = null;

  List<Byte> BYTE_LIST = Collections.singletonList(BYTE);
  List<Short> SHORT_LIST = Collections.singletonList(SHORT);
  List<Integer> INT_LIST = Collections.singletonList(INT);
  List<Long> LONG_LIST = Collections.singletonList(LONG);
  List<Float> FLOAT_LIST = Collections.singletonList(FLOAT);
  List<Double> DOUBLE_LIST = Collections.singletonList(DOUBLE);
  List<Boolean> BOOLEAN_LIST = Collections.singletonList(BOOLEAN);
  List<Character> CHAR_LIST = Collections.singletonList(CHAR);
  List<String> STRING_LIST = Collections.singletonList(STRING);
  List<RefedInterface1> VERTX_GEN_LIST = Collections.singletonList(VERTX_GEN);
  List<JsonObject> JSON_OBJECT_LIST = Collections.singletonList(JSON_OBJECT);
  List<JsonArray> JSON_ARRAY_LIST = Collections.singletonList(JSON_ARRAY);
  List<TestDataObject> DATA_OBJECT_LIST = Collections.singletonList(DATA_OBJECT);
  List<TestEnum> ENUM_LIST = Collections.singletonList(ENUM);

  Set<Byte> BYTE_SET = Collections.singleton(BYTE);
  Set<Short> SHORT_SET = Collections.singleton(SHORT);
  Set<Integer> INT_SET = Collections.singleton(INT);
  Set<Long> LONG_SET = Collections.singleton(LONG);
  Set<Float> FLOAT_SET = Collections.singleton(FLOAT);
  Set<Double> DOUBLE_SET = Collections.singleton(DOUBLE);
  Set<Boolean> BOOLEAN_SET = Collections.singleton(BOOLEAN);
  Set<Character> CHAR_SET = Collections.singleton(CHAR);
  Set<String> STRING_SET = Collections.singleton(STRING);
  Set<RefedInterface1> VERTX_GEN_SET = Collections.singleton(VERTX_GEN);
  Set<JsonObject> JSON_OBJECT_SET = Collections.singleton(JSON_OBJECT);
  Set<JsonArray> JSON_ARRAY_SET = Collections.singleton(JSON_ARRAY);
  Set<TestDataObject> DATA_OBJECT_SET = Collections.singleton(DATA_OBJECT);
  Set<TestEnum> ENUM_SET = Collections.singleton(ENUM);

  Map<String, Byte> BYTE_MAP = Collections.singletonMap("foo", BYTE);
  Map<String, Short> SHORT_MAP = Collections.singletonMap("foo", SHORT);
  Map<String, Integer> INT_MAP = Collections.singletonMap("foo", INT);
  Map<String, Long> LONG_MAP = Collections.singletonMap("foo", LONG);
  Map<String, Float> FLOAT_MAP = Collections.singletonMap("foo", FLOAT);
  Map<String, Double> DOUBLE_MAP = Collections.singletonMap("foo", DOUBLE);
  Map<String, Boolean> BOOLEAN_MAP = Collections.singletonMap("foo", BOOLEAN);
  Map<String, Character> CHAR_MAP = Collections.singletonMap("foo", CHAR);
  Map<String, String> STRING_MAP = Collections.singletonMap("foo", STRING);
  Map<String, JsonObject> JSON_OBJECT_MAP = Collections.singletonMap("foo", JSON_OBJECT);
  Map<String, JsonArray> JSON_ARRAY_MAP = Collections.singletonMap("foo", JSON_ARRAY);
}


text:
require 'pp'
require 'set'

begin
  require 'rubygems'
rescue LoadError
end

begin
  require 'systemu'
rescue LoadError
  puts "Please install systemu for better-looking results"

  # small drop-in replacement for systemu... far from perfect though, so please
  # install the library

  def systemu command
    stdout = `#{command} 2>&1`
    status, stdout, stderr = $?, stdout, ''
  end
end

class String
  { :red => 31,
    :green => 32,
    :yellow => 33,
  }.each do |key, value|
    define_method key do
      "\e[#{value}m" + self + "\e[0m"
    end
  end

  def /(str)
    File.join(self, str.to_s)
  end
end

class Array
  def commonize
    snips, rest = map{|s| [s[0,1], s[1..-1]]}.transpose
    unless snips.uniq.size != 1 or rest.any?{|r| File.basename(r) == r}
      rest.commonize
    else
      self.map{|e| e.gsub(/^\//, '')}
    end
  end

  def namize
    commonize.map do |e|
      dir = File.dirname(e)
      file = File.basename(e, File.extname(e))
      ( dir / file ).gsub(/^\.\//, '')
    end
  end
end

$stdout.sync = true

class SpecWrap
  def initialize(*files)
    @files = files.flatten
    @names = @files.namize
    @specs = Hash[*@files.zip(@names).flatten]
    @done = Set.new
  end

  def run
    @specs.sort_by{|s| s.last}.each do |file, name|
      spec = SpecFile.new(file, name, term_width)
      spec.run
      spec.short_summary
      @done << spec
    end

    @done.sort_by{|d| d.name}.each do |spec|
      puts(spec.long_summary) if spec.failed?
    end

    summarize
  end

  def summarize
    total_passed = @done.inject(0){|s,v| s + v.passed }
    total_failed = @done.inject(0){|s,v| s + v.failed }
    total_specs = total_failed + total_passed

    puts "#{total_specs} examples, #{total_failed} failures"
    puts

    if total_failed.nonzero?
      failed = @done.select{|d| d.failed.nonzero? or d.passed.zero?}.map{|f| f.name.red }
      puts "These failed: #{failed.join(', ')}"
      exit 1
    else
      puts("No failing examples, let's add some tests!")
    end
  end

  def term_width
    @names.sort_by{|s| s.size }.last.size
  end
end

class SpecFile
  attr_reader :file, :name, :passed, :failed, :mark_passed

  def initialize file, name, term_width
    @file, @name, @term_width = file, name, term_width
    @inc = $:.map{|e| "-I#{e}" }.join(" ")
  end

  def run
    init
    execute
    parse
    done
    self
  end

  def init
    print "Running #@name... ".ljust(@term_width + 20)
  end

  def execute
    @status, @stdout, @stderr = systemu("ruby #@inc #@file")
  end

  def done
    @ran = true
  end

  def short_summary
    f = lambda{|n| n.to_s.rjust(3) }
    total = f[@passed + @failed] rescue nil
    failed, passed = f[@failed], f[@passed]
    color = :red
    width = 22

    if total_failure?
      text = 'total failure'.center(width)
    elsif failed?
      text = "#{total} specs - #{failed} failed".rjust(width)
      if @stdout =~ /Usually you should not worry about this failure, just install the/
        lib = @stdout.scan(/^no such file to load -- (.*?)$/).flatten.first
        text = "needs #{lib}".center(width)
        @mark_passed = true
      end
    elsif (not @mark_passed) and succeeded?
      color = :green
      text = "#{total} specs - all passed".rjust(width)
    end

    puts "[ #{text.send(color)} ]"
  end

  def long_summary
    puts "[ #@name ]".center(80, '-'), "ExitStatus:".yellow
    pp @status
    puts "StdOut:".yellow, @stdout, "StdErr:".yellow, @stderr
  end

  def parse
    @passed = 0
    @failed = 0
    found = false
    @stdout.grep(/(\d+) examples?, (\d+) failures?/)
    @passed, @failed = $1.to_i, $2.to_i
  end

  def failed?
    not succeeded?
  end

  def total_failure?
    succeeded? == nil
  end

  def succeeded?
    run unless @ran
    return @mark_passed unless @mark_passed.nil?
    crits = [
      [@status.exitstatus.zero?, @stderr.empty?],
      [@passed, @failed],
      [@passed.nonzero?, @failed.zero?],
    ]
    crits.all?{|c| c.all? }
  rescue
    nil
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primaryColor">#2D8727</color>
    <color name="primaryColorDark">#3B322C</color>
    <color name="accentColor">#284B63</color>
</resources>