text:
package lejos.hardware.device.tetrix;

import lejos.hardware.port.I2CPort;
import lejos.hardware.sensor.I2CSensor;
import lejos.utility.Delay;
import lejos.utility.EndianTools;

/**
 * HiTechnic Tetrix Motor Controller abstraction. Provides TetrixMotor and TetrixEncoderMotor instances
 * which are used to control the Tetrix motors.
 *

 * Use {@link TetrixControllerFactory#newMotorController} to retrieve a TetrixMotorController instance.
 *
 * @see lejos.hardware.device.tetrix.TetrixControllerFactory
 * @see lejos.hardware.device.tetrix.TetrixMotor
 * @see lejos.hardware.device.tetrix.TetrixEncoderMotor
 * @author Kirk P. Thompson
 */
public class TetrixMotorController extends I2CSensor {
    /** Represents Motor 1 as indicated on the controller
     */
    public static final int MOTOR_1 = 0;
    /** Represents Motor 2 as indicated on the controller
     */
    public static final int MOTOR_2 = 1;

    private static final int CHANNELS = 2;
    private static final int KEEPALIVE_PING_INTERVAL = 2450;

    static final int CMD_FORWARD = 0;
    static final int CMD_BACKWARD = 1;
    static final int CMD_FLT = 2;
    static final int CMD_STOP = 3;
    static final int CMD_SETPOWER = 4;
    static final int CMD_ROTATE = 5;
    static final int CMD_ROTATE_TO = 6;
    static final int CMD_GETPOWER = 7;
    static final int CMD_RESETTACHO = 8;
    static final int CMD_SETREVERSE = 10;
    static final int CMD_ISMOVING = 11;
    static final int CMD_SETREGULATE = 12;
    static final int CMD_GETTACHO = 13;
    static final int CMD_GETSPEED = 14;
    static final int CMD_GETLIMITANGLE = 15;

    int[] motorState = {STATE_STOPPED, STATE_STOPPED};
    private static final int STATE_STOPPED = 0;
    private static final int STATE_RUNNING_FWD = 1;
    private static final int STATE_RUNNING_BKWD = 2;
    private static final int STATE_ROTATE_TO = 3;

    // common registers
    private static final int REG_ALL_MOTORCONTROL = 0x40;
    private static final int REG_BATTERY = 0x54;
    private static final int REG_ENCODERSREAD = 0x4C; // used by tachmonitor to read both encoders at once
    // register map for the motor-specific registers
    private static final int REG_IDX_ENCODER_TARGET = 0;
    private static final int REG_IDX_MODE = 1;
    private static final int REG_IDX_POWER = 2;
    private static final int REG_IDX_ENCODER_CURRENT = 3;
    static final int[][] REGISTER_MAP = // [REG_IDX_xxx][channel]
        {{0x40, 0x48}, // Encoder Target (write)
         {0x44, 0x47}, // Mode
         {0x45, 0x46}, // Power
         {0x4C, 0x50}  // Encoder Value (read)
        };

    // Mode OR masks
    private static final int MODEBIT_REVERSE = 0x08;
//    private static final int MODEBIT_NTO = 0x10;
//    private static final int MODEBIT_ERROR = 0x40;
    private static final int MODEBIT_BUSY = 0x80;
    private static final int MODEBIT_SEL_POWER = 0x00;
    private static final int MODEBIT_SEL_SPEED = 0x01;
    private static final int MODEBIT_SEL_POSITION = 0x02;
    private static final int MODEBIT_SEL_RST_ENCODER = 0x03;

    // motor parameters
    private int[][] motorParams = new int[4][CHANNELS];
    private static final int MOTPARAM_POWER = 0; // current power value
    private static final int MOTPARAM_REGULATED = 1; // 0=false=power control, 1=speed control
    private static final int MOTPARAM_REVERSED = 2; // 1=reversed, 0= normal
    private static final int MOTPARAM_ROTATE = 3; // 1=rotate to target mode
    static final int MOTPARAM_OP_TRUE=1;
    static final int MOTPARAM_OP_FALSE=0;

    // motor and monitor instance buckets
    Object[] motors= new Object[CHANNELS];
    BUSYMonitor[] bUSYMonitors = new BUSYMonitor[CHANNELS];
    TachoMonitor tachoMonitor;
    boolean[] busyMonitorWaiting = {false,false};

    private static final byte MOTTYPE_EMPTY = -1;
    private static final byte MOTTYPE_BASIC = 0;
    private static final byte MOTTYPE_ENCODER = 1;
    private static final byte MOTTYPE_REGULATED = 2;
    byte[] motorType = {MOTTYPE_EMPTY,MOTTYPE_EMPTY};

    // I2C buffer
    private byte[] buf = new byte[12];

    private int[] limitangle = {0,0};

    /**
     * Instantiate a HiTechnic TETRIX Motor Controller connected to the given port and daisy chain position.
     *
     * @param port The sensor port the controller (if daisy-chained, the first) is connected to.
     * @param daisyChainPosition The position of the controller in the daisy chain.
     * @see TetrixControllerFactory#DAISY_CHAIN_POSITION_1
     * @see TetrixControllerFactory#DAISY_CHAIN_POSITION_2
     * @see TetrixControllerFactory#DAISY_CHAIN_POSITION_3
     * @see TetrixControllerFactory#DAISY_CHAIN_POSITION_4
     * @throws IllegalStateException if a Motor Controller was not found with given port and daisyChainPosition
     */
    public TetrixMotorController(I2CPort port, int daisyChainPosition) {
        super(port, daisyChainPosition);
        address = daisyChainPosition;
        if (!(getVendorID().equalsIgnoreCase(TetrixControllerFactory.TETRIX_VENDOR_ID) &&
            getProductID().equalsIgnoreCase(TetrixControllerFactory.TETRIX_MOTORCON_PRODUCT_ID))) {
            throw new IllegalStateException("Not a motor controller");
        }
        initController();

        // This thread will keep the controller active. Without I2C activity within 2.5 seconds, it times out.
        // We could use the NTO bit of mode (MODEBIT_NTO) to keep the controller from timing
        // out but the motors would still run if the EV3 faulted, was shutdown, etc. which could be unsafe with big,
        // metal robots with sharp slicing attachments.
        Thread t1 = new Thread(new Runnable(){
            public void run() {
                byte[] buf1 = new byte[1];
                for (;;){
                    getData(REG_VERSION, buf1, 0);
                    Delay.msDelay(KEEPALIVE_PING_INTERVAL);
                    // let the thread die if we are constantly getting tachocounts as this will keep the contoller active instead
                    if (tachoMonitorAlive()) break;
                }
            }
        });
        t1.setDaemon(true);
        t1.start();
    }

    // When a rotate is issued, an instance monitors the BUSY bit and sets STATE_STOPPED when the command completes.
    // Also does any required RegulatedMotorListener STOP and notifies any wait() in waitRotateComplete().
    // Used by rotate() method only.
    private class BUSYMonitor extends Thread {
        int channel;
        BUSYMonitor(int channel){
            this.channel = channel;
        }
        @Override
		public void run(){
            byte buf1[] = {(byte)MODEBIT_BUSY};
            while ((buf1[0] & MODEBIT_BUSY) == MODEBIT_BUSY) {
                Delay.msDelay(100);
                //System.out.println("bsy");
                getData(REGISTER_MAP[REG_IDX_MODE][channel], buf1, 1);
            }
            motorState[channel]=STATE_STOPPED;
            if (motorType[channel]==MOTTYPE_REGULATED) {
            	((TetrixRegulatedMotor) motors[channel]).doListenerState(TetrixRegulatedMotor.LISTENERSTATE_STOP);
            }
            //System.out.println("busy done");
            // exit any wait for state of [ImmediateReturn = false]
            synchronized (bUSYMonitors[channel]) {
            	busyMonitorWaiting[channel]=false;
            	bUSYMonitors[channel].notify();
        	}
        }
    }

    // used by TetrixRegulatedMotor to monitor/manage tacho-related
    private class TachoMonitor extends Thread{
        private static final int POLL_DELAY_MS = 100;

        private boolean threadDie = false;
        private int[] TachoCount = new int[CHANNELS];
        private byte[] buffer = new byte[8];
        private volatile float[] degpersec = new float[CHANNELS];
        private float[][] samples = new float[CHANNELS][3];
        private int sampleIndex=0;
        private boolean[] ismoving = new boolean[CHANNELS];

        TachoMonitor(){
            this.setDaemon(true);
        }

        synchronized int getTachoCount(int channel) {
            return TachoCount[channel];
        }

        synchronized int getSpeed(int channel) {
            return (int)(degpersec[channel] * 100);
        }

        boolean isMoving(int channel){
        	return ismoving[channel];
        }

        @Override
		public void run(){
            int retVal;
            int failCount;
            int[] tachoBegin = new int[CHANNELS];
            long endTime, beginTime, timeDelta;
            float[] degpersecAccum = new float[CHANNELS];

            beginTime = System.currentTimeMillis();
            Main: while (!threadDie){
                Delay.msDelay(POLL_DELAY_MS);
                getData(REG_ENCODERSREAD, buffer, 8);

                // baseline the time after successful I2C transaction
                endTime = System.currentTimeMillis();
                timeDelta = endTime - beginTime;
                beginTime = endTime;

                // parse the buffer into the counts
                synchronized (this){
                    TachoCount[MOTOR_1] = EndianTools.decodeIntBE(buffer, 0);
                    TachoCount[MOTOR_2] = EndianTools.decodeIntBE(buffer, 4);
                }

                // Do velocity calcs (deg per sec)
                for (int i=0;i<CHANNELS;i++) {
                    synchronized (this){
                        // rotate the index if needed
                        if (i==CHANNELS-1) {
                            if (++sampleIndex >= samples[i].length) sampleIndex = 0;
                        }
                        // save a dps sample
                        samples[i][sampleIndex] = (float)Math.abs(TachoCount[i] - tachoBegin[i]) / timeDelta * 250;
                        tachoBegin[i] = TachoCount[i];
                    }

                    // average the samples and the last result (degpersec)
                    for (int ii=0;ii<samples[i].length;ii++) {
                        degpersecAccum[i] += samples[i][ii];
                    }
                    this.degpersec[i] = degpersecAccum[i] / (samples[i].length + 1);
                    degpersecAccum[i] = this.degpersec[i];
                    synchronized (this){
                    	ismoving[i] = (((int)degpersec[i])!=0);
                    }
                }
            }
        }
    }

    boolean tachoMonitorAlive() {
        return tachoMonitor!=null && tachoMonitor.isAlive();
    }

    /**
     * Get a TetrixMotor instance that is associated with the motorID.
     *
     * @param motorID The motor ID number. This is indicated on the HiTechnic Motor Controller and is
     * represented using  {@link #MOTOR_1} or  {@link #MOTOR_2}.
     * @return The TetrixMotor instance
     * @throws IllegalArgumentException if invalid motorID
     * @throws UnsupportedOperationException if motorID has already been used for a Tetrix motor instance
     * other than TetrixMotor.
     * @see lejos.hardware.device.tetrix.TetrixMotor
     * @see #getEncoderMotor
     * @see #getRegulatedMotor
     */
	public TetrixMotor getBasicMotor(int motorID) {
        getMotor(motorID, MOTTYPE_BASIC);
        return (TetrixMotor) motors[motorID];
    }

    /**
     * Get a TetrixEncoderMotor instance that is associated with the motorID. The motor must
     * have an encoder installed for a TetrixEncoderMotor instance to work correctly.
     *
     * @param motorID The motor ID number. This is indicated on the HiTechnic Motor Controller and is
     * represented using  {@link #MOTOR_1} or  {@link #MOTOR_2}.
     * @return The TetrixEncoderMotor instance
     * @throws IllegalArgumentException if invalid motorID
     * @throws UnsupportedOperationException if motorID has already been used for a Tetrix motor instance
     * other than TetrixEncoderMotor.
     * @see lejos.hardware.device.tetrix.TetrixEncoderMotor
     * @see #getBasicMotor
     * @see #getRegulatedMotor
     */
    public TetrixEncoderMotor getEncoderMotor(int motorID) {
        getMotor(motorID, MOTTYPE_ENCODER);
        return (TetrixEncoderMotor) motors[motorID];
    }

    /**
     * Get a TetrixRegulatedMotor instance that is associated with the motorID. The motor must
     * have an encoder installed for a TetrixRegulatedMotor instance to work correctly.
     *
     * @param motorID The motor ID number. This is indicated on the HiTechnic Motor Controller and is
     * represented using  {@link #MOTOR_1} or  {@link #MOTOR_2}.
     * @return The TetrixRegulatedMotor instance
     * @throws IllegalArgumentException if invalid motorID
     * @throws UnsupportedOperationException if motorID has already been used for a Tetrix motor instance
     * other than TetrixRegulatedMotor.
     * @see TetrixRegulatedMotor
     * @see #getBasicMotor
     * @see #getEncoderMotor
     */
    public TetrixRegulatedMotor getRegulatedMotor(int motorID) {
        getMotor(motorID, MOTTYPE_REGULATED);
        return (TetrixRegulatedMotor) motors[motorID];
    }

    private void getMotor(int motorID, byte motorTypeValue){
    	if (motorID<MOTOR_1 || motorID>MOTOR_2) {
            throw new IllegalArgumentException("Invalid motor ID");
        }

        if (motorType[motorID]==MOTTYPE_EMPTY) {
        	switch(motorTypeValue) {
	        	case MOTTYPE_REGULATED:
	        		motors[motorID]=new TetrixRegulatedMotor(this, motorID);
	        		break;
	        	case MOTTYPE_ENCODER:
	        		motors[motorID]=new TetrixEncoderMotor(this, motorID);
	        		break;
	        	case MOTTYPE_BASIC:
	        		motors[motorID]=new TetrixMotor(this, motorID);
        	}
        	motorType[motorID]=motorTypeValue;
        }
        if (motorType[motorID]!=motorTypeValue) {
        	throw new UnsupportedOperationException("Wrong motor type");
        }

        //start the tacho monitor if not already for encoder-enabled motors
        if (motorTypeValue > MOTTYPE_BASIC && tachoMonitor==null) {
            this.tachoMonitor = new TachoMonitor();
            this.tachoMonitor.start();
        }
    }

//    void dumpArray(int[] arr) {
//        for (int i=0;i<arr.length;i++) {
//            System.out.print(arr[i] + ":");
//        }
//        System.out.println("");
//        Button.waitForAnyPress();
//    }

    private void setMode(int channel, boolean resetEncoder) {
//        int mode=MODEBIT_SEL_POWER | MODEBIT_NTO;
        int mode=MODEBIT_SEL_POWER;

        // constant speed SEL bit and not in ROTATE (POS) state, set the bit. This is done because
        // if we set both the MODEBIT_SEL_SPEED and MODEBIT_SEL_POSITION, it equals MODEBIT_SEL_RST_ENCODER and
        // cancels out the ROTATE command
        if (motorParams[MOTPARAM_REGULATED][channel]==MOTPARAM_OP_TRUE && motorState[channel]!=STATE_ROTATE_TO) {
            mode = mode | MODEBIT_SEL_SPEED;
        }
        // run to position SEL bit
        if (motorParams[MOTPARAM_ROTATE][channel]==MOTPARAM_OP_TRUE) {
            mode = mode | MODEBIT_SEL_POSITION;
        }
        // reverse operation bit
        if (motorParams[MOTPARAM_REVERSED][channel]==MOTPARAM_OP_TRUE) {
            mode = mode | MODEBIT_REVERSE;
        }
        // if encoder reset requested
        if (resetEncoder) {
            mode = mode |  MODEBIT_SEL_RST_ENCODER;
        }

        // set the mode
        sendData(REGISTER_MAP[REG_IDX_MODE][channel], (byte)(mode & 0xff));
    }

    private int getEncoderValue(int channel) {
        // use latest tachoMonitor value for the motor if available
        if (tachoMonitorAlive()) {
            return tachoMonitor.getTachoCount(channel);
        }
        // .. otherwise, query the controller to get it
        getData(REGISTER_MAP[REG_IDX_ENCODER_CURRENT][channel], buf, 4);
        return EndianTools.decodeIntBE(buf, 0);
    }

    private void rotate(int channel, int value, int cmd){
        byte workingByte=0;
        motorParams[MOTPARAM_ROTATE][channel]=MOTPARAM_OP_TRUE;

        if (cmd==CMD_ROTATE) {
            // set the target based current + degrees passed
            value = getEncoderValue(channel) + value * 4;
        } else if(cmd==CMD_ROTATE_TO) {
            value *= 4;
        } else return;

        this.limitangle[channel] = Math.round(value * .25f) ;

        // set the encoder position
        EndianTools.encodeIntBE(value, buf, 0);
        sendData(REGISTER_MAP[REG_IDX_ENCODER_TARGET][channel], buf, 4);
        motorState[channel]=STATE_ROTATE_TO;

        // set the mode
        setMode(channel, false);

        // set the power to turn on the motor. Ensure it is positive (do not adjust for BACKWARDS)
        workingByte=(byte)motorParams[MOTPARAM_POWER][channel];
        sendData(REGISTER_MAP[REG_IDX_POWER][channel], workingByte);

        // set up the RegulatedMotorListener notifier and waitToComplete notifier for the rotate
        bUSYMonitors[channel] = new BUSYMonitor(channel);
        bUSYMonitors[channel].start();

        return;
    }

    void waitRotateComplete(int channel) {
    	synchronized (bUSYMonitors[channel]) {
    		busyMonitorWaiting[channel]=true;
    		while (busyMonitorWaiting[channel]) {
	    		try {
					bUSYMonitors[channel].wait();
				} catch (InterruptedException e) {
					// ignore
				}
    		}
    	}
    }

    private void motorGo(int channel, int command) {
        byte workingByte=0;
        int retval;

        motorState[channel]=command + 1; // STATE_RUNNING_FWD, STATE_RUNNING_BKWD assuming command IN(CMD_FORWARD,CMD_BACKWARD)
        motorParams[MOTPARAM_ROTATE][channel]=MOTPARAM_OP_FALSE; //false
        // set the mode
        setMode(channel, false);
        // set the power to turn on the motor
        workingByte=(byte)motorParams[MOTPARAM_POWER][channel];
        if (command==CMD_BACKWARD) {
            workingByte*=-1; // negative power runs backwards
        }
        sendData(REGISTER_MAP[REG_IDX_POWER][channel], workingByte);
    }

    /**
     * Execute a command. designed to never block because it is shared across two motors. The rotate WAITS are done
     * in the TetrixEncoderMotor class
     * @param command the command
     * @param operand the value from the caller. Mostly not used and set to 0
     * @param channel the channel: MOTOR_1, MOTOR_2
     * @return a value depending on the command
     */
    synchronized int doCommand(int command, int operand, int channel) {
        byte workingByte=0;
        int commandRetVal=0;

        switch (command) {
            case CMD_FORWARD:
                if (motorState[channel]==STATE_RUNNING_FWD) break;
                if (motorType[channel]==MOTTYPE_REGULATED) {
                	if (motorState[channel]!=STATE_STOPPED) {
                		((TetrixRegulatedMotor) motors[channel]).doListenerState(TetrixRegulatedMotor.LISTENERSTATE_STOP);
                	}
                	((TetrixRegulatedMotor) motors[channel]).doListenerState(TetrixRegulatedMotor.LISTENERSTATE_START);
                }
                motorGo(channel, command);
                break;
            case CMD_BACKWARD:
                if (motorState[channel]==STATE_RUNNING_BKWD) break;
                if (motorType[channel]==MOTTYPE_REGULATED) {
                	if (motorState[channel]!=STATE_STOPPED) {
                		((TetrixRegulatedMotor) motors[channel]).doListenerState(TetrixRegulatedMotor.LISTENERSTATE_STOP);
                	}
                	((TetrixRegulatedMotor) motors[channel]).doListenerState(TetrixRegulatedMotor.LISTENERSTATE_START);
                }
                motorGo(channel, command);
                break;
            case CMD_FLT:
                workingByte=-128;
            case CMD_STOP:
                if (command==CMD_STOP) workingByte=0;
                sendData(REGISTER_MAP[REG_IDX_POWER][channel], workingByte);
                Delay.msDelay(50);
                if (motorType[channel]==MOTTYPE_REGULATED && motorState[channel]!=STATE_STOPPED && motorState[channel]!=STATE_ROTATE_TO) {
                	((TetrixRegulatedMotor) motors[channel]).doListenerState(TetrixRegulatedMotor.LISTENERSTATE_STOP);
                }
                motorState[channel]=STATE_STOPPED;
                break;
            case CMD_SETPOWER:
                motorParams[MOTPARAM_POWER][channel] = operand;
                // if not running, exit
                if (motorState[channel]==STATE_STOPPED)  break;

                // set the power if running to take effect immediately
                workingByte = (byte)motorParams[MOTPARAM_POWER][channel];
                if (motorState[channel]==STATE_RUNNING_BKWD ) {
                    workingByte *= -1;
                }
                sendData(REGISTER_MAP[REG_IDX_POWER][channel], workingByte);
                break;
            case CMD_ROTATE:
            case CMD_ROTATE_TO:
            	if (motorType[channel]==MOTTYPE_REGULATED) {
                	if (motorState[channel]!=STATE_STOPPED) {
                		((TetrixRegulatedMotor) motors[channel]).doListenerState(TetrixRegulatedMotor.LISTENERSTATE_STOP);
                	}
                	((TetrixRegulatedMotor) motors[channel]).doListenerState(TetrixRegulatedMotor.LISTENERSTATE_START);
                }
                rotate(channel, operand, command);
                break;
            case CMD_GETPOWER:
                commandRetVal=motorParams[MOTPARAM_POWER][channel];
                break;
            case CMD_GETTACHO:
                commandRetVal=getEncoderValue(channel);
                break;
            case CMD_RESETTACHO:
                // reset encoder/tacho
                setMode(channel, true);
                Delay.msDelay(30); // small delay to allow encoder value reset in controller to happen
                motorState[channel]=STATE_STOPPED;
                break;
            case CMD_SETREVERSE:
                motorParams[MOTPARAM_REVERSED][channel]=operand;
                setMode(channel, false);
                break;
            case CMD_ISMOVING:
                commandRetVal=MOTPARAM_OP_TRUE;
                if (motorState[channel]==STATE_STOPPED) commandRetVal=MOTPARAM_OP_FALSE;
                // over-ride previous decision if regulated motor and it is moving
                if (tachoMonitorAlive()) {
                	commandRetVal = tachoMonitor.isMoving(channel)?MOTPARAM_OP_TRUE:MOTPARAM_OP_FALSE;
                }
                break;
            case CMD_SETREGULATE:
                motorParams[MOTPARAM_REGULATED][channel]=operand; //1=true, 0=false
                break;
            case CMD_GETSPEED:
                commandRetVal = 0;
                if (tachoMonitorAlive()) {
                    commandRetVal = tachoMonitor.getSpeed(channel);
                }
                break;
            case CMD_GETLIMITANGLE:
                commandRetVal = limitangle[channel];
                break;
            default:
                throw new IllegalArgumentException("Invalid Command");
        }
        return commandRetVal;

    }

    private void initController() {
        byte[] initBuf = {0,0,0,0,0,0,0,0,0,0,0,0};
        sendData(REG_ALL_MOTORCONTROL, initBuf, initBuf.length);
        Delay.msDelay(50);
        // reset motor params, encoder/tacho, and set NTO mode
//        byte mode = (byte)(MODEBIT_SEL_RST_ENCODER | MODEBIT_NTO) & 0xff;
        byte mode = (byte)MODEBIT_SEL_RST_ENCODER & 0xff;
        for (int i = 0;i<CHANNELS;i++){
            motorParams[MOTPARAM_POWER][i] = 0;         // current power value
            motorParams[MOTPARAM_REGULATED][i] = MOTPARAM_OP_FALSE;     // 0=false=power control, 1=speed control
            motorParams[MOTPARAM_REVERSED][i] = MOTPARAM_OP_FALSE;      // 1=reversed, 0= normal
            motorParams[MOTPARAM_ROTATE][i] = MOTPARAM_OP_FALSE;        // 1=rotate to target mode, 0=no rotate
            sendData(REGISTER_MAP[REG_IDX_MODE][i], mode);
        }
    }

    /**
     * Return the current battery voltage supplied to the controller.
     * @return The current battery voltage in volts
     */
    public synchronized float getVoltage() {
        int retVal;

        getData(REG_BATTERY, buf, 2);
        retVal=(buf[0] & 0xff)<<2;
        retVal=retVal | (buf[1] & 0x03);
        return retVal * .02f;
    }
}


text:
import unittest
from baidubce.services.sms import sms_client as sms
from baidubce.exception import BceServerError
from baidubce.exception import BceHttpClientError
from QaConf import *
import sys
import logging
import os

if sys.version_info[0] == 2 :
    reload(sys)
    sys.setdefaultencoding('utf-8')

__author__ = 'chsun'

file_path = os.path.normpath(os.path.dirname(__file__))
sys.path.append(file_path + '/../../')

import QaConf
from baidubce.services.sms import sms_client as sms
from baidubce import exception as ex

logging.basicConfig(level=logging.DEBUG, filename='./sms_sample.log', filemode='w')
LOG = logging.getLogger(__name__)
CONF = QaConf

class TestSmsClientSendMessageNorQa(unittest.TestCase):

    def setUp(self):
        self.sms = sms.SmsClient(CONF.config)
        # 签名
        self.invoke_id_valid = 'y2W4LRun-9sMD-MeGd'
        self.invoke_id_inValid = 'not-ready-invoke-id'
        # 模版
        self.template_valid = 'smsTpl:78d20e6c-201c-4f97-b57b-240e9dc7d831'
        self.template_inValid = 'smsTpl:ae63a600-1474-4d40-b8d8-9ed9f924bf3b'

    def tearDown(self):
        pass

    def test(self):
        # 签名可用 模版可用
        sendResponse = self.sms.send_message_2(self.invoke_id_valid,self.template_valid,'13261559193',{'code': "测试发送短信"})
        self.assertEqual('1000', sendResponse.code)
        # 签名可用 模版不可用
        try:
            sendResponse = self.sms.send_message_2(self.invoke_id_valid,self.template_inValid,'13261559193',{})
        except BceHttpClientError as e:
            self.assertEqual('模板不可用', e.last_error.args[0])
        # 签名不可用 模版可用
        try:
            sendResponse = self.sms.send_message_2(self.invoke_id_inValid,self.template_valid,'13261559193',{'code': "测试发送短信"})
        except BceHttpClientError as e:
            self.assertEqual('请求参数不正确', e.last_error.args[0])
        # 签名不可用 模版不可用
        try:
            sendResponse = self.sms.send_message_2(self.invoke_id_inValid,self.template_inValid,'13261559193',{'code': "测试发送短信"})
        except BceHttpClientError as e:
            self.assertEqual('请求参数不正确', e.last_error.args[0])

if __name__ == '__main__':
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file Facilities for drawing circles in WebGL as quads (triangle fan).
 */

import {RefCounted} from 'neuroglancer/util/disposable';
import {Buffer} from 'neuroglancer/webgl/buffer';
import {GL} from 'neuroglancer/webgl/context';
import {QuadRenderHelper} from 'neuroglancer/webgl/quad';
import {ShaderBuilder, ShaderProgram} from 'neuroglancer/webgl/shader';
import {getSquareCornersBuffer} from 'neuroglancer/webgl/square_corners_buffer';

export const VERTICES_PER_CIRCLE = 4;

export class CircleShader extends RefCounted {
  private squareCornersBuffer: Buffer;
  private quadHelper: QuadRenderHelper;

  constructor(gl: GL, public circlesPerInstance: number = 1) {
    super();
    this.squareCornersBuffer = getSquareCornersBuffer(
        gl, -1, -1, 1, 1, /*minorTiles=*/circlesPerInstance, /*majorTiles=*/1);
    this.quadHelper = this.registerDisposer(new QuadRenderHelper(gl, circlesPerInstance));
  }

  defineShader(builder: ShaderBuilder, crossSectionFade: boolean) {
    // XY corners of square ranging from [-1, -1] to [1, 1].
    builder.addAttribute('highp vec2', 'aCircleCornerOffset');

    // x and y components: The x and y radii of the point in normalized device coordinates.
    // z component: Starting point of border from [0, 1]..
    // w component: Fraction of total radius that is feathered.
    builder.addUniform('highp vec4', 'uCircleParams');

    // 2-D position within circle quad, ranging from [-1, -1] to [1, 1].
    builder.addVarying('highp vec2', 'vCircleCoord');
    builder.addVertexCode(`
void emitCircle(vec4 position) {
  gl_Position = position;
  gl_Position.xy += aCircleCornerOffset * uCircleParams.xy * gl_Position.w;
  vCircleCoord = aCircleCornerOffset;
}
`);
    if (crossSectionFade) {
      builder.addFragmentCode(`
float getCircleAlphaMultiplier() {
  return 1.0 - 2.0 * abs(0.5 - gl_FragCoord.z);
}
`);
    } else {
      builder.addFragmentCode(`
float getCircleAlphaMultiplier() {
  return 1.0;
}
`);
    }
    builder.addFragmentCode(`
vec4 getCircleColor(vec4 interiorColor, vec4 borderColor) {
  float radius = length(vCircleCoord);
  if (radius > 1.0) {
    discard;
  }

  float borderColorFraction = clamp((radius - uCircleParams.z) / uCircleParams.w, 0.0, 1.0);
  float feather = clamp((1.0 - radius) / uCircleParams.w, 0.0, 1.0);
  vec4 color = mix(interiorColor, borderColor, borderColorFraction);

  return vec4(color.rgb, color.a * feather * getCircleAlphaMultiplier());
}
`);
  }

  draw(
      shader: ShaderProgram, renderContext: {viewportWidth: number, viewportHeight: number},
      options: {
        interiorRadiusInPixels: number,
        borderWidthInPixels: number,
        featherWidthInPixels: number
      },
      count: number) {
    const {gl} = shader;
    const aCircleCornerOffset = shader.attribute('aCircleCornerOffset');
    this.squareCornersBuffer.bindToVertexAttrib(aCircleCornerOffset, /*components=*/2);
    const totalRadius =
        options.interiorRadiusInPixels + options.borderWidthInPixels + options.featherWidthInPixels;
    gl.uniform4f(
        shader.uniform('uCircleParams'), totalRadius / renderContext.viewportWidth,
        totalRadius / renderContext.viewportHeight, options.interiorRadiusInPixels / totalRadius,
        options.featherWidthInPixels === 0 ? 1e-6 : options.featherWidthInPixels / totalRadius);
    this.quadHelper.draw(gl, count);
    shader.gl.disableVertexAttribArray(aCircleCornerOffset);
  }
}


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <include layout="@layout/header" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingTop="20dp" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="loops"
                android:textSize="25sp" />

            <TextView
                android:id="@+id/loops"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="non touching loops"
                android:textSize="25sp" />

            <TextView
                android:id="@+id/nonTouchingLoops"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="forward paths"
                android:textSize="25sp" />

            <TextView
                android:id="@+id/forwardpaths"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="25sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="over all T.F."
                android:textSize="25sp" />

            <TextView
                android:id="@+id/overalltf"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:textSize="25sp" />

            <Button
                android:id="@+id/button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:text="draw SFG"
                android:textSize="24sp" />
        </LinearLayout>

        <include layout="@layout/footer" />
    </LinearLayout>

</ScrollView>


text:
facts("Images") do
  context("type creation") do
    pic = image("this"; volume="/a", volume="/b")
    @fact pic.base.name => "ubuntu:14.04"
    @fact pic.volumes => ["/a", "/b"]

    for name in names(RudeOil.BuildImage)
      if name ∉ [:name, :base, :volumes, :ppas]
        @fact getfield(pic, name) => RudeOil.DEFAULT_IMAGE[name]
      end
    end
  end

  context("dockerfile creation") do
    context("empty") do
      pic = RudeOil.BuildImage("that")
      @fact dockerfile(pic) => ismatch("FROM\\s+$(pic.base.name)")
      @fact dockerfile(pic) => ismatch("RUN\\s+pip") |> not
      @fact dockerfile(pic) => ismatch("RUN\\s+apt-get install") |> not
      @fact dockerfile(pic) => ismatch("RUN\\s+mkdir") |> not
    end
    context("packages") do
      pic = image("that", packages=["pack", "age"])
      match = "RUN\\s+apt-get\\s+install\\s+-y\\s+pack\\s+age"
      @fact dockerfile(pic) => ismatch(match)
    end
    context("pips") do
      pic = image("that", pips=["pack", "age"])
      @fact dockerfile(pic) => ismatch("RUN pip install pack age")
    end
    context("volumes") do
      pic = image("that", volume="/a", volume="/b")
      @fact dockerfile(pic) => ismatch("RUN mkdir -p /a /b")
      @fact dockerfile(pic) => ismatch("VOLUME /a /b")
    end
  end

  context("docker image creation") do
    first = image("mynewimage"; workdir="/myvol", volume="/myvol", packages=["julia"])
    context("single image") do
      activate(machine) do vm
        vm |> first |> run
        images = split(readchomp(RudeOil.command(vm, "images", first.name)), '\n')[2:end]
        images = [split(u, ' ')[1] for u in images]
        @fact images => contains(first.name)
      end
    end
    context("chained image") do
      second = image("mysecondimage"; packages=["python"])
      activate(machine) do vm
        vm |> first |> second |> run
        images = split(readchomp(RudeOil.command(vm, "images", "")), '\n')[2:end]
        images = [split(u, ' ')[1] for u in images]
        @fact images => contains(first.name)
        @fact images => contains(second.name)
      end
    end
  end

  context("Upstream docker image") do
    pic = image("ubuntu:14.04")
    @fact names(pic) => [:name]
  end
end


text:
package com.sonoport.freesound.query.sound;

import java.util.Collections;
import java.util.Map;
import java.util.Set;

import com.sonoport.freesound.License;
import com.sonoport.freesound.response.UploadedSoundDetails;
import com.sonoport.freesound.response.mapping.UploadedSoundDetailsMapper;

/**
 * Query used to provide additional details relating to a previously uploaded sound. Sounds requiring these queries are
 * listed as 'Pending Description' in the 'Pending Uploads' query.
 *
 * Note that there is a bug in the API meaning that if the optional parameters (name and pack) are not specified, the
 * call will fail (with a 500 response). A bug has been raised with Freesound at:
 * https://github.com/MTG/freesound/issues/648
 */
public class DescribeSound extends AbstractSoundUploadQuery<UploadedSoundDetails, DescribeSound> {

	/** Name of the parameter to pass the filename through as. */
	protected static final String UPLOAD_FILENAME_PARAMETER_NAME = "upload_filename";

	/** Path to API endpoint. */
	private static final String PATH = "/sounds/describe/";

	/** Name of the previously uploaded file. */
	private final String uploadFilename;

	/**
	 * @param uploadFilename Name of the previously uploaded file
	 * @param description Description to apply to sound
	 * @param license License to apply to sound
	 * @param tags Tags to associate with sound
	 * @param oauthToken OAuth2 access token to present
	 */
	public DescribeSound(
			final String uploadFilename,
			final String description,
			final License license,
			final Set<String> tags,
			final String oauthToken) {
		super(PATH, oauthToken, new UploadedSoundDetailsMapper());

		this.uploadFilename = uploadFilename;
		this.setDescription(description);
		this.setLicense(license);
		this.setTags(tags);
	}

	@Override
	public Map<String, String> getRouteParameters() {
		return Collections.emptyMap();
	}

	@Override
	public Map<String, Object> getQueryParameters() {
		final Map<String, Object> queryParameters = super.getQueryParameters();

		queryParameters.put(UPLOAD_FILENAME_PARAMETER_NAME, uploadFilename);

		return queryParameters;
	}

}


text:
process.stdin.resume();//this is how to get input from console
process.stdin.setEncoding('utf8');

console.log("initiating process ,argv: " + process.argv[2] +","+process.argv[3] + " \nPlease input: " );

process.stdin.on('data',function (data) {
	// body...
	console.log('I receive: '+data.toString() )
})

setInterval(function () {
//	//console.log("进程 " + process.argv[2] + " 执行。" );
	process.exit();
},10000);


text:
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var MariaGenerator = module.exports = function MariaGenerator() {
  yeoman.Base.apply(this, arguments);

  this.config.defaults({
    'appPath': 'app'
  });
  this.appPath = 'app';

  this.testFramework = this.options['test-framework'] || 'mocha';

  this.config.set('testFramework', this.testFramework);

  if (this.options.appPath) {
    this.appPath = this.options.appPath;
    this.config.set('appPath', this.options.appPath);
  }

  this.hookFor(this.testFramework, {
    as: 'app',
    options: {
      options: {
        'skip-install': this.options['skip-install']
      }
    }
  });

  this.on('end', function () {
    if (['app', 'maria'].indexOf(this.generatorName) >= 0) {
      this.installDependencies({ skipInstall: this.options['skip-install'] });
    }
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(MariaGenerator, yeoman.Base);

MariaGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  console.log(this.yeoman);
  console.log('Out of the box I include HTML5 Boilerplate, jQuery, Maria.js and Modernizr.');

  var prompts = [{
    type: 'checkbox',
    name: 'features',
    message: 'What more would you like?',
    choices: []
  }];

  if (!this.options.bootstrap) {
    prompts[0].choices.push({
      name: 'Twitter Bootstrap for Sass',
      value: 'compassBootstrap',
      checked: true
    });
  }

  if (!this.options.coffee) {
    prompts[0].choices.push({
      name: 'Use CoffeeScript',
      value: 'coffee',
      checked: false
    });
  }

  if (prompts[0].choices.length > 0) {
    this.prompt(prompts, function (answers) {
      var features = answers.features;

      function hasFeature(feat) { return features.indexOf(feat) !== -1; }

      // manually deal with the response, get back and store the results.
      // we change a bit this way of doing to automatically do this in the self.prompt() method.
      this.compassBootstrap = true;
      if (!this.options.bootstrap) {
        this.compassBootstrap = hasFeature('compassBootstrap');
      }

      if (!this.options.coffee) {
        this.options.coffee = hasFeature('coffee');
      }

      this.config.set('coffee', this.options.coffee);
      this.config.set('compassBootstrap', this.compassBootstrap);

      cb();
    }.bind(this));
  } else {
    this.compassBootstrap = this.options.bootstrap;
    this.config.set('coffee', this.options.coffee);
    this.config.set('compassBootstrap', this.options.bootstrap);
    cb();
  }
};

MariaGenerator.prototype.setupEnv = function setupEnv() {
  var appPath = this.config.get('appPath');
  this.mkdir(appPath);
  this.mkdir(appPath + '/scripts');
  this.mkdir(appPath + '/styles');
  this.mkdir(appPath + '/images');
  this.copy('app/404.html', appPath + '/404.html');
  this.copy('app/favicon.ico', appPath + '/favicon.ico');
  this.copy('app/robots.txt', appPath + '/robots.txt');
  this.copy('app/htaccess', appPath + '/.htaccess');
};

MariaGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};

MariaGenerator.prototype.git = function git() {
  this.copy('gitignore', '.gitignore');
  this.copy('gitattributes', '.gitattributes');
};

MariaGenerator.prototype.bower = function bower() {
  this.template('bowerrc', '.bowerrc');
  this.template('_bower.json', 'bower.json');
};

MariaGenerator.prototype.packageJSON = function packageJSON() {
  this.template('_package.json', 'package.json');
};

MariaGenerator.prototype.gruntfile = function gruntfile() {
  if (this.testFramework === 'jasmine') {
    this.write('Gruntfile.js', this.engine(this.read('Gruntfile.js')).replace(/mocha/g, 'jasmine'));
  } else {
    this.template('Gruntfile.js');
  }
};

MariaGenerator.prototype.mainStylesheet = function mainStylesheet() {
  var appPath = this.config.get('appPath');
  if (this.compassBootstrap) {
    return this.template('main.scss', appPath + '/styles/main.scss');
  }
  var contentText = [
    'body {\n    background: #fafafa;\n}',
    '\n.hero-unit {\n    margin: 50px auto 0 auto;\n    width: 300px;\n}'
  ];
  this.write(appPath + '/styles/main.css', contentText.join('\n'));
};

MariaGenerator.prototype.writeIndex = function writeIndex() {
  this.indexFile = this.readFileAsString(path.join(this.sourceRoot(), 'app/index.html'));
  this.indexFile = this.engine(this.indexFile, this);

  var vendorJS = [
    'bower_components/jquery/jquery.js',
    'bower_components/maria/maria.js'
  ];

  this.indexFile = this.appendScripts(this.indexFile, 'scripts/vendor.js', vendorJS);

  if (this.compassBootstrap) {
    // wire Twitter Bootstrap plugins
    this.indexFile = this.appendScripts(this.indexFile, 'scripts/plugins.js', [
      'bower_components/sass-bootstrap/js/affix.js',
      'bower_components/sass-bootstrap/js/alert.js',
      'bower_components/sass-bootstrap/js/dropdown.js',
      'bower_components/sass-bootstrap/js/tooltip.js',
      'bower_components/sass-bootstrap/js/modal.js',
      'bower_components/sass-bootstrap/js/transition.js',
      'bower_components/sass-bootstrap/js/button.js',
      'bower_components/sass-bootstrap/js/popover.js',
      'bower_components/sass-bootstrap/js/carousel.js',
      'bower_components/sass-bootstrap/js/scrollspy.js',
      'bower_components/sass-bootstrap/js/collapse.js',
      'bower_components/sass-bootstrap/js/tab.js'
    ]);
  }

  this.indexFile = this.appendFiles({
    html: this.indexFile,
    fileType: 'js',
    searchPath: ['.tmp', 'app'],
    optimizedPath: 'scripts/main.js',
    sourceFileList: [
      'scripts/namespace.js'
    ]
  });
  var appPath = this.config.get('appPath');
  this.write(appPath + '/index.html', this.indexFile);
};

MariaGenerator.prototype.namespaceJs = function namespaceJs() {
  var appPath = this.config.get('appPath');
  var dirPath = this.options.coffee ? '../templates/coffeescript/' : '../templates';
  var ext = this.options.coffee ? 'coffee' : 'js';
  this.sourceRoot(path.join(__dirname, dirPath));
  this.template('app.' + ext, appPath + '/scripts/namespace.' + ext);
};


text:
import React from 'react';
import ReactDOM from 'react-dom';

window.React = React;

import App from './components/App';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);


text:
/**
 * @module SOCIAL
 */
 var SOCIAL = (function (SOCIAL) {

    /**
     * @property breadcrumbs
     * @type {{content: string, title: string, isValid: isValid, href: string}[]}
     *
     * Data structure that defines the sub-level tabs for
     * our plugin, used by the navbar controller to show
     * or hide tabs based on some criteria
     */
     SOCIAL.breadcrumbs = [
     {
      content: ' User',
      title: "Search info about a Twitter User",
      isValid: function () { return true; },
      href: "#/social/user"
    },
    {
      content: ' Tweets',
      title: "Search Tweets based on keywords",
      isValid: function () { return true; },
      href: "#/social/tweets"
    }
    ];

    /**
     * @function NavBarController
     *
     * @param $scope
     *
     * The controller for this plugin's navigation bar
     *
     */
     SOCIAL.NavBarController = function ($scope, workspace) {

      $scope.breadcrumbs = SOCIAL.breadcrumbs;
      $scope.hash = workspace.hash();

      $scope.$on('$routeChangeSuccess', function () {
        $scope.hash = workspace.hash();
      });

      $scope.isValid = function(link) {
        return true;
      };

      $scope.isActive = function (href) {
        return workspace.isLinkActive(href);
      };
    };

    return SOCIAL;

  }(SOCIAL || { }));


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <property name="jnlp.title"    value="JST SearchBox" />
  <property name="jnlp.Name"     value="SearchBox" />
  <property name="jnlp.name"     value="searchbox" />
  <property name="jnlp.codebase" value="https://ateraimemo.com/swing/searchbox/" />
  <property name="jnlp.homepage" value="https://ateraimemo.com/Swing/SearchBox.html" />
</project>


text: <div<?php echo $attributes;?>><?php echo $text;?></div>


text:
import abc
from enum import Enum
from typing import List, Union

from pyflink.datastream.connectors import Sink, DeliveryGuarantee
from pyflink.java_gateway import get_gateway
from pyflink.util.java_utils import to_jarray

__all__ = ['FlushBackoffType',
           'ElasticsearchEmitter',
           'Elasticsearch6SinkBuilder',
           'Elasticsearch7SinkBuilder',
           'ElasticsearchSink']

class FlushBackoffType(Enum):
    """
    Used to control whether the sink should retry failed requests at all or with which kind back off
    strategy.

    :data: `CONSTANT`:

    After every failure, it waits a configured time until the retries are exhausted.

    :data: `EXPONENTIAL`:

    After every failure, it waits initially the configured time and increases the waiting time
    exponentially until the retries are exhausted.

    :data: `NONE`:

    The failure is not retried.
    """

    CONSTANT = 0,
    EXPONENTIAL = 1,
    NONE = 2,

    def _to_j_flush_backoff_type(self):
        JFlushBackoffType = get_gateway().jvm \
            .org.apache.flink.connector.elasticsearch.sink.FlushBackoffType
        return getattr(JFlushBackoffType, self.name)

class ElasticsearchEmitter(object):
    """
    Emitter which is used by sinks to prepare elements for sending them to Elasticsearch.
    """

    def __init__(self, j_emitter):
        self._j_emitter = j_emitter

    @staticmethod
    def static_index(index: str, key_field: str = None, doc_type: str = None) \
            -> 'ElasticsearchEmitter':
        """
        Creates an emitter with static index which is invoked on every record to convert it to
        Elasticsearch actions.
        """
        JMapElasticsearchEmitter = get_gateway().jvm \
            .org.apache.flink.connector.elasticsearch.sink.MapElasticsearchEmitter
        j_emitter = JMapElasticsearchEmitter(index, doc_type, key_field, False)
        return ElasticsearchEmitter(j_emitter)

    @staticmethod
    def dynamic_index(index_field: str, key_field: str = None, doc_type: str = None) \
            -> 'ElasticsearchEmitter':
        """
        Creates an emitter with dynamic index which is invoked on every record to convert it to
        Elasticsearch actions.
        """
        JMapElasticsearchEmitter = get_gateway().jvm \
            .org.apache.flink.connector.elasticsearch.sink.MapElasticsearchEmitter
        j_emitter = JMapElasticsearchEmitter(index_field, doc_type, key_field, True)
        return ElasticsearchEmitter(j_emitter)

class ElasticsearchSinkBuilderBase(abc.ABC):
    """
    Base builder to construct a ElasticsearchSink.
    """

    @abc.abstractmethod
    def __init__(self):
        self._j_elasticsearch_sink_builder = None

    @abc.abstractmethod
    def get_http_host_class(self):
        """
        Gets the org.apache.http.HttpHost class which path is different in different Elasticsearch
        version.
        """
        pass

    def set_emitter(self, emitter: ElasticsearchEmitter) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the emitter which is invoked on every record to convert it to Elasticsearch actions.

        :param emitter: The emitter to process records into Elasticsearch actions.
        """
        self._j_elasticsearch_sink_builder.setEmitter(emitter._j_emitter)
        return self

    def set_hosts(self, hosts: Union[str, List[str]]) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the hosts where the Elasticsearch cluster nodes are reachable.
        """
        if not isinstance(hosts, list):
            hosts = [hosts]
        JHttpHost = self.get_http_host_class()
        j_http_hosts_list = [JHttpHost.create(x) for x in hosts]
        j_http_hosts_array = to_jarray(JHttpHost, j_http_hosts_list)
        self._j_elasticsearch_sink_builder.setHosts(j_http_hosts_array)
        return self

    def set_delivery_guarantee(self, delivery_guarantee: DeliveryGuarantee) \
            -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the wanted DeliveryGuarantee. The default delivery guarantee is DeliveryGuarantee#NONE
        """
        j_delivery_guarantee = delivery_guarantee._to_j_delivery_guarantee()
        self._j_elasticsearch_sink_builder.setDeliveryGuarantee(j_delivery_guarantee)
        return self

    def set_bulk_flush_max_actions(self, num_max_actions: int) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the maximum number of actions to buffer for each bulk request. You can pass -1 to
        disable it. The default flush size 1000.
        """
        self._j_elasticsearch_sink_builder.setBulkFlushMaxActions(num_max_actions)
        return self

    def set_bulk_flush_max_size_mb(self, max_size_mb: int) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the maximum size of buffered actions, in mb, per bulk request. You can pass -1 to
        disable it.
        """
        self._j_elasticsearch_sink_builder.setBulkFlushMaxSizeMb(max_size_mb)
        return self

    def set_bulk_flush_interval(self, interval_millis: int) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the bulk flush interval, in milliseconds. You can pass -1 to disable it.
        """
        self._j_elasticsearch_sink_builder.setBulkFlushInterval(interval_millis)
        return self

    def set_bulk_flush_backoff_strategy(self,
                                        flush_backoff_type: FlushBackoffType,
                                        max_retries: int,
                                        delay_millis: int) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the type of back off to use when flushing bulk requests. The default bulk flush back
        off type is FlushBackoffType#NONE.

        Sets the amount of delay between each backoff attempt when flushing bulk requests, in
        milliseconds.

        Sets the maximum number of retries for a backoff attempt when flushing bulk requests.
        """
        self._j_elasticsearch_sink_builder.setBulkFlushBackoffStrategy(
            flush_backoff_type._to_j_flush_backoff_type(), max_retries, delay_millis)
        return self

    def set_connection_username(self, username: str) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the username used to authenticate the connection with the Elasticsearch cluster.
        """
        self._j_elasticsearch_sink_builder.setConnectionUsername(username)
        return self

    def set_connection_password(self, password: str) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the password used to authenticate the connection with the Elasticsearch cluster.
        """
        self._j_elasticsearch_sink_builder.setConnectionPassword(password)
        return self

    def set_connection_path_prefix(self, prefix: str) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets a prefix which used for every REST communication to the Elasticsearch cluster.
        """
        self._j_elasticsearch_sink_builder.setConnectionPathPrefix(prefix)
        return self

    def set_connection_request_timeout(self, timeout: int) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the timeout for requesting the connection of the Elasticsearch cluster from the
        connection manager.
        """
        self._j_elasticsearch_sink_builder.setConnectionRequestTimeout(timeout)
        return self

    def set_connection_timeout(self, timeout: int) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the timeout for establishing a connection of the Elasticsearch cluster.
        """
        self._j_elasticsearch_sink_builder.setConnectionTimeout(timeout)
        return self

    def set_socket_timeout(self, timeout: int) -> 'ElasticsearchSinkBuilderBase':
        """
        Sets the timeout for waiting for data or, put differently, a maximum period inactivity
        between two consecutive data packets.
        """
        self._j_elasticsearch_sink_builder.setSocketTimeout(timeout)
        return self

    def build(self) -> 'ElasticsearchSink':
        """
        Constructs the ElasticsearchSink with the properties configured this builder.
        """
        return ElasticsearchSink(self._j_elasticsearch_sink_builder.build())

class Elasticsearch6SinkBuilder(ElasticsearchSinkBuilderBase):
    """
    Builder to construct an Elasticsearch 6 compatible ElasticsearchSink.

    The following example shows the minimal setup to create a ElasticsearchSink that submits
    actions on checkpoint or the default number of actions was buffered (1000).

    Example:
    ::

        >>> sink = Elasticsearch6SinkBuilder() \\
        ...     .set_hosts('localhost:9200') \\
        ...     .set_emitter(ElasticsearchEmitter.static_index("user", "key_col")) \\
        ...     .build()
    """

    def __init__(self):
        self._j_elasticsearch_sink_builder = get_gateway().jvm \
            .org.apache.flink.connector.elasticsearch.sink.Elasticsearch6SinkBuilder()

    def get_http_host_class(self):
        return get_gateway().jvm.org.apache.flink.elasticsearch6.shaded.org.apache.http.HttpHost

class Elasticsearch7SinkBuilder(ElasticsearchSinkBuilderBase):
    """
    Builder to construct an Elasticsearch 7 compatible ElasticsearchSink.

    The following example shows the minimal setup to create a ElasticsearchSink that submits
    actions on checkpoint or the default number of actions was buffered (1000).

    Example:
    ::

        >>> sink = Elasticsearch7SinkBuilder() \\
        ...     .set_hosts('localhost:9200') \\
        ...     .set_emitter(ElasticsearchEmitter.dynamic_index("index_col", "key_col")) \\
        ...     .build()
    """

    def __init__(self):
        self._j_elasticsearch_sink_builder = get_gateway().jvm \
            .org.apache.flink.connector.elasticsearch.sink.Elasticsearch7SinkBuilder()

    def get_http_host_class(self):
        return get_gateway().jvm.org.apache.flink.elasticsearch7.shaded.org.apache.http.HttpHost

class ElasticsearchSink(Sink):
    """
    Flink Sink to insert or update data in an Elasticsearch index. The sink supports the following
    delivery guarantees.

    DeliveryGuarantee.NONE does not provide any guarantees: actions are flushed to Elasticsearch
    only depending on the configurations of the bulk processor. In case of a failure, it might
    happen that actions are lost if the bulk processor still has buffered actions.

    DeliveryGuarantee.AT_LEAST_ONCE on a checkpoint the sink will wait until all buffered actions
    are flushed to and acknowledged by Elasticsearch. No actions will be lost but actions might be
    sent to Elasticsearch multiple times when Flink restarts. These additional requests may cause
    inconsistent data in ElasticSearch right after the restart, but eventually everything will be
    consistent again.
    """
    def __init__(self, j_elasticsearch_sink):
        super(ElasticsearchSink, self).__init__(sink=j_elasticsearch_sink)


text:
* Name      : Nick Heiner
* Twitter   : [@nickheiner](https://twitter.com/nickheiner)
* GitHub    : [nickheiner](https://github.com/nickheiner)

##Abstract

Grunt is a powerful tool for automating your build process. It's simple enough to hack together a task in a few minutes, but what makes a task that other people will want to use, and that you'll want to use three months from now? As someone who's been writing grunt tasks in my day job almost exclusively for the past year, I've exhaustively explored all the ways to shoot yourself in the foot. In this talk, I'll share my experiences and lessons learned on how to do it right the first time.

I previously spoke at the [angularjs-dc meetup](http://www.meetup.com/AngularJS-DC/events/162821672/) about Grunt.
[Here are the slides](http://nickheiner.github.io/gruntled-talk).

##Speaker Bio

![Nick profile pic](https://avatars1.githubusercontent.com/u/829827?s=250)

Nick is a web developer at [Opower](http://www.opower.com), where he uses node.js and angular to help people better understand
(and thereby reduce) their energy usage. He lives near Washington DC and enjoys speaking at local meetups.
Prior to Opower, he interned at Google and Microsoft. Nick has contributed to open source projects such as
Bower, Foundation, and Chai.


text:
<?php

declare(strict_types=1);

namespace Brain\Hierarchy\Branch;

/**
 * @author  Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
 * @license http://opensource.org/licenses/MIT MIT
 */
final class BranchPrivacyPolicy implements Branch
{
    /**
     * @return string
     */
    public function name(): string
    {
        return 'privacy_policy';
    }

    /**
     * @param \WP_Query $query
     * @return bool
     */
    public function is(\WP_Query $query): bool
    {
        return $query->is_privacy_policy();
    }

    /**
     * @param \WP_Query $query
     * @return list<string>
     */
    public function leaves(\WP_Query $query): array
    {
        return ['privacy-policy'];
    }
}


text:
class IndexedDBKey {
 public:
  IndexedDBKey(); // Defaults to WebKit::WebIDBKey::InvalidType.
  explicit IndexedDBKey(const WebKit::WebIDBKey& key);
  ~IndexedDBKey();

  void SetNull();
  void SetInvalid();
  void SetString(const string16& string);
  void SetDate(double date);
  void SetNumber(double number);
  void Set(const WebKit::WebIDBKey& key);

  WebKit::WebIDBKey::Type type() const { return type_; }
  const string16& string() const { return string_; }
  double date() const { return date_; }
  double number() const { return number_; }

  operator WebKit::WebIDBKey() const;

 private:
  WebKit::WebIDBKey::Type type_;
  string16 string_;
  double date_;
  double number_;
};

#endif  // CONTENT_COMMON_INDEXED_DB_KEY_H_


text:
require 'test_helper'

class ShortUrlsShowTest < ActionDispatch::IntegrationTest
  def setup
    @admin = users(:cthulhu)
    @short_url = short_urls(:hits_test)
    log_in_as(@admin)
  end

  test 'shows slug as heading' do
    get short_url_path(@short_url)
    assert_select 'h2', @short_url.slug
  end

  test 'shows edit and delete buttons' do
    get short_url_path(@short_url)
    assert_select 'a[href=?]', edit_short_url_path(@short_url)
    assert_select 'a[href=?]', delete_short_url_path(@short_url)
  end

  test 'shows stats' do
    get short_url_path(@short_url)
    assert_select 'div.short-url-stats', 1
    assert_select 'div.short-url-stat', 2
    assert_select 'span.stat-gloss', 2
    assert_select 'span.stat-entry', 2
  end
end


text:
class Profile;

namespace user_prefs {
class PrefRegistrySyncable;
}

namespace gcm {

class GCMClientFactory;
class GCMDriver;

// Providing GCM service, via GCMDriver, to a profile.
class GCMProfileService : public KeyedService {
 public:
  // Returns whether GCM is enabled for |profile|.
  static bool IsGCMEnabled(Profile* profile);

  // Register profile-specific prefs for GCM.
  static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);

#if defined(OS_ANDROID)
  explicit GCMProfileService(Profile* profile);
#else
  GCMProfileService(Profile* profile,
                    scoped_ptr<GCMClientFactory> gcm_client_factory);
#endif
  virtual ~GCMProfileService();

  // TODO(jianli): obsolete methods that are going to be removed soon.
  void AddAppHandler(const std::string& app_id, GCMAppHandler* handler);
  void RemoveAppHandler(const std::string& app_id);
  void Register(const std::string& app_id,
                const std::vector<std::string>& sender_ids,
                const GCMDriver::RegisterCallback& callback);

  // KeyedService:
  virtual void Shutdown() OVERRIDE;

  // Returns the user name if the profile is signed in or an empty string
  // otherwise.
  // TODO(jianli): To be removed when sign-in enforcement is dropped.
  std::string SignedInUserName() const;

  // For testing purpose.
  void SetDriverForTesting(GCMDriver* driver);

  GCMDriver* driver() const { return driver_.get(); }

  content::PushMessagingService* push_messaging_service() {
    return &push_messaging_service_;
  }

 protected:
  // Used for constructing fake GCMProfileService for testing purpose.
  GCMProfileService();

 private:
  // The profile which owns this object.
  Profile* profile_;

  scoped_ptr<GCMDriver> driver_;

  // Implementation of content::PushMessagingService using GCMProfileService.
  PushMessagingServiceImpl push_messaging_service_;

  // TODO(jianli): To be removed when sign-in enforcement is dropped.
#if !defined(OS_ANDROID)
  class IdentityObserver;
  scoped_ptr<IdentityObserver> identity_observer_;
#endif

  DISALLOW_COPY_AND_ASSIGN(GCMProfileService);
};

}  // namespace gcm

#endif  // CHROME_BROWSER_SERVICES_GCM_GCM_PROFILE_SERVICE_H_


text:
package cliente.appsamblea.database;

/**
 * Created by carlos on 15/03/15.
 */
public class TurnoPalabra {
}


text:
describe('Directive: User Directive', function() {
    'use strict';

    beforeEach(module('brewbear-component', 'brewbear-services',
        'brewbear-templates'));

    beforeEach(inject(function($rootScope, $compile, $httpBackend,
        UserService, $q, $timeout) {
        this.mockScope = $rootScope.$new();
        this.$httpBackend = $httpBackend;
        this.$compile = $compile;
        this.$timeout = $timeout;
        this.$q = $q;
        this.UserService = UserService;

        var vm = this;
        spyOn(this.UserService, 'getUser').and.callFake(function() {
            return vm.$q.resolve({
                user: {
                    id: 1,
                    name: 'Test',
                    email: 'test@dot.com'
                }
            });
        });

        this.initDirective = function() {
            this.element = this.$compile('<user-account class="account-dir">' +
                '</user-account>')(this.mockScope);
            this.mockScope.$apply();
        };
    }));

    describe('directive initialization - ', function() {
        it('verifies the directive was instantiated', function() {
            this.initDirective();

            expect(this.element).toBeDefined();
            expect(this.element.hasClass('account-dir')).toEqual(true);

            this.$timeout.flush();
            var controller = this.element.controller('userAccount');
            expect(controller.user).toEqual({
                id: 1,
                name: 'Test',
                email: 'test@dot.com'
            });
            expect(this.UserService.getUser.calls.count()).toEqual(1);
        });
    });

    describe('updating a user', function() {
        var vm;
        beforeEach(function() {
            this.initDirective();
            this.controller = this.element.controller('userAccount');
            this.$timeout.flush();
            vm = this;
        });

        it('does nothing if the form is not valid', function() {
            spyOn(this.UserService, 'updateUser');
            this.controller.saveChanges(false);

            expect(this.UserService.updateUser).not.toHaveBeenCalled();
        });

        it('Returns a success message correctly', function() {
            spyOn(this.UserService, 'updateUser').and.callFake(function() {
                return vm.$q.resolve({
                    error: false
                });
            });
            expect(this.controller.message).not.toBeDefined();

            this.controller.saveChanges(true);
            this.$timeout.flush(2000);

            expect(this.controller.message.error).toEqual(false);

            this.$timeout.flush(3000);
            expect(this.controller.message).not.toBeDefined();
        });

        it('returns an error message correctly', function() {
            spyOn(this.UserService, 'updateUser').and.callFake(function() {
                return vm.$q.resolve({
                    error: true
                });
            });

            expect(this.controller.message).not.toBeDefined();

            this.controller.saveChanges(true);
            this.$timeout.flush(2000);

            expect(this.controller.message.error).toEqual(true);

            this.$timeout.flush(3000);
            expect(this.controller.message).not.toBeDefined();
        });
    });
});


text:
import { Laya } from "Laya";
import { Camera } from "laya/d3/core/Camera";
import { DirectionLight } from "laya/d3/core/light/DirectionLight";
import { Scene3D } from "laya/d3/core/scene/Scene3D";
import { Sprite3D } from "laya/d3/core/Sprite3D";
import { Vector3 } from "laya/d3/math/Vector3";
import { Stage } from "laya/display/Stage";
import { Loader } from "laya/net/Loader";
import { Handler } from "laya/utils/Handler";
import { Stat } from "laya/utils/Stat";
import { Laya3D } from "Laya3D";
import { CameraMoveScript } from "../common/CameraMoveScript";

export class SkinnedMeshSprite3DDemo {
	private scene: Scene3D;

	constructor() {
		//初始化引擎
		Laya3D.init(0, 0);
		Laya.stage.scaleMode = Stage.SCALE_FULL;
		Laya.stage.screenMode = Stage.SCREEN_NONE;
		//显示性能面板
		Stat.show();

		//创建场景
		this.scene = (<Scene3D>Laya.stage.addChild(new Scene3D()));

		//创建相机
		var camera: Camera = (<Camera>this.scene.addChild(new Camera(0, 0.1, 100)));
		camera.transform.translate(new Vector3(0, 0.5, 1));
		camera.transform.rotate(new Vector3(-15, 0, 0), true, false);
		camera.addComponent(CameraMoveScript);

		//添加光照
		var directionLight: DirectionLight = (<DirectionLight>this.scene.addChild(new DirectionLight()));
		directionLight.color = new Vector3(1, 1, 1);
		directionLight.transform.rotate(new Vector3(-3.14 / 3, 0, 0));

		//预加载资源
		Laya.loader.create("res/threeDimen/skinModel/dude/dude.lh", Handler.create(this, this.onComplete));

	}

	onComplete(): void {
		//添加父级猴子
		var dude: Sprite3D = (<Sprite3D>this.scene.addChild(Loader.getRes("res/threeDimen/skinModel/dude/dude.lh")));
		//缩放
		var scale: Vector3 = new Vector3(0.1, 0.1, 0.1);
		dude.transform.localScale = scale;
		dude.transform.rotate(new Vector3(0, 3.14, 0));
	}

}


text:
"Entrepreneurship Education in Schools: Empirical Evidence on the Teacher's Role" says that

"The findings indicate that the training teachers have received in entrepreneurship seems to be the main factor determining the observable entrepreneurship education provided by the teachers."

%\citepp{entrepreneurship-pihkala}

% "The teacher is the central actor in entrepreneurship education and the teachers' role in defining the time, frequency, contents and methods of entrepreneurship education is decisive. (Fiet, 2001a; Jones, 2010; Lobler, 2006; Seikkula-Leino, Rusko- vaara, Ikavalko, Mattila, \& Rytkola, 2010; Ruskovaara \& Pihkala, 2013)."

\textbf{Considerations for digital learning}
The playful side of teaching and learning (Solomon, 2007) as well as teacher training that develops the competences of a mentor, enabler, or coach should enhance entrepreneurship education practices.
\todo{Svara på i Genomförande. Relevancy of "fun"}

When shifting the focus from Gibb's (2002) idea of developing students' understanding of entrepreneurship to the teacher, what are the ways for a teacher to see, feel, do, think, and learn entrepreneurship? How to provide teachers with the skills to cope with, create, and perhaps enjoy uncertainty and complexity?
\todo{Svara på i Analys}
\todo{Refer to entrepreneurship definition}

%\subsection{Proposition}
%On this basis, we formulate the following proposition:

%Proposition 1: Entrepreneurship education practices do not differ between male and female teachers.

% Teachers' business enterprise background's positive effect on entrepreneurship education.

%Proposition 2: The stronger the teacher's business background is, the more he/she is bound to execute entrepreneurship education.

%Proposition 3: The more the teacher has work experience, the more he/she is inclined to conduct entrepreneurship education.

%Proposition 4: Entrepreneurship education differs between education levels.

%Proposition 5: Enterprise-related teacher training positively affects teachers' entrepreneurship education practices.

\textbf{Result}

\textbf{Teachers' gender and entrepreneurship education practices}
Even though we have found studies with a feminist approach to entrepreneurship education and studies concerning women entrepreneurs (Komulainen, Keskitalo-Foley, Korhonen, \& Lappalainen, 2010; Korhonen, 2012), their findings do not show any indications of differences or similarities between women and men. According to Bennett (2006), a lecturer's gender does not play a significant role in inclining entrepreneurship education.

% Viktigt för YoungDrive, såklart!
\textbf{The teacher's professional teaching experience has no significance in terms of entrepreneurship education.} These findings suggest that as a competence area, entrepreneurship education is not dependent on the teacher's experience as a teacher.

\textbf{Entrepreneurship education correlates positively with entrepreneurial activity} according to Dickson et al. (2008).
\todo{Kommentera i Analys}

% Elena Ruskovaara is working as a researcher, lecturer, and project manager at Lappeenranta University of Tech- nology. For the past 15 years, she has worked in the field of further education for teachers and has been involved in many national and international entrepreneurship proj- ects. Her main interests are entrepreneurship education and especially the challenges of measuring and evaluating entrepreneurship education.

% A large number of useful methods and practices have been discovered (Seikkula-Leino, 2007), and training concerning different pedagogical solutions could be of great value.


text:
unless defined?(JRUBY_VERSION)
  require 'simplecov'
  require 'coveralls'

  SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
    SimpleCov::Formatter::HTMLFormatter,
    Coveralls::SimpleCov::Formatter
  ]

  SimpleCov.start do
    project_name 'thread_safe'

    add_filter '/examples/'
    add_filter '/pkg/'
    add_filter '/test/'
    add_filter '/tasks/'
    add_filter '/yard-template/'
    add_filter '/yardoc/'

    command_name 'Mintest'
  end
end

require 'minitest/autorun'

require 'minitest/reporters'
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new(color: true)

require 'thread'
require 'thread_safe'

THREADS = (RUBY_ENGINE == 'ruby' ? 100 : 10)

if defined?(JRUBY_VERSION) && ENV['TEST_NO_UNSAFE']
  # to be used like this: rake test TEST_NO_UNSAFE=true
  load 'test/package.jar'
  java_import 'thread_safe.SecurityManager'
  manager = SecurityManager.new

  # Prevent accessing internal classes
  manager.deny java.lang.RuntimePermission.new("accessClassInPackage.sun.misc")
  java.lang.System.setSecurityManager manager

  class TestNoUnsafe < Minitest::Test
    def test_security_manager_is_used
      begin
        java_import 'sun.misc.Unsafe'
        flunk
      rescue SecurityError
      end
    end

    def test_no_unsafe_version_of_chmv8_is_used
      require 'thread_safe/jruby_cache_backend' # make sure the jar has been loaded
      assert !Java::OrgJrubyExtThread_safe::JRubyCacheBackendLibrary::JRubyCacheBackend::CAN_USE_UNSAFE_CHM
    end
  end
end

module ThreadSafe
  module Test
    class Latch
      def initialize(count = 1)
        @count = count
        @mutex = Mutex.new
        @cond  = ConditionVariable.new
      end

      def release
        @mutex.synchronize do
          @count -= 1 if @count > 0
          @cond.broadcast if @count.zero?
        end
      end

      def await
        @mutex.synchronize do
          @cond.wait @mutex if @count > 0
        end
      end
    end

    class Barrier < Latch
      def await
        @mutex.synchronize do
          if @count.zero? # fall through
          elsif @count > 0
            @count -= 1
            @count.zero? ? @cond.broadcast : @cond.wait(@mutex)
          end
        end
      end
    end

    class HashCollisionKey
      attr_reader :hash, :key
      def initialize(key, hash = key.hash % 3)
        @key  = key
        @hash = hash
      end

      def eql?(other)
        other.kind_of?(self.class) && @key.eql?(other.key)
      end

      def even?
        @key.even?
      end

      def <=>(other)
        @key <=> other.key
      end
    end

    # having 4 separate HCK classes helps for a more thorough CHMV8 testing
    class HashCollisionKey2 < HashCollisionKey; end
    class HashCollisionKeyNoCompare < HashCollisionKey
      def <=>(other)
        0
      end
    end
    class HashCollisionKey4 < HashCollisionKeyNoCompare; end

    HASH_COLLISION_CLASSES = [HashCollisionKey, HashCollisionKey2, HashCollisionKeyNoCompare, HashCollisionKey4]

    def self.HashCollisionKey(key, hash = key.hash % 3)
      HASH_COLLISION_CLASSES[rand(4)].new(key, hash)
    end

    class HashCollisionKeyNonComparable < HashCollisionKey
      undef <=>
    end
  end
end


text:
package org.jetbrains.plugins.scala
package lang
package psi
package api
package expr

import org.jetbrains.plugins.scala.lang.psi.api.base.ScConstructor
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScTemplateDefinition

/**
* @author Alexander Podkhalyuzin
* Date: 06.03.2008
*/
trait ScNewTemplateDefinition extends ScExpression with ScTemplateDefinition {
  def constructor: Option[ScConstructor]

  //It's very rare case, when we need to desugar apply first.
  def desugaredApply: Option[ScExpression]

  override def getTextOffset: Int = extendsBlock.getTextOffset
}


text:
<?php

namespace Apine\Core;

/**
 * Cookie writing and reading tool
 *
 * Tool to easily read and write cookies
 */
final class Cookie {

	/**
	 * Get cookie by name
	 *
	 * @param string $cookie_name
	 * @return string
	 */
	public static function get ($cookie_name) {

		if (isset($_COOKIE[$cookie_name]))
			return $_COOKIE[$cookie_name];

	}

	/**
	 * Set a new cookie value
	 *
	 * @param string $cookie_name
	 * @param string $value
	 * @param integer $expiration_time
	 *        Expiration date in miliseconds
	 * @return boolean
	 */
	public static function set ($cookie_name, $value, $expiration_time = 0) {

		$ar_domain = explode('.', $_SERVER['SERVER_NAME']);

		if (count($ar_domain) >= 3) {
			$start = strlen($ar_domain[0]) + 1;
			$main_session_server = substr($_SERVER['SERVER_NAME'], $start);
		} else {
			$main_session_server = $_SERVER['SERVER_NAME'];
		}

		if ($expiration_time == 0) {
			return setcookie($cookie_name, $value, null, '/');
		}else {
			return setcookie($cookie_name, $value, $expiration_time, '/');
		}

	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML3.2 EN">

<META NAME="GENERATOR" CONTENT="DOCTEXT">
<TITLE>MPE_IO_Stdout_to_file</TITLE>

MPE_IO_Stdout_to_file

Re-direct stdout to a file

Synopsis

void MPE_IO_Stdout_to_file( char *name, int mode )

Parameters

name
Name of file.  If it contains '%d', this value will be replaced with
the rank of the process in 'MPI_COMM_WORLD'.

mode
Mode to open the file in (see the man page for 'open').  A common
value is '0644' (Read/Write for owner, Read for everyone else).
Note that this
value is `anded` with your current 'umask' value.

Notes

Some systems may complain when standard output ('stdout') is closed.

Location:../src/misc/src/mpe_io.c


text:
Below are instructions for setting up optional features of CityVoice. These instructions assume you've deployed using Heroku as detailed in the [Deploying on Heroku](README.md#deploying-on-heroku) documentation.

## Email notifications

Add the free Sendgrid Heroku addon:

    $ heroku addons:add sendgrid:starter

Add the Heroku scheduled jobs addon:

    $ heroku addons:add scheduler:standard

An example for setting this up on Heroku with a custom domain of `myappdomain.com`:

    $ heroku config:set APP_URL=http://www.myappdomain.com

Then, open the Heroku scheduled jobs console:

    $ heroku addons:open scheduler

Once in the web interface, set up a new scheduled job with the `rake notifications:task` to be run at whatever interval you want.

## Custom map tiles

By default, CityVoice uses Mapquest's free map tiles. Alternately, you can use [Mapbox](https://mapbox.com) to design your own custom map tiles.

You can do this by creating a map on Mapbox and setting the map ID in the `MAPBOX_MAP_ID` environment variable. For example:

	$ heroku config:set MAPBOX_MAP_ID=mymapidgoeshere

## Google Analytics

In production, you may want to set up Google Analytics with the environment variable used as a flag:

    $ heroku config:set GOOGLE_ANALYTICS_ID=foo123

## Password protection

If you want collect telephone feedback but keep the web interface provide, you can password-protect the web site by setting the following environment variables:

    $ heroku config:set LOCK_CITYVOICE=true
    $ heroku config:set CITYVOICE_LOCK_USERNAME=xxxxxxxxxx
    $ heroku config:set CITYVOICE_LOCK_PASSWORD=`rake secret`

If you forget the username or password, you can always find them again with the Heroku utility:

    $ heroku config
          CITYVOICE_LOCK_USERNAME=very-clever-name
          CITYVOICE_LOCK_PASSWORD=8974ijhdf98sydfkjshdfher0sdufkjshdfkj


text:
package com.imrenagi.service_auth.config;

import com.imrenagi.service_auth.service.security.MysqlUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

/**
 * Created by imrenagi on 5/11/17.
 */
//@Configuration
//@EnableAuthorizationServer
public class InMemoryOAuth2Config extends AuthorizationServerConfigurerAdapter {

    private TokenStore tokenStore = new InMemoryTokenStore();

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Autowired
    private MysqlUserDetailsService userDetailsService;

    @Autowired
    private Environment env;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("browser")
                .authorizedGrantTypes("refresh_token", "password")
                .scopes("ui")
                .and()
                .withClient("service-account")
                .secret(env.getProperty("SERVICE_ACCOUNT_PASSWORD"))
                .authorizedGrantTypes("client_credentials", "refresh_token")
                .scopes("server");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .tokenStore(this.tokenStore)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }
}


text:
CKEDITOR.plugins.setLang( 'removeformat', 'bs', {
	toolbar: 'Poništi format'
} );


text:
<?php
/**
 * Handles the view functionality of our MVC framework
 */
class LoginView extends View
{

} //end class


text:
using EOLib.Domain.Protocol;
using EOLib.Net;

namespace EOLib.PacketHandlers.Init
{
    public interface IInitPacketHandler
    {
        InitReply Reply { get; }

        bool HandlePacket(IPacket packet);
    }
}


text:
package net.java.sip.communicator.service.keybindings;

import java.io.*;
import java.text.*;
import java.util.*;

import javax.swing.*;

/**
 * Convenience methods providing a quick means of loading and saving
 * keybindings. None preserve disabled mappings. The formats provided are as
 * follows:

 * SERIAL_HASH- Serialized hash map of bindings. Ordering is preserved if
 * available.

 * SERIAL_INPUT- Serialized input map of bindings.

 * PROPERTIES_PAIR- Persistence provided by java.util.Properties using plain
 * text key/value pairs.

 * PROPERTIES_XML- Persistence provided by java.util.Properties using its XML
 * format.
 *
 * @author Damian Johnson (atagar1@gmail.com)
 * @version September 21, 2007
 */
public enum Persistence
{
    SERIAL_HASH, SERIAL_INPUT, PROPERTIES_PAIRS, PROPERTIES_XML;

    private static final String PROPERTIES_COMMENT =
        "Keybindings (mapping of KeyStrokes to string representations of actions)";

    /**
     * Returns the enum representation of a string. This is case sensitive.
     *
     * @param str toString representation of this enum
     * @return enum associated with a string
     * @throws IllegalArgumentException if argument is not represented by this
     *             enum.
     */
    public static Persistence fromString(String str)
    {
        for (Persistence type : Persistence.values())
        {
            if (str.equals(type.toString()))
                return type;
        }
        throw new IllegalArgumentException();
    }

    /**
     * Attempts to load this type of persistent keystroke map from a given path.
     * This is unable to parse any null content.
     *
     * @param path absolute path to resource to be loaded
     * @return keybinding map reflecting file contents
     * @throws IOException if unable to load resource
     * @throws ParseException if unable to parse content
     */
    public LinkedHashMap<KeyStroke, String> load(String path)
        throws IOException,
        ParseException
    {
        return load(new FileInputStream(path));
    }

    /**
     * Attempts to load this type of persistent keystroke map from a given
     * stream. This is unable to parse any null content.
     *
     * @param input source of keybindings to be parsed
     * @return keybinding map reflecting file contents
     * @throws IOException if unable to load resource
     * @throws ParseException if unable to parse content
     */
    public LinkedHashMap<KeyStroke, String> load(InputStream input)
        throws IOException,
        ParseException
    {
        LinkedHashMap<KeyStroke, String> output =
            new LinkedHashMap<KeyStroke, String>();

        if (this == SERIAL_HASH || this == SERIAL_INPUT)
        {
            Object instance = null; // Loaded serialized object

            try
            {
                ObjectInputStream objectInput = new ObjectInputStream(input);
                instance = objectInput.readObject();
                objectInput.close();
            }
            catch (ClassNotFoundException exc)
            {
                throw new ParseException("Unable to load serialized content", 0);
            }

            if (this == SERIAL_HASH)
            {
                if (!(instance instanceof HashMap<?, ?>))
                {
                    throw new ParseException(
                        "Serialized resource doesn't represent a HashMap", 0);
                }

                HashMap<?, ?> mapping = (HashMap<?, ?>)instance;
                for (Object key : mapping.keySet())
                {
                    Object value = mapping.get(key);

                    if (key instanceof KeyStroke && value instanceof String)
                    {
                        output.put((KeyStroke) key, (String) value);
                    }
                    else
                    {
                        if (key == null || value == null)
                        {
                            throw new ParseException(
                                "Unable to load null content", 0);
                        }
                        else
                        {
                            StringBuilder message = new StringBuilder();
                            message
                                .append("Entry doesn't represent a keybinding: ");
                            message.append(key.getClass().getName());
                            message.append(" -> ");
                            message.append(value.getClass().getName());
                            message
                                .append("\nMust match KeyStroke -> String mapping");
                            throw new ParseException(message.toString(), 0);
                        }
                    }
                }
            }
            else
            {
                if (!(instance instanceof InputMap))
                {
                    throw new ParseException(
                        "Serialized resource doesn't represent an InputMap", 0);
                }

                InputMap mapping = (InputMap) instance;
                if (mapping.keys() != null)
                {
                    for (KeyStroke shortcut : mapping.keys())
                    {
                        if (shortcut == null || mapping.get(shortcut) == null)
                        {
                            throw new ParseException(
                                "Unable to load null content", 0);
                        }
                        else
                        {
                            output.put(shortcut, mapping.get(shortcut)
                                .toString());
                        }
                    }
                }
            }
        }
        else if (this == PROPERTIES_PAIRS || this == PROPERTIES_XML)
        {
            Properties properties = new Properties();
            if (this == PROPERTIES_PAIRS)
                properties.load(input);
            else if (this == PROPERTIES_XML)
                properties.loadFromXML(input);

            for (Object key : properties.keySet())
            {
                Object value = properties.get(key);

                if (key instanceof String && value instanceof String)
                {
                    KeyStroke keystroke = KeyStroke.getKeyStroke((String) key);
                    if (keystroke == null)
                    {
                        StringBuilder message = new StringBuilder();
                        message
                            .append("Unable to parse keystroke, see the getKeyStroke(String) method of ");
                        message.append(KeyStroke.class.getName());
                        message.append(" for proper format");
                        throw new ParseException(message.toString(), 0);
                    }
                    else
                    {
                        output.put(keystroke, (String) value);
                    }
                }
                else
                {
                    if (key == null || value == null)
                    {
                        throw new ParseException("Unable to load null content",
                            0);
                    }
                    else
                    {
                        StringBuilder message = new StringBuilder();
                        message
                            .append("Entry doesn't represent a keybinding: ");
                        message.append(key.getClass().getName());
                        message.append(" -> ");
                        message.append(value.getClass().getName());
                        message
                            .append("\nMust match String -> String mapping where the first string represents a keystroke");
                        throw new ParseException(message.toString(), 0);
                    }
                }
            }
        }

        input.close();
        return output;
    }

    /**
     * Writes the persistent state of the bindings to an output stream.
     *
     * @param output stream where persistent state should be written
     * @param bindings keybindings to be saved
     * @throws IOException if unable to save bindings
     * @throws UnsupportedOperationException if any keys or values of the
     *             binding are null
     */
    public void save(OutputStream output, Map<KeyStroke, String> bindings)
        throws IOException
    {
        for (KeyStroke key : bindings.keySet())
        {
            if (key == null || bindings.get(key) == null)
            {
                throw new UnsupportedOperationException(
                    "Invalid binding: Shortcuts and actions cannot be null");
            }
        }

        if (this == SERIAL_HASH || this == SERIAL_INPUT)
        {
            Object mapping; // Mapping to be serialized
            if (this == SERIAL_HASH)
                mapping = bindings;
            else
            {
                InputMap inputMap = new InputMap();
                for (KeyStroke shortcut : bindings.keySet())
                {
                    inputMap.put(shortcut, bindings.get(shortcut));
                }
                mapping = inputMap;
            }

            ObjectOutputStream objectOutput = new ObjectOutputStream(output);
            objectOutput.writeObject(mapping);
            objectOutput.flush();
            objectOutput.close();
        }
        else if (this == PROPERTIES_PAIRS || this == PROPERTIES_XML)
        {
            Properties properties = new Properties();
            for (KeyStroke shortcut : bindings.keySet())
            {
                properties.setProperty(shortcut.toString(), bindings
                    .get(shortcut));
            }

            if (this == PROPERTIES_PAIRS)
                properties.store(output, PROPERTIES_COMMENT);
            else
                properties.storeToXML(output, PROPERTIES_COMMENT);
        }
    }

    /**
     * Writes the persistent state of the bindings to a file.
     *
     * @param path absolute path to where bindings should be saved
     * @param bindings keybindings to be saved
     * @throws IOException if unable to save bindings
     * @throws UnsupportedOperationException if any keys or values of the
     *             binding are null
     */
    public void save(String path, Map<KeyStroke, String> bindings)
        throws IOException
    {
        FileOutputStream output = new FileOutputStream(path);
        try
        {
            save(output, bindings);
            output.flush();
            output.close();
        }
        catch (IOException exc)
        {
            output.flush();
            output.close();
            throw exc;
        }
        catch (UnsupportedOperationException exc)
        {
            output.flush();
            output.close();
            throw exc;
        }
    }

    /**
     * Provides the textual output of what this persistence format would save
     * given a set of bindings. This silently fails, returning null if unable to
     * generate output from bindings.
     *
     * @param bindings bindings for which to generate saved output
     * @return string reflecting what would be saved by this persistence format
     */
    public String getOutput(Map<KeyStroke, String> bindings)
    {
        /*-
         * This utilizes a rather lengthy chain of redirection to generate output as a string:
         * PipedOutputStream ->
         * PipedInputStream ->
         * Scanner ->
         * StringBuilder ->
         * String
         */

        PipedOutputStream pipeOut = new PipedOutputStream();
        PipedInputStream pipeIn = new PipedInputStream();
        Scanner scanner = new Scanner(pipeIn);

        try
        {
            pipeOut.connect(pipeIn);
            save(pipeOut, bindings);
            pipeOut.flush();
            pipeOut.close();

            StringBuilder builder = new StringBuilder();
            if (scanner.hasNextLine())
                builder.append(scanner.nextLine());
            while (scanner.hasNextLine())
            {
                builder.append("\n");
                builder.append(scanner.nextLine());
            }
            scanner.close();
            pipeIn.close();
            return builder.toString();
        }
        catch (IOException exc)
        {
            return null;
        }
        catch (UnsupportedOperationException exc)
        {
            return null;
        }
    }

    @Override
    public String toString()
    {
        if (this == SERIAL_HASH)
            return "Serialized Hash Map";
        else if (this == SERIAL_INPUT)
            return "Serialized Input Map";
        else if (this == PROPERTIES_XML)
            return "Properties XML";
        else
            return getReadableConstant(this.name());
    }

    /**
     * Provides a more readable version of constant names. Spaces replace
     * underscores and this changes the input to lowercase except the first
     * letter of each word. For instance, "RARE_CARDS" would become
     * "Rare Cards".
     *
     * @param input string to be converted
     * @return reader friendly variant of constant name
     */
    public static String getReadableConstant(String input)
    {
        char[] name = input.toCharArray();

        boolean isStartOfWord = true;
        for (int i = 0; i < name.length; ++i)
        {
            char chr = name[i];
            if (chr == '_')
                name[i] = ' ';
            else if (isStartOfWord)
                name[i] = Character.toUpperCase(chr);
            else
                name[i] = Character.toLowerCase(chr);
            isStartOfWord = chr == '_';
        }

        return new String(name);
    }
}