text:
package jp.co.thcomp.bluetoothhelper;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import jp.co.thcomp.util.LogUtil;
import jp.co.thcomp.util.ThreadUtil;

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class BleCentral {
    private static final String TAG = BleCentral.class.getSimpleName();
    private static final long DefaultConnectionTimeoutMS = 30 * 1000;
    private static final int MsgConnectionTimeout = "MsgConnectionTimeout".hashCode();
    public static final int StatusDisableBluetooth = BluetoothAccessHelper.StatusDisableBluetooth;
    public static final int StatusNoSupportBluetooth = BluetoothAccessHelper.StatusNoSupportBluetooth;
    public static final int StatusInit = BluetoothAccessHelper.StatusInit;
    public static final int StatusStartBluetooth = BluetoothAccessHelper.StatusStartBluetooth;

    private Context mContext;
    private BluetoothAccessHelper mBtHelper;
    private OnBluetoothStatusListener mBluetoothStatusListener;
    private OnFoundLeDeviceListener mFoundLeDeviceListener;
    private int mCentralState = CentralStateInit;
    private DeviceDiscoverer mDeviceDiscoverer;
    private HashMap<String, OnServicesDiscoveredListener> mDiscoveringServiceDeviceMap = new HashMap<>();
    private HashMap<LocalCharacteristicInfo, List<OnCharacteristicReadListener>> mReadCharacteristicMap = new HashMap<>();
    private HashMap<String, FoundLeDevice> mFoundLeDeviceMap = new HashMap<>();
    private HashMap<String, BluetoothGatt> mConnectedGattMap = new HashMap<>();
    private HashMap<String, Long> mConnectionTimeoutMap = new HashMap<>();
    private BluetoothGattCharacteristic mCurrentReadingCharacteristic = null;
    private ArrayList<BluetoothGattCharacteristic> mRequestingReadCharacteristicList = new ArrayList<>();
    private Handler mMainLooperHandler;
    private long mConnectionTimeoutMS = DefaultConnectionTimeoutMS;

    private static final int CentralStateInit = 0;
    private static final int CentralStateStart = 1;
    private static final int CentralStateDiscoverPeripheral = 2;

    public BleCentral(Context context) {
        mContext = context;
        mBtHelper = new BluetoothAccessHelper(context);
        mBtHelper.setOnBluetoothStatusListener(getBluetoothStatusListener());

        mDeviceDiscoverer = DeviceDiscoverer.getInstance(context);
        mMainLooperHandler = new Handler(context.getMainLooper(), mMainLooperCallback);
    }

    public void setOnBluetoothStatusListener(OnBluetoothStatusListener listener) {
        mBluetoothStatusListener = listener;
    }

    public void setOnFoundLeDeviceListener(OnFoundLeDeviceListener listener) {
        mFoundLeDeviceListener = listener;
    }

    public void start() {
        if (mCentralState == CentralStateInit) {
            mCentralState = CentralStateStart;
            mBtHelper.startBluetoothHelper();
        }
    }

    public void stop() {
        stopScanPeripheral();

        if ((mCentralState & CentralStateStart) == CentralStateStart) {
            mBtHelper.stopBluetoothHelper();
            mCentralState &= (~CentralStateStart);
        }
    }

    public boolean startScanPeripheral(int durationMS) {
        LogUtil.d(TAG, "startScanPeripheral(S): duration: " + durationMS);

        boolean ret = false;
        if (((mCentralState & CentralStateStart) == CentralStateStart) && ((mCentralState & CentralStateDiscoverPeripheral) == CentralStateInit)) {
            mFoundLeDeviceMap.clear();
            ret = mDeviceDiscoverer.startDiscoverLeDevices(durationMS, mRootFoundLeDeviceListener);
            if (ret) {
                mCentralState |= CentralStateDiscoverPeripheral;
            }
        }

        LogUtil.d(TAG, "startScanPeripheral(E): ret: " + ret);
        return ret;
    }

    public void stopScanPeripheral() {
        LogUtil.d(TAG, "stopScanPeripheral(S):");
        if ((mCentralState & CentralStateDiscoverPeripheral) == CentralStateDiscoverPeripheral) {
            mCentralState &= (~CentralStateDiscoverPeripheral);
            mDeviceDiscoverer.stopDiscoverLeDevices(mRootFoundLeDeviceListener, true);
        }
        LogUtil.d(TAG, "stopScanPeripheral(E):");
    }

    public FoundLeDevice[] getFoundLeDeviceList() {
        return mFoundLeDeviceMap.values().toArray(new FoundLeDevice[0]);
    }

    public boolean discoverServices(BluetoothDevice device, OnServicesDiscoveredListener listener) {
        LogUtil.d(TAG, "discoverServices(S)");

        boolean ret = false;
        String macAddress = device.getAddress();
        if (!mDiscoveringServiceDeviceMap.containsKey(macAddress)) {
            connectPeripheral(device);

            synchronized (mConnectedGattMap) {
                BluetoothGatt gatt = mConnectedGattMap.get(macAddress);
                if (gatt != null) {
                    if ((ret = gatt.discoverServices())) {
                        mDiscoveringServiceDeviceMap.put(macAddress, listener);
                    } else {
                        LogUtil.e(TAG, "discover service failed");
                    }
                }
            }
        }

        LogUtil.d(TAG, "discoverServices(E): ret: " + ret);
        return ret;
    }

    public void writeCharacteristic(BluetoothDevice fDevice, final UUID fServiceUuid, final UUID fCharacteristicUuid, final byte[] fData) {
        LogUtil.d(TAG, "writeCharacteristic(S): service uuid: " + fServiceUuid + ", characteristic uuid: " + fCharacteristicUuid);

        connectPeripheral(fDevice);

        String macAddress = fDevice.getAddress();
        final BluetoothGatt fGatt = mConnectedGattMap.get(macAddress);

        if (fGatt != null) {
            BluetoothGattService service = null;
            FoundLeDevice foundLeDevice = mFoundLeDeviceMap.get(macAddress);
            if (foundLeDevice != null) {
                List<BluetoothGattService> serviceList = foundLeDevice.getServiceList();
                if (serviceList != null && serviceList.size() > 0) {
                    for (BluetoothGattService tempService : serviceList) {
                        if (tempService.getUuid().equals(fServiceUuid)) {
                            service = tempService;
                            break;
                        }
                    }
                }
            }

            if (service != null) {
                writeCharacteristic(fGatt, service, fCharacteristicUuid, fData);
            } else {
                // 1度だけserviceを探してみる
                discoverServices(fDevice, new OnServicesDiscoveredListener() {
                    @Override
                    public void onServicesDiscovered(BluetoothDevice device, List<BluetoothGattService> serviceList) {
                        if (serviceList != null && serviceList.size() > 0) {
                            for (BluetoothGattService service : serviceList) {
                                if (fServiceUuid.equals(service.getUuid())) {
                                    writeCharacteristic(fGatt, service, fCharacteristicUuid, fData);
                                    break;
                                }
                            }
                        }
                    }
                });
            }
        }

        LogUtil.d(TAG, "writeCharacteristic(E):");
    }

    private void writeCharacteristic(BluetoothGatt gatt, BluetoothGattService service, UUID characteristicUuid, byte[] data) {
        BluetoothGattCharacteristic targetCharacteristic = service.getCharacteristic(characteristicUuid);
        if (targetCharacteristic != null) {
            targetCharacteristic.setValue(data);
            if (gatt.writeCharacteristic(targetCharacteristic)) {
                LogUtil.d(TAG, "success write characteristic data: " + Arrays.toString(data));
            } else {
                LogUtil.d(TAG, "fail write characteristic data: " + Arrays.toString(data));
            }
        } else {
            LogUtil.e(TAG, "not found characteristic: " + characteristicUuid);
        }
    }

    public BluetoothGattCharacteristic[] getCharacteristics(BluetoothDevice device, UUID serviceUuid) {
        LogUtil.d(TAG, "getCharacteristics(S): service uuid: " + serviceUuid);
        connectPeripheral(device);

        BluetoothGattCharacteristic[] ret = null;
        String macAddress = device.getAddress();
        FoundLeDevice foundLeDevice = mFoundLeDeviceMap.get(macAddress);
        if (foundLeDevice != null) {
            List<BluetoothGattService> serviceList = foundLeDevice.getServiceList();
            BluetoothGattService service = null;

            if (serviceList != null && serviceList.size() > 0) {
                for (BluetoothGattService tempService : serviceList) {
                    if (serviceUuid.equals(tempService.getUuid())) {
                        service = tempService;
                        break;
                    }
                }
            }

            if (service != null) {
                ArrayList<BluetoothGattCharacteristic> tempRet = new ArrayList<>();
                List<BluetoothGattCharacteristic> tempList = service.getCharacteristics();
                if (tempList != null && tempList.size() > 0) {
                    tempRet.addAll(tempList);
                }

                for (BluetoothGattService includedService : service.getIncludedServices()) {
                    tempRet.addAll(Arrays.asList(getCharacteristics(includedService)));
                }
                ret = tempRet.toArray(new BluetoothGattCharacteristic[0]);
            }
        }

        LogUtil.d(TAG, "getCharacteristics(E)");
        return ret;
    }

    private BluetoothGattCharacteristic[] getCharacteristics(BluetoothGattService service) {
        LogUtil.d(TAG, "getCharacteristics(S): service uuid: " + service.getUuid());
        ArrayList<BluetoothGattCharacteristic> tempRet = new ArrayList<>();
        List<BluetoothGattService> serviceList = service.getIncludedServices();
        BluetoothGattCharacteristic[] ret = null;

        if (serviceList != null && serviceList.size() > 0) {
            for (BluetoothGattService includedService : serviceList) {
                tempRet.addAll(Arrays.asList(getCharacteristics(includedService)));
            }
        }

        List<BluetoothGattCharacteristic> tempList = service.getCharacteristics();
        if (tempList != null && tempList.size() > 0) {
            tempRet.addAll(tempList);
        }
        ret = tempRet.toArray(new BluetoothGattCharacteristic[0]);

        LogUtil.d(TAG, "getCharacteristics(E): ret length: " + ret.length);
        return ret;
    }

    public void readCharacteristic(final BluetoothDevice device, final BluetoothGattCharacteristic characteristic, final OnCharacteristicReadListener listener) {
        LogUtil.d(TAG, "readCharacteristic(S): characteristic uuid: " + characteristic.getUuid());
        String macAddress = device.getAddress();
        final BluetoothGatt gatt = mConnectedGattMap.get(macAddress);
        byte[] data = characteristic.getValue();

        if (gatt != null) {
            if (data != null && data.length > 0) {
                ThreadUtil.runOnMainThread(mContext, new Runnable() {
                    @Override
                    public void run() {
                        listener.onCharacteristicRead(gatt, characteristic, BluetoothGatt.GATT_SUCCESS);
                    }
                });
            } else {
                List<OnCharacteristicReadListener> characteristicReadListenerList = mReadCharacteristicMap.get(characteristic);
                LocalCharacteristicInfo localCharacteristicInfo = new LocalCharacteristicInfo(device, characteristic);
                if (characteristicReadListenerList == null) {
                    characteristicReadListenerList = new ArrayList<>();
                    mReadCharacteristicMap.put(localCharacteristicInfo, characteristicReadListenerList);
                }
                characteristicReadListenerList.add(listener);

                synchronized (mRequestingReadCharacteristicList) {
                    if (mCurrentReadingCharacteristic == null) {
                        mCurrentReadingCharacteristic = characteristic;
                        gatt.readCharacteristic(characteristic);
                    } else {
                        // 1つずつしかreadを受け付けないのでonCharacteristicReadがコールされるまで保留
                        mRequestingReadCharacteristicList.add(characteristic);
                    }
                }
            }
        }
        LogUtil.d(TAG, "readCharacteristic(E)");
    }

    public void connectPeripheral(BluetoothDevice device) {
        LogUtil.d(TAG, "connectPeripheral(S)");
        synchronized (mConnectedGattMap) {
            String macAddress = device.getAddress();
            BluetoothGatt gatt = mConnectedGattMap.get(macAddress);
            if (gatt == null) {
                gatt = device.connectGatt(mContext, false, mBtGattCallback);
                if (gatt != null) {
                    if (gatt.connect()) {
                        // 実際には未だ接続は完了していない(コネクション確立要求を受け付けただけ)
                        mConnectedGattMap.put(macAddress, gatt);
                    } else {
                        LogUtil.e(TAG, "BluetoothGatt connect failed");
                    }
                }
            }
        }
        LogUtil.d(TAG, "connectPeripheral(E)");
    }

    public void disconnectPeripheral(BluetoothDevice device) {
        LogUtil.d(TAG, "disconnectPeripheral(S)");

        String macAddress = device.getAddress();
        synchronized (mConnectedGattMap) {
            BluetoothGatt gatt = mConnectedGattMap.remove(macAddress);
            if (gatt != null) {
                gatt.disconnect();
                gatt.close();
            }
        }

        mFoundLeDeviceMap.remove(macAddress);
        mConnectionTimeoutMap.remove(macAddress);
        mDiscoveringServiceDeviceMap.remove(macAddress);

        LogUtil.d(TAG, "disconnectPeripheral(E)");
    }

    private BluetoothAccessHelper.OnBluetoothStatusListener getBluetoothStatusListener() {
        return new BluetoothAccessHelper.OnBluetoothStatusListener() {
            @Override
            public void onStatusChange(int status, int scanMode) {
                BleCentral.OnBluetoothStatusListener listener = mBluetoothStatusListener;

                switch (status) {
                    case StatusDisableBluetooth:
                        if (listener != null) {
                            listener.onStatusChange(status, scanMode);
                        }
                        break;
                    case StatusNoSupportBluetooth:
                        if (listener != null) {
                            listener.onStatusChange(status, scanMode);
                        }
                        break;
                    case StatusStartBluetooth:
                        if (listener != null) {
                            listener.onStatusChange(status, scanMode);
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private DeviceDiscoverer.OnFoundLeDeviceListener mRootFoundLeDeviceListener = new DeviceDiscoverer.OnFoundLeDeviceListener() {
        @Override
        public void onFoundLeDevice(FoundLeDevice foundLeDevice) {
            boolean notifyFoundLeDevice = false;
            String macAddress = foundLeDevice.getDevice().getAddress();

            if (!mFoundLeDeviceMap.containsKey(macAddress)) {
                mFoundLeDeviceMap.put(macAddress, foundLeDevice);

                if (!mConnectedGattMap.containsKey(macAddress)) {
                    notifyFoundLeDevice = true;
                }
            }

            if (notifyFoundLeDevice) {
                OnFoundLeDeviceListener listener = mFoundLeDeviceListener;
                if (listener != null) {
                    listener.onFoundLeDevice(foundLeDevice);
                }
            }
        }

        @Override
        public void onTimeoutFindLeDevice() {
            OnFoundLeDeviceListener listener = mFoundLeDeviceListener;
            if (listener != null) {
                listener.onTimeoutFindLeDevice();
            }
        }
    };

    private Handler.Callback mMainLooperCallback = new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == MsgConnectionTimeout) {
                ConnectionInfo connectInfo = (ConnectionInfo) message.obj;
                if ((connectInfo != null) && (connectInfo.device != null)) {
                    boolean connectionTimeout = false;
                    String macAddress = connectInfo.device.getAddress();
                    synchronized (mConnectedGattMap) {
                        Long connectionTimeoutMS = mConnectionTimeoutMap.get(macAddress);
                        if (connectionTimeoutMS != null) {
                            if (connectionTimeoutMS > connectInfo.connectionTimeoutMS) {
                                // 更新されているので、無視
                            } else {
                                connectionTimeout = true;
                            }
                        }
                    }

                    if (connectionTimeout) {
                        // コネクションが所定期間使われなかったので切断
                        disconnectPeripheral(connectInfo.device);
                    }
                }
            }
            return false;
        }
    };

    private BluetoothGattCallback mBtGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);

            BluetoothDevice device = gatt.getDevice();
            String macAddress = device.getAddress();

            if (newState == BluetoothGatt.STATE_CONNECTED) {
                LogUtil.d(TAG, "BluetoothGatt.STATE_CONNECTED: discover services: " + gatt.getDevice().getAddress());

                OnServicesDiscoveredListener listener;
                if ((listener = mDiscoveringServiceDeviceMap.remove(macAddress)) != null) {
                    // サービス検索が空ぶっていたので、再度実行
                    discoverServices(device, listener);
                }
            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                LogUtil.d(TAG, "BluetoothGatt.STATE_DISCONNECTED");
                synchronized (mConnectedGattMap) {
                    mConnectionTimeoutMap.remove(macAddress);
                }
                disconnectPeripheral(device);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);

            BluetoothDevice device = gatt.getDevice();
            String macAddress = device.getAddress();

            LogUtil.d(TAG, "onServicesDiscovered: " + device.getAddress());

            // コネクションタイマー更新
            synchronized (mConnectedGattMap) {
                long connectionTimeoutMS = System.currentTimeMillis() + mConnectionTimeoutMS;
                mConnectionTimeoutMap.put(macAddress, System.currentTimeMillis() + mConnectionTimeoutMS);
                mMainLooperHandler.sendMessageDelayed(Message.obtain(mMainLooperHandler, MsgConnectionTimeout, new ConnectionInfo(device, connectionTimeoutMS)), mConnectionTimeoutMS);
            }

            OnServicesDiscoveredListener listener = mDiscoveringServiceDeviceMap.remove(macAddress);
            if (listener != null) {
                // 見つかったserviceはこのタイミングでしか取得できないことが多い?次のデバイス発見通知で得られるScanResultから取得できなかった模様
                List<BluetoothGattService> serviceList = gatt.getServices();
                FoundLeDevice foundLeDevice = mFoundLeDeviceMap.get(macAddress);

                if (foundLeDevice != null) {
                    // 既にデバイスが発見された後のときは、保持しているインスタンスにServiceリストを設定
                    ArrayList<ParcelUuid> serviceUuidList = new ArrayList<>();

                    for (BluetoothGattService service : serviceList) {
                        serviceUuidList.add(ParcelUuid.fromString(service.getUuid().toString()));
                    }

                    foundLeDevice.setServiceList(serviceList);
                }
                listener.onServicesDiscovered(device, serviceList);
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);

            if (status == BluetoothGatt.GATT_SUCCESS) {
                LogUtil.d(TAG, "onCharacteristicRead: UUID: " + characteristic.getUuid() + ", value: " + Arrays.toString(characteristic.getValue()));

                BluetoothDevice device = gatt.getDevice();
                synchronized (mRequestingReadCharacteristicList) {
                    mCurrentReadingCharacteristic = null;
                    while (mRequestingReadCharacteristicList.size() > 0) {
                        mCurrentReadingCharacteristic = mRequestingReadCharacteristicList.remove(0);
                        if (mCurrentReadingCharacteristic.getValue() == null) {
                            LogUtil.d(TAG, "readCharacteristic: UUID: " + mCurrentReadingCharacteristic.getUuid());
                            gatt.readCharacteristic(mCurrentReadingCharacteristic);
                            break;
                        }
                    }
                }

                LocalCharacteristicInfo localCharacteristicInfo = new LocalCharacteristicInfo(device, characteristic);
                List<OnCharacteristicReadListener> listenerList = mReadCharacteristicMap.remove(localCharacteristicInfo);
                if (listenerList != null) {
                    for (OnCharacteristicReadListener listener : listenerList) {
                        listener.onCharacteristicRead(gatt, characteristic, BluetoothGatt.GATT_SUCCESS);
                    }
                }

                // コネクションタイマー更新
                synchronized (mConnectedGattMap) {
                    long connectionTimeoutMS = System.currentTimeMillis() + mConnectionTimeoutMS;
                    String macAddress = device.getAddress();
                    mConnectionTimeoutMap.put(macAddress, System.currentTimeMillis() + mConnectionTimeoutMS);
                    mMainLooperHandler.sendMessageDelayed(Message.obtain(mMainLooperHandler, MsgConnectionTimeout, new ConnectionInfo(device, connectionTimeoutMS)), mConnectionTimeoutMS);
                }
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            LogUtil.d(TAG, "onCharacteristicWrite(S): UUID: " + characteristic.getUuid() + ", value: " + Arrays.toString(characteristic.getValue()));
            LogUtil.d(TAG, "onCharacteristicWrite(E)");
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            LogUtil.d(TAG, "onCharacteristicChanged(S): UUID: " + characteristic.getUuid() + ", value: " + Arrays.toString(characteristic.getValue()));
            LogUtil.d(TAG, "onCharacteristicChanged(E)");
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorRead(gatt, descriptor, status);
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            super.onDescriptorWrite(gatt, descriptor, status);
        }

        @Override
        public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
            super.onReliableWriteCompleted(gatt, status);
        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
        }

        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
        }
    };

    private static class ConnectionInfo {
        public BluetoothDevice device;
        public long connectionTimeoutMS;

        public ConnectionInfo(BluetoothDevice device, long connectionTimeoutMS) {
            this.device = device;
            this.connectionTimeoutMS = connectionTimeoutMS;
        }
    }

    private static class LocalCharacteristicInfo {
        public BluetoothDevice device;
        public BluetoothGattCharacteristic characteristic;

        public LocalCharacteristicInfo(BluetoothDevice device, BluetoothGattCharacteristic characteristic) {
            this.device = device;
            this.characteristic = characteristic;
        }

        @Override
        public boolean equals(Object o) {
            boolean ret = false;

            if (o != null && o instanceof LocalCharacteristicInfo) {
                LocalCharacteristicInfo targetInfo = (LocalCharacteristicInfo) o;
                ret = targetInfo.device.equals(device) && targetInfo.characteristic.equals(characteristic);
            }

            return ret;
        }

        @Override
        public int hashCode() {
            return device.hashCode() + characteristic.hashCode();
        }

        @Override
        public String toString() {
            return super.toString();
        }
    }

    public interface OnBluetoothStatusListener extends BluetoothAccessHelper.OnBluetoothStatusListener {
        // 拡張なし
    }

    public interface OnFoundLeDeviceListener extends DeviceDiscoverer.OnFoundLeDeviceListener {
        // 拡張なし
    }

    public interface OnServicesDiscoveredListener {
        public void onServicesDiscovered(BluetoothDevice device, List<BluetoothGattService> serviceList);
    }

    public interface OnCharacteristicReadListener {
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status);
    }
}


text:
package org.denovogroup.rangzen;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * Handles interaction with Android's Bluetooth subsystem.
 */
public class BluetoothSpeaker {
  /** Logging tag, attached to all Android log messages. */
  private static final String TAG = "BluetoothSpeaker";

  /** The expected size of peer exchanges. */
  public static final int EXCHANGE_SIZE = 1024 * 30;

  /** Constant int passed to request to enable Bluetooth, required by Android. */
  public static final int REQUEST_ENABLE_BT = 54321;

  /** SDP name for creating Rangzen service on listening socket. */
  private static final String SDP_NAME = "RANGZEN_SDP_NAME";

  /** Payload for exchange. */
  private static byte[] mPayload;

  /** A UUID for this particular device. */
  private UUID mThisDeviceUUID;

  /** A handle, retrieved from the OS, to the Wifi Direct framework. */
  private BluetoothAdapter mBluetoothAdapter;

  /** A handle to a server socket which receives connections from remote BT peers. */
  private BluetoothServerSocket mServerSocket;

  /** Socket received from accepting on server socket. */
  /* package */ BluetoothSocket mSocket;

  /** Thread which calls accept on the server socket. */
  private Thread mConnectionAcceptingThread;

  /** Ongoing exchange. */
  private Exchange mExchange;

  /** Context of the Rangzen Service. */
  private RangzenService mContext;

  /** Receives Bluetooth related broadcasts. */
  private BluetoothBroadcastReceiver mBluetoothBroadcastReceiver;

  /**
   * @param context A context, from which to access the Bluetooth subsystem.
   * @param peerManager The app's PeerManager instance.
   */
  public BluetoothSpeaker(RangzenService context, PeerManager peerManager) {
    super();

    mPayload = new byte[EXCHANGE_SIZE];
    for (int i=0; i < EXCHANGE_SIZE; i++) {
      mPayload[i] = (byte) i;
    }

    this.mContext = context;
    this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    this.mBluetoothBroadcastReceiver = new BluetoothBroadcastReceiver(context);
    this.mThisDeviceUUID = getUUIDFromMACAddress(mBluetoothAdapter.getAddress());
    Log.i(TAG, "This device's UUID is " + mThisDeviceUUID.toString());

    if (mBluetoothAdapter == null) {
      // TODO (lerner): Tell the server that this device doesn't do Bluetooth.
      // TODO (lerner): Opt this device out of data collection?
      Log.e(TAG, "Device doesn't support Bluetooth.");
      return;
    } else if (!mBluetoothAdapter.isEnabled()) {
      Log.d(TAG, "Got a non-null Bluetooth Adapter but it's not enabled.");
       // TODO(lerner): This is contrary to Android user experience, which
       // states that apps should never turn on Bluetooth without explicit
       // user interaction. We should instead prompt the user with the
       // Android built-in intent for asking to turn on Bluetooth.
      if (mBluetoothAdapter.enable()) {
        Log.i(TAG, "Enabling Bluetooth.");
      } else {
        Log.e(TAG, "Attempt to enable Bluetooth returned false.");
      }

    }
    if (mBluetoothAdapter.isEnabled()) {
      try {
        createListeningSocket();
        spawnConnectionAcceptingThread();
      } catch (IOException e) {
        Log.e(TAG, "Failed to create listening BT server socket. " + e);
        Log.e(TAG, "Can't receive incoming connections.");
      }
    }

    Log.d(TAG, "Finished creating BluetoothSpeaker.");
  }

  /**
   * Retrieve a BluetoothDevice corresponding to the given address.
   *
   * @return A BluetoothDevice with the given address.
   */
  public BluetoothDevice getDevice(String address) {
    if (mBluetoothAdapter != null) {
      try {
        return mBluetoothAdapter.getRemoteDevice(address);
      } catch (IllegalArgumentException e) {
        Log.e(TAG, "Passed illegal address to get remote bluetooth device: " + address);
        return null;
      }
    } else {
      return null;
    }

  }
  /**
   * Retrieve our Bluetooth MAC address.
   *
   * @return The Bluetooth MAC address of this device.
   */
  public String getAddress() {
    if (mBluetoothAdapter != null) {
      return mBluetoothAdapter.getAddress();
    } else {
      return null;
    }

  }

  /**
   * Sanity check a string for whether it looks basically like a BT MAC. Just
   * regexes the string, looking for 6 groups of hex digits deparated by : or -.
   * Case insensitive.
   *
   * @param s A string which is to be checked for whether it looks like a Bluetooth
   * MAC address.
   * @return True if the string looks like a MAC address, false otherwise.
   */
  public static boolean looksLikeBluetoothAddress(String s) {
     return Pattern.matches("^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$", s);
  }

  /**
   * Check whether the address is owned by IANA or is the broadcast address
   * (FF:FF:FF:FF:FF:FF).
   *
   * TODO(lerner): Improve this check. We might want to reject all multicast/broadcast
   * and such; addresses not assigned to anyone; or other reserved addresses that
   * I might not have been able to find.
   *
   * @param s An address to be checked.
   * @return True if the address appears to be IANA owned or a broadcast address.
   * Returns false if the address doesn't seem to be a MAC address at all.
   */
  public static boolean isReservedMACAddress(String s) {
    if (!looksLikeBluetoothAddress(s)) {
      return false;
    }
    // Normalize the address to simplify the regexes.
    s = s.replace(":", "-");
    s = s.toUpperCase();

    // Check against IANA-owned addresses and the broadcast address.
    //
    // https://www.iana.org/assignments/ethernet-numbers/ethernet-numbers.xhtml
    // IANA is assigned all addresses starting 00-00-5E and 01-00-5E (the flipped
    // least significant bit in the first octet indicates multicast instead of unicast).
    //
    // The second to least significant bit also has special meaning (group/individual)
    // so I interpret that 2/3 are also reserved to IANA, even though their
    // doc (linked above) only mentions 00-00-5E and 01-00-5E.
    if (Pattern.matches("^0[0-3]-00-5E.*", s)) {
      return true;
    }
    else if (Pattern.matches("^FF-FF-FF-FF-FF-FF$", s)) { // Broadcast address.
      return true;
    }
    return false;
  }

  /**
   * Creates a thread which listens on the BluetoothSpeaker's
   * BluetoothServerSocket as long as Bluetooth reamins on, accepting any
   * incoming connections and completing exchanges with them.
   *
   * If Bluetooth is turned off (or an exception occurs for any other reason
   * while accepting a new connection), the thread dies and will be restarted
   * later when Bluetooth is on again.
   */
  private void spawnConnectionAcceptingThread() {
    mConnectionAcceptingThread = new Thread() {
      @Override
      public void run() {
        while (true) {
          try {
            // Wait between accepting connections.
            try {
              Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
              Log.e(TAG, "Connection accepting thread was interrupted during sleep: " + e);
            }
            acceptConnection();
          } catch (IOException e) {
            Log.e(TAG, "IOException while accepting/responding to a connection" + e);
            if (!mBluetoothAdapter.isEnabled()) {
              Log.e(TAG, "Bluetooth adapter is disabled; not accepting connections.");
              mServerSocket = null;
              return;
            }
          }
        }
      }
    };
    mConnectionAcceptingThread.start();
  }

  /**
   * Create a listening Bluetooth socket and listen for Rangzen connections.
   */
  private void createListeningSocket() throws IOException {
      mServerSocket = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(SDP_NAME, mThisDeviceUUID);
      Log.i(TAG, String.format("Listening (insecure RFCOMM) - name <%s>, UUID <%s>.",
                               SDP_NAME, mThisDeviceUUID));
  }

    /**
   * Accept a connection to the BluetoothServerSocket we've set up.
   * @throws IOException
   */
  private void acceptConnection() throws IOException {
    if (mServerSocket == null) {
      throw new IOException("ServerSocket is null, not trying to accept().");
    } else if (!mBluetoothAdapter.isEnabled()) {
      throw new IOException("Bluetooth adapter is disabled, not trying to accept().");
    }
    Log.i(TAG, "Calling mServerSocket.accept()");
    mSocket = mServerSocket.accept();
    Log.i(TAG, "Accepted socket from " + mSocket.getRemoteDevice());
    Log.i(TAG, "Accepted socket connected? " + mSocket.isConnected());
    mExchange = new BandwidthMeasurementExchange(mSocket.getInputStream(),
                             mSocket.getOutputStream(),
                             false,
                             new FriendStore(mContext, StorageBase.ENCRYPTION_DEFAULT),
                             new MessageStore(mContext, StorageBase.ENCRYPTION_DEFAULT),
                             mContext.mBandwidthExchangeCallback);
    //mExchange.execute((Boolean) null);
    // Start the exchange.
    mContext.exchangeStartTimeMillis = System.currentTimeMillis();
    (new Thread(mExchange)).start();
  }

  /**
   * Called periodically by the background tasks method of the Rangzen Service.
   * Recreates the listening socket and thread if they're not active. The listening
   * thread might be inactive if Bluetooth was turned off previously.
   */
  public void tasks() {
    // Log.v(TAG, "Starting BluetoothSpeaker tasks.");
    if (mServerSocket == null         && mBluetoothAdapter != null &&
        mBluetoothAdapter.isEnabled() && !mConnectionAcceptingThread.isAlive()) {
      try {
        Log.v(TAG, "No ServerSocket, creating a new one.");
        createListeningSocket();
        spawnConnectionAcceptingThread();
      } catch (IOException e) {
        Log.e(TAG, "Tasks: failed to create listening BT server socket. " + e);
        Log.e(TAG, "Can't receive incoming connections.");
      }
    }
  }

  /**
   * Convert buffer to string.
   *
   * TODO(lerner): Improve encoding. Currently uses default encoding and 10
   * bytes, whatever they are, ignoring any terminators.
   *
   * @return 10 bytes of the array, rendered as characters in the default encoding.
   */
  private String bufferToString(char[] charArray) {
    return new String(charArray, 0, 10);
  }

  public void connect(Peer peer, PeerConnectionCallback callback) {
    // Start connecting in a new thread, passing the callback and peer.
    // Return.
    (new Thread(new ConnectionRunnable(peer, callback))).start();
    return;
  }

  /**
   * Use the bytes of the given address to generate a type-3 UUID.
   *
   * @param address The MAC address to be converted into a UUID.
   * @return A UUID corresponding to the MAC address given.
   */
  private UUID getUUIDFromMACAddress(String address) {
    if (address == null) {
      return null;
    } else {
      return UUID.nameUUIDFromBytes(address.getBytes());
    }
  }

  /**
   * A thread which attempts to connect to the given peer and return a Bluetooth
   * Socket to that peer through the success() method of the connection callback.
   */
  private class ConnectionRunnable implements Runnable {
    /** The peer to which we're attempting to connect. */
    private Peer mPeer;

    /** A callback to report success (and the open socket) or failure. */
    private PeerConnectionCallback mCallback;

    /**
     * Create a new ConnectionRunnable which will connect to the given peer
     * and report success or failure on the given callback.
     *
     * @param peer A remote peer to connect to.
     * @param callback A PeerConnectionCallback to report success or failure.
     */
    public ConnectionRunnable(Peer peer, PeerConnectionCallback callback) {
      this.mPeer = peer;
      this.mCallback = callback;
    }

    /**
     * Connect to the peer and report success or failure.
     */
    public void run() {
      BluetoothDevice device = mPeer.getNetwork().getBluetoothDevice();
      if (device == null) {
        mCallback.failure("No bluetooth device for peer " + mPeer.toString());
        return;
      }
      UUID remoteUUID = getUUIDFromMACAddress(device.getAddress());
      BluetoothSocket socket;
      try {
        socket = device.createInsecureRfcommSocketToServiceRecord(remoteUUID);
      } catch (IOException e) {
        mCallback.failure(
            String.format("Failed to create insecure RFCOMM socket to %s on peer %s. IOException: %s",
                           remoteUUID, mPeer, e)
        );
        return;
      }

      try {
        socket.connect();
      } catch (IOException e) {
        mCallback.failure(
            String.format("Exception connceting to %s on peer %s. IOException: %s",
                           remoteUUID, mPeer, e)
        );
        return;
      }
      if (socket.isConnected()) {
        mCallback.success(socket);
      } else {
        mCallback.failure(String.format("Socket to %s on %s wasn't connected after connection attempt.",
                                        remoteUUID, mPeer));
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package wiki

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"runtime/debug"

	"github.com/suzuken/wiki/controller"
	"github.com/suzuken/wiki/httputil"
)

var errUnauthrized = errors.New("unauthorized")

// Auth verify if session user is logged in.
func Auth(h handler) handler {
	return func(w http.ResponseWriter, r *http.Request) error {
		if !controller.LoggedIn(r) {
			return &httputil.HTTPError{
				Status: http.StatusUnauthorized,
				Err:    errUnauthrized,
			}
		}
		h.ServeHTTP(w, r)
		return nil
	}
}

func m(method string, h handler) handler {
	return func(w http.ResponseWriter, r *http.Request) error {
		if r.Method != method {
			return &httputil.HTTPError{Status: http.StatusMethodNotAllowed}
		}
		h.ServeHTTP(w, r)
		return nil
	}
}

func GET(h handler) handler  { return m("GET", h) }
func POST(h handler) handler { return m("POST", h) }

type handler func(w http.ResponseWriter, r *http.Request) error

func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	runHandler(w, r, h, handleError)
}

type errFn func(w http.ResponseWriter, r *http.Request, status int, err error)

func logError(req *http.Request, err error, rv interface{}) {
	if err != nil {
		var buf bytes.Buffer
		fmt.Fprintf(&buf, "Error serving %s: %v\n", req.URL, err)
		if rv != nil {
			fmt.Fprintln(&buf, rv)
			buf.Write(debug.Stack())
		}
		log.Print(buf.String())
	}
}

func runHandler(w http.ResponseWriter, r *http.Request,
	fn func(w http.ResponseWriter, r *http.Request) error, errfn errFn) {
	defer func() {
		if rv := recover(); rv != nil {
			err := errors.New("handler panic")
			logError(r, err, rv)
			errfn(w, r, http.StatusInternalServerError, err)
		}
	}()

	r.Body = http.MaxBytesReader(w, r.Body, 2048)
	r.ParseForm()
	var buf httputil.ResponseBuffer
	err := fn(&buf, r)
	if err == nil {
		buf.WriteTo(w)
	} else if e, ok := err.(*httputil.HTTPError); ok {
		if e.Status >= 500 {
			logError(r, err, nil)
		}
		errfn(w, r, e.Status, e.Err)
	} else {
		logError(r, err, nil)
		errfn(w, r, http.StatusInternalServerError, err)
	}
}

func errorText(err error) string {
	if err == errUnauthrized {
		return "You are unauthorized."
	}
	return "Internal Server error."
}

func handleError(w http.ResponseWriter, r *http.Request, status int, err error) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(status)
	io.WriteString(w, errorText(err))
}


text:
$("#CreateDuplicateButton").click(function () {
    var id = $("[data-primarykey]").val();

    if (id) {
        $(".form.factory").hide();
        $("[data-primarykey]").val("");
        window.displayMessage(window.Resources.Labels.ItemDuplicated, "success");
        $(".form.factory").fadeIn(1000);
    };
});

$("#ReturnToViewButton").click(function() {
    $(".form.factory").hide();
    $(".view.factory").fadeIn();
});


text:
<link rel="stylesheet" type="text/css" href="/static/common/css/iconList.css" />

            <button class="close" id="add_close" type='button' data-dismiss='modal' aria-hidden='true'></button>

 菜单编辑

                    <form action="" class="form-horizontal" id="editMenu">

                            父级菜单

                                    <input type="text" name="pidName" class="m-wrap" value="{{menu.pidName}}" readonly/>
                                    <input type="hidden" name="pid" class="m-wrap" value="{{menu.pid}}" readonly/>
                                    <input type="hidden" name="id" class="m-wrap" value="{{menu.id}}" readonly/>
                                    选择

                            编码

                                <input type="text" name="code" class="m-wrap" value="{{menu.code}}"/>
                                  编码必须唯一

                            名称

                                <input type="text" name="menu_name" class="m-wrap"  value="{{menu.name}}"/>

                            地址

                                <input type="text" name="url" class="m-wrap"  value="{{menu.url}}"/>

                            排序

                                <input type="text" name="sort" class="m-wrap" value="{{menu.sort}}"/>

                            图标

                                    <input class="m-wrap" type="text" name="icon" readonly value="{{menu.icon}}">
                                    选择

                                        图标集

                                            {% for item in icon %}

                                            {% endfor %}

                            是否菜单

                                    {% if menu.ismenu == 0 %}
                                        <input type="checkbox" checked value="0" class="toggle" name="ismenu"/>
                                    {% else %}
                                        <input type="checkbox" value="1" class="toggle" name="ismenu"/>
                                    {% endif %}

                    </form>

            <button id="compile_close" data-dismiss='modal' style="display: none;"></button>
            <button class="btn btn-default" type='button'  onclick="compile_save()">
                保存
            </button>
            <button class="btn btn-default" type='button' data-dismiss='modal'>
                取消
            </button>


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SuperSocket.Common;
using SuperSocket.ProtoBase;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;

namespace SuperSocket.Facility.PolicyServer
{
    /// <summary>
    /// PolicyServer base class
    /// </summary>
    public abstract class PolicyServer : AppServer<PolicySession, StringPackageInfo>
    {
        private string m_PolicyFile;
        private string m_PolicyRequest = "<policy-file-request/>";
        /// <summary>
        /// Gets the policy response.
        /// </summary>
        protected byte[] PolicyResponse { get; private set; }
        private int m_ExpectedReceivedLength;

        /// <summary>
        /// Initializes a new instance of the <see cref="PolicyServer"/> class.
        /// </summary>
        public PolicyServer()
        {

        }

        /// <summary>
        /// Setups the specified root config.
        /// </summary>
        /// <param name="rootConfig">The root config.</param>
        /// <param name="config">The config.</param>
        /// <returns></returns>
        protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
        {
            var policyRequest = config.Options.GetValue("policyRequest");
            if (!string.IsNullOrEmpty(policyRequest))
                m_PolicyRequest = policyRequest;

            m_ExpectedReceivedLength = Encoding.UTF8.GetByteCount(m_PolicyRequest);

            ReceiveFilterFactory = new PolicyReceiveFilterFactory(m_ExpectedReceivedLength);

            m_PolicyFile = config.Options.GetValue("policyFile");

            if (string.IsNullOrEmpty(m_PolicyFile))
            {
                if(Logger.IsErrorEnabled)
                    Logger.Error("Configuration option policyFile is required!");
                return false;
            }

            if (!Path.IsPathRooted(m_PolicyFile))
                m_PolicyFile = GetFilePath(m_PolicyFile);

            if (!File.Exists(m_PolicyFile))
            {
                if (Logger.IsErrorEnabled)
                    Logger.Error("The specified policyFile doesn't exist! " + m_PolicyFile);
                return false;
            }

            PolicyResponse = SetupPolicyResponse(File.ReadAllBytes(m_PolicyFile));

            this.NewRequestReceived += new RequestHandler<PolicySession, StringPackageInfo>(PolicyServer_NewRequestReceived);

            return true;
        }

        /// <summary>
        /// Setups the policy response.
        /// </summary>
        /// <param name="policyFileData">The policy file data.</param>
        /// <returns></returns>
        protected virtual byte[] SetupPolicyResponse(byte[] policyFileData)
        {
            return policyFileData;
        }

        /// <summary>
        /// Gets the policy file response.
        /// </summary>
        /// <param name="clientEndPoint">The client end point.</param>
        /// <returns></returns>
        protected virtual byte[] GetPolicyFileResponse(IPEndPoint clientEndPoint)
        {
            return PolicyResponse;
        }

        void PolicyServer_NewRequestReceived(PolicySession session, StringPackageInfo requestInfo)
        {
            ProcessRequest(session, requestInfo.Body);
        }

        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="request">The request.</param>
        protected virtual void ProcessRequest(PolicySession session, string request)
        {
            if (string.Compare(request, m_PolicyRequest, StringComparison.InvariantCultureIgnoreCase) != 0)
            {
                session.Close();
                return;
            }

            var response = GetPolicyFileResponse(session.RemoteEndPoint);
            session.Send(response, 0, response.Length);
        }
    }
}


text:
'07:47:03
'30.09.2013
'Autor: LargoWinch

Imports System.Net.Sockets
Imports System.Net
Imports L2Crypt
Imports System.Threading

Public Class L_LoginClient
    Public SessionId As Integer
    Public _address As EndPoint
    Public _client As TcpClient
    Public _stream As NetworkStream
    Private _buffer() As Byte
    Private _loginCrypt As L_LoginCrypt
    Public BlowfishKey() As Byte
    Public RsaPair As ScrambledKeyPair

    Public Sub New(ByVal tcpClient As TcpClient)
        ' Logger.extra_info("connection from " & tcpClient.Client.RemoteEndPoint )
        _client = tcpClient
        _stream = tcpClient.GetStream()
        _address = tcpClient.Client.RemoteEndPoint
        SessionId = New Random().Next(Integer.MaxValue)

        initializeNetwork()
    End Sub

    Public Sub initializeNetwork()
        RsaPair = ClientManager.getInstance().getScrambledKeyPair()
        BlowfishKey = ClientManager.getInstance().getBlowfishKey()
        _loginCrypt = New L_LoginCrypt()
        _loginCrypt.updateKey(BlowfishKey)

        CType(New System.Threading.Thread(AddressOf read), System.Threading.Thread).Start()
        CType(New System.Threading.Thread(AddressOf sendInit), System.Threading.Thread).Start()
    End Sub

    Public Sub sendInit()
        sendPacket(New SM_INIT(Me))
    End Sub

    Public Sub sendPacket(ByVal sbp As L_SendBasePacket)
        sbp.write()
        Dim data() As Byte = sbp.ToByteArray()
        data = _loginCrypt.encrypt(data, 0, data.Length)
        Dim array As New List(Of Byte)()
        array.AddRange(BitConverter.GetBytes(CShort(Fix(data.Length + 2))))
        array.AddRange(data)
        _stream.Write(array.ToArray(), 0, array.Count)
        _stream.Flush()
    End Sub

    Public Sub read()
        Try
            _buffer = New Byte(1) {}
            _stream.BeginRead(_buffer, 0, 2, New AsyncCallback(AddressOf OnReceiveCallbackStatic), Nothing)
        Catch ex As Exception
            close()
            Throw ex
        End Try
    End Sub

    Private Sub OnReceiveCallbackStatic(ByVal result As IAsyncResult)
        Dim rs As Integer = 0
        Try
            rs = _stream.EndRead(result)

            If rs > 0 Then
                Dim Length As Short = BitConverter.ToInt16(_buffer, 0)
                _buffer = New Byte(Length - 2 - 1) {}
                _stream.BeginRead(_buffer, 0, Length - 2, New AsyncCallback(AddressOf OnReceiveCallback), result.AsyncState)
            End If
        Catch s As Exception
            ' Logger.warning(" was closed by force." & _address)
            close()
        End Try
    End Sub

    Public Sub close()
        ClientManager.getInstance().removeClient(Me)
    End Sub

    Private Sub OnReceiveCallback(ByVal result As IAsyncResult)
        _stream.EndRead(result)

        Dim buff(_buffer.Length - 1) As Byte
        _buffer.CopyTo(buff, 0)

        If Not _loginCrypt.decrypt(buff, 0, buff.Length) Then
            Logger.error("blowfish failed on. please restart auth server.")
        Else
            handlePacket(buff)
            CType(New System.Threading.Thread(AddressOf read), System.Threading.Thread).Start()
        End If
    End Sub

    Private Sub handlePacket(ByVal buff() As Byte)
        Dim id As Byte = buff(0)

        'string str = "header: "+buff[0]+"\n";
        'foreach (byte b in buff)
        '    str += b.ToString("x2")+" ";

        'Console.WriteLine(str);
        'File.WriteAllText("header" + buff[0], str);

        Dim msg As L_ReceiveBasePacket = Nothing
        Select Case id
            Case &H0
                msg = New RequestAuthLogin(Me, buff)
            Case &H2
                msg = New RequestServerLogin(Me, buff)
            Case &H5
                msg = New RequestServerList(Me, buff)
            Case &H7
                msg = New AuthGameGuard(Me, buff)

            Case Else
                Logger.warning("LoginClient: received unk request " & id)
        End Select

        If msg IsNot Nothing Then
            CType(New Thread(New ThreadStart(AddressOf msg.run)), Thread).Start()
        End If
    End Sub

    Public login1, login2 As Integer
    Public Sub setLoginPair(ByVal key1 As Integer, ByVal key2 As Integer)
        login1 = key1
        login2 = key2
    End Sub

    Public play1, play2 As Integer
    Public Sub setPlayPair(ByVal key1 As Integer, ByVal key2 As Integer)
        play1 = key1
        play2 = key2
    End Sub

    Public activeAccount As L_L2Account
End Class


text:
<resources>
    <string name="app_name">VideoCapture4</string>

    <!-- TODO: Remove or change this placeholder text -->
    <string name="hello_blank_fragment">Hello blank fragment</string>
</resources>


text:
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-main">

            </button>
            Tic Tac Toe

                    Home

                    Hall of Fame

            <form class="navbar-form navbar-left" id="gameSearchIdStyle" ng-show="showLogoutMenu">
                <input type="text" class="form-control col-lg-8" placeholder="Game Id" ng-model="gameId" />
                Play Game
            </form>

                <form class="navbar-form" ng-show="showLoginMenu">

                        <input type="text" class="form-control" placeholder="username" ng-model="username" />
                        <input type="password" class="form-control" placeholder="password" ng-model="password" />

                    <button class="btn btn-primary" id="loginNavBtn" ng-click="login(username, password)">Login</button>
                </form>
                <form class="navbar-form" ng-show="showLogoutMenu">
                    <button class="btn btn-primary" ng-click="logout()">Logout</button>
                </form>


text:
using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;

namespace Cmt
{
	namespace Net
	{
		/// <summary>
		/// Represents the consensus based matching and tracking algorithm.
		/// </summary>
		public ref class TrackerCmt
		{
		private:
			cmt::CMT *cmt;
			OpenCV::Net::Arr ^previous;
			~TrackerCmt() { this->!TrackerCmt(); }
			!TrackerCmt();
		public:
			/// <summary>
			/// Initializes a new instance of the <see cref="TrackerCmt"/> class.
			/// </summary>
			TrackerCmt();

			/// <summary>
			/// Initializes the tracker with the given image and bounding box.
			/// </summary>
			/// <param name="image">The source image representing the initial state of tracking.</param>
			/// <param name="rect">The bounding box representing the initial state of tracking.</param>
			void Initialize(OpenCV::Net::Arr ^image, OpenCV::Net::Rect rect);

			/// <summary>
			/// Updates the state of the tracker with a new image.
			/// </summary>
			/// <param name="image">The source image on which to look for the target.</param>
			void ProcessFrame(OpenCV::Net::Arr ^image);

			/// <summary>
			/// Gets or sets a value indicating whether to estimate the scale of the tracked object.
			/// </summary>
			property bool EstimateScale
			{
				bool get() { return cmt->consensus.estimate_scale; }
				void set(bool value) { cmt->consensus.estimate_scale = value; }
			}

			/// <summary>
			/// Gets or sets a value indicating whether to estimate the rotation of the tracked object.
			/// </summary>
			property bool EstimateRotation
			{
				bool get() { return cmt->consensus.estimate_rotation; }
				void set(bool value) { cmt->consensus.estimate_rotation = value; }
			}

			/// <summary>
			/// Gets the currently tracked bounding box.
			/// </summary>
			property OpenCV::Net::RotatedRect BoundingBox
			{
				OpenCV::Net::RotatedRect get()
				{
					return OpenCV::Net::RotatedRect(
						OpenCV::Net::Point2f(cmt->bb_rot.center.x, cmt->bb_rot.center.y),
						OpenCV::Net::Size2f(cmt->bb_rot.size.width, cmt->bb_rot.size.height),
						cmt->bb_rot.angle);
				}
			}

			/// <summary>
			/// Gets the confidence level for the currently tracked bounding box.
			/// </summary>
			property float Confidence
			{
				float get() { return cmt->confidence; }
			}

			/// <summary>
			/// Gets the currently active points for visualization purposes.
			/// </summary>
			property System::Collections::Generic::IEnumerable<OpenCV::Net::Point2f> ^ ActivePoints
			{
				System::Collections::Generic::IEnumerable<OpenCV::Net::Point2f> ^ get()
				{
					return gcnew ActivePointEnumerable(cmt);
				}
			}

		private:
			ref class ActivePointEnumerable : public System::Collections::Generic::IEnumerable<OpenCV::Net::Point2f>
			{
			private:
				cmt::CMT *cmt;
			internal:
				ActivePointEnumerable(cmt::CMT *cmt):
					cmt(cmt)
				{
				}

			public:
				virtual System::Collections::IEnumerator ^ EnumerableGetEnumerator() =
					System::Collections::IEnumerable::GetEnumerator
				{
					return this->GenericEnumerableGetEnumerator();
				}

				virtual System::Collections::Generic::IEnumerator<OpenCV::Net::Point2f> ^ GenericEnumerableGetEnumerator() =
					System::Collections::Generic::IEnumerable<OpenCV::Net::Point2f>::GetEnumerator
				{
					return gcnew ActivePointEnumerator(cmt);
				}
			};

			ref class ActivePointEnumerator : public System::Collections::Generic::IEnumerator<OpenCV::Net::Point2f>
			{
			private:
				int index;
				cmt::CMT *cmt;

			internal:
				ActivePointEnumerator(cmt::CMT *cmt):
					cmt(cmt),
					index(-1)
				{
				}

				property Object ^ CurrentNonGeneric {
					virtual Object ^ get() = System::Collections::IEnumerator::Current::get { return Current; }
				}

			public:
				~ActivePointEnumerator() { }
				virtual void Reset() { index = -1; }

				property OpenCV::Net::Point2f Current {
					virtual OpenCV::Net::Point2f get() { return *((OpenCV::Net::Point2f*)&cmt->points_active.at(index)); }
				}

				virtual bool MoveNext()
				{
					return ++index < cmt->points_active.size();
				}
			};
		};
	}
}


text:
/**
 * Firebase's namespacing system requires that all includes are done within the
 * same scope, and ES2015 modules don't play well with this system.
 */

import firebase from 'firebase/app'

// Disable Firebase features you don't want by commenting the import
import 'firebase/auth'
import 'firebase/database'
import 'firebase/storage'

export default firebase


text: Coding The Matrix


text:
import * as assert from 'assert';
import * as vscode from 'vscode';
import * as utils from '../utils';

suite.skip('Notebook Editor', function () {

	const contentSerializer = new class implements vscode.NotebookSerializer {
		deserializeNotebook() {
			return new vscode.NotebookData(
				[new vscode.NotebookCellData(vscode.NotebookCellKind.Code, '// code cell', 'javascript')],
			);
		}
		serializeNotebook() {
			return new Uint8Array();
		}
	};

	const disposables: vscode.Disposable[] = [];
	const testDisposables: vscode.Disposable[] = [];

	suiteTeardown(async function () {
		utils.assertNoRpc();
		await utils.revertAllDirty();
		await utils.closeAllEditors();
		utils.disposeAll(disposables);
		disposables.length = 0;

		for (let doc of vscode.workspace.notebookDocuments) {
			assert.strictEqual(doc.isDirty, false, doc.uri.toString());
		}
	});

	suiteSetup(function () {
		disposables.push(vscode.workspace.registerNotebookSerializer('notebook.nbdtest', contentSerializer));
	});

	teardown(async function () {
		utils.disposeAll(testDisposables);
		testDisposables.length = 0;
	});

	test('showNotebookDocment', async function () {

		const p = utils.asPromise(vscode.workspace.onDidOpenNotebookDocument);
		const uri = await utils.createRandomFile(undefined, undefined, '.nbdtest');

		const editor = await vscode.window.showNotebookDocument(uri);
		assert.strictEqual(uri.toString(), editor.document.uri.toString());

		const event = await p;
		assert.strictEqual(event.uri.toString(), uri.toString());

		const includes = vscode.workspace.notebookDocuments.includes(editor.document);
		assert.strictEqual(true, includes);
	});

	// TODO@rebornix deal with getting started
	test.skip('notebook editor has viewColumn', async function () {

		const uri1 = await utils.createRandomFile(undefined, undefined, '.nbdtest');
		const editor1 = await vscode.window.showNotebookDocument(uri1);

		assert.strictEqual(editor1.viewColumn, vscode.ViewColumn.One);

		const uri2 = await utils.createRandomFile(undefined, undefined, '.nbdtest');
		const editor2 = await vscode.window.showNotebookDocument(uri2, { viewColumn: vscode.ViewColumn.Beside });
		assert.strictEqual(editor2.viewColumn, vscode.ViewColumn.Two);
	});

	test.skip('Opening a notebook should fire activeNotebook event changed only once', async function () {
		const openedEditor = utils.asPromise(vscode.window.onDidChangeActiveNotebookEditor);
		const resource = await utils.createRandomFile(undefined, undefined, '.nbdtest');
		const editor = await vscode.window.showNotebookDocument(resource);
		assert.ok(await openedEditor);
		assert.strictEqual(editor.document.uri.toString(), resource.toString());
	});

	test('Active/Visible Editor', async function () {
		const firstEditorOpen = utils.asPromise(vscode.window.onDidChangeActiveNotebookEditor);
		const resource = await utils.createRandomFile(undefined, undefined, '.nbdtest');
		const firstEditor = await vscode.window.showNotebookDocument(resource);
		await firstEditorOpen;
		assert.strictEqual(vscode.window.activeNotebookEditor, firstEditor);
		assert.strictEqual(vscode.window.visibleNotebookEditors.includes(firstEditor), true);

		const secondEditor = await vscode.window.showNotebookDocument(resource, { viewColumn: vscode.ViewColumn.Beside });
		assert.strictEqual(secondEditor === vscode.window.activeNotebookEditor, true);
		assert.notStrictEqual(firstEditor, secondEditor);
		assert.strictEqual(vscode.window.visibleNotebookEditors.includes(secondEditor), true);
		assert.strictEqual(vscode.window.visibleNotebookEditors.includes(firstEditor), true);
		assert.strictEqual(vscode.window.visibleNotebookEditors.length, 2);
	});

	test('Notebook Editor Event - onDidChangeVisibleNotebookEditors on open/close', async function () {
		const openedEditor = utils.asPromise(vscode.window.onDidChangeVisibleNotebookEditors);
		const resource = await utils.createRandomFile(undefined, undefined, '.nbdtest');
		await vscode.window.showNotebookDocument(resource);
		assert.ok(await openedEditor);

		const firstEditorClose = utils.asPromise(vscode.window.onDidChangeVisibleNotebookEditors);
		await utils.closeAllEditors();
		await firstEditorClose;
	});

	test('Notebook Editor Event - onDidChangeVisibleNotebookEditors on two editor groups', async function () {
		const resource = await utils.createRandomFile(undefined, undefined, '.nbdtest');
		let count = 0;
		testDisposables.push(vscode.window.onDidChangeVisibleNotebookEditors(() => {
			count = vscode.window.visibleNotebookEditors.length;
		}));

		await vscode.window.showNotebookDocument(resource, { viewColumn: vscode.ViewColumn.Active });
		assert.strictEqual(count, 1);

		await vscode.window.showNotebookDocument(resource, { viewColumn: vscode.ViewColumn.Beside });
		assert.strictEqual(count, 2);

		await utils.closeAllEditors();
		assert.strictEqual(count, 0);
	});
});


text:
require File.join(File.dirname(__FILE__), '../responders/users_responder')

class UsersController < ApplicationController
  self.responder = UsersResponder

  attr_reader :user, :users
end


text:
import app from '~/app';
import _ from 'lodash';
import '~/views/forms/edit/edit';
import '~/views/forms/edit/bch/directives/edit-biosafety-decision.directive';

	export { default as template } from './edit-biosafety-decision.html';

  export default ["$scope", "$controller", function($scope, $controller) {

		$controller('editController', {
			$scope: $scope
		});

   }];


text:
@class PSMTabBarControl;

@interface DemoWindowController : NSWindowController <NSToolbarDelegate> {
	IBOutlet NSTabView				*tabView;
	IBOutlet NSTextField            *tabField;
	IBOutlet NSDrawer				*drawer;

	IBOutlet PSMTabBarControl		*tabBar;

	IBOutlet NSButton               *isProcessingButton;
	IBOutlet NSButton				*isEditedButton;
	IBOutlet NSButton				*hasLargeImageButton;
	IBOutlet NSTextField			*objectCounterField;
	IBOutlet NSPopUpButton			*iconButton;

	IBOutlet NSPopUpButton			*popUp_style;
	IBOutlet NSPopUpButton			*popUp_orientation;
	IBOutlet NSPopUpButton			*popUp_tearOff;
	IBOutlet NSButton				*button_canCloseOnlyTab;
	IBOutlet NSButton				*button_disableTabClosing;
	IBOutlet NSButton				*button_hideForSingleTab;
	IBOutlet NSButton				*button_showAddTab;
	IBOutlet NSButton				*button_useOverflow;
	IBOutlet NSButton				*button_automaticallyAnimate;
	IBOutlet NSButton				*button_allowScrubbing;
	IBOutlet NSButton				*button_sizeToFit;
	IBOutlet NSTextField			*textField_minWidth;
	IBOutlet NSTextField			*textField_maxWidth;
	IBOutlet NSTextField			*textField_optimumWidth;
}

- (void)addDefaultTabs;

// UI
- (IBAction)addNewTab:(id)sender;
- (IBAction)closeTab:(id)sender;
- (IBAction)stopProcessing:(id)sender;
- (IBAction)setIconNamed:(id)sender;
- (IBAction)setObjectCount:(id)sender;
- (IBAction)setTabLabel:(id)sender;

// Actions
- (IBAction)isProcessingAction:(id)sender;
- (IBAction)isEditedAction:(id)sender;
- (IBAction)hasLargeImageAction:(id)sender;

- (PSMTabBarControl *)tabBar;

// delegate
- (void)tabView:(NSTabView *)aTabView didSelectTabViewItem:(NSTabViewItem *)tabViewItem;
- (BOOL)tabView:(NSTabView *)aTabView shouldCloseTabViewItem:(NSTabViewItem *)tabViewItem;
- (void)tabView:(NSTabView *)aTabView didCloseTabViewItem:(NSTabViewItem *)tabViewItem;

// toolbar
- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag;
- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar;
- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar;
- (IBAction)toggleToolbar:(id)sender;
- (BOOL)validateToolbarItem:(NSToolbarItem *)theItem;

@end


text:
package example.popularItems.ProFID;

import java.util.HashMap;

public interface MultipleValueED {

	/**
	 * Returns the value of the parameter hold by the implementor
	 * of this interface.
	 */
	public HashMap<Integer, Double> getContent();

	/**
	 * Modifies the value of the parameter hold by the implementor
	 * of this interface.
	 */
	public void setContent(HashMap<Integer, Double> map);

	public boolean isConverged() ;

	public void setConverged(boolean converged) ;

}


text:
class CreateStays < ActiveRecord::Migration
  def change
    create_table :stays do |t|
      t.integer :band_id
      t.integer :event_id

      t.string :contact_name
      t.string :contact_phone

      t.string :street
      t.string :city
      t.string :state
      t.integer :zip

      t.boolean :pets

      t.timestamps null: false
    end
  end
end


text:
package org.mindtrails.MockClasses;

import org.mindtrails.domain.Participant;
import org.mindtrails.domain.questionnaire.SecureQuestionnaireData;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.persistence.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dan on 10/26/15.
 */
@Entity
@Table(name="TestQuestionnaire")
@Data
@EqualsAndHashCode(callSuper=false)
public class TestQuestionnaire extends SecureQuestionnaireData {

    private String value;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "TestMultiValue", joinColumns = @JoinColumn(name = "id"))
    @Column(name = "multiValue")
    private List<String> multiValue;

    private double timeOnPage;

    public TestQuestionnaire() {}
    public TestQuestionnaire(String value) {
        this.value = value;
        this.date = new Date();

    }

    @Override
    public Map<String,Object> modelAttributes(Participant p) {
        Map<String,Object> atts = new HashMap<>();
        atts.put("test", "pickles");
        return atts;
    }

}


text:
package org.ovirt.engine.core.vdsbroker.jsonrpc;

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

import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.di.Injector;
import org.ovirt.engine.core.vdsbroker.PollAllVmStatsOnlyRefresher;
import org.ovirt.engine.core.vdsbroker.ResourceManager;
import org.ovirt.engine.core.vdsbroker.VdsManager;
import org.ovirt.engine.core.vdsbroker.VmStatsRefresher;
import org.ovirt.engine.core.vdsbroker.VmsMonitoring;
import org.ovirt.engine.core.vdsbroker.vdsbroker.VdsBrokerObjectsBuilder;
import org.ovirt.engine.core.vdsbroker.vdsbroker.entities.VmInternalData;
import org.ovirt.engine.core.vdsbroker.xmlrpc.XmlRpcObjectDescriptor;
import org.ovirt.vdsm.jsonrpc.client.events.EventSubscriber;
import org.reactivestreams.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EventVmStatsRefresher extends VmStatsRefresher {

    private static final Logger log = LoggerFactory.getLogger(EventVmStatsRefresher.class);
    private Subscription subscription;
    private DbFacade dbFacade;
    private ResourceManager resourceManager;
    private PollAllVmStatsOnlyRefresher allVmStatsOnlyRefresher;

    public EventVmStatsRefresher(VdsManager manager) {
        super(manager);
        // we still want to fetch GetAllVmStats as we did before
        this.allVmStatsOnlyRefresher = Injector.injectMembers(new PollAllVmStatsOnlyRefresher(vdsManager));
        dbFacade = DbFacade.getInstance();
        resourceManager = ResourceManager.getInstance();
    }

    @Override
    public void startMonitoring() {
        allVmStatsOnlyRefresher.startMonitoring();
        final String hostname = vdsManager.getVdsHostname();
        resourceManager.subscribe(new EventSubscriber(hostname + "|*|VM_status|*") {

            @Override
            public void onSubscribe(Subscription sub) {
                subscription = sub;
                subscription.request(1);
            }

            @Override
            public void onNext(Map<String, Object> map) {
                try {
                    printEventInDebug(map);

                    List<Pair<VM, VmInternalData>> changedVms = new ArrayList<>();
                    convertEvent(changedVms, map);

                    if (!changedVms.isEmpty()) {
                        getVmsMonitoring().perform(changedVms, System.nanoTime(), vdsManager, false);
                        processDevices(changedVms.stream().map(pair -> pair.getSecond().getVmDynamic()),
                                System.nanoTime());
                    }
                } finally {
                    subscription.request(1);
                }
            }

            private void printEventInDebug(Map<String, Object> map) {
                if (!log.isDebugEnabled()) {
                    return;
                }
                StringBuilder sb = new StringBuilder();
                XmlRpcObjectDescriptor.toStringBuilder(map, sb);

                log.debug("processing event for host {} data:\n{}", vdsManager.getVdsName(), sb);
            }

            private VmsMonitoring getVmsMonitoring() {
                return new VmsMonitoring(auditLogDirector);
            }

            @SuppressWarnings("unchecked")
            private void convertEvent(List<Pair<VM, VmInternalData>> changedVms,
                    Map<String, Object> map) {
                Double notifyTime = VdsBrokerObjectsBuilder.removeNotifyTimeFromVmStatusEvent(map);

                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    Guid vmid = new Guid(entry.getKey());
                    VM dbVm = dbFacade.getVmDao().get(vmid);
                    VmInternalData vdsmVm;
                    if (dbVm == null) {
                        vdsmVm = createVmInternalData(vmid, (Map<String, Object>) map.get(vmid.toString()), notifyTime);
                    } else {
                        vdsmVm = createVmInternalData(dbVm, (Map<String, Object>) map.get(vmid.toString()), notifyTime);

                        // if dbVm runs on different host, monitoring expect it to be null
                        if (!vdsManager.getVdsId().equals(dbVm.getRunOnVds())) {
                            dbVm = null;
                        }
                    }

                    changedVms.add(new Pair<>(dbVm, vdsmVm));
                }
            }

            private VmInternalData createVmInternalData(Guid vmId, Map<String, Object> xmlRpcStruct, Double notifyTime) {
                VM fakeVm = new VM();
                fakeVm.setId(vmId);
                return createVmInternalData(fakeVm, xmlRpcStruct, notifyTime);
            }

            private VmInternalData createVmInternalData(VM dbVm, Map<String, Object> xmlRpcStruct, Double notifyTime) {
                // send a clone of vm dynamic to be overridden with new data
                VmDynamic clonedVmDynamic = new VmDynamic(dbVm.getDynamicData());
                VdsBrokerObjectsBuilder.updateVMDynamicData(clonedVmDynamic, xmlRpcStruct, vdsManager.getCopyVds());
                return new VmInternalData(clonedVmDynamic, dbVm.getStatisticsData(), notifyTime);
            }

            @Override
            public void onError(Throwable t) {
                // communication issue is delivered as a message so we need to request for more
                subscription.request(1);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    @Override
    public void stopMonitoring() {
        allVmStatsOnlyRefresher.stopMonitoring();
        subscription.cancel();
    }

}


text:
package hudson.plugins.git.browser;

import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitChangeSetUtil;

import org.eclipse.jgit.lib.ObjectId;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class GitRepositoryBrowserTest {

    private GitRepositoryBrowser browser;
    private GitChangeSet changeSet;
    private Collection<GitChangeSet.Path> paths;

    private final String baseURL = "https://github.com/jenkinsci/git-plugin/";

    private final boolean useAuthorName;
    private final String gitImplementation;
    private final ObjectId sha1;

    public GitRepositoryBrowserTest(String useAuthorName, String gitImplementation, ObjectId sha1) {
        this.useAuthorName = Boolean.valueOf(useAuthorName);
        this.gitImplementation = gitImplementation;
        this.sha1 = sha1;
    }

    @Parameterized.Parameters(name = "{0},{1},{2}")
    public static Collection permuteAuthorNameAndGitImplementationAndObjectId() {
        List<Object[]> values = new ArrayList<>();
        String[] allowed = {"true", "false"};
        String[] implementations = {"git", "jgit"};
        ObjectId[] sha1Array = { // Use commits from git-plugin repo history
            ObjectId.fromString("016407404eeda093385ba2ebe9557068b519b669"), // simple commit
            ObjectId.fromString("4289aacbb493cfcb78c8276c52e945802942ffd5"), // merge commit
            ObjectId.fromString("daf453dfc43db81ede5cde60d0469fda0b3321ab"), // simple commit
            ObjectId.fromString("c685e980a502fa10e3a5fa08e02ab4194950c1df"), // Introduced findbugs warning
            ObjectId.fromString("8e4ef541b8f319fd2019932a6cddfc480fc7ca28"), // Old commit
            ObjectId.fromString("75ef0cde74e01f16b6da075d67cf88b3503067f5"), // First commit - no files, no parent
        };
        for (String authorName : allowed) {
            for (String gitImplementation : implementations) {
                for (ObjectId sha1 : sha1Array) {
                    Object[] combination = {authorName, gitImplementation, sha1};
                    values.add(combination);
                }
            }
        }
        return values;
    }

    @Before
    public void setUp() throws IOException, InterruptedException {
        browser = new GitRepositoryBrowserImpl();
        changeSet = GitChangeSetUtil.genChangeSet(sha1, gitImplementation, useAuthorName);
        paths = changeSet.getPaths();
    }

    @Test
    public void testGetRepoUrl() {
        assertThat(browser.getRepoUrl(), is(nullValue()));
    }

    @Test
    public void testGetDiffLink() throws Exception {
        for (GitChangeSet.Path path : paths) {
            assertThat(browser.getDiffLink(path), is(getURL(path, true)));
        }
    }

    @Test
    public void testGetFileLink() throws Exception {
        for (GitChangeSet.Path path : paths) {
            assertThat(browser.getFileLink(path), is(getURL(path, false)));
        }
    }

    @Test
    public void testGetNormalizeUrl() {
        assertThat(browser.getNormalizeUrl(), is(true));
    }

    @Test
    public void testGetIndexOfPath() throws Exception {
        Set<Integer> foundLocations = new HashSet<>(paths.size());
        for (GitChangeSet.Path path : paths) {
            int location = browser.getIndexOfPath(path);

            // Assert that location is in bounds
            assertThat(location, is(lessThan(paths.size())));
            assertThat(location, is(greaterThan(-1)));

            // Assert that location has not been seen before
            assertThat(foundLocations, not(hasItem(location)));
            foundLocations.add(location);
        }

        // Assert that exact number of locations were found
        assertThat(foundLocations.size(), is(paths.size()));
    }

    private URL getURL(GitChangeSet.Path path, boolean isDiffLink) throws MalformedURLException {
        return new URL(baseURL + path.getPath() + (isDiffLink ? "-diff-link" : "-file-link"));
    }

    public class GitRepositoryBrowserImpl extends GitRepositoryBrowser {

        public URL getDiffLink(GitChangeSet.Path path) throws IOException {
            return getURL(path, true);
        }

        public URL getFileLink(GitChangeSet.Path path) throws IOException {
            return getURL(path, false);
        }

        @Override
        public URL getChangeSetLink(GitChangeSet e) throws IOException {
            throw new UnsupportedOperationException("Not implemented.");
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>TFramedTransportFactory (apache-cassandra API)</title>
<meta name="date" content="2016-06-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.thrift

Class TFramedTransportFactory

java.lang.Object

org.apache.cassandra.thrift.TFramedTransportFactory

All Implemented Interfaces:

ITransportFactory

public class TFramedTransportFactory
extends java.lang.Object
implements ITransportFactory

Field Summary

Fields inherited from interface org.apache.cassandra.thrift.ITransportFactory

PROPERTY_KEY

Constructor Summary

Constructors

Constructor and Description

TFramedTransportFactory()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

org.apache.thrift.transport.TTransport
openTransport(java.lang.String host,
             int port)

Opens a client transport to a thrift server.

void
setOptions(java.util.Map<java.lang.String,java.lang.String> options)

Sets an implementation defined set of options.

java.util.Set<java.lang.String>
supportedOptions()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TFramedTransportFactory

public TFramedTransportFactory()

Method Detail

openTransport

public org.apache.thrift.transport.TTransport openTransport(java.lang.String host,
                                                            int port)
                                                     throws org.apache.thrift.transport.TTransportException

Description copied from interface: ITransportFactory

Opens a client transport to a thrift server.
 Example:

 TTransport transport = clientTransportFactory.openTransport(address, port);
 Cassandra.Iface client = new Cassandra.Client(new BinaryProtocol(transport));

Specified by:

openTransport in interface ITransportFactory

Parameters:

host - fully qualified hostname of the server

port - RPC port of the server

Returns:

open and ready to use transport

Throws:

org.apache.thrift.transport.TTransportException

setOptions

public void setOptions(java.util.Map<java.lang.String,java.lang.String> options)

Description copied from interface: ITransportFactory

Sets an implementation defined set of options.
 Keys in this map must conform to the set set returned by ITransportFactory#supportedOptions.

Specified by:

setOptions in interface ITransportFactory

Parameters:

options - option map

supportedOptions

public java.util.Set<java.lang.String> supportedOptions()

Specified by:

supportedOptions in interface ITransportFactory

Returns:

set of options supported by this transport factory implementation

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>BusyBee</title>

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

    <link href="css/business-casual.css" rel="stylesheet">

    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">

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

                </button>

                <form class="navbar-form" role="login">
                <button type="button" class="btn btn-default" aria-label="Left Align">

                </button>

                        <input type="text" class="form-control" placeholder="I need help with...">

                     <button type="button" class="btn btn-primary">Add</button>
                    <button type="button" class="btn btn-default">Track Your Helpers</button>
                    <button type="button" class="btn btn-default">Add Friends</button>
                </form>

Do some good.

                    <input type="checkbox" aria-label="...">
                    Cake for John's Birthday

 He likes Batman and will be 7 years-old. Chocolate and vanilla are fine.

                    <input type="checkbox" aria-label="...">
                    Need a Babysitter

 Going out for the night because I'm throwing a surprise party for Hillary. Lisa and Rob need supervision.

                    <input type="checkbox" aria-label="...">
                    Drop Off FedEx Package

 Got a medium-sized, light package but never find enough time to drop it off. Please help (I'll make you cookies)!

                        <input type="checkbox" aria-label="...">
                        Collect Laundry

 Laundromat on tenth street. Need my favorite dress for the party tonight!

 <input type="checkbox" aria-label="..."> One Last Ingredient

 Need baking soda to make my famous bread!

Copyright © BusyBee 2017


text:
Shortener
=========

Url Shortener for BeenVerified

I wrote this application quickly for BeenVerified's interview process. I hadn't written Ruby before.
Takes a URL in an input box, applies Base-58 encoding to the DB primary key, spits it out as a short URL.
To run:

```
~$ bundle install
~$ rake create_db
~$ rake run
```


text:
package workbench.db.postgres;

import java.sql.Statement;

import workbench.AppArguments;
import workbench.TestUtil;

import workbench.db.ConnectionMgr;
import workbench.db.ConnectionProfile;
import workbench.db.WbConnection;

import workbench.sql.BatchRunner;

import workbench.util.ArgumentParser;
import workbench.util.SqlUtil;
import workbench.util.StringUtil;

/**
 *
 * @author Thomas Kellerer
 */
public class PostgresTestUtil
{

	public static final String TEST_USER = "wbjunit";
	public static final String TEST_PWD = "wbjunit";
	public static final String PROFILE_NAME = "WBJUnitPostgres";

	/**
	 * Return a connection to a locally running PostgreSQL database
	 */
	public static WbConnection getPostgresConnection()
	{
		return getPostgresConnection("wbjunit", TEST_USER, TEST_PWD, PROFILE_NAME);
	}
	public static WbConnection getPostgresConnection(String dbName, String username, String password, String profileName)
	{
		try
		{
			WbConnection con = ConnectionMgr.getInstance().findConnection(PROFILE_NAME);
			if (con != null) return con;

			ArgumentParser parser = new AppArguments();
			parser.parse("-url='jdbc:postgresql://localhost/" + dbName + "' -username=" + username + " -password=" + password + " -driver=org.postgresql.Driver");
			ConnectionProfile prof = BatchRunner.createCmdLineProfile(parser);
			prof.setName(profileName);
			ConnectionMgr.getInstance().addProfile(prof);
			con = ConnectionMgr.getInstance().getConnection(prof, PROFILE_NAME);
			return con;
		}
		catch (Throwable th)
		{
			return null;
		}
	}

	public static void initTestCase(String schema)
		throws Exception
	{
		TestUtil util = new TestUtil(schema);
		util.prepareEnvironment();

		WbConnection con = getPostgresConnection();
		if (con == null) return;

		Statement stmt = null;
		try
		{
			stmt = con.createStatement();

			if (StringUtil.isBlank(schema))
			{
				schema = "junit";
			}
			else
			{
				schema = schema.toLowerCase();
			}

			dropAllObjects(con);

			stmt.execute("create schema "+ schema);
			stmt.execute("set session schema '" + schema + "'");
			con.commit();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			con.rollbackSilently();
		}
		finally
		{
			SqlUtil.closeStatement(stmt);
		}
	}

	public static void cleanUpTestCase()
	{
		WbConnection con = getPostgresConnection();
		dropAllObjects(con);
		ConnectionMgr.getInstance().disconnectAll();
	}

	public static void dropAllObjects(WbConnection con)
	{
		if (con == null) return;

		Statement stmt = null;
		try
		{
			stmt = con.createStatement();
			stmt.execute("drop owned by wbjunit cascade");
			con.commit();
			con.getObjectCache().clear();
		}
		catch (Exception e)
		{
			con.rollbackSilently();
		}
		finally
		{
			SqlUtil.closeStatement(stmt);
		}
	}
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yattatech.settings;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 *
 * @author Adriano
 */
public final class Settings {

    private static final Properties PROPERTIES = getPropertiesFile();

    private Settings() {
            throw new AssertionError();
    }

    private static Properties getPropertiesFile() {

        InputStream inputStream = null;
        try {
            Properties properties = new Properties();
            inputStream           = Settings.class.getResourceAsStream("/shalom.config.properties");
            properties.load(inputStream);
            return properties;
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception e) {}
            }
        }
    }

    /**
     * Searches for the property with the specified name in
     * this property list.
     *
     * @param name property name
     * @return the found value or null if
     * nothing was found
     *
     */
    public static String getProperty(String name) {
        return PROPERTIES.getProperty(name);
    }

    /**
     * Searches for the property with the specified name in
     * this property list and cast to int.
     *
     * @param name property name
     * @return the found value or 0 if
     * nothing was found
     *
     */
    public static int getPropertyAsInt(String name) {
        String value = getProperty(name);
        return value == null ? 0 : Integer.parseInt(value);
    }
}


text:
namespace _02.OrderedBag
{
    using System;

    public class Product : IComparable<Product>
    {
        public Product(string name, decimal price)
        {
            this.Name = name;
            this.Price = price;
        }

        public string Name { get; set; }

        public decimal Price { get; set; }

        public int CompareTo(Product other)
        {
            return this.Price.CompareTo(other.Price);
        }

        public override string ToString()
        {
            return string.Format("Product name: {0}, price: {1:F2}", this.Name, this.Price);
        }
    }
}