text:
package com.nhinds.lastpass.encryption;

import java.security.GeneralSecurityException;

public interface KeyProvider {

	byte[] getKey(String username, String password, int iterations) throws GeneralSecurityException;

	String getHash(byte[] key, String password, int iterations) throws GeneralSecurityException;

}

redpajama_set_name: RedPajamaGithub


text:
<?php

defined('KAZINDUZI_PATH') || exit('No direct script access allowed');

class Security
{

    /**
     * @var  string  keyname used for token storage
     */
    public static $token_name = 'security_token';

    /**
     * @var integer expiration time for the security token
     */
    public static $token_expiration = 7200;

    /**
     * Check if the given token matches the currently stored security token.
     * @param   string   token to check
     * @return  boolean
     * @uses    Security::token
     */
    public static function check($token)
    {
        return self::compareStrings(self::token(), $token);
    }

    /**
     * Compare two strings to avoid timing attacks
     *
     * C function memcmp() internally used by PHP, exits as soon as a difference
     * is found in the two buffers. That makes possible of leaking
     * timing information useful to an attacker attempting to iteratively guess
     * the unknown string (e.g. password).
     *
     * @param  string $expected
     * @param  string $actual
     * @return bool
     */
    public static function compareStrings($expected, $actual)
    {
        $expected = (string) $expected;
        $actual = (string) $actual;
        $lenExpected = strlen($expected);
        $lenActual = strlen($actual);
        $len = min($lenExpected, $lenActual);
        $result = 0;
        for ($i = 0; $i < $len; $i++) {
            $result |= ord($expected[$i]) ^ ord($actual[$i]);
        }
        $result |= $lenExpected ^ $lenActual;
        return ($result === 0);
    }

    /**
     * Generate and store a unique token which can be used to help prevent
     * $token = Security::token();
     * You can insert this token into your forms as a hidden field.
     * This provides a basic, but effective, method of preventing CSRF attacks.     *
     * @param   boolean  force a new token to be generated?
     * @return  string
     * @uses    Session::instance
     */
    public static function token($new = false)
    {
        $session = Session::instance();
        $token = $session->get(self::$token_name);
        $isExpired = (time() - (int) $session->get('token_expiration_time')) > 0 ? true : false;
        if ($new === true || !$token || $isExpired) {
            $token = self::generateToken();
            $session->set(self::$token_name, $token);
            $session->set('token_expiration_time', time() + self::$token_expiration);
        }
        return $token;
    }

    /**
     * Generate the secure random string
     *
     * @return string
     */
    protected static function generateToken()
    {
        if (version_compare(PHP_VERSION, '5.3.4', '>=') && function_exists('openssl_random_pseudo_bytes')) {
            return base64_encode(openssl_random_pseudo_bytes(32));
        } else {
            return sha1(uniqid(mt_rand(), true));
        }
    }

    /**
     * Remove image tags from a string.
     * @param   string  string to sanitize
     * @return  string
     */
    public static function removeImageTags($str)
    {
        return preg_replace('/<img[^>]+\>/is', '$1', $str);
    }

    /**
     * Encodes PHP tags in a string.
     * @param   string  string to sanitize
     * @return  string
     */
    public static function encodePHPTags($str)
    {
        return str_replace(array('<?', '?>'), array('<?', '?>'), $str);
    }

    /**
     * BCrypt hashing pas
     * @param string $password
     * @return string
     */
    public static function bcryptPassword($password)
    {
        $Crypt = new Bcrypt();
        $Crypt->setSalt('MyKazinduziIsGreat');
        return $Crypt->hash($password);
    }

}


text:
package cn.edu.siso.rlxapf.util.tcp;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.Timer;
import java.util.TimerTask;

import cn.edu.siso.rlxapf.R;
import cn.edu.siso.rlxapf.bean.HarmonicDatasBean;
import cn.edu.siso.rlxapf.bean.NoticeDatasBean;
import cn.edu.siso.rlxapf.bean.ParameterDatasBean;
import cn.edu.siso.rlxapf.bean.RealTimeDatasBean;
import cn.edu.siso.rlxapf.util.ProtocolUtil;
import cn.edu.siso.rlxapf.util.TCPUtil;

public class TcpClientManager {

    private static TcpClientManager instance = null;
    private static boolean isConnect = false;

    private TCPUtil tcpUtil = null;

    private Timer tcpTimer = null; // TCP超时定时器

    public static final String KEY_TCP_OPERATE_TYPE = "operate_type";
    public class TcpOperateType {
        public static final String CONNECT = "connect";
        public static final String OPERATE = "operate";
    }

    public static final String KEY_TCP_RES_TYPE = "res_type";
    public class TcpResType {
        public static final String SUCCESS = "success";
        public static final String ERROR = "error";
        public static final String CLOSE = "close";
        public static final String CRC = "crc";
        public static final String LENGTH = "length";
        public static final String TIMEOUT = "timeout";
    }

    public static final String KEY_TCP_RES_CODE = "res_code";
    public static final String KEY_TCP_RES_DATA = "res_data";

    public static final String TAG = "TcpClientManager";

    public enum  TcpCmdType {
        EMPTY, CONNECT_DEVICE,
        LOAD_PARAMS, UPDATE_PARAMS, SAVE_PARAMS, EXPORT_PARAMS, RESTORE_PARAMS,
        STOP_DEVICE, START_DEVICE,
        REAL_DATA, SPECTRUM_DATA,
        DEVICE_WARNING};
    public static final String KEY_TCP_CMD_TYPE = "cmd_type";

    private TcpClientManager() {
        tcpUtil = new TCPUtil();
    }

    public static TcpClientManager getInstance() {
        if (instance == null) {
            instance = new TcpClientManager();
        }

        return instance;
    }

    public void connect(Context context, String deviceId, String compass, Handler tcpHandler) {
        tcpUtil.connect(deviceId, compass, new OnTcpConnectListener(tcpHandler));

        // 执行任务时启动超时定时器
        tcpTimer = new Timer();
        tcpTimer.schedule(new TimeOutTask(tcpHandler, TcpCmdType.CONNECT_DEVICE),
                context.getResources().getInteger(R.integer.tcp_time_out));
    }

    /**
     * 发送TCP指令
     * @param type TcpCmdType 指令类型
     * @param params String[] 指令参数
     * @return int -1 设备未连接 0 设备已连接
     */
    public int sendCmd(Context context, TcpCmdType type, String[] params, Handler tcpHandler) {

        if (!isConnect) {
            return -1;
        }

        // 执行异步任务
        new TcpAsyncTask(context, new OnTcpReceiveListener(tcpHandler, type)).execute(params);

        // 因为启动和停止设备没有返回值,所以不启动定时器
        if (!(type == TcpCmdType.START_DEVICE)
                && !(type == TcpCmdType.STOP_DEVICE)
                && !(type == TcpCmdType.SAVE_PARAMS)
                && !(type == TcpCmdType.EXPORT_PARAMS)
                && !(type == TcpCmdType.RESTORE_PARAMS)) {
            // 执行任务时启动超时定时器
            tcpTimer = new Timer();
            tcpTimer.schedule(new TimeOutTask(tcpHandler, type),
                    context.getResources().getInteger(R.integer.tcp_time_out));
        }

        return 0;
    }

    public boolean getConnectStatus() {
        return isConnect;
    }

    public int close(String deviceId) {
        if (!isConnect) {
            return -1;
        }

        tcpUtil.close(deviceId);

        return 0;
    }

    private void clearTimer() {
        if (tcpTimer != null) {
            tcpTimer.cancel();
            tcpTimer = null;
        }
    }

    private class OnTcpConnectListener implements TCPUtil.OnConnectListener {

        private Handler tcpHandler = null;

        public OnTcpConnectListener (Handler tcpHandler) {
            this.tcpHandler = tcpHandler;
        }

        @Override
        public void onSuccess(String deviceId) {

            isConnect = true;

            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.CONNECT);
            data.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
            data.putString(KEY_TCP_RES_DATA, deviceId);
            msg.setData(data);

            // 清空定时器
            clearTimer();

            tcpHandler.sendMessage(msg);
        }

        @Override
        public void onError(int errorCode, String errorMsg) {
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.CONNECT);
            data.putString(KEY_TCP_RES_TYPE, TcpResType.ERROR);
            data.putString(KEY_TCP_RES_CODE, String.valueOf(errorCode));
            data.putString(KEY_TCP_RES_DATA, errorMsg);
            msg.setData(data);

            // 清空定时器
            clearTimer();

            tcpHandler.sendMessage(msg);
        }

        @Override
        public void onClose(String deviceId) {

            isConnect = false;

            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.CONNECT);
            data.putString(KEY_TCP_RES_TYPE, TcpResType.CLOSE);
            data.putString(KEY_TCP_RES_DATA, deviceId);
            msg.setData(data);

            // 清空定时器
            clearTimer();

            tcpHandler.sendMessage(msg);
        }
    }

    private class OnTcpReceiveListener implements TCPUtil.OnReceiveListener {

        private Handler tcpHandler = null;
        private TcpCmdType type = TcpCmdType.EMPTY;

        public OnTcpReceiveListener(Handler tcpHandler, TcpCmdType type) {
            this.tcpHandler = tcpHandler;
            this.type = type;
        }

        public TcpCmdType getCmdType() {
            return type;
        }

        @Override
        public void onReceive(String deviceId, byte[] data) {
            Message msg = new Message();
            Bundle bundle = new Bundle();

            // 下载参数
            if (type == TcpCmdType.LOAD_PARAMS) {
                ParameterDatasBean datasBean = new ParameterDatasBean();
                int res = datasBean.parse(data);

                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.LOAD_PARAMS.ordinal()));
                if (res == -1) {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.CRC);
                } else if (res == -2) {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.LENGTH);
                } else {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
                    String bean = JSON.toJSONString(datasBean, SerializerFeature.WriteMapNullValue);
                    bundle.putString(KEY_TCP_RES_DATA, bean);
                }
            }

            // 更新参数
            if (type == TcpCmdType.UPDATE_PARAMS) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.UPDATE_PARAMS.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
            }

            // 保存参数
            if (type == TcpCmdType.SAVE_PARAMS) {
                Log.i(TAG, "===保存参数成功===");

                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.SAVE_PARAMS.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
            }

            // 导出参数
            if (type == TcpCmdType.EXPORT_PARAMS) {
                Log.i(TAG, "===导出参数成功===");

                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.EXPORT_PARAMS.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
            }

            // 恢复出厂设置参数
            if (type == TcpCmdType.RESTORE_PARAMS) {
                Log.i(TAG, "===恢复出厂设置成功===");

                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.RESTORE_PARAMS.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
            }

            // 启动设备
            if (type == TcpCmdType.START_DEVICE) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.START_DEVICE.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
            }

            // 停止设备
            if (type == TcpCmdType.STOP_DEVICE) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.STOP_DEVICE.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
            }

            // 读取实时数据
            if (type == TcpCmdType.REAL_DATA) {
                RealTimeDatasBean datasBean = new RealTimeDatasBean();

                int res = datasBean.parse(data);
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.REAL_DATA.ordinal()));
                if (res == -1) {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.CRC);
                } else if (res == -2) {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.LENGTH);
                } else {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
                    String bean = JSON.toJSONString(datasBean, SerializerFeature.WriteMapNullValue);
                    bundle.putString(KEY_TCP_RES_DATA, bean);
                }
            }

            // 读取谐波数据
            if (type == TcpCmdType.SPECTRUM_DATA) {
                HarmonicDatasBean datasBean = new HarmonicDatasBean();
                int res = datasBean.parse(data);
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.SPECTRUM_DATA.ordinal()));
                if (res == -1) {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.CRC);
                } else if (res == -2) {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.LENGTH);
                } else {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
                    // 谐波数据还未定义
                    String bean = JSON.toJSONString(datasBean, SerializerFeature.WriteMapNullValue);
                    bundle.putString(KEY_TCP_RES_DATA, bean);
                }
            }

            // 设备故障
            if (type == TcpCmdType.DEVICE_WARNING) {
                NoticeDatasBean datasBean = new NoticeDatasBean();
                int res = datasBean.parse(data);
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.DEVICE_WARNING.ordinal()));
                if (res == -1) {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.CRC);
                } else if (res == -2) {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.LENGTH);
                } else {
                    bundle.putString(KEY_TCP_RES_TYPE, TcpResType.SUCCESS);
                    String bean = JSON.toJSONString(datasBean, SerializerFeature.WriteMapNullValue);
                    bundle.putString(KEY_TCP_RES_DATA, bean);
                }
            }

            // 清空定时器
            clearTimer();

            msg.setData(bundle);
            tcpHandler.sendMessage(msg);
        }
    }

    private class TcpAsyncTask extends AsyncTask<String, Void, Void> {

        private OnTcpReceiveListener listener = null;
        private Context context = null;

        public TcpAsyncTask(Context context, OnTcpReceiveListener listener) {
            super();
            this.listener = listener;
            this.context = context;
        }

        @Override
        protected Void doInBackground(String... params) {

            // 保存参数
            if (listener.getCmdType() == TcpCmdType.SAVE_PARAMS) {
                tcpUtil.send(ProtocolUtil.saveParams(), listener);
            }

            // 恢复出厂设置
            if (listener.getCmdType() == TcpCmdType.RESTORE_PARAMS) {
                tcpUtil.send(ProtocolUtil.loadDefaultParams(), listener);
            }

            // 导出参数
            if (listener.getCmdType() == TcpCmdType.EXPORT_PARAMS) {
                tcpUtil.send(ProtocolUtil.exportParams(), listener);
            }

            // 下载参数
            if (listener.getCmdType() == TcpCmdType.LOAD_PARAMS) {
                tcpUtil.send(ProtocolUtil.readParamsDatas(Integer.valueOf(params[0]).byteValue()),
                        listener);
            }

            // 更新参数
            if (listener.getCmdType() == TcpCmdType.UPDATE_PARAMS) {
                byte deviceAddr = Integer.valueOf(params[0]).byteValue();
                String preferenceKey = params[1];
                String preferenceValue = params[2];
                byte[] bytesMsg = null;

                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_unit_key))) {
                    bytesMsg = ProtocolUtil.writeParamsUnitCount(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_system_ct_key))) {
                    bytesMsg = ProtocolUtil.writeParamsSystemCTChangeRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_load_ct_key))) {
                    bytesMsg = ProtocolUtil.writeParamsLoadCTChangeRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_target_power_key))) {
                    bytesMsg = ProtocolUtil.writeParamsObjectPowerFactor(deviceAddr, Double.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_3_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic3CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_5_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic5CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_7_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic7CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_9_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic9CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_11_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic11CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_13_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic13CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_15_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic15CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_17_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic17CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_19_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic19CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_21_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic21CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_23_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic23CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_25_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonic25CompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_26_compensate_key))) {
                    bytesMsg = ProtocolUtil.writeParamsHarmonicEvenCompensationRate(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_sampling_model_key))) {
                    bytesMsg = ProtocolUtil.writeParamsSampleMode(deviceAddr, Integer.valueOf(preferenceValue));
                }
                if (preferenceKey.equals(context.getResources().getString(R.string.param_preferences_compensate_model_key))) {
                    bytesMsg = ProtocolUtil.writeParamsCompensationMode(deviceAddr, Integer.valueOf(preferenceValue));
                }

                tcpUtil.send(bytesMsg, listener);
            }

            // 停止设备
            if (listener.getCmdType() == TcpCmdType.STOP_DEVICE) {
//                tcpUtil.send(ProtocolUtil.stopDevice(Integer.valueOf(params[0]).byteValue()),
//                        listener);
                tcpUtil.send(ProtocolUtil.stopDevice(), listener);
            }

            // 启动设备
            if (listener.getCmdType() == TcpCmdType.START_DEVICE) {
//                tcpUtil.send(ProtocolUtil.startDevice(Integer.valueOf(params[0]).byteValue()),
//                        listener);
                tcpUtil.send(ProtocolUtil.startDevice(), listener);
            }

            // 实时数据
            if (listener.getCmdType() == TcpCmdType.REAL_DATA) {
                tcpUtil.send(ProtocolUtil.readRealTimeDatas(Integer.valueOf(params[0]).byteValue()),
                        listener);
            }

            // 谐波数据
            if (listener.getCmdType() == TcpCmdType.SPECTRUM_DATA) {
                tcpUtil.send(ProtocolUtil.readHarmonicSpectrum(Integer.valueOf(params[0]).byteValue()),
                        listener);
            }

            // 设备告警数据
            if (listener.getCmdType() == TcpCmdType.DEVICE_WARNING) {
                tcpUtil.send(ProtocolUtil.readNoticeCheck(Integer.valueOf(params[0]).byteValue()),
                        listener);
            }

            return null;
        }
    }

    private class TimeOutTask extends TimerTask {

        private Handler tcpHandler = null;
        private TcpCmdType tcpType = TcpCmdType.EMPTY;

        public TimeOutTask(Handler tcpHandler, TcpCmdType tcpType) {
            super();

            this.tcpHandler = tcpHandler;
            this.tcpType = tcpType;
        }

        @Override
        public void run() {
            Message msg = new Message();
            Bundle bundle = new Bundle();

            // 连接设备超时
            if (tcpType == TcpCmdType.CONNECT_DEVICE) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.CONNECT);
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            // 载入参数超时
            if (tcpType == TcpCmdType.LOAD_PARAMS) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.LOAD_PARAMS.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            // 更新参数超时
            if (tcpType == TcpCmdType.UPDATE_PARAMS) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.UPDATE_PARAMS.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            // 保存参数超时
            if (tcpType == TcpCmdType.SAVE_PARAMS) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.SAVE_PARAMS.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            // 导出参数超时
            if (tcpType == TcpCmdType.EXPORT_PARAMS) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.EXPORT_PARAMS.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            // 恢复出厂设置
            if (tcpType == TcpCmdType.RESTORE_PARAMS) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.RESTORE_PARAMS.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            // 启动设备超时
            if (tcpType == TcpCmdType.START_DEVICE) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.START_DEVICE.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            // 停止设备超时
            if (tcpType == TcpCmdType.STOP_DEVICE) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.STOP_DEVICE.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            // 实时数据超时
            if (tcpType == TcpCmdType.REAL_DATA) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.REAL_DATA.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            // 谐波数据超时
            if (tcpType == TcpCmdType.SPECTRUM_DATA) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.SPECTRUM_DATA.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            // 设备告警超时
            if (tcpType == TcpCmdType.DEVICE_WARNING) {
                bundle.putString(KEY_TCP_OPERATE_TYPE, TcpOperateType.OPERATE);
                bundle.putString(KEY_TCP_CMD_TYPE, String.valueOf(TcpCmdType.DEVICE_WARNING.ordinal()));
                bundle.putString(KEY_TCP_RES_TYPE, TcpResType.TIMEOUT);
            }

            msg.setData(bundle);
            tcpHandler.sendMessage(msg);
        }
    }
}


text:
#include <boost/random/normal_distribution.hpp>
#include <limits>

#define BOOST_RANDOM_DISTRIBUTION boost::random::normal_distribution<>
#define BOOST_RANDOM_ARG1 mean
#define BOOST_RANDOM_ARG2 sigma
#define BOOST_RANDOM_ARG1_DEFAULT 0.0
#define BOOST_RANDOM_ARG2_DEFAULT 1.0
#define BOOST_RANDOM_ARG1_VALUE 7.5
#define BOOST_RANDOM_ARG2_VALUE 0.25

#define BOOST_RANDOM_DIST0_MIN -(std::numeric_limits<double>::infinity)()
#define BOOST_RANDOM_DIST0_MAX (std::numeric_limits<double>::infinity)()
#define BOOST_RANDOM_DIST1_MIN -(std::numeric_limits<double>::infinity)()
#define BOOST_RANDOM_DIST1_MAX (std::numeric_limits<double>::infinity)()
#define BOOST_RANDOM_DIST2_MIN -(std::numeric_limits<double>::infinity)()
#define BOOST_RANDOM_DIST2_MAX (std::numeric_limits<double>::infinity)()

#define BOOST_RANDOM_TEST1_PARAMS (-100.0)
#define BOOST_RANDOM_TEST1_MAX 0

#define BOOST_RANDOM_TEST2_PARAMS (100.0)
#define BOOST_RANDOM_TEST2_MIN 0

#include "test_distribution.ipp"


text:
import React, { PropTypes, Component } from 'react';
import M from '../_common/M';
import RangeGroup from '../_common/RangeGroup';

export default class BetterDurationCard extends Component {

	static propTypes = {
		actions: PropTypes.object.isRequired,
		tickTrade: PropTypes.object.isRequired,
		onChange: PropTypes.func,
	};

	render() {
		const { actions, tickTrade } = this.props;
		return (
			<div>
				<input id="ticks" type="radio" name="duration" />
				<label htmlFor="ticks">
					<M m="Ticks" />
					<RangeGroup
						min={5} max={10}
						items={['5', '6', '7', '8', '9', '10']}
						value={+tickTrade.get('duration')}
						onChange={e => {
							actions.updateTickTradeParameters({ duration: e.target.value });
							this.getPrice();
						}}
					/>
				</label>
				<input id="seconds" type="radio" name="duration" disabled />
				<label htmlFor="seconds">
					<M m="Seconds" />
					<RangeGroup
						min={10} max={60}
						items={['10', '20', '30', '40', '50', '60']}
						value={+tickTrade.get('duration')}
						onChange={e => {
							actions.updateTickTradeParameters({ duration: e.target.value });
							this.getPrice();
						}}
					/>
				</label>
				<input id="minutes" type="radio" name="duration" disabled />
				<label htmlFor="minutes">
					<M m="Minutes" />
					<RangeGroup
						min={1} max={60}
						items={['1', '10', '20', '30', '40', '50', '60']}
						value={+tickTrade.get('duration')}
						onChange={e => {
							actions.updateTickTradeParameters({ duration: e.target.value });
							this.getPrice();
						}}
					/>
				</label>
				<input id="hours" type="radio" name="duration" disabled />
				<label htmlFor="hours">
					<M m="Hours" />
					<RangeGroup
						min={1} max={24}
						items={['1', '6', '12', '18', '24']}
						value={+tickTrade.get('duration')}
						onChange={e => {
							actions.updateTickTradeParameters({ duration: e.target.value });
							this.getPrice();
						}}
					/>
				</label>
				<input id="days" type="radio" name="duration" disabled />
				<label htmlFor="days">
					<M m="Days" />
					<RangeGroup
						min={1} max={365}
						items={['1', '10', '30', '60', '365']}
						value={+tickTrade.get('duration')}
						onChange={e => {
							actions.updateTickTradeParameters({ duration: e.target.value });
							this.getPrice();
						}}
					/>
				</label>
			</div>
		);
	}
}


text:
package org.apache.calcite.sql;

import org.apache.calcite.sql.parser.SqlParserPos;

/**
 * A SqlPrimaryIndex is a class that can be used to create a primary index,
 * which is used by the SQL CREATE TABLE function.
 */
public class SqlPrimaryIndex extends SqlIndex {
  private final boolean explicitNoPrimaryIndex;

  public SqlPrimaryIndex(SqlParserPos pos, SqlNodeList columns,
                         SqlIdentifier name, boolean isUnique, boolean explicitNoPrimaryIndex) {
    super(pos, columns, name, isUnique);
    this.explicitNoPrimaryIndex = explicitNoPrimaryIndex;
  }

  @Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
    if (explicitNoPrimaryIndex) {
      writer.keyword("NO PRIMARY INDEX");
      return;
    }
    if (isUnique) {
      writer.keyword("UNIQUE");
    }
    writer.keyword("PRIMARY INDEX");
    if (name != null) {
      name.unparse(writer, leftPrec, rightPrec);
    }
    if (columns != null) {
      SqlWriter.Frame frame = writer.startList("(", ")");
      for (SqlNode c : columns) {
        writer.sep(",");
        c.unparse(writer, 0, 0);
      }
      writer.endList(frame);
    }
  }
}


text:
#include "config.h"
#include "wine/port.h"

#include <stdarg.h>

#define COBJMACROS

#include "windef.h"
#include "winbase.h"
#include "winerror.h"

#include "objbase.h"
#include "rpcproxy.h"

#include "cpsf.h"
#include "ndr_misc.h"
#include "ndr_stubless.h"
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(ole);

/* I don't know what MS's std proxy structure looks like,
   so this probably doesn't match, but that shouldn't matter */
typedef struct {
  IRpcProxyBuffer IRpcProxyBuffer_iface;
  LPVOID *PVtbl;
  LONG RefCount;
  const IID* piid;
  LPUNKNOWN pUnkOuter;
  IUnknown *base_object;  /* must be at offset 0x10 from PVtbl */
  IRpcProxyBuffer *base_proxy;
  PCInterfaceName name;
  LPPSFACTORYBUFFER pPSFactory;
  LPRPCCHANNELBUFFER pChannel;
} StdProxyImpl;

static const IRpcProxyBufferVtbl StdProxy_Vtbl;

static inline StdProxyImpl *impl_from_IRpcProxyBuffer(IRpcProxyBuffer *iface)
{
    return CONTAINING_RECORD(iface, StdProxyImpl, IRpcProxyBuffer_iface);
}

static inline StdProxyImpl *impl_from_proxy_obj( void *iface )
{
    return CONTAINING_RECORD(iface, StdProxyImpl, PVtbl);
}

#ifdef __i386__

extern void call_stubless_func(void);
__ASM_GLOBAL_FUNC(call_stubless_func,
                  "movl 4(%esp),%ecx\n\t"         /* This pointer */
                  "movl (%ecx),%ecx\n\t"          /* This->lpVtbl */
                  "movl -8(%ecx),%ecx\n\t"        /* MIDL_STUBLESS_PROXY_INFO */
                  "movl 8(%ecx),%edx\n\t"         /* info->FormatStringOffset */
                  "movzwl (%edx,%eax,2),%edx\n\t" /* FormatStringOffset[index] */
                  "addl 4(%ecx),%edx\n\t"         /* info->ProcFormatString + offset */
                  "movzwl 8(%edx),%eax\n\t"       /* arguments size */
                  "pushl %eax\n\t"
                  __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                  "leal 8(%esp),%eax\n\t"         /* &This */
                  "pushl %eax\n\t"
                  __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                  "pushl %edx\n\t"                /* format string */
                  __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                  "pushl (%ecx)\n\t"              /* info->pStubDesc */
                  __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
                  "call " __ASM_NAME("ndr_client_call") "\n\t"
                  "leal 12(%esp),%esp\n\t"
                  __ASM_CFI(".cfi_adjust_cfa_offset -12\n\t")
                  "popl %edx\n\t"                 /* arguments size */
                  __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
                  "movl (%esp),%ecx\n\t"  /* return address */
                  "addl %edx,%esp\n\t"
                  "jmp *%ecx" );

#include "pshpack1.h"
struct thunk
{
  BYTE mov_eax;
  DWORD index;
  BYTE jmp;
  LONG handler;
};
#include "poppack.h"

static inline void init_thunk( struct thunk *thunk, unsigned int index )
{
    thunk->mov_eax = 0xb8; /* movl $n,%eax */
    thunk->index   = index;
    thunk->jmp     = 0xe9; /* jmp */
    thunk->handler = (char *)call_stubless_func - (char *)(&thunk->handler + 1);
}

#elif defined(__x86_64__)

extern void call_stubless_func(void);
__ASM_GLOBAL_FUNC(call_stubless_func,
                  "movq %rcx,0x8(%rsp)\n\t"
                  "movq %rdx,0x10(%rsp)\n\t"
                  "movq %r8,0x18(%rsp)\n\t"
                  "movq %r9,0x20(%rsp)\n\t"
                  "leaq 0x8(%rsp),%r8\n\t"        /* &This */
                  "movq (%rcx),%rcx\n\t"          /* This->lpVtbl */
                  "movq -0x10(%rcx),%rcx\n\t"     /* MIDL_STUBLESS_PROXY_INFO */
                  "movq 0x10(%rcx),%rdx\n\t"      /* info->FormatStringOffset */
                  "movzwq (%rdx,%r10,2),%rdx\n\t" /* FormatStringOffset[index] */
                  "addq 8(%rcx),%rdx\n\t"         /* info->ProcFormatString + offset */
                  "movq (%rcx),%rcx\n\t"          /* info->pStubDesc */
                  "subq $0x38,%rsp\n\t"
                  __ASM_CFI(".cfi_adjust_cfa_offset 0x38\n\t")
                  "movq %xmm1,0x20(%rsp)\n\t"
                  "movq %xmm2,0x28(%rsp)\n\t"
                  "movq %xmm3,0x30(%rsp)\n\t"
                  "leaq 0x18(%rsp),%r9\n\t"       /* fpu_args */
                  "call " __ASM_NAME("ndr_client_call") "\n\t"
                  "addq $0x38,%rsp\n\t"
                  __ASM_CFI(".cfi_adjust_cfa_offset -0x38\n\t")
                  "ret" );

#include "pshpack1.h"
struct thunk
{
    BYTE mov_r10[3];
    DWORD index;
    BYTE mov_rax[2];
    void *call_stubless;
    BYTE jmp_rax[2];
};
#include "poppack.h"

static const struct thunk thunk_template =
{
    { 0x49, 0xc7, 0xc2 }, 0,  /* movq $index,%r10 */
    { 0x48, 0xb8 }, 0,        /* movq $call_stubless_func,%rax */
    { 0xff, 0xe0 }            /* jmp *%rax */
};

static inline void init_thunk( struct thunk *thunk, unsigned int index )
{
    *thunk = thunk_template;
    thunk->index = index;
    thunk->call_stubless = call_stubless_func;
}

#else  /* __i386__ */

#warning You must implement stubless proxies for your CPU

struct thunk
{
  DWORD index;
};

static inline void init_thunk( struct thunk *thunk, unsigned int index )
{
    thunk->index = index;
}

#endif  /* __i386__ */

#define BLOCK_SIZE 1024
#define MAX_BLOCKS 64  /* 64k methods should be enough for anybody */

static const struct thunk *method_blocks[MAX_BLOCKS];

static const struct thunk *allocate_block( unsigned int num )
{
    unsigned int i;
    struct thunk *prev, *block;

    block = VirtualAlloc( NULL, BLOCK_SIZE * sizeof(*block),
                          MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE );
    if (!block) return NULL;

    for (i = 0; i < BLOCK_SIZE; i++) init_thunk( &block[i], BLOCK_SIZE * num + i + 3 );
    VirtualProtect( block, BLOCK_SIZE * sizeof(*block), PAGE_EXECUTE_READ, NULL );
    prev = InterlockedCompareExchangePointer( (void **)&method_blocks[num], block, NULL );
    if (prev) /* someone beat us to it */
    {
        VirtualFree( block, 0, MEM_RELEASE );
        block = prev;
    }
    return block;
}

static BOOL fill_stubless_table( IUnknownVtbl *vtbl, DWORD num )
{
    const void **entry = (const void **)(vtbl + 1);
    DWORD i, j;

    if (num - 3 > BLOCK_SIZE * MAX_BLOCKS)
    {
        FIXME( "%u methods not supported\n", num );
        return FALSE;
    }
    for (i = 0; i < (num - 3 + BLOCK_SIZE - 1) / BLOCK_SIZE; i++)
    {
        const struct thunk *block = method_blocks[i];
        if (!block && !(block = allocate_block( i ))) return FALSE;
        for (j = 0; j < BLOCK_SIZE && j < num - 3 - i * BLOCK_SIZE; j++, entry++)
            if (*entry == (LPVOID)-1) *entry = &block[j];
    }
    return TRUE;
}

HRESULT StdProxy_Construct(REFIID riid,
                           LPUNKNOWN pUnkOuter,
                           const ProxyFileInfo *ProxyInfo,
                           int Index,
                           LPPSFACTORYBUFFER pPSFactory,
                           LPRPCPROXYBUFFER *ppProxy,
                           LPVOID *ppvObj)
{
  StdProxyImpl *This;
  PCInterfaceName name = ProxyInfo->pNamesArray[Index];
  CInterfaceProxyVtbl *vtbl = ProxyInfo->pProxyVtblList[Index];

  TRACE("(%p,%p,%p,%p,%p) %s\n", pUnkOuter, vtbl, pPSFactory, ppProxy, ppvObj, name);

  /* TableVersion = 2 means it is the stubless version of CInterfaceProxyVtbl */
  if (ProxyInfo->TableVersion > 1) {
    ULONG count = ProxyInfo->pStubVtblList[Index]->header.DispatchTableCount;
    vtbl = (CInterfaceProxyVtbl *)((const void **)vtbl + 1);
    TRACE("stubless vtbl %p: count=%d\n", vtbl->Vtbl, count );
    fill_stubless_table( (IUnknownVtbl *)vtbl->Vtbl, count );
  }

  if (!IsEqualGUID(vtbl->header.piid, riid)) {
    ERR("IID mismatch during proxy creation\n");
    return RPC_E_UNEXPECTED;
  }

  This = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(StdProxyImpl));
  if (!This) return E_OUTOFMEMORY;

  if (!pUnkOuter) pUnkOuter = (IUnknown *)This;
  This->IRpcProxyBuffer_iface.lpVtbl = &StdProxy_Vtbl;
  This->PVtbl = vtbl->Vtbl;
  /* one reference for the proxy */
  This->RefCount = 1;
  This->piid = vtbl->header.piid;
  This->base_object = NULL;
  This->base_proxy = NULL;
  This->pUnkOuter = pUnkOuter;
  This->name = name;
  This->pPSFactory = pPSFactory;
  This->pChannel = NULL;

  if(ProxyInfo->pDelegatedIIDs && ProxyInfo->pDelegatedIIDs[Index])
  {
      HRESULT r = create_proxy( ProxyInfo->pDelegatedIIDs[Index], NULL,
                                &This->base_proxy, (void **)&This->base_object );
      if (FAILED(r))
      {
          HeapFree( GetProcessHeap(), 0, This );
          return r;
      }
  }

  *ppProxy = &This->IRpcProxyBuffer_iface;
  *ppvObj = &This->PVtbl;
  IUnknown_AddRef((IUnknown *)*ppvObj);
  IPSFactoryBuffer_AddRef(pPSFactory);

  TRACE( "iid=%s this %p proxy %p obj %p vtbl %p base proxy %p base obj %p\n",
         debugstr_guid(riid), This, *ppProxy, *ppvObj, This->PVtbl, This->base_proxy, This->base_object );
  return S_OK;
}

static HRESULT WINAPI StdProxy_QueryInterface(LPRPCPROXYBUFFER iface,
                                             REFIID riid,
                                             LPVOID *obj)
{
  StdProxyImpl *This = impl_from_IRpcProxyBuffer(iface);
  TRACE("(%p)->QueryInterface(%s,%p)\n",This,debugstr_guid(riid),obj);

  if (IsEqualGUID(&IID_IUnknown,riid) ||
      IsEqualGUID(This->piid,riid)) {
    *obj = &This->PVtbl;
    InterlockedIncrement(&This->RefCount);
    return S_OK;
  }

  if (IsEqualGUID(&IID_IRpcProxyBuffer,riid)) {
    *obj = &This->IRpcProxyBuffer_iface;
    InterlockedIncrement(&This->RefCount);
    return S_OK;
  }

  return E_NOINTERFACE;
}

static ULONG WINAPI StdProxy_AddRef(LPRPCPROXYBUFFER iface)
{
  StdProxyImpl *This = impl_from_IRpcProxyBuffer(iface);
  TRACE("(%p)->AddRef()\n",This);

  return InterlockedIncrement(&This->RefCount);
}

static ULONG WINAPI StdProxy_Release(LPRPCPROXYBUFFER iface)
{
  ULONG refs;
  StdProxyImpl *This = impl_from_IRpcProxyBuffer(iface);
  TRACE("(%p)->Release()\n",This);

  refs = InterlockedDecrement(&This->RefCount);
  if (!refs)
  {
    if (This->pChannel)
      IRpcProxyBuffer_Disconnect(&This->IRpcProxyBuffer_iface);

    if (This->base_object) IUnknown_Release( This->base_object );
    if (This->base_proxy) IRpcProxyBuffer_Release( This->base_proxy );

    IPSFactoryBuffer_Release(This->pPSFactory);
    HeapFree(GetProcessHeap(),0,This);
  }

  return refs;
}

static HRESULT WINAPI StdProxy_Connect(LPRPCPROXYBUFFER iface,
                                      LPRPCCHANNELBUFFER pChannel)
{
  StdProxyImpl *This = impl_from_IRpcProxyBuffer(iface);
  TRACE("(%p)->Connect(%p)\n",This,pChannel);

  This->pChannel = pChannel;
  IRpcChannelBuffer_AddRef(pChannel);
  if (This->base_proxy) IRpcProxyBuffer_Connect( This->base_proxy, pChannel );
  return S_OK;
}

static VOID WINAPI StdProxy_Disconnect(LPRPCPROXYBUFFER iface)
{
  StdProxyImpl *This = impl_from_IRpcProxyBuffer(iface);
  TRACE("(%p)->Disconnect()\n",This);

  if (This->base_proxy) IRpcProxyBuffer_Disconnect( This->base_proxy );

  IRpcChannelBuffer_Release(This->pChannel);
  This->pChannel = NULL;
}

static const IRpcProxyBufferVtbl StdProxy_Vtbl =
{
  StdProxy_QueryInterface,
  StdProxy_AddRef,
  StdProxy_Release,
  StdProxy_Connect,
  StdProxy_Disconnect
};

static void StdProxy_GetChannel(LPVOID iface,
                                   LPRPCCHANNELBUFFER *ppChannel)
{
  StdProxyImpl *This = impl_from_proxy_obj( iface );
  TRACE("(%p)->GetChannel(%p) %s\n",This,ppChannel,This->name);

  *ppChannel = This->pChannel;
}

static void StdProxy_GetIID(LPVOID iface,
                               const IID **ppiid)
{
  StdProxyImpl *This = impl_from_proxy_obj( iface );
  TRACE("(%p)->GetIID(%p) %s\n",This,ppiid,This->name);

  *ppiid = This->piid;
}

HRESULT WINAPI IUnknown_QueryInterface_Proxy(LPUNKNOWN iface,
                                            REFIID riid,
                                            LPVOID *ppvObj)
{
  StdProxyImpl *This = impl_from_proxy_obj( iface );
  TRACE("(%p)->QueryInterface(%s,%p) %s\n",This,debugstr_guid(riid),ppvObj,This->name);
  return IUnknown_QueryInterface(This->pUnkOuter,riid,ppvObj);
}

ULONG WINAPI IUnknown_AddRef_Proxy(LPUNKNOWN iface)
{
  StdProxyImpl *This = impl_from_proxy_obj( iface );
  TRACE("(%p)->AddRef() %s\n",This,This->name);
  return IUnknown_AddRef(This->pUnkOuter);
}

ULONG WINAPI IUnknown_Release_Proxy(LPUNKNOWN iface)
{
  StdProxyImpl *This = impl_from_proxy_obj( iface );
  TRACE("(%p)->Release() %s\n",This,This->name);
  return IUnknown_Release(This->pUnkOuter);
}

/***********************************************************************
 *           NdrProxyInitialize [RPCRT4.@]
 */
void WINAPI NdrProxyInitialize(void *This,
                              PRPC_MESSAGE pRpcMsg,
                              PMIDL_STUB_MESSAGE pStubMsg,
                              PMIDL_STUB_DESC pStubDescriptor,
                              unsigned int ProcNum)
{
  TRACE("(%p,%p,%p,%p,%d)\n", This, pRpcMsg, pStubMsg, pStubDescriptor, ProcNum);
  NdrClientInitializeNew(pRpcMsg, pStubMsg, pStubDescriptor, ProcNum);
  StdProxy_GetChannel(This, &pStubMsg->pRpcChannelBuffer);
  IRpcChannelBuffer_GetDestCtx(pStubMsg->pRpcChannelBuffer,
                               &pStubMsg->dwDestContext,
                               &pStubMsg->pvDestContext);
  TRACE("channel=%p\n", pStubMsg->pRpcChannelBuffer);
}

/***********************************************************************
 *           NdrProxyGetBuffer [RPCRT4.@]
 */
void WINAPI NdrProxyGetBuffer(void *This,
                             PMIDL_STUB_MESSAGE pStubMsg)
{
  HRESULT hr;
  const IID *riid = NULL;

  TRACE("(%p,%p)\n", This, pStubMsg);
  pStubMsg->RpcMsg->BufferLength = pStubMsg->BufferLength;
  pStubMsg->dwStubPhase = PROXY_GETBUFFER;
  StdProxy_GetIID(This, &riid);
  hr = IRpcChannelBuffer_GetBuffer(pStubMsg->pRpcChannelBuffer,
                                  (RPCOLEMESSAGE*)pStubMsg->RpcMsg,
                                  riid);
  if (FAILED(hr))
  {
    RpcRaiseException(hr);
    return;
  }
  pStubMsg->fBufferValid = TRUE;
  pStubMsg->BufferStart = pStubMsg->RpcMsg->Buffer;
  pStubMsg->BufferEnd = pStubMsg->BufferStart + pStubMsg->BufferLength;
  pStubMsg->Buffer = pStubMsg->BufferStart;
  pStubMsg->dwStubPhase = PROXY_MARSHAL;
}

/***********************************************************************
 *           NdrProxySendReceive [RPCRT4.@]
 */
void WINAPI NdrProxySendReceive(void *This,
                               PMIDL_STUB_MESSAGE pStubMsg)
{
  ULONG Status = 0;
  HRESULT hr;

  TRACE("(%p,%p)\n", This, pStubMsg);

  if (!pStubMsg->pRpcChannelBuffer)
  {
    WARN("Trying to use disconnected proxy %p\n", This);
    RpcRaiseException(RPC_E_DISCONNECTED);
  }

  pStubMsg->dwStubPhase = PROXY_SENDRECEIVE;
  /* avoid sending uninitialised parts of the buffer on the wire */
  pStubMsg->RpcMsg->BufferLength = pStubMsg->Buffer - (unsigned char *)pStubMsg->RpcMsg->Buffer;
  hr = IRpcChannelBuffer_SendReceive(pStubMsg->pRpcChannelBuffer,
                                    (RPCOLEMESSAGE*)pStubMsg->RpcMsg,
                                    &Status);
  pStubMsg->dwStubPhase = PROXY_UNMARSHAL;
  pStubMsg->BufferLength = pStubMsg->RpcMsg->BufferLength;
  pStubMsg->BufferStart = pStubMsg->RpcMsg->Buffer;
  pStubMsg->BufferEnd = pStubMsg->BufferStart + pStubMsg->BufferLength;
  pStubMsg->Buffer = pStubMsg->BufferStart;

  /* raise exception if call failed */
  if (hr == RPC_S_CALL_FAILED) RpcRaiseException(*(DWORD*)pStubMsg->Buffer);
  else if (FAILED(hr)) RpcRaiseException(hr);
}

/***********************************************************************
 *           NdrProxyFreeBuffer [RPCRT4.@]
 */
void WINAPI NdrProxyFreeBuffer(void *This,
                              PMIDL_STUB_MESSAGE pStubMsg)
{
  TRACE("(%p,%p)\n", This, pStubMsg);

  if (pStubMsg->fBufferValid)
  {
    IRpcChannelBuffer_FreeBuffer(pStubMsg->pRpcChannelBuffer,
                                 (RPCOLEMESSAGE*)pStubMsg->RpcMsg);
    pStubMsg->fBufferValid = TRUE;
  }
}

/***********************************************************************
 *           NdrProxyErrorHandler [RPCRT4.@]
 */
HRESULT WINAPI NdrProxyErrorHandler(DWORD dwExceptionCode)
{
  WARN("(0x%08x): a proxy call failed\n", dwExceptionCode);

  if (FAILED(dwExceptionCode))
    return dwExceptionCode;
  else
    return HRESULT_FROM_WIN32(dwExceptionCode);
}

HRESULT WINAPI
CreateProxyFromTypeInfo( LPTYPEINFO pTypeInfo, LPUNKNOWN pUnkOuter, REFIID riid,
                         LPRPCPROXYBUFFER *ppProxy, LPVOID *ppv )
{
    typedef INT (WINAPI *MessageBoxA)(HWND,LPCSTR,LPCSTR,UINT);
    HMODULE hUser32 = LoadLibraryA("user32");
    MessageBoxA pMessageBoxA = (void *)GetProcAddress(hUser32, "MessageBoxA");

    FIXME("%p %p %s %p %p\n", pTypeInfo, pUnkOuter, debugstr_guid(riid), ppProxy, ppv);
    if (pMessageBoxA)
    {
        pMessageBoxA(NULL,
            "The native implementation of OLEAUT32.DLL cannot be used "
            "with Wine's RPCRT4.DLL. Remove OLEAUT32.DLL and try again.\n",
            "Wine: Unimplemented CreateProxyFromTypeInfo",
            0x10);
        ExitProcess(1);
    }
    return E_NOTIMPL;
}

HRESULT WINAPI
CreateStubFromTypeInfo(ITypeInfo *pTypeInfo, REFIID riid, IUnknown *pUnkServer,
                       IRpcStubBuffer **ppStub )
{
    typedef INT (WINAPI *MessageBoxA)(HWND,LPCSTR,LPCSTR,UINT);
    HMODULE hUser32 = LoadLibraryA("user32");
    MessageBoxA pMessageBoxA = (void *)GetProcAddress(hUser32, "MessageBoxA");

    FIXME("%p %s %p %p\n", pTypeInfo, debugstr_guid(riid), pUnkServer, ppStub);
    if (pMessageBoxA)
    {
        pMessageBoxA(NULL,
            "The native implementation of OLEAUT32.DLL cannot be used "
            "with Wine's RPCRT4.DLL. Remove OLEAUT32.DLL and try again.\n",
            "Wine: Unimplemented CreateProxyFromTypeInfo",
            0x10);
        ExitProcess(1);
    }
    return E_NOTIMPL;
}


text:
namespace boost { namespace xpressive { namespace detail
{

    ///////////////////////////////////////////////////////////////////////////////
    // epsilon_matcher
    //
    struct epsilon_matcher
    {
        BOOST_XPR_QUANT_STYLE(quant_none, 0, true)

        template<typename BidiIter, typename Next>
        static bool match(match_state<BidiIter> &state, Next const &next)
        {
            return next.match(state);
        }
    };

}}}

#endif


text:
layout: page
title: Projects
date: 2015-09-28T13:37:57-04:00
description: Past and ongoing projects
image:
  feature: abstract-4.jpg
  credit: dargadgetz
  creditlink: http://www.dargadgetz.com/ios-7-abstract-wallpaper-pack-for-iphone-5-and-ipod-touch-retina/
comments: false
share: false
---

     Awesome Chat (May 8th, 2016)

        A realtime chat room built in a few hours (and a lot of coffee) with React.JS, Socket.io, Redux architecture, in order to grasp the full stack.

    Omni (December 2015)

        Omni, the omniprescent bot. Omni tracks my favorite sites and notifies me upon any sort of update. i.e. watching a favorite subreddit thread and notifiying me of a new post.
        Utilizes phantomJS and cheerioJS. Can track sites which require a login. Specialized and tailored per domain.

    Knowledge-Based Artificial Intelligence: RPM agent (Summer 2015)

Created a knowledge-based AI agent to solve Raven's Progressive Matrix (RPM) problems.
        RPM problems are visual intelligence tests. This paper discusses the approach and design of my agent. Source code available upon request.

    Wisp - People Caching (Summer 2014)

          A native iOS application for collaborating on anonymous change in your local area. Post a pin on a map, with an idea for what you want to occur, such that other users can go and participate (receiving points).


text:
extern WND_TREE g_resp_wave_view_children[];

#endif


text:
import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import moment from 'moment';
import 'moment/locale/pt-br';

import PostFeaturedImage from './PostFeaturedImage';

class PostCard extends React.Component {

	render() {
		const {
			postUpdateDate,
			postCategoryId,
			postCategoryName,
			postCategoryColor,
			featuredImageUrl,
			featuredImageAlt,
			postLink,
			postTitle,
			postExcerpt
		} = this.props;

		const lasUpdateDate = moment(postUpdateDate).format('DD MMM, YYYY');

		let postFeaturedImageComponent = '';
		if(featuredImageUrl !== null) {
			postFeaturedImageComponent = <PostFeaturedImage
											imageSrc={featuredImageUrl}
											imageAlt={featuredImageAlt}
											postLink={postLink}
										/>;
		}

		const borderStyle = {
			borderColor: postCategoryColor
		}
		const categoryStyle = {
			fontSize: '1em',
			fontWeight: '700',
			paddingTop: '3px',
			paddingBottom: '3px',
			paddingLeft: '10px',
			paddingRight: '10px',
			color: '#fff',
			backgroundColor: postCategoryColor

		}
		let classes = 'ish-item ish-color' + postCategoryId;

		if(this.props.lastCard === true) {
			classes = classes + ' post-card--latest';
		}

		return (

					{postFeaturedImageComponent}

<Link to={postLink} className="ish-underline">{postTitle}</Link>

{lasUpdateDate}

<Link to="#" className="ish-underline" style={categoryStyle}>{postCategoryName}</Link>

								<Link to={postLink} className="ish-underline ish-underline-visible">Leia mais</Link>

		);
	}
}

export default PostCard;


text:
const char kNewMenuStyleFieldTrialName[] = "NewMenuStyle";
const char kNewMenuStyleFieldTrialGroupName[] = "OldStyle";

namespace ui {

void NativeTheme::SetScrollbarColors(unsigned inactive_color,
                                     unsigned active_color,
                                     unsigned track_color) {
  thumb_inactive_color_ = inactive_color;
  thumb_active_color_ = active_color;
  track_color_ = track_color;
}

// NativeTheme::instance() is implemented in the platform specific source files,
// such as native_theme_win.cc or native_theme_linux.cc

// static
bool NativeTheme::IsNewMenuStyleEnabled() {
  static bool enable_new_menu_style =
      !CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableNewMenuStyle);
  // Run experiment only if there is no kDisableNewMenuStyle flag.
  if (enable_new_menu_style) {
    enable_new_menu_style =
        base::FieldTrialList::FindFullName(kNewMenuStyleFieldTrialName) !=
        kNewMenuStyleFieldTrialGroupName;
  }
  return enable_new_menu_style;
}

NativeTheme::NativeTheme()
    : thumb_inactive_color_(0xeaeaea),
      thumb_active_color_(0xf4f4f4),
      track_color_(0xd3d3d3) {
}

NativeTheme::~NativeTheme() {}

}  // namespace ui


text:
<resources>
    <declare-styleable name="DrawInsetsFrameLayout">
        <attr name="insetBackground" format="reference|color"/>
    </declare-styleable>
</resources>


text:
var toHtml = require('../lib/stringify'),
    toDom = require('../lib/parser'),
    expect = require('chai').expect,
    fs = require('fs');

function file(path) {
    return fs.readFileSync(__dirname + '/js/' + path).toString();
}

describe('stringify', function () {

    it ('should convert dom to jsx html', function () {
        var html = fs.readFileSync(__dirname + '/stringify.html').toString();
        var jsx = fs.readFileSync(__dirname + '/stringify.jsx').toString();

        expect(toHtml(toDom(html).children[0])).to.equal(jsx);
    });

});


text:
package org.olat.modules.cp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.form.flexible.FormItem;
import org.olat.core.gui.components.form.flexible.FormItemContainer;
import org.olat.core.gui.components.form.flexible.elements.FormLink;
import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement;
import org.olat.core.gui.components.form.flexible.impl.FormBasicController;
import org.olat.core.gui.components.form.flexible.impl.FormEvent;
import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer;
import org.olat.core.gui.components.form.flexible.impl.elements.FormSubmit;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.components.tree.TreeNode;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.util.nodes.INode;

/**
 *
 * Description:

 * Controller to select to list of nodes to print
 * VCRP-14
 *
 *

 * Initial Date:  9 mars 2011

 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 */
//fxdiff VCRP-14: print cp
public class CPSelectPrintPagesController extends FormBasicController {

	private final Map<String,MultipleSelectionElement> identToSelectionMap = new HashMap<String,MultipleSelectionElement>();
	private final List<MultipleSelectionElement> nodeSelections = new ArrayList<MultipleSelectionElement>();

	private final  CPManifestTreeModel ctm;

	private FormLink selectAll;
	private FormLink deselectAll;
	private FormSubmit submit;

	public CPSelectPrintPagesController(UserRequest ureq, WindowControl wControl, CPManifestTreeModel ctm) {
		super(ureq, wControl, "cpprint");

		this.ctm = ctm;

		initForm(ureq);
	}

	@Override
	protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
		setFormTitle("print.node.list.title");
		setFormDescription("print.node.list.desc");

		if(formLayout instanceof FormLayoutContainer) {
			FormLayoutContainer layoutContainer = (FormLayoutContainer)formLayout;
			TreeNode rootNode = ctm.getRootNode();
			initTreeRec(0, rootNode, layoutContainer);
			layoutContainer.contextPut("nodeSelections", nodeSelections);
		}

		selectAll = uifactory.addFormLink("checkall", "form.checkall", null, formLayout, Link.LINK);
		deselectAll = uifactory.addFormLink("uncheckall", "form.uncheckall", null, formLayout, Link.LINK);

		FormLayoutContainer buttonLayout = FormLayoutContainer.createButtonLayout("print-cancel", getTranslator());
		formLayout.add(buttonLayout);
		buttonLayout.setRootForm(mainForm);
		submit = uifactory.addFormSubmitButton("print-button", "print.node", buttonLayout);
		uifactory.addFormCancelButton("cancel", buttonLayout, ureq, getWindowControl());
	}

	private void initTreeRec(int level, TreeNode node, FormLayoutContainer layoutcont) {
		String[] cssClass = new String[]{"b_tree_l" + level};
		String[] singleKey = new String[]{node.getIdent()};
		String[] singleValue = new String[]{node.getTitle()};
		MultipleSelectionElement nodeSelection = uifactory.addCheckboxesVertical("print.node.list." + nodeSelections.size(), layoutcont, singleKey, singleValue, cssClass, 1);
		nodeSelection.setLabel("print.node.list", null);
		nodeSelection.setUserObject(new SelectNodeObject(node, level));
		nodeSelection.addActionListener(this, FormEvent.ONCLICK);
		nodeSelection.select(node.getIdent(), true);
		nodeSelections.add(nodeSelection);
		identToSelectionMap.put(node.getIdent(), nodeSelection);
		layoutcont.add(nodeSelection.getComponent().getComponentName(), nodeSelection);

		int numOfChildren = node.getChildCount();
		for(int i=0; i<numOfChildren; i++) {
			initTreeRec(level + 1, (TreeNode)node.getChildAt(i), layoutcont);
		}
	}

	public List<String> getSelectedNodeIdents() {
		if(nodeSelections == null || nodeSelections.isEmpty()) {
			return Collections.emptyList();
		}

		List<String> selectedNodeIdents = new ArrayList<String>();
		for(MultipleSelectionElement nodeSelection:nodeSelections) {
			if(nodeSelection.isMultiselect() &&nodeSelection.isSelected(0)) {
				SelectNodeObject treeNode = (SelectNodeObject)nodeSelection.getUserObject();
				String ident = treeNode.getNode().getIdent();
				selectedNodeIdents.add(ident);
			}
		}
		return selectedNodeIdents;
	}

	@Override
	protected void doDispose() {
		//
	}

	@Override
	protected void formInnerEvent(UserRequest ureq, FormItem source, FormEvent event) {
		if(nodeSelections.contains(source)) {
			MultipleSelectionElement nodeSelection = (MultipleSelectionElement)source;
			if(nodeSelection.isMultiselect()) {
				selectRec(nodeSelection, nodeSelection.isSelected(0));
			}
			// check for at least one selected node
			submit.setEnabled(false);
			for(MultipleSelectionElement selection:nodeSelections) {
				if (selection.isSelected(0)) {
					submit.setEnabled(true);
					break;
				}
			}
		} else if (source == selectAll) {
			for(MultipleSelectionElement nodeSelection:nodeSelections) {
				if(nodeSelection.isMultiselect() && !nodeSelection.isSelected(0)) {
					SelectNodeObject treeNode = (SelectNodeObject)nodeSelection.getUserObject();
					String ident = treeNode.getNode().getIdent();
					nodeSelection.select(ident, true);
				}
			}
			submit.setEnabled(true);
		} else if (source == deselectAll) {
			for(MultipleSelectionElement nodeSelection:nodeSelections) {
				if(nodeSelection.isMultiselect() && nodeSelection.isSelected(0)) {
					SelectNodeObject treeNode = (SelectNodeObject)nodeSelection.getUserObject();
					String ident = treeNode.getNode().getIdent();
					nodeSelection.select(ident, false);
				}
			}
			submit.setEnabled(false);
		} else {
				super.formInnerEvent(ureq, source, event);
		}
	}

	private void selectRec(MultipleSelectionElement nodeSelection, boolean select) {
		SelectNodeObject userObject = (SelectNodeObject)nodeSelection.getUserObject();
		TreeNode node = userObject.getNode();
		if(nodeSelection.isMultiselect()) {
			nodeSelection.select(node.getIdent(), select);
		}

		for(int i=node.getChildCount(); i-->0; ) {
			INode child = node.getChildAt(i);
			String ident = child.getIdent();
			MultipleSelectionElement childNodeSelection = identToSelectionMap.get(ident);
			selectRec(childNodeSelection, select);
		}
	}

	@Override
	protected void formOK(UserRequest ureq) {
		fireEvent(ureq, Event.DONE_EVENT);
	}

	@Override
	protected void formCancelled(UserRequest ureq) {
		fireEvent(ureq, Event.CANCELLED_EVENT);
	}

	public class SelectNodeObject {
		private final int indentation;
		private final TreeNode node;

		public SelectNodeObject(TreeNode node, int indentation) {
			this.node = node;
			this.indentation = indentation;
		}

		public String getIndentation() {
			return Integer.toString(indentation);
		}

		public TreeNode getNode() {
			return node;
		}
	}
}


text:
<!DOCTYPE html >

          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
          <title>ScalaTest 3.0.1  - org.scalatest.ParallelTestExecution</title>
          <meta name="description" content="ScalaTest 3.0.1 - org.scalatest.ParallelTestExecution" />
          <meta name="keywords" content="ScalaTest 3.0.1 org.scalatest.ParallelTestExecution" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

        ScalaTest 3.0.1
        < Back

            <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
            
            

Packages

        

        package

              root

Definition Classes

root

        

        package

              org

Definition Classes

root

        

        package

              scalatest

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

Definition Classes

org

        

        package

              compatible

Definition Classes

scalatest

        

        package

              concurrent

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

Definition Classes

scalatest

        

        package

              easymock

Definition Classes

scalatest

        

        package

              enablers

Definition Classes

scalatest

        

        package

              events

Definition Classes

scalatest

        

        package

              exceptions

Definition Classes

scalatest

        

        package

              fixture

Definition Classes

scalatest

        

        package

              jmock

Definition Classes

scalatest

        

        package

              junit

Definition Classes

scalatest

        

        package

              matchers

Definition Classes

scalatest

        

        package

              mockito

Definition Classes

scalatest

        

        package

              path

Definition Classes

scalatest

        

        package

              prop

Definition Classes

scalatest

        

        package

              refspec

Definition Classes

scalatest

        

        package

              selenium

Definition Classes

scalatest

        

        package

              tagobjects

Definition Classes

scalatest

        

        package

              tags

Definition Classes

scalatest

        

        package

              testng

Definition Classes

scalatest

        

        package

              time

Definition Classes

scalatest

        

        package

              tools

Definition Classes

scalatest

        

        package

              words

Definition Classes

scalatest

                          Alerter

                          Alerting

                          AppendedClues

                          Args

                          Assertions

                          AsyncFeatureSpec

                          AsyncFeatureSpecLike

                          AsyncFlatSpec

                          AsyncFlatSpecLike

                          AsyncFreeSpec

                          AsyncFreeSpecLike

                          AsyncFunSpec

                          AsyncFunSpecLike

                          AsyncFunSuite

                          AsyncFunSuiteLike

                          AsyncTestRegistration

                          AsyncTestSuite

                          AsyncTestSuiteMixin

                          AsyncWordSpec

                          AsyncWordSpecLike

                          BeforeAndAfter

                          BeforeAndAfterAll

                          BeforeAndAfterAllConfigMap

                          BeforeAndAfterEach

                          BeforeAndAfterEachTestData

                          CancelAfterFailure

                          Canceled

                          Checkpoints

                        <a class="trait" href="CompleteLastly.html" title="Trait that provides a HtmlTag(<code>complete</code>)-HtmlTag(<code>lastly</code>) construct, which ensures
cleanup code in HtmlTag(<code>lastly</code>) is executed whether the code passed to HtmlTag(<code>complete</code>)
completes abruptly with an exception or successfully results in a HtmlTag(<code>Future</code>),
HtmlTag(<a href="FutureOutcome.html"><code>FutureOutcome</code></a>), or other type with an
implicit HtmlTag(<a href="enablers/Futuristic.html"><code>Futuristic</code></a>) instance.HtmlTag(</a>)HtmlTag(</a>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)">
                        <a href="CompleteLastly.html" title="Trait that provides a HtmlTag(<code>complete</code>)-HtmlTag(<code>lastly</code>) construct, which ensures
cleanup code in HtmlTag(<code>lastly</code>) is executed whether the code passed to HtmlTag(<code>complete</code>)
completes abruptly with an exception or successfully results in a HtmlTag(<code>Future</code>),
HtmlTag(<a href="FutureOutcome.html"><code>FutureOutcome</code></a>), or other type with an
implicit HtmlTag(<a href="enablers/Futuristic.html"><code>Futuristic</code></a>) instance.HtmlTag(</a>)HtmlTag(</a>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)">
                          CompleteLastly

                          CompositeStatus

                          ConfigMap

                          ConfigMapWrapperSuite

                          DiagrammedAssertions

                          DiagrammedExpr

                          DistributedSuiteSorter

                          DistributedTestSorter

                          Distributor

                          DoNotDiscover

                          Documenter

                          Documenting

                          DynaTags

                        <a class="trait" href="EitherValues.html" title="Trait that provides an implicit conversion that adds HtmlTag(<code>left.value</code>) and HtmlTag(<code>right.value</code>) methods
to HtmlTag(<code>Either</code>), which will return the selected value of the HtmlTag(<code>Either</code>) if defined,
or throw HtmlTag(<code>TestFailedException</code>) if not.HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)">
                        <a href="EitherValues.html" title="Trait that provides an implicit conversion that adds HtmlTag(<code>left.value</code>) and HtmlTag(<code>right.value</code>) methods
to HtmlTag(<code>Either</code>), which will return the selected value of the HtmlTag(<code>Either</code>) if defined,
or throw HtmlTag(<code>TestFailedException</code>) if not.HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)">
                          EitherValues

                          Entry

                          Exceptional

                          Failed

                          FailedStatus

                          FeatureSpec

                          FeatureSpecLike

                          Filter

                          Finders

                          FixtureContext

                          FlatSpec

                          FlatSpecLike

                          FreeSpec

                          FreeSpecLike

                          FunSpec

                          FunSpecLike

                          FunSuite

                          FunSuiteLike

                          FutureOutcome

                        <a class="trait" href="GivenWhenThen.html" title="Trait that contains methods named HtmlTag(<code>given</code>), HtmlTag(<code>when</code>), HtmlTag(<code>then</code>), and HtmlTag(<code>and</code>),
which take a string message and implicit HtmlTag(<a href="Informer.html"><code>Informer</code></a>), and forward the message to the informer.HtmlTag(</a>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)">
                        <a href="GivenWhenThen.html" title="Trait that contains methods named HtmlTag(<code>given</code>), HtmlTag(<code>when</code>), HtmlTag(<code>then</code>), and HtmlTag(<code>and</code>),
which take a string message and implicit HtmlTag(<a href="Informer.html"><code>Informer</code></a>), and forward the message to the informer.HtmlTag(</a>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)">
                          GivenWhenThen

                          Ignore

                          Informer

                          Informing

                          Inside

                          Inspectors

                          LoneElement

                          Matchers

                          MustMatchers

                          NonImplicitAssertions

                          Notifier

                          Notifying

                          OneInstancePerTest

                          OptionValues

                          Outcome

                          OutcomeOf

                          ParallelTestExecution

                        <a class="trait" href="PartialFunctionValues.html" title="Trait that provides an implicit conversion that adds a HtmlTag(<code>valueAt</code>) method
to HtmlTag(<code>PartialFunction</code>), which will return the value (result) of the function applied to the argument passed to HtmlTag(<code>valueAt</code>),
or throw HtmlTag(<code>TestFailedException</code>) if the partial function is not defined at the argument.HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)">
                        <a href="PartialFunctionValues.html" title="Trait that provides an implicit conversion that adds a HtmlTag(<code>valueAt</code>) method
to HtmlTag(<code>PartialFunction</code>), which will return the value (result) of the function applied to the argument passed to HtmlTag(<code>valueAt</code>),
or throw HtmlTag(<code>TestFailedException</code>) if the partial function is not defined at the argument.HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)">
                          PartialFunctionValues

                          Payloads

                          Pending

                          PendingStatement

                          PrivateMethodTester

                          PropSpec

                          PropSpecLike

                          RandomTestOrder

                          RecoverMethods

                          Reporter

                          Rerunner

                          ResourcefulReporter

                          Retries

                          Sequential

                          SequentialNestedSuiteExecution

                          SeveredStackTraces

                          Shell

                          StatefulStatus

                          Status

                          Stepwise

                          StepwiseNestedSuiteExecution

                          Stopper

                          StreamlinedXml

                          StreamlinedXmlEquality

                        <a class="trait" href="StreamlinedXmlNormMethods.html" title="Subtrait of HtmlTag(<a href="../scalactic/NormMethods.html"><code>NormMethods</code></a>) that provides
an implicit HtmlTag(<code>Uniformity[T]</code>) for subtypes of HtmlTag(<code>scala.xml.NodeSeq</code>) that enables
you to streamline XML by invoking HtmlTag(<code>.norm</code>) on it.HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</a>)">

                          StreamlinedXmlNormMethods

                          Succeeded

                          SucceededStatus

                          Suite

                          SuiteMixin

                          Suites

                          Tag

                          TagAnnotation

                          TestData

                          TestRegistration

                          TestSuite

                          TestSuiteMixin

                          Tracker

                        <a class="trait" href="TryValues.html" title="Trait that provides an implicit conversion that adds HtmlTag(<code>success</code>) and HtmlTag(<code>failure</code>) methods
to HtmlTag(<code>scala.util.Try</code>), enabling you to make assertions about the value of a HtmlTag(<code>Success</code>) or
the exception of a HtmlTag(<code>Failure</code>).HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)">
                        <a href="TryValues.html" title="Trait that provides an implicit conversion that adds HtmlTag(<code>success</code>) and HtmlTag(<code>failure</code>) methods
to HtmlTag(<code>scala.util.Try</code>), enabling you to make assertions about the value of a HtmlTag(<code>Success</code>) or
the exception of a HtmlTag(<code>Failure</code>).HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)HtmlTag(</code>)">
                          TryValues

                          WordSpec

                          WordSpecLike

                          WrapWith

                          run

t

org.scalatest

ParallelTestExecution

        

        trait

        ParallelTestExecution extends OneInstancePerTest

Trait that causes that the tests of any suite it is mixed into to be run in parallel if
a Distributor is passed to runTests.

ScalaTest's normal approach for running suites of tests in parallel is to run different suites in parallel,
but the tests of any one suite sequentially. This approach should provide sufficient distribution of the work load
in most cases, but some suites may encapsulate multiple long-running tests. Such suites may dominate the execution
time of the run. If so, mixing in this trait into just those suites will allow their long-running tests to run in parallel with each
other, thereby helping to reduce the total time required to run an entire run.

To make it easier for users to write tests that run in parallel, this trait runs each test in its own instance of the class.
Running each test in its own instance enables tests to use the same instance vars and mutable objects referenced from
instance variables without needing to synchronize. Although ScalaTest provides functional approaches to
factoring out common test code that can help avoid such issues, running each test in its own instance is an insurance policy that makes
running tests in parallel easier and less error prone.

For the details on how ParallelTestExecution works, see the documentation for methods run, runTests, and runTest,
which this trait overrides.

Note: This trait's implementation of runTest is final, to ensure that behavior
related to individual tests are executed by the same thread that executes the actual test. This means,
for example, that you won't be allowed to write ...with ParallelTestExecution with BeforeAndAfter.
Instead, you'd need to put ParallelTestExecution last, as
in: with BeforeAndAfter with ParallelTestExecution. For more details, see the documentation
for the runTest method.

Self Type

ParallelTestExecution with Suite

Source

ParallelTestExecution.scala

            Linear Supertypes

OneInstancePerTest, SuiteMixin, AnyRef, Any

          

            <input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />

          

            Ordering

Alphabetic

By Inheritance

                  Inherited

ParallelTestExecution

OneInstancePerTest

SuiteMixin

AnyRef

Any

Hide All

Show All

              Visibility

Public

All

Abstract Value Members

        

        abstract
        def

        expectedTestCount(filter: Filter): Int

The total number of tests that are expected to run when this Suite's run method is invoked.

The total number of tests that are expected to run when this Suite's run method is invoked.

filter

a Filter with which to filter tests to count based on their tags

Definition Classes

SuiteMixin

        

        abstract
        def

        nestedSuites: IndexedSeq[Suite]

An immutable IndexedSeq of this SuiteMixin object's nested Suites.

An immutable IndexedSeq of this SuiteMixin object's nested Suites. If this SuiteMixin contains no nested Suites,
this method returns an empty IndexedSeq.

Definition Classes

SuiteMixin

        

        abstract
        def

        rerunner: Option[String]

The fully qualified name of the class that can be used to rerun this suite.

The fully qualified name of the class that can be used to rerun this suite.

Definition Classes

SuiteMixin

        

        abstract
        def

        runNestedSuites(args: Args): Status

Runs zero to many of this suite's nested suites.

Runs zero to many of this suite's nested suites.

args

the Args for this run

returns

a Status object that indicates when all nested suites started by this method have completed, and whether or not a failure occurred.

Attributes

protected

Definition Classes

SuiteMixin

Exceptions thrown

NullArgumentException if args is null.

        

        abstract
        val

        styleName: String

This suite's style name.

This suite's style name.

This lifecycle method provides a string that is used to determine whether this suite object's
style is one of the chosen styles for
the project.

Definition Classes

SuiteMixin

        

        abstract
        def

        suiteId: String

A string ID for this Suite that is intended to be unique among all suites reported during a run.

A string ID for this Suite that is intended to be unique among all suites reported during a run.

The suite ID is intended to be unique, because ScalaTest does not enforce that it is unique. If it is not
unique, then you may not be able to uniquely identify a particular test of a particular suite. This ability is used,
for example, to dynamically tag tests as having failed in the previous run when rerunning only failed tests.

returns

this Suite object's ID.

Definition Classes

SuiteMixin

        

        abstract
        def

        suiteName: String

A user-friendly suite name for this Suite.

A user-friendly suite name for this Suite.

This trait's
implementation of this method returns the simple name of this object's class. This
trait's implementation of runNestedSuites calls this method to obtain a
name for Reports to pass to the suiteStarting, suiteCompleted,
and suiteAborted methods of the Reporter.

returns

this Suite object's suite name.

Definition Classes

SuiteMixin

        

        abstract
        def

        tags: Map[String, Set[String]]

A Map whose keys are String names of tagged tests and
whose associated values are the Set of tag names for the test.

A Map whose keys are String names of tagged tests and
whose associated values are the Set of tag names for the test. If a test has no associated tags, its name
does not appear as a key in the returned Map. If this Suite contains no tests with tags, this
method returns an empty Map.

Subclasses may override this method to define and/or discover tags in a custom manner, but overriding method implementations
should never return an empty Set as a value. If a test has no tags, its name should not appear as a key in the
returned Map.

Definition Classes

SuiteMixin

        

        abstract
        def

        testDataFor(testName: String, theConfigMap: ConfigMap): TestData

Provides a TestData instance for the passed test name, given the passed config map.

Provides a TestData instance for the passed test name, given the passed config map.

This method is used to obtain a TestData instance to pass to withFixture(NoArgTest)
and withFixture(OneArgTest) and the beforeEach and afterEach methods
of trait BeforeAndAfterEach.

testName

the name of the test for which to return a TestData instance

theConfigMap

the config map to include in the returned TestData

returns

a TestData instance for the specified test, which includes the specified config map

Definition Classes

SuiteMixin

        

        abstract
        def

        testNames: Set[String]

A Set of test names.

A Set of test names. If this Suite contains no tests, this method returns an empty Set.

Although subclass and subtrait implementations of this method may return a Set whose iterator produces String
test names in a well-defined order, the contract of this method does not required a defined order. Subclasses are free to
implement this method and return test names in either a defined or undefined order.

Definition Classes

SuiteMixin

Concrete Value Members

        

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        

        def

        clone(): AnyRef

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        def

        createTestSpecificReporter(testSorter: DistributedTestSorter, testName: String): Reporter

Attributes

protected[org.scalatest]

        

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        

        def

        finalize(): Unit

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

        

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

        

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        

        def

        newInstance: Suite with ParallelTestExecution

Construct a new instance of this Suite.

Construct a new instance of this Suite.

This trait's implementation of runTests invokes this method to create
a new instance of this Suite for each test. This trait's implementation
of this method uses reflection to call this.getClass.newInstance. This
approach will succeed only if this Suite's class has a public, no-arg
constructor. In most cases this is likely to be true, because to be instantiated
by ScalaTest's Runner a Suite needs a public, no-arg
constructor. However, this will not be true of any Suite defined as
an inner class of another class or trait, because every constructor of an inner
class type takes a reference to the enclosing instance. In such cases, and in
cases where a Suite class is explicitly defined without a public,
no-arg constructor, you will need to override this method to construct a new
instance of the Suite in some other way.

Here's an example of how you could override newInstance to construct
a new instance of an inner class:

import org.scalatest.Suite

class Outer {
  class InnerSuite extends Suite with ParallelTestExecution {
    def testOne() {}
    def testTwo() {}
    override def newInstance = new InnerSuite
  }
}

Definition Classes

ParallelTestExecution → OneInstancePerTest

        

        final
        def

        notify(): Unit

Definition Classes

AnyRef

        

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

        

        def

        run(testName: Option[String], args: Args): Status

Modifies the behavior of super.run to facilitate parallel test execution.

Modifies the behavior of super.run to facilitate parallel test execution.

This trait's implementation of this method only changes the supertrait implementation if both
testName and args.distributedTestSorter are defined. If either
testName or args.distributedTestSorter is empty, it
simply invokes super.run, passing along the same testName
and args object.

If both testName and args.distributedTestSorter are defined, however,
this trait's implementation of this method will create a "test-specific reporter" whose apply
method will invoke the apply method of the DistributedTestSorter, which takes
a test name as well as the event. It will then invoke super.run passing along
the same testName and an Args object that is the same except with the
original reporter replaced by the test-specific reporter.

testName

an optional name of one test to execute. If None, all relevant tests should be executed.
                I.e., None acts like a wildcard that means execute all relevant tests in this Suite.

args

the Args for this run

returns

a Status object that indicates when all tests and nested suites started by this method have completed, and whether or not a failure occurred.

Definition Classes

ParallelTestExecution → SuiteMixin

        

        final
        def

        runTest(testName: String, args: Args): Status

Modifies the behavior of super.runTest to facilitate parallel test execution.

Modifies the behavior of super.runTest to facilitate parallel test execution.

This trait's implementation of this method only changes the supertrait implementation if
args.distributor is defined. If args.distributor is empty, it
simply invokes super.runTests, passing along the same testName
and args object.

If args.distributor is defined, then it uses the args.runTestInNewInstance
flag to decide what to do. If runTestInNewInstance
is true, this is the general instance responsible for running all tests, so
it first notifies args.distributedTestSorter (if defined) that it is
distributing this test by invoking distributingTest on it, passing in the
testName. Then it wraps a new instance of this class, obtained by invoking
newInstance in a suite whose run method will ensure that only the test whose
name was passed to this method as testName is executed. Finally, this trait's
implementation of this method submits this wrapper suite to the distributor.

If runTestInNewInstance is false, this is the test-specific (distributed)
instance, so this trait's implementation of this method simply invokes super.runTest,
passing along the same testName and args object, delegating responsibility
for actually running the test to the super implementation. After super.runTest returns
(or completes abruptly by throwing an exception), it notifies args.distributedTestSorter
(if defined) that it has completed running the test by invoking completedTest on it,
passing in the testName.

Note: this trait's implementation of this method is final to ensure that
any other desired runTest behavior is executed by the same thread that executes
the test. For example, if you were to mix in BeforeAndAfter after
ParallelTestExecution, the before and after code would
be executed by the general instance on the main test thread, rather than by the test-specific
instance on the distributed thread. Marking this method final ensures that
traits like BeforeAndAfter can only be "super" to ParallelTestExecution
and, therefore, that its before and after code will be run
by the same distributed thread that runs the test itself.

testName

the name of one test to execute.

args

the Args for this run

returns

a Status object that indicates when the test started by this method has completed, and whether or not it failed .

Attributes

protected

Definition Classes

ParallelTestExecution → OneInstancePerTest → SuiteMixin

        

        def

        runTests(testName: Option[String], args: Args): Status

Modifies the behavior of super.runTests to facilitate parallel test execution.

Modifies the behavior of super.runTests to facilitate parallel test execution.

This trait's implementation of this method always invokes super.runTests to delegate
to OneInstancePerTest's implementation, but it may pass in a modified args object.
If args.runTestInNewInstance is false and args.distributor is defined,
this trait's implementation of this method will wrap the passed args.reporter in a new Reporter
that can sort events fired by parallel tests back into sequential order, with a timeout. It will pass this new reporter to
super.runTests (in args.reporter) as well as a defined DistributedTestSorter
(in args.distributedTestSorter) that can be used to communicate with the sorting reporter. Otherwise, if args.runTestInNewInstance is
true or args.distributor is empty, this trait's implementation of this method simply calls super.runTests,
passing along the same testName and args.

testName

an optional name of one test to run. If None, all relevant tests should be run.
                I.e., None acts like a wildcard that means run all relevant tests in this Suite.

args

the Args for this run

returns

a Status object that indicates when all tests started by this method have completed, and whether or not a failure occurred.

Attributes

protected

Definition Classes

ParallelTestExecution → OneInstancePerTest → SuiteMixin

        

        def

        sortingTimeout: Span

A maximum amount of time to wait for out-of-order events generated by running the tests
of this Suite in parallel while sorting the events back into a more
user-friendly, sequential order.

A maximum amount of time to wait for out-of-order events generated by running the tests
of this Suite in parallel while sorting the events back into a more
user-friendly, sequential order.

The default implementation of this method returns the value specified via -T to
Runner, or 2 seconds, if no -T was supplied.

returns

a maximum amount of time to wait for events while resorting them into sequential order

Attributes

protected

        

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        

        def

        toString(): String

Definition Classes

AnyRef → Any

        

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

Inherited from OneInstancePerTest

Inherited from SuiteMixin

Inherited from AnyRef

Inherited from Any

Ungrouped


text:
@implementation GroupCountBubble

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }

    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    CGFloat radius = (self.bounds.size.height / 2.0);
    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:self.bounds xRadius:radius yRadius:radius];
    [[NSColor colorWithCalibratedWhite:.25 alpha:.5] setFill];
    [[NSColor colorWithCalibratedWhite:.15 alpha:.6] setStroke];
    [path setLineWidth:.5];
    [path fill];
    [path stroke];
}

@end


text:
package com.intellij.refactoring.rename;

import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiJavaCodeReferenceElement;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.ConflictsUtil;
import com.intellij.refactoring.util.RefactoringUIUtil;

/**
 * @author dsl
 */
public class ClassHidesUnqualifiableClassUsageInfo extends UnresolvableCollisionUsageInfo {
  private final PsiClass myHiddenClass;

  public ClassHidesUnqualifiableClassUsageInfo(PsiJavaCodeReferenceElement element, PsiClass renamedClass, PsiClass hiddenClass) {
    super(element, renamedClass);
    myHiddenClass = hiddenClass;
  }

  public String getDescription() {
    final PsiElement container = ConflictsUtil.getContainer(myHiddenClass);
    return RefactoringBundle.message("renamed.class.will.hide.0.in.1", RefactoringUIUtil.getDescription(myHiddenClass, false),
                                     RefactoringUIUtil.getDescription(container, false));
  }
}