text:
package com.bmj.greader.ui.module.repo.adapter;

import android.media.Image;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bmj.greader.R;
import com.bmj.greader.common.wrapper.ImageLoader;
import com.bmj.greader.data.model.MultiItem;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

/**
 * Created by Administrator on 2016/12/26 0026.
 */
public class SearchUserRecyclerAdapter extends BaseMultiItemQuickAdapter<MultiItem> {

    public SearchUserRecyclerAdapter(List<MultiItem> data){
        super(data);
        addItemType(MultiItem.SMALL,R.layout.item_user3);
        addItemType(MultiItem.LARGE,R.layout.item_user3);
    }

    @Override
    protected void convert(BaseViewHolder holder, MultiItem user) {
        switch (holder.getItemViewType()){
            case MultiItem.SMALL:
                holder.getView(R.id.iu3_user_avatar_large).setVisibility(View.GONE);
                ImageLoader.load(user.getContent().getAvatar_url(),(ImageView)holder.getView(R.id.iu3_user_avatar_small));
                break;
            case MultiItem.LARGE:
                holder.getView(R.id.iu3_user_avatar_small).setVisibility(View.GONE);
                ImageLoader.load(user.getContent().getAvatar_url(),(ImageView)holder.getView(R.id.iu3_user_avatar_large));
                break;
        }
        holder.setText(R.id.iu3_user_login,user.getContent().getLogin());
    }
}


text:
package dialog;

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class IntegerTextField extends JTextField {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private long maxValue = Long.MAX_VALUE;

	private long minValue = 0;

	private int maxLength = String.valueOf(maxValue).length();

	private boolean isIPField = false;

	/**
	 * Default constructor for IntegerTextField.
	 */
	public IntegerTextField() {
		super();
	}

	protected Document createDefaultModel() {
		return new IntegerDocument();
	}

	public void setMinValue(long value) {
		minValue = value;
	}

	public long getMinValue() {
		return minValue;
	}

	public void setIPField(boolean value) {
		isIPField = value;
	}

	public boolean getIPField() {
		return isIPField;
	}

	public void setMaxValue(long value) {
		maxValue = value;
	}

	public long getMaxValue() {
		return maxValue;
	}

	public void setMaxLength(int value) {
		maxLength = value;
	}

	public int getMaxLength() {
		return maxLength;
	}

	private class IntegerDocument extends PlainDocument {
		/**
		 *
		 */
		private static final long serialVersionUID = 1L;

		public void insertString(int offs, String str, AttributeSet a)
				throws BadLocationException {
			long typedValue = -1;

			StringBuffer textBuffer = new StringBuffer(IntegerTextField.this
					.getText().trim());
			//The offset argument must be greater than or equal to 0, and less than or equal to the length of this string buffer
			if ((offs >= 0) && (offs <= textBuffer.length())) {
				textBuffer.insert(offs, str);
				String textValue = textBuffer.toString();
				if (textBuffer.length() > maxLength) {
					JOptionPane.showMessageDialog(IntegerTextField.this,
							"The number of characters must be less than or equal to "
									+ getMaxLength(), "Error Message",
							JOptionPane.ERROR_MESSAGE);
					return;
				}

				if ((textValue == null) || (textValue.equals(""))) {
					remove(0, getLength());
					super.insertString(0, "", null);
					return;
				}

				if (textValue.equals("-") && minValue < 0) {
					super.insertString(offs, new String(str), a);
					return;
				}

				// 	    if(maxLength == 3 && str.equals(".") && isIPField)
				if (str.equals(".") && isIPField) {
					super.insertString(offs, new String(str), a);
					return;
				} else {
					try {
						typedValue = Long.parseLong(textValue);
						if ((typedValue > maxValue) || (typedValue < minValue)) {
							JOptionPane.showMessageDialog(
									IntegerTextField.this,
									"The value can only be from "
											+ getMinValue() + " to "
											+ getMaxValue(), "Error Message",
									JOptionPane.ERROR_MESSAGE);
						} else {
							super.insertString(offs, new String(str), a);
						}
					} catch (NumberFormatException ex) {
						Toolkit.getDefaultToolkit().beep();
						JOptionPane.showMessageDialog(IntegerTextField.this,
								"Only numeric values allowed.",
								"Error Message", JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
require('babel/register');

var webpack = require('webpack');
var config = require('../webpack.config.js').production;

var bundler = webpack(config);

bundler.run(function(err, stats) {
  if (err) {
    console.error(err);
  }
  console.log(stats.toString());
});


text:
package com.fairytale110.mycustomviews.Widget.CY;

import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.fairytale110.mycustomviews.R;

/**
 * Created by   fairytale110
 * Creat date   2016/9/5 16:55
 * Copy Right   www.xkyiliao.com
 * function    数字 切换控件 继承 android.widget.TextSwitcher
 *
 */
public class CYNumberSwitcher extends TextSwitcher implements ViewSwitcher.ViewFactory, CYAnimator {

    private ValueAnimator mValueAnimator;
    private long animatorTime = 1500L;  //动画时长
    private int dataToShow = 0;             //要显示的值

    public CYNumberSwitcher(Context paramContext) {
        this(paramContext,null);
    }

    public CYNumberSwitcher(Context paramContext, AttributeSet paramAttributeSet) {
        super(paramContext, paramAttributeSet);
        setFactory(this);
    }

    private void d() {
        setFactory(this);
    }

    @Override
    public final void reset() {
        if ((Build.VERSION.SDK_INT >= 11) && (this.mValueAnimator != null)) {
            this.mValueAnimator.cancel();
        }
        setText("0");
    }

    /**
     * 设置要显示的值
     * @param paramInt
     */
    public final void setDataToShow(int paramInt) {
        this.dataToShow = paramInt;
        setText(String.valueOf(this.dataToShow));
    }

    @Override
    public final void setShowTime(long paramLong) {
        this.animatorTime = paramLong;
    }

    @Override
    public final void setShowData() {
        setText(String.valueOf(this.dataToShow));
    }

    @Override
    public final void startAnim() {
        if (Build.VERSION.SDK_INT < 11) {
            setShowData();
            return;
        }
        this.mValueAnimator = ValueAnimator.ofInt(new int[]{0, this.dataToShow});
        this.mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator paramAnonymousValueAnimator) {
                CYNumberSwitcher.this.setText(String.valueOf(paramAnonymousValueAnimator.getAnimatedValue()));
            }
        });
        this.mValueAnimator.setDuration(this.animatorTime);
        this.mValueAnimator.start();
    }

    public View makeView() {
        TextView localTextView = new TextView(getContext());
        localTextView.setTextSize(1, 34.0F);
        localTextView.setTextColor(getResources().getColor(R.color.text_black_dau));
        localTextView.setGravity(17);
        return localTextView;
    }
}


text: Core classes and artifacts


text:
class LinearDecayingRotation
: public RotationalEphemeris< LinearDecayingRotation >
{

public:

	LinearDecayingRotation(
		const PDE::Vector3& xRotationAxis, const PDE::Vector3& xZeroLongitudeAtEquatorJ2000,
		const double dPeriodInHoursJ2000, const double dDecayRatePerYear, const double dMaximumPeriod )
	: mxRotationAxis( xRotationAxis )
	, mxZeroLongitudeAtEquator( xZeroLongitudeAtEquatorJ2000 )
	, mdRate( DayRateFromHourPeriod( dPeriodInHoursJ2000 ) )
	, mdMinimumRate( DayRateFromHourPeriod( dMaximumPeriod ) )
	, mdDecayRate( DecayRateFromHourPerYear( dPeriodInHoursJ2000, dDecayRatePerYear ) )
	{
	}

	PDE::Matrix3 EvaluateOrientation( const double dJDT ) const
	{
		return EvaluateOrientation( dJDT, mdRate, mdDecayRate, mdMinimumRate, mxRotationAxis, mxZeroLongitudeAtEquator );
	}

	static PDE::Matrix3 EvaluateOrientation(
		const double dJDT, const double dRate, const double dDecayRate,
		const double dMinimumRate, const PDE::Vector3& xAxis, const PDE::Vector3& xZeroLonLat )
	{
		const double dT = dJDT - J2000;
		double dActualRate = dRate + dT * dDecayRate;
		if( dActualRate < dMinimumRate )
		{
			dActualRate = dMinimumRate;
		}

		return SimpleRotation::EvaluateOrientation( dJDT, dActualRate, xAxis, xZeroLonLat );
	}

private:

	PDE::Vector3 mxRotationAxis;
	PDE::Vector3 mxZeroLongitudeAtEquator;
	double mdRate;
	double mdMinimumRate;
	double mdDecayRate;

};

#endif


text:
package com.ociweb.hazelcast.stage;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

import com.ociweb.hazelcast.HazelcastConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ociweb.pronghorn.pipe.LittleEndianDataInputBlobReader;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.pipe.PipeConfig;
import com.ociweb.pronghorn.pipe.RawDataSchema;
import com.ociweb.pronghorn.stage.PronghornStage;
import com.ociweb.pronghorn.stage.scheduling.GraphManager;

public class ConnectionStage extends PronghornStage {

    private final static Logger log = LoggerFactory.getLogger(ConnectionStage.class);

    private final Pipe<RawDataSchema> inputMessagesToSend;

    private final Pipe<RequestResponseSchema>[] outputMessagesReceived;
    private final long[] outputActiveCorrelationId;
    private static final int END_FLAG = 64;

    private final HazelcastConfigurator conf;

    private final long pingTimeSeconds = 200;
    private final long timeLimitMilliSeconds = pingTimeSeconds * 1000;//TODO: where to set this ping?

    protected boolean isAuthenticated = false;
    private long touched;

    private final static byte BIT_FLAG_START = (byte) 0x80;
    private final static byte BIT_FLAG_END = (byte) 0x40;

    private InetSocketAddress addr;
    private SocketChannel channel;
    private ByteBuffer initializerData;
    private ByteBuffer pingData;
    private ByteBuffer lengthData;

    private ByteBuffer[] pendingWriteBuffers;

    protected int authPort = -1;
    protected int authAddrLen = -1;
    protected int authUUIDLen = -1;
    protected int authUUIDOwner = -1;
    protected StringBuilder authResponse = new StringBuilder(128);

    //NOTE: in the future if this is a performance issue we can extract a routing stage out of this connectionStages
    private PipeConfig<RawDataSchema> inputSocketPipeConfig;
    private Pipe<RawDataSchema> inputSocketPipe;
    private LittleEndianDataInputBlobReader<RawDataSchema> reader;

    @SuppressWarnings("unchecked")
    public ConnectionStage(GraphManager graphManager,
                           Pipe<RawDataSchema> input,
                           Pipe<RequestResponseSchema> output,
                           HazelcastConfigurator conf) {
        super(graphManager, input, output);
        this.inputMessagesToSend = input;
        this.outputMessagesReceived = new Pipe[]{output};

        this.outputActiveCorrelationId = new long[1];
        Arrays.fill(outputActiveCorrelationId, Long.MIN_VALUE);

        this.conf = conf;
    }

    protected ConnectionStage(GraphManager graphManager,
                              Pipe<RawDataSchema> input,
                              Pipe<RequestResponseSchema>[] outputs,
                              HazelcastConfigurator conf) {
        super(graphManager, input, outputs);
        this.inputMessagesToSend = input;
        this.outputMessagesReceived = outputs;

        this.outputActiveCorrelationId = new long[outputs.length];
        Arrays.fill(outputActiveCorrelationId, Long.MIN_VALUE);

        this.conf = conf;
    }

    @Override
    public void startup() {
        addr = conf.buildInetSocketAddress(this.stageId); //may also get called later if this node should go down.
        buildNewChannel();

        pendingWriteBuffers = new ByteBuffer[3];

        CharSequence uuid = conf.getUUID(this.stageId);
        CharSequence uuidOwner = conf.getOwnerUUID(this.stageId);

        int bytesMaxEstimate = 100 + 3 + 18 + 3 + ((uuid.length() + uuidOwner.length()) * 6);

        byte[] initBytes;
        int idx = 0;
        int lenIdx;
        int tLen;

        if (conf.isCustomAuth()) {
            byte[] customCred = conf.getCustomCredentials();
            tLen = customCred.length;
            bytesMaxEstimate += tLen;
            initBytes = new byte[bytesMaxEstimate];
            idx = buildConInit(initBytes, idx);

            lenIdx = idx;
            idx = writeHeader(initBytes, idx, -1, -1, 0x3);

            idx = littleIndianWriteToArray(initBytes, idx, tLen);
            System.arraycopy(customCred, 0, initBytes, idx, tLen);
            idx += tLen;

        } else {
            CharSequence username = conf.getUserName(this.stageId);
            CharSequence password = conf.getPassword(this.stageId);
            bytesMaxEstimate += ((username.length() + password.length()) * 6);
            initBytes = new byte[bytesMaxEstimate];
            idx = buildConInit(initBytes, idx);

            lenIdx = idx;
            idx = writeHeader(initBytes, idx, -1, -1, 0x2);

            idx = utf8WriteToArray(username, initBytes, idx);
            idx = utf8WriteToArray(password, initBytes, idx);
        }

        //encode 3 optional missing values for the UUID, ownerUUID and isOwner,  These are encoded as -1 (the only value that would not get confused with something else (TODO: needs to be in developers guide.)
        initBytes[idx++] = -1;
        initBytes[idx++] = -1;
        initBytes[idx++] = -1;

        //set this frame length now that we know what the value is.
        int len = idx - 6;//do not count the first 6 connection bytes these are assumed to always be present.
        initBytes[lenIdx++] = (byte) (0xFF & (len));
        initBytes[lenIdx++] = (byte) (0xFF & (len >> 8));
        initBytes[lenIdx++] = (byte) (0xFF & (len >> 16));
        initBytes[lenIdx++] = (byte) (0xFF & (len >> 24));

        //TODO: we may be able to update this login/connect script later
        initializerData = ByteBuffer.wrap(initBytes, 0, idx);  //only builds connection, connect does not happen till later in run loop.
        initializerData.position(idx); //so we can call flip before each usage.

        pingData = ByteBuffer.allocate(1);
        pingData.put((byte) 0xF);

        lengthData = ByteBuffer.allocate(4);

        allocateIncomingBuffer();
    }

    private void allocateIncomingBuffer() {
        int size = Integer.MAX_VALUE;
        int j = outputMessagesReceived.length;
        if (j == 0) {
            throw new UnsupportedOperationException("Must have at least 1 output pipe.");
        }
        while (--j >= 0) {
            size = Math.min(size, outputMessagesReceived[j].sizeOfBlobRing);
        }

        inputSocketPipeConfig = new PipeConfig<RawDataSchema>(RawDataSchema.instance, 20, size);
        inputSocketPipe = new Pipe<RawDataSchema>(inputSocketPipeConfig);
        inputSocketPipe.initBuffers();
        reader = new LittleEndianDataInputBlobReader<RawDataSchema>(inputSocketPipe);
        LittleEndianDataInputBlobReader.openRawRead(reader, 0, 0);//must be zero length to start
    }

    private int buildConInit(byte[] initBytes, int idx) {
        initBytes[idx++] = (byte) 'C';
        initBytes[idx++] = (byte) 'B';
        initBytes[idx++] = (byte) '2';
        initBytes[idx++] = (byte) 'J';
        initBytes[idx++] = (byte) 'V';
        initBytes[idx++] = (byte) 'M';
        return idx;
    }

    private static int writeInt32(int value, int bytePos, byte[] byteBuffer) {
        byteBuffer[bytePos++] = (byte) (0xFF & (value));
        byteBuffer[bytePos++] = (byte) (0xFF & (value >> 8));
        byteBuffer[bytePos++] = (byte) (0xFF & (value >> 16));
        byteBuffer[bytePos++] = (byte) (0xFF & (value >> 24));
        return bytePos;
    }

    static int writeHeader(byte[] initBytes, int idx, int corId, int parId, int messageType) {

        idx += 4; //save room for frame length

        initBytes[idx++] = 1;  //version 1 byte const
        initBytes[idx++] = BIT_FLAG_START | BIT_FLAG_END;  //flags   1 byte  begin/end  zeros
        initBytes[idx++] = (byte) (0xFF & messageType);
        initBytes[idx++] = (byte) (0xFF & (messageType >> 8));

        idx = writeInt32(corId, idx, initBytes);
        idx = writeInt32(parId, idx, initBytes);

        initBytes[idx++] = 18;  //  2 bytes for data offset, Only NOT 18 when we add data to header in the future.
        initBytes[idx++] = 0;

        return idx;
    }

    private int utf8WriteToArray(CharSequence uuidOwner, byte[] initBytes,
                                 int idx) {
        int tLen = Pipe.convertToUTF8(uuidOwner, 0, uuidOwner.length(), initBytes, idx + 4, 0xFFFFFFFF);
        idx = littleIndianWriteToArray(initBytes, idx, tLen);
        idx += tLen;
        return idx;
    }

    private int littleIndianWriteToArray(byte[] initBytes, int idx, int tLen) {
        initBytes[idx++] = (byte) (tLen & 0xFF); //HZ wants little indian
        initBytes[idx++] = (byte) ((tLen >> 8) & 0xFF);
        initBytes[idx++] = (byte) ((tLen >> 16) & 0xFF);
        initBytes[idx++] = (byte) ((tLen >> 24) & 0xFF);
        return idx;
    }

    int exitReason = -1;

    @Override
    public void run() {
        long now = System.currentTimeMillis();

        //connect if not connected
        if (!channel.isConnected()) {
            if (!connect(now)) {
                exitReason = 1;
                return;//unable to connect try again later
            }
        }

        //if channel is open
        if (channel.isConnected()) {

            //this may be the auth credentials so must do now
            if (hasPendingWrites()) {
                System.out.println("hasPendingWrites calling buffer write");
                if (!nonBlockingByteBufferWrite(now)) {
                    exitReason = 2;
                    return;//do not continue because we have pending writes which must be done first.
                }
            }

            if (isAuthenticated) {
                //////////
                //all pending writes have completed so check for need to send the ping
                /////////
                if (timeStampTooOld(now)) {
                    pingData.flip();
                    pendingWriteBuffers[0] = pingData;

                    System.out.println("timeStampTooOld calling buffer write");
                    if (!nonBlockingByteBufferWrite(now)) {
                        exitReason = 3;
                        return;//try again later, can't send ping now.
                    }
                }

                // low level read.
                while (Pipe.hasContentToRead(inputMessagesToSend)) {
                    //is there stuff to send, send it.

                    int msgIdx = Pipe.takeMsgIdx(inputMessagesToSend);
                    int meta = Pipe.takeRingByteMetaData(inputMessagesToSend); //for string and byte array
                    int len = Pipe.takeRingByteLen(inputMessagesToSend);
/*                    if (len < 18) {
                        throw new UnsupportedOperationException("Error there are no messages smaller than the 18 byte header and we got "+len);
                    }
                    pendingWriteBuffers[0] = Pipe.wrappedBlobReadingRingA(inputMessagesToSend, meta, len);

                    pendingWriteBuffers[1] = Pipe.wrappedBlobReadingRingB(inputMessagesToSend, meta, len);
                    pendingWriteBuffers[2] = null;
 */
                    int vli = len + 4;
                    lengthData.clear(); //TODO: once we measure performance if this stage is holding things up we can move this back to the encoder stage.
                    lengthData.put((byte) (0xFF & vli));
                    lengthData.put((byte) (0xFF & (vli >> 8)));
                    lengthData.put((byte) (0xFF & (vli >> 16)));
                    lengthData.put((byte) (0xFF & (vli >> 24)));
                    lengthData.flip();

                    pendingWriteBuffers[0] = lengthData;
                    pendingWriteBuffers[1] = Pipe.wrappedBlobReadingRingA(inputMessagesToSend, meta, len);
                    pendingWriteBuffers[2] = Pipe.wrappedBlobReadingRingB(inputMessagesToSend, meta, len);

                    if (!nonBlockingByteBufferWrite(now)) {
                        exitReason = 4;
                        break;
                    }

                    Pipe.confirmLowLevelRead(inputMessagesToSend, Pipe.sizeOf(inputMessagesToSend, msgIdx));
                    Pipe.releaseReadLock(inputMessagesToSend);
                }
            }

            readDataFromConnection();
            exitReason = 5;
        } else {
            exitReason = 6;
        }
    }

    private void readDataFromConnection() {

        try {
            //continues to run while there is room and the channel has data
            pumpByteChannelIntoRawDataPipe(channel, inputSocketPipe); //Move as part of the new WebServer

            //accum data on to the reader stream, enables the crossing of message boundaries.
            LittleEndianDataInputBlobReader.appendNextFieldToReader(reader, inputSocketPipe);

            //now consume the frames off the ring in blocks larger than how we wrote it.
            consumeFrameIfPresent(inputSocketPipe, reader);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void consumeFrameIfPresent(Pipe<RawDataSchema> targetPipe,
            LittleEndianDataInputBlobReader<RawDataSchema> localReader) throws IOException {
        int available = localReader.available();
        int frameByteCount;
        if (available>=18 && (frameByteCount = localReader.peekInt()) <= available) {
            int pipeIdx = selectOutputPipe();
            if (pipeIdx < 0) {
                return;//do nothing, can not find pipe
            }

            consumeFrameFromReader(pipeIdx);
            Pipe.releasePendingAsReadLock(targetPipe, frameByteCount);
        }
    }

    public void pumpByteChannelIntoRawDataPipe(ReadableByteChannel sourceChannel, Pipe<RawDataSchema> targetPipe) throws IOException {
        while (Pipe.hasRoomForWrite(targetPipe)) {

            int originalBlobPosition = Pipe.getBlobWorkingHeadPosition(targetPipe);
            ByteBuffer targetByteBuffer = Pipe.wrappedBlobForWriting(originalBlobPosition, targetPipe);
            int len;//if data is read then we build a record around it
            if ((len = sourceChannel.read(targetByteBuffer))>0) {
                int size = Pipe.addMsgIdx(targetPipe,RawDataSchema.MSG_CHUNKEDSTREAM_1);
                Pipe.moveBlobPointerAndRecordPosAndLength(originalBlobPosition, len, targetPipe);

                Pipe.confirmLowLevelWrite(targetPipe, size);
                Pipe.publishWrites(targetPipe);
            } else {
                //if nothing was read then the channel is empty, try again later.
                break;
            }
        }
    }

    public void consumeFrameFromReader(int pipeIdx) throws IOException {
        Pipe<RequestResponseSchema> selectedPipe = outputMessagesReceived[pipeIdx];

        //first check if its bigger than the smallest frame size then check that we have the full frame
        if (Pipe.hasRoomForWrite(selectedPipe)) {
            int frameSize = reader.readInt();
            int version = reader.readByte();
            assert (version < 2) : "No support for other versions";
            int flags = reader.readByte();
            int type = reader.readShort();//taskId;
            int correlationId = reader.readInt();
            int partitionId = reader.readInt();
            int offset = reader.readShort();

            reader.skip(offset - 18);
            int remainingBytes = frameSize - offset;

            switch (type) {

                case 0x6d: //auth response
                    assert (!isAuthenticated);

                    authResponse.setLength(0);

                    //address
                    authAddrLen = LittleEndianDataInputBlobReader.readUTF(reader, authResponse, reader.readInt());

                    authPort = reader.readInt();

                    // text UUID
                    authUUIDLen = LittleEndianDataInputBlobReader.readUTF(reader, authResponse, reader.readInt());

                    // text UUID owner
                    authUUIDOwner = LittleEndianDataInputBlobReader.readUTF(reader, authResponse, reader.readInt());

                    isAuthenticated = true;

                    break;

                // TODO: Add support for Ping response here

                default:
                    assert (isAuthenticated);

                    //TODO: write to free pipe, if none found then fail need more pipes.
                    int responseSize = Pipe.addMsgIdx(selectedPipe, RequestResponseSchema.MSG_RESPONSE_1);

                    //send type in the upper 16 and the flags in the lower
                    Pipe.addIntValue((type << 16) | flags, selectedPipe);
                    Pipe.addIntValue(correlationId, selectedPipe);
                    Pipe.addIntValue(partitionId, selectedPipe);

                    reader.readInto(selectedPipe, remainingBytes);

                    Pipe.confirmLowLevelWrite(selectedPipe, responseSize);
                    Pipe.publishWrites(selectedPipe);

                    if (0 != (flags & END_FLAG)) {
                        outputActiveCorrelationId[pipeIdx] = Long.MIN_VALUE;
                    } else {
                        //this is only a fragment so block this pipe until we get the end.
                        outputActiveCorrelationId[pipeIdx] = correlationId;
                    }

            }

        }
    }

    private int selectOutputPipe() {
        final int correlationPeek = LittleEndianDataInputBlobReader.peekInt(reader, 8);

        int selectedPipe = -1;
        //find a free pipe
        int j = outputActiveCorrelationId.length;
        while (--j >= 0) {
            //only selected if one has not been selected
            if (selectedPipe < 0 && Long.MIN_VALUE == outputActiveCorrelationId[j] && Pipe.hasRoomForWrite(outputMessagesReceived[j])) {
                selectedPipe = j;
            }
            if (correlationPeek == outputActiveCorrelationId[j]) {
                return j;
            }
        }
        return selectedPipe;
    }

    private static boolean isFrameFullyFilled(ByteBuffer buffer) {

        int frameSize = 0xFF & buffer.get(0);
        frameSize |= (0xFF & buffer.get(1)) << 8;
        frameSize |= (0xFF & buffer.get(2)) << 16;
        frameSize |= (0xFF & buffer.get(3)) << 24;

        return frameSize <= buffer.position();

    }

    private boolean timeStampTooOld(long now) {
        return (now - touched) > timeLimitMilliSeconds;
    }

    private boolean connect(long now) {

        //Note this connection message can also be kicked off because the expected state is connected and the connection was lost.
        //     create socket and connect when we get the connect message
        try {

            if (!channel.isOpen()) {
                //once a connection is closed it can not be re-opened so we have no choice but create a new connection.
                //NOTE: this is a concern because we now have garbage to be collected.  TODO: X, review what can be done to make this garbage free?
                buildNewChannel();
            }

            if (channel.isConnectionPending() || !channel.connect(addr)) {
                if (!channel.finishConnect()) {
                    return false;
                }
            }

            if (hasPendingWrites() && pendingWriteBuffers[0] != initializerData) {
                //move them all down.
                int x = pendingWriteBuffers.length - 1;
                assert (null == pendingWriteBuffers[x]);
                while (--x >= 1) {
                    pendingWriteBuffers[x] = pendingWriteBuffers[x - 1]; //TODO: This is sending too soon? we have not gotten ack back for connect.
                }
            }

            initializerData.flip();
            pendingWriteBuffers[0] = initializerData;
            log.debug("Sending initialization data of " + initializerData.remaining());
            return nonBlockingByteBufferWrite(now);

        } catch (Throwable t) {
            //this is not unreasonable if we are waiting for the broker to be started.
            log.debug("Unable to connect", t);
            buildNewChannel(); //rebuild-connection to start fresh.
            return false;
        }
    }

    private boolean hasPendingWrites() {
        int x = pendingWriteBuffers.length;
        boolean result = false;
        while (--x >= 0) {
            result |= ((null != pendingWriteBuffers[x]) && (pendingWriteBuffers[x].hasRemaining()));
        }
        return result;
    }

    private void buildNewChannel() {
        try {
            channel = (SocketChannel) SocketChannel.open().configureBlocking(false);
            assert (!channel.isBlocking()) : "Blocking must be turned off for all socket connections";
        } catch (IOException e) {
            throw new RuntimeException("CHECK NETWORK CONNECTION, New non blocking SocketChannel not supported on this platform", e);
        }
    }

    private boolean nonBlockingByteBufferWrite(long now) {
        for (int i = 0; i < pendingWriteBuffers.length; i++) {
            if (null != pendingWriteBuffers[i] && pendingWriteBuffers[i].hasRemaining()) {
                try {
                    if (channel.write(pendingWriteBuffers[i]) > 0) {
                        touched = now;
                    }
                    if (0 == pendingWriteBuffers[i].remaining()) {
                        pendingWriteBuffers[i] = null;
                    } else {
                        System.out.println("ConnectionStage.nonBlockingByteBufferWrite: finish later with "+ pendingWriteBuffers[i].remaining());
                        //finish later
                        return false;
                    }
                } catch (Exception e) {
                    if (!(e instanceof NotYetConnectedException) && !(e instanceof IOException)) {
                        e.printStackTrace();
                        //TODO: what to do on failure.
                    }
                    System.out.println("ConnectionStage.nonBlockingByteBufferWrite: Error and unable to send");
                    return false;
                }
            }
        }
        return true;
    }

}


text:
// I18N constants
//
// LANG: "pt_br", ENCODING: UTF-8
// Portuguese Brazilian Translation
//
// Author: Marcio Barbosa, <marcio@mpg.com.br>
// MSN: tomarshall@msn.com - ICQ: 69419933
// Site: http://www.mpg.com.br
//
// Last revision: 06 september 2007
// Please don´t remove this information
// If you modify any source, please insert a comment with your name and e-mail
//
// Distributed under the same terms as HTMLArea itself.
// This notice MUST stay intact for use (see license.txt).
{
  "Click a color...": "Selecione uma côr...",
  "Close": "Fechar",
  "Color: ": "Côr:",
  "Sample": "Exemplo",
  "Web Safe: ": "Web Segura:"
}


text:
package qa.messaging.flook;

/**
 * Created by IntelliJ IDEA.
 * User: truggles
 * Date: Jul 28, 2005
 * Time: 7:16:58 PM
 * To change this template use File | Settings | File Templates.
 */
public class FLookEmail implements java.io.Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public String to;
    public String from;
    public String subject;
    public String message;
    public Object[] attachments;

    public FLookEmail() {
        this.attachments = new Object[0];
    }

    public FLookEmail(String to, String from,  String subject, String message, Object[] attachments) {

        this.to = to;
        this.from = from;
        this.subject = subject;
        this.message = message;

        if (attachments != null)
            this.attachments = attachments;
        else
            this.attachments = new Object[0];
    }

    public String toString() {
        return  "To:       " + to + "\n" +
                "From:     " + from + "\n" +
                "Subject:  " + subject + "\n" +
                "Attachments:" + attachments.length;
    }

    public String completeToString() {
        return  "===========================================\n" +
                this.toString() + "\n" +
                "-------------------------------------------\n" +
                message + "\n" +
                "===========================================";
    }
}


text:
static struct
{
  const char* name;
  lexint_t limit;
  bool neg_plus_one;    // Is a negated value allowed to be 1 bigger
} _str_uif_types[UIF_COUNT] =
{
  { "U8", {0x100, 0, false}, false },
  { "U16", {0x10000, 0, false}, false },
  { "U32", {0x100000000LL, 0, false}, false },
  { "U64", {0, 1, false}, false },
  { "U128", {0, 0, false}, false },  // Limit checked by lexer
  { "ULong", {0, 1, false}, false }, // Limited to 64 bits
  { "USize", {0, 1, false}, false }, // Limited to 64 bits
  { "I8", {0x80, 0, false}, true },
  { "I16", {0x8000, 0, false}, true },
  { "I32", {0x80000000, 0, false}, true },
  { "I64", {0x8000000000000000ULL, 0, false}, true },
  { "I128", {0, 0x8000000000000000ULL, false}, true },
  { "ILong", {0x8000000000000000ULL, 0, false}, true }, // Limited to 64 bits
  { "ISize", {0x8000000000000000ULL, 0, false}, true }, // Limited to 64 bits
  { "F32", {0, 0, false}, false },
  { "F64", {0, 0, false}, false }
};

typedef struct lit_op_info_t
{
  const char* name;
  size_t arg_count;
  bool can_propogate_literal;
  bool neg_plus_one;
} lit_op_info_t;

static lit_op_info_t _operator_fns[] =
{
  { "add", 1, true, false },
  { "sub", 1, true, false },
  { "mul", 1, true, false },
  { "div", 1, true, false },
  { "mod", 1, true, false },
  { "neg", 0, true, true },
  { "shl", 1, true, false },
  { "shr", 1, true, false },
  { "op_and", 1, true, false },
  { "op_or", 1, true, false },
  { "op_xor", 1, true, false },
  { "op_not", 0, true, false },
  { "eq", 1, false, false },
  { "ne", 1, false, false },
  { "lt", 1, false, false },
  { "le", 1, false, false },
  { "gt", 1, false, false },
  { "ge", 1, false, false },
  { NULL, 0, false, false }  // Terminator
};

static lit_op_info_t* lookup_literal_op(const char* name)
{
  for(int i = 0; _operator_fns[i].name != NULL; i++)
    if(strcmp(name, _operator_fns[i].name) == 0)
      return &_operator_fns[i];

  return NULL;
}

bool expr_literal(pass_opt_t* opt, ast_t* ast, const char* name)
{
  ast_t* type = type_builtin(opt, ast, name);

  if(is_typecheck_error(type))
    return false;

  ast_settype(ast, type);
  return true;
}

void make_literal_type(ast_t* ast)
{
  ast_t* type = ast_from(ast, TK_LITERAL);
  ast_settype(ast, type);
}

bool is_type_literal(ast_t* type)
{
  if(type == NULL)
    return false;

  return ast_id(type) == TK_LITERAL;
}

// Type chains

// TODO: explain what the hell is going on

#define CHAIN_CARD_BASE   0 // Basic type
#define CHAIN_CARD_ARRAY  1 // Array member

typedef struct lit_chain_t
{
  size_t cardinality; // Tuple cardinality / CHAIN_CARD_* value
  size_t index;
  ast_t* formal;
  ast_t* cached_type;
  const char* name;
  int cached_uif_index;
  bool valid_for_float;
  struct lit_chain_t* next; // Next node
} lit_chain_t;

static int uifset(pass_opt_t* opt, ast_t* type, lit_chain_t* chain);

static bool coerce_literal_to_type(ast_t** literal_expr, ast_t* target_type,
  lit_chain_t* chain, pass_opt_t* options, bool report_errors);

static bool unify(ast_t* ast, pass_opt_t* options, bool report_errors);

static void chain_init_head(lit_chain_t* head)
{
  assert(head != NULL);

  head->cardinality = CHAIN_CARD_BASE;
  head->formal = NULL;
  head->cached_type = NULL;
  head->name = NULL;
  head->cached_uif_index = -1;
  head->valid_for_float = false;
  head->next = head;
}

static void chain_clear_cache(lit_chain_t* chain)
{
  assert(chain != NULL);

  while(chain->cardinality != CHAIN_CARD_BASE)
    chain = chain->next;

  chain->formal = NULL;
  chain->cached_type = NULL;
  chain->name = NULL;
  chain->cached_uif_index = -1;
  chain->valid_for_float = false;
}

static void chain_add(lit_chain_t* chain, lit_chain_t* new_link,
  size_t cardinality)
{
  assert(new_link != NULL);
  assert(cardinality != CHAIN_CARD_BASE);

  new_link->cardinality = cardinality;
  new_link->index = 0;

  assert(chain != NULL);
  assert(chain->next != NULL);
  new_link->next = chain->next;
  chain->next = new_link;

  chain_clear_cache(new_link);
}

static void chain_remove(lit_chain_t* old_tail)
{
  assert(old_tail != NULL);
  assert(old_tail->next != NULL);
  assert(old_tail->next->next != NULL);
  assert(old_tail->next->next->cardinality == CHAIN_CARD_BASE);

  old_tail->next = old_tail->next->next;
  chain_clear_cache(old_tail);
}

// Determine the UIF types that satisfy the given "simple" type.
// Here a simple type is defined as a non-tuple type that does not depend on
// any formal parameters.
static int uifset_simple_type(pass_opt_t* opt, ast_t* type)
{
  assert(type != NULL);

  int set = 0;

  for(int i = 0; i < UIF_COUNT; i++)
  {
    ast_t* uif = type_builtin(opt, type, _str_uif_types[i].name);
    ast_setid(ast_childidx(uif, 3), TK_VAL);
    ast_setid(ast_childidx(uif, 4), TK_EPHEMERAL);

    if(is_subtype(uif, type, NULL, opt))
      set |= (1 << i);

    ast_free(uif);
  }

  return set;
}

// Determine the UIF types that the given formal parameter may be
static int uifset_formal_param(pass_opt_t* opt, ast_t* type_param_ref,
  lit_chain_t* chain)
{
  assert(type_param_ref != NULL);
  assert(ast_id(type_param_ref) == TK_TYPEPARAMREF);

  ast_t* type_param = (ast_t*)ast_data(type_param_ref);

  assert(type_param != NULL);
  assert(ast_id(type_param) == TK_TYPEPARAM);
  assert(chain != NULL);

  ast_t* constraint = ast_childidx(type_param, 1);
  assert(constraint != NULL);

  // If the constraint is not a subtype of (Real[A] & Number) then there are no
  // legal types in the set
  BUILD(typeargs, type_param,
    NODE(TK_TYPEARGS,
      NODE(TK_TYPEPARAMREF, DATA(type_param)
        ID(ast_name(ast_child(type_param))) NODE(TK_VAL) NONE)));

  ast_t* number = type_builtin(opt, type_param, "Number");
  ast_t* real = type_builtin_args(opt, type_param, "Real", typeargs);
  ast_setid(ast_childidx(real, 3), TK_BOX);

  bool is_real = is_subtype(constraint, real, NULL, opt);
  bool is_number = is_subtype(constraint, number, NULL, opt);
  ast_free(number);
  ast_free(real);

  if(!is_real || !is_number)
    // The formal param is not a subset of (Real[A] & Number)
    return UIF_NO_TYPES;

  int uif_set = 0;

  for(int i = 0; i < UIF_COUNT; i++)
  {
    ast_t* uif = type_builtin(opt, type_param, _str_uif_types[i].name);

    BUILD(params, type_param, NODE(TK_TYPEPARAMS, TREE(ast_dup(type_param))));
    BUILD(args, type_param, NODE(TK_TYPEARGS, TREE(uif)));

    if(check_constraints(NULL, params, args, false, opt))
      uif_set |= (1 << i);

    ast_free(args);
    ast_free(params);
  }

  if(uif_set == 0)  // No legal types
    return UIF_NO_TYPES;

  // Given formal parameter is legal to coerce to
  if(chain->formal != NULL && chain->formal != type_param)
  {
    ast_error(opt->check.errors, type_param_ref,
      "Cannot infer a literal type with multiple formal parameters");
    return UIF_ERROR;
  }

  chain->formal = type_param;
  chain->name = ast_name(ast_child(type_param));
  return uif_set | UIF_CONSTRAINED;
}

// Determine the UIF types that the given non-tuple union type may be
static int uifset_union(pass_opt_t* opt, ast_t* type, lit_chain_t* chain)
{
  assert(type != NULL);
  assert(ast_id(type) == TK_UNIONTYPE);

  int uif_set = 0;

  // Process all elements of the union
  for(ast_t* p = ast_child(type); p != NULL; p = ast_sibling(p))
  {
    int r = uifset(opt, p, chain);

    if(r == UIF_ERROR)  // Propogate errors
      return UIF_ERROR;

    bool child_valid = (r != UIF_NO_TYPES);
    bool child_formal = ((r & UIF_CONSTRAINED) != 0);
    bool others_valid = ((uif_set & UIF_ALL_TYPES) != 0);
    bool others_formal = ((uif_set & UIF_CONSTRAINED) != 0);

    if(child_valid && others_valid && (child_formal != others_formal))
    {
      // We're unioning a formal parameter and a UIF type, not allowed
      ast_error(opt->check.errors, type, "could not infer literal type, ambiguous union");
      return UIF_ERROR;
    }

    uif_set |= r;
  }

  return uif_set;
}

// Determine the UIF types that the given non-tuple intersection type may be
static int uifset_intersect(pass_opt_t* opt, ast_t* type, lit_chain_t* chain)
{
  assert(type != NULL);
  assert(ast_id(type) == TK_ISECTTYPE);

  int uif_set = UIF_ALL_TYPES;
  int constraint = 0;

  for(ast_t* p = ast_child(type); p != NULL; p = ast_sibling(p))
  {
    int r = uifset(opt, p, chain);

    if(r == UIF_ERROR)  // Propogate errors
      return UIF_ERROR;

    if((r & UIF_CONSTRAINED) != 0)
    {
      // We have a formal parameter
      constraint = r;
    }
    else
    {
      uif_set |= r;
    }
  }

  if(constraint != 0)
  {
    // We had a formal parameter
    int constraint_set = constraint & UIF_ALL_TYPES;

    if((constraint_set & uif_set) != constraint_set)
      // UIF type limits formal parameter types, no UIF guaranteed
      return UIF_NO_TYPES;

    return constraint;
  }

  return uif_set;
}

// Determine the UIF types that the given type may be
static int uifset(pass_opt_t* opt, ast_t* type, lit_chain_t* chain)
{
  assert(chain != NULL);

  if(is_typecheck_error(type))
    return UIF_NO_TYPES;

  switch(ast_id(type))
  {
    case TK_UNIONTYPE:
      return uifset_union(opt, type, chain);

    case TK_ISECTTYPE:
      return uifset_intersect(opt, type, chain);

    case TK_ARROW:
      // Since we don't care about capabilities we can just use the rhs
      assert(ast_id(ast_childidx(type, 1)) == TK_NOMINAL);
      return uifset(opt, ast_childidx(type, 1), chain);

    case TK_TYPEPARAMREF:
      if(chain->cardinality != CHAIN_CARD_BASE) // Incorrect cardinality
        return UIF_NO_TYPES;

      return uifset_formal_param(opt, type, chain);

    case TK_TUPLETYPE:
      if(chain->cardinality != ast_childcount(type)) // Incorrect cardinality
        return UIF_NO_TYPES;

      return uifset(opt, ast_childidx(type, chain->index), chain->next);

    case TK_NOMINAL:
      if(strcmp(ast_name(ast_childidx(type, 1)), "Array") == 0)
      {
        if(chain->cardinality != CHAIN_CARD_ARRAY) // Incorrect cardinality
          return UIF_NO_TYPES;

        ast_t* type_args = ast_childidx(type, 2);
        assert(ast_childcount(type_args) == 1);
        return uifset(opt, ast_child(type_args), chain->next);
      }

      if(strcmp(ast_name(ast_childidx(type, 1)), "Vector") == 0)
      {
        if(chain->cardinality != CHAIN_CARD_ARRAY) // Incorrect cardinality
          return UIF_NO_TYPES;

        ast_t* type_args = ast_childidx(type, 2);
        assert(ast_childcount(type_args) == 2);
        return uifset(opt, ast_child(type_args), chain->next);
      }

      if(chain->cardinality != CHAIN_CARD_BASE) // Incorrect cardinality
        return UIF_NO_TYPES;

      return uifset_simple_type(opt, type);

    case TK_DONTCARE:
    case TK_FUNTYPE:
      return UIF_NO_TYPES;

    default:
      ast_error(opt->check.errors, type, "Internal error: uif type, node %d", ast_id(type));
      assert(0);
      return UIF_ERROR;
  }
}

// Fill the given UIF type cache
static bool uif_type(pass_opt_t* opt, ast_t* literal, ast_t* type,
  lit_chain_t* chain_head, bool report_errors)
{
  assert(chain_head != NULL);
  assert(chain_head->cardinality == CHAIN_CARD_BASE);

  chain_head->formal = NULL;
  int r = uifset(opt, type, chain_head->next);

  if(r == UIF_ERROR)
    return false;

  if(r == UIF_NO_TYPES)
  {
    if(report_errors)
      ast_error(opt->check.errors, literal,
        "could not infer literal type, no valid types found");

    return false;
  }

  assert(type != NULL);

  if((r & UIF_CONSTRAINED) != 0)
  {
    // Type is a formal parameter
    assert(chain_head->formal != NULL);
    assert(chain_head->name != NULL);
    assert(chain_head->cached_uif_index < 0);

    BUILD(uif_type, type,
      NODE(TK_TYPEPARAMREF, DATA(chain_head->formal)
      ID(chain_head->name) NODE(TK_VAL) NONE));

    chain_head->cached_type = uif_type;
    chain_head->valid_for_float = ((r & UIF_INT_MASK) == 0);
    return true;
  }

  // Type is one or more UIFs
  for(int i = 0; i < UIF_COUNT; i++)
  {
    if(r == (1 << i))
    {
      chain_head->valid_for_float = (((1 << i) & UIF_INT_MASK) == 0);
      chain_head->cached_type =
        type_builtin(opt, type, _str_uif_types[i].name);
      //ast_setid(ast_childidx(chain_head->cached_type, 4), TK_EPHEMERAL);
      chain_head->name = _str_uif_types[i].name;
      chain_head->cached_uif_index = i;
      return true;
    }
  }

  ast_error(opt->check.errors, literal, "Multiple possible types for literal");
  return false;
}

// Assign a UIF type from the given target type to the given AST
static bool uif_type_from_chain(pass_opt_t* opt, ast_t* literal,
  ast_t* target_type, lit_chain_t* chain, bool require_float,
  bool report_errors)
{
  assert(literal != NULL);
  assert(chain != NULL);

  lit_chain_t* chain_head = chain;
  while(chain_head->cardinality != CHAIN_CARD_BASE)
    chain_head = chain_head->next;

  if(chain_head->cached_type == NULL)
  {
    // This is the first time we've needed this type, find it
    if(!uif_type(opt, literal, target_type, chain_head, report_errors))
      return false;
  }

  if(require_float && !chain_head->valid_for_float)
  {
    if(report_errors)
      ast_error(opt->check.errors, literal, "Inferred possibly integer type %s for float literal",
        chain_head->name);

    return false;
  }

  if(ast_id(literal) == TK_INT && chain_head->cached_uif_index >= 0)
  {
    // Check for literals that are outside the range of their type.
    // Note we don't check for types bound to type parameters.
    int i = chain_head->cached_uif_index;

    if(_str_uif_types[i].limit.low != 0 || _str_uif_types[i].limit.high != 0)
    {
      // There is a limit specified for this type, the literal must be smaller
      // than that.
      bool neg_plus_one = false;

      if(_str_uif_types[i].neg_plus_one)
      {
        // If the literal is immediately negated it can be equal to the given
        // limit. This is because of how the world chooses to encode negative
        // integers.
        // For example, the maximum value in an I8 is 127. But the minimum
        // value is -128.
        // We don't actually calculate the negative value here, but we have a
        // looser test if the literal is immediately negated.
        // We do not do this if the negation is not immediate, eg "-(128)".
        ast_t* parent = ast_parent(literal);
        assert(parent != NULL);
        ast_t* parent_type = ast_type(parent);

        if(parent_type != NULL && ast_id(parent_type) == TK_OPERATORLITERAL &&
          ast_child(parent) == literal &&
          ((lit_op_info_t*)ast_data(parent_type))->neg_plus_one)
          neg_plus_one = true;
      }

      lexint_t* actual = ast_int(literal);
      int test;

      // if the value has the negative bit set from evaluation
      // then we need to check the positive value
      if(actual->is_negative)
      {
        lexint_t t;
        lexint_zero(&t);
        lexint_sub(&t, &t, actual);
        test = lexint_cmp(&t, &_str_uif_types[i].limit);
        neg_plus_one = true;
      }
      else
      {
        test = lexint_cmp(actual, &_str_uif_types[i].limit);
      }

      if((test > 0) || (!neg_plus_one && (test == 0)))
      {
        // Illegal value.
        ast_error(opt->check.errors, literal, "Literal value is out of range for type (%s)",
          chain_head->name);
        return false;
      }
    }
  }

  ast_settype(literal, chain_head->cached_type);
  return true;
}

// Coerce a literal group (tuple or array) to be the specified target type
static bool coerce_group(ast_t** astp, ast_t* target_type, lit_chain_t* chain,
  size_t cardinality, pass_opt_t* options, bool report_errors)
{
  assert(astp != NULL);
  ast_t* literal_expr = *astp;
  assert(literal_expr != NULL);
  assert(ast_id(literal_expr) == TK_TUPLE || ast_id(literal_expr) == TK_ARRAY
         || ast_id(literal_expr) == TK_VECTOR
         || ast_id(literal_expr) == TK_MEMBERS);
  // TK_MEMBERS case is only for coerece a literal compile-time vector
  assert(chain != NULL);
  assert(cardinality != CHAIN_CARD_BASE);

  size_t i = 0;
  lit_chain_t link;

  chain_add(chain, &link, cardinality);

  // Process each group element separately
  ast_t* p = ast_child(literal_expr);

  if(ast_id(literal_expr) == TK_ARRAY || ast_id(literal_expr) == TK_VECTOR)
  {
    // The first child of an array AST is the forced type, skip it
    p = ast_sibling(p);
  }

  for(; p != NULL; p = ast_sibling(p))
  {
    ast_t* p_type = ast_type(p);

    if(is_typecheck_error(p_type))
      return false;

    if(is_type_literal(p_type))
    {
      // This element is a literal
      if(cardinality != CHAIN_CARD_ARRAY)
      {
        chain_clear_cache(&link);
        link.index = i;
      }

      if(!coerce_literal_to_type(&p, target_type, &link, options,
        report_errors))
        return false;
    }

    i++;
  }

  chain_remove(chain);
  return true;
}

// This method coerces a constant object which is expected to be a vector
// to have members of the correct type. This should be the only instance
// of a compile-time constant that we encounter in coercion
static bool coerce_constant_object(ast_t** astp, ast_t* target_type,
  lit_chain_t* chain, pass_opt_t* options, bool report_errors)
{
  assert(astp != NULL);
  ast_t* literal_expr = *astp;
  ast_t* members = ast_childidx(literal_expr, 1);
  return coerce_group(&members, target_type, chain, CHAIN_CARD_ARRAY,
                      options, report_errors);
}

// Coerce a literal control block to be the specified target type
static bool coerce_control_block(ast_t** astp, ast_t* target_type,
  lit_chain_t* chain, pass_opt_t* opt, bool report_errors)
{
  assert(astp != NULL);
  ast_t* literal_expr = *astp;
  assert(literal_expr != NULL);

  ast_t* lit_type = ast_type(literal_expr);
  assert(lit_type != NULL);
  assert(ast_id(lit_type) == TK_LITERAL);
  ast_t* block_type = ast_type(lit_type);

  for(ast_t* p = ast_child(lit_type); p != NULL; p = ast_sibling(p))
  {
    assert(ast_id(p) == TK_LITERALBRANCH);
    ast_t* branch = (ast_t*)ast_data(p);
    assert(branch != NULL);

    if(!coerce_literal_to_type(&branch, target_type, chain, opt,
      report_errors))
    {
      ast_free_unattached(block_type);
      return false;
    }

    block_type = type_union(opt, block_type, ast_type(branch));
  }

  if(is_typecheck_error(block_type))
    return false;

  // block_type may be a sub-tree of the current type of literal_expr.
  // This means we must copy it before setting it as the type since ast_settype
  // will first free the existing type of literal_expr, which may include
  // block_type.
  if(ast_parent(block_type) != NULL)
    block_type = ast_dup(block_type);

  ast_settype(literal_expr, block_type);
  return true;
}

// Coerce a literal expression to given tuple or non-tuple types
static bool coerce_literal_to_type(ast_t** astp, ast_t* target_type,
  lit_chain_t* chain, pass_opt_t* opt, bool report_errors)
{
  assert(astp != NULL);
  ast_t* literal_expr = *astp;
  assert(literal_expr != NULL);

  ast_t* lit_type = ast_type(literal_expr);

  if(lit_type == NULL ||
    (ast_id(lit_type) != TK_LITERAL && ast_id(lit_type) != TK_OPERATORLITERAL))
  {
    // Not a literal
    return true;
  }

  if(ast_child(lit_type) != NULL)
  {
    // Control block literal
    return coerce_control_block(astp, target_type, chain, opt,
      report_errors);
  }

  switch(ast_id(literal_expr))
  {
    case TK_TUPLE:  // Tuple literal
    {
      size_t cardinality = ast_childcount(literal_expr);
      if(!coerce_group(astp, target_type, chain, cardinality, opt,
        report_errors))
        return false;

      break;
    }

    case TK_INT:
      return uif_type_from_chain(opt, literal_expr, target_type, chain,
        false, report_errors);

    case TK_FLOAT:
      return uif_type_from_chain(opt, literal_expr, target_type, chain,
        true, report_errors);

    case TK_VECTOR:
      if(!coerce_group(astp, target_type, chain, CHAIN_CARD_ARRAY, opt,
        report_errors))
        return false;
      break;

    case TK_ARRAY:
      if(!coerce_group(astp, target_type, chain, CHAIN_CARD_ARRAY, opt,
        report_errors))
        return false;
      break;

    // We get here when we have a literal vector whose type we do not yet know
    case TK_CONSTANT_OBJECT:
      if(!coerce_constant_object(astp, target_type, chain, opt, report_errors))
        return false;

      ast_settype(literal_expr, target_type);
      return true;

    case TK_SEQ:
    {
      // Only coerce the last expression in the sequence
      ast_t* last = ast_childlast(literal_expr);

      if(!coerce_literal_to_type(&last, target_type, chain, opt,
        report_errors))
        return false;

      ast_settype(literal_expr, ast_type(last));
      return true;
    }

    case TK_CALL:
    {
      AST_GET_CHILDREN(literal_expr, positional, named, receiver);
      ast_t* arg = ast_child(positional);

      if(!coerce_literal_to_type(&receiver, target_type, chain, opt,
        report_errors))
        return false;

      if(arg != NULL &&
        !coerce_literal_to_type(&arg, target_type, chain, opt,
        report_errors))
        return false;

      ast_settype(literal_expr, ast_type(ast_child(receiver)));
      return true;
    }

    case TK_DOT:
    {
      ast_t* receiver = ast_child(literal_expr);
      if(!coerce_literal_to_type(&receiver, target_type, chain, opt,
        report_errors))
        return false;

      break;
    }

    case TK_RECOVER:
    {
      ast_t* expr = ast_childidx(literal_expr, 1);
      if(!coerce_literal_to_type(&expr, target_type, chain, opt,
        report_errors))
        return false;

      break;
    }

    case TK_CONSTANT:
    {
      ast_t* expr = ast_child(literal_expr);
      if(!coerce_literal_to_type(&expr, target_type, chain, opt,
        report_errors))
        return false;

     expr_constant(opt, &literal_expr);
     return true;
    }

    default:
      ast_error(opt->check.errors, literal_expr, "Internal error, coerce_literal_to_type node %s",
        ast_get_print(literal_expr));
      assert(0);
      return false;
  }

  // Need to reprocess node now all the literals have types
  ast_settype(literal_expr, NULL);
  return (pass_expr(astp, opt) == AST_OK);
}

bool coerce_literals(ast_t** astp, ast_t* target_type, pass_opt_t* opt)
{
  assert(astp != NULL);
  ast_t* literal_expr = *astp;
  assert(literal_expr != NULL);

  if(ast_id(literal_expr) == TK_NONE)
    return true;

  ast_t* lit_type = ast_type(literal_expr);

  if(lit_type != NULL && ast_id(lit_type) != TK_LITERAL &&
    ast_id(lit_type) != TK_OPERATORLITERAL)
    return true;

  if(target_type == NULL && !unify(literal_expr, opt, true))
    return false;

  lit_chain_t chain;
  chain_init_head(&chain);
  return coerce_literal_to_type(astp, target_type, &chain, opt, true);
}

// Unify all the branches of the given AST to the same type
static bool unify(ast_t* ast, pass_opt_t* opt, bool report_errors)
{
  assert(ast != NULL);
  ast_t* type = ast_type(ast);

  if(is_typecheck_error(type))
    return false;

  if(!is_type_literal(type)) // Not literal, nothing to unify
    return true;

  assert(type != NULL);
  ast_t* non_literal = ast_type(type);

  if(non_literal != NULL)
  {
    // Type has a non-literal element, coerce literals to that
    lit_chain_t chain;
    chain_init_head(&chain);
    return coerce_literal_to_type(&ast, non_literal, &chain, opt,
      report_errors);
    //return coerce_literals(&ast, non_literal, opt);
  }

  // Still a pure literal
  return true;
}

bool literal_member_access(ast_t* ast, pass_opt_t* opt)
{
  assert(ast != NULL);
  assert(ast_id(ast) == TK_DOT || ast_id(ast) == TK_TILDE);

  AST_GET_CHILDREN(ast, receiver, name_node);

  if(!unify(receiver, opt, true))
    return false;

  ast_t* recv_type = ast_type(receiver);

  if(is_typecheck_error(recv_type))
    return false;

  if(ast_id(recv_type) != TK_LITERAL) // Literals resolved
    return true;

  // Receiver is a pure literal expression
  // Look up member name
  assert(ast_id(name_node) == TK_ID);
  const char* name = ast_name(name_node);
  lit_op_info_t* op = lookup_literal_op(name);

  if(op == NULL || ast_id(ast_parent(ast)) != TK_CALL)
  {
    ast_error(opt->check.errors, ast, "Cannot look up member %s on a literal", name);
    return false;
  }

  // This is a literal operator
  ast_t* op_type = ast_from(ast, TK_OPERATORLITERAL);
  ast_setdata(op_type, (void*)op);
  ast_settype(ast, op_type);
  return true;
}

bool literal_call(ast_t* ast, pass_opt_t* opt)
{
  assert(ast != NULL);
  assert(ast_id(ast) == TK_CALL);

  AST_GET_CHILDREN(ast, positional_args, named_args, receiver);

  ast_t* recv_type = ast_type(receiver);

  if(is_typecheck_error(recv_type))
    return false;

  if(ast_id(recv_type) == TK_LITERAL)
  {
    ast_error(opt->check.errors, ast, "Cannot call a literal");
    return false;
  }

  if(ast_id(recv_type) != TK_OPERATORLITERAL) // Nothing to do
    return true;

  lit_op_info_t* op = (lit_op_info_t*)ast_data(recv_type);
  assert(op != NULL);

  if(ast_childcount(named_args) != 0)
  {
    ast_error(opt->check.errors, named_args, "Cannot use named arguments with literal operator");
    return false;
  }

  ast_t* arg = ast_child(positional_args);

  if(arg != NULL)
  {
    if(!unify(arg, opt, true))
      return false;

    ast_t* arg_type = ast_type(arg);

    if(is_typecheck_error(arg_type))
      return false;

    if(ast_id(arg_type) != TK_LITERAL)  // Apply argument type to receiver
      return coerce_literals(&receiver, arg_type, opt);

    if(!op->can_propogate_literal)
    {
      ast_error(opt->check.errors, ast, "Cannot infer operand type");
      return false;
    }
  }

  size_t arg_count = ast_childcount(positional_args);

  if(op->arg_count != arg_count)
  {
    ast_error(opt->check.errors, ast, "Invalid number of arguments to literal operator");
    return false;
  }

  make_literal_type(ast);
  return true;
}

bool literal_is(ast_t* ast, pass_opt_t* opt)
{
  assert(ast != NULL);
  assert(ast_id(ast) == TK_IS || ast_id(ast) == TK_ISNT);

  AST_GET_CHILDREN(ast, left, right);

  ast_t* l_type = ast_type(left);
  ast_t* r_type = ast_type(right);

  if(is_typecheck_error(l_type) || is_typecheck_error(r_type))
    return false;

  if(!is_type_literal(l_type) && !is_type_literal(r_type))
    // No literals here.
    return true;

  if(is_type_literal(l_type) && !is_type_literal(r_type))
  {
    // Coerce left to type of right.
    return coerce_literals(&left, r_type, opt);
  }

  if(!is_type_literal(l_type) && is_type_literal(r_type))
  {
    // Coerce right to type of left.
    return coerce_literals(&right, l_type, opt);
  }

  // Both sides are literals, that's a problem.
  assert(is_type_literal(l_type));
  assert(is_type_literal(r_type));
  ast_error(opt->check.errors, ast, "Cannot infer type of operands");
  return false;
}

void literal_unify_control(ast_t* ast, pass_opt_t* opt)
{
  unify(ast, opt, false);
}


text:
package org.kitesdk.data;

import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Closeables;
import com.google.common.io.Resources;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.apache.avro.Schema;
import org.apache.avro.reflect.ReflectData;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.kitesdk.data.spi.ColumnMappingParser;
import org.kitesdk.data.spi.DefaultConfiguration;
import org.kitesdk.data.spi.FieldPartitioner;
import org.kitesdk.data.spi.HadoopFileSystemURLStreamHandler;
import org.kitesdk.data.spi.PartitionStrategyParser;
import org.kitesdk.data.spi.SchemaUtil;
import org.kitesdk.data.spi.Schemas;
import org.kitesdk.data.spi.partition.IdentityFieldPartitioner;
import org.kitesdk.data.spi.partition.ProvidedFieldPartitioner;

/**
 *

 * The structural definition of a {@link Dataset}.
 *

 *

 * Each {@code Dataset} has an associated {@link Schema} and optional
 * {@link PartitionStrategy} defined at the time of creation. You use instances
 * of this class to hold this information. You are strongly encouraged to use
 * the inner {@link Builder} to create new instances.
 *

 */
@Immutable
public class DatasetDescriptor {

  private final Schema schema;
  private final URL schemaUrl;
  private final URI schemaUri;
  private final Format format;
  private final URI location;
  private final Map<String, String> properties;
  private final PartitionStrategy partitionStrategy;
  private final ColumnMapping columnMappings;
  private final CompressionType compressionType;

  /**
   * Create an instance of this class with the supplied {@link Schema},
   * optional URL, {@link Format}, optional location URL, and optional
   * {@link PartitionStrategy}.
   */
  public DatasetDescriptor(Schema schema, @Nullable URL schemaUrl, Format format,
      @Nullable URI location, @Nullable Map<String, String> properties,
      @Nullable PartitionStrategy partitionStrategy) {
    this(schema, schemaUrl, format, location, properties, partitionStrategy,
        null);
  }

  /**
   * Create an instance of this class with the supplied {@link Schema}, optional
   * URL, {@link Format}, optional location URL, optional
   * {@link PartitionStrategy}, and optional {@link ColumnMapping}.
   *
   * @since 0.14.0
   */
  public DatasetDescriptor(Schema schema, @Nullable URL schemaUrl,
      Format format, @Nullable URI location,
      @Nullable Map<String, String> properties,
      @Nullable PartitionStrategy partitionStrategy,
      @Nullable ColumnMapping columnMapping) {
    this(schema, toURI(schemaUrl), format, location,
        properties, partitionStrategy, columnMapping, null);
  }

  /**
   * Create an instance of this class with the supplied {@link Schema}, optional
   * URL, {@link Format}, optional location URL, optional
   * {@link PartitionStrategy}, optional {@link ColumnMapping}, and optional
   * {@link CompressionType}.
   *
   * @since 0.17.0
   */
  public DatasetDescriptor(Schema schema, @Nullable URI schemaUri,
      Format format, @Nullable URI location,
      @Nullable Map<String, String> properties,
      @Nullable PartitionStrategy partitionStrategy,
      @Nullable ColumnMapping columnMapping,
      @Nullable CompressionType compressionType) {
    // URI can be null if the descriptor is configuring a new Dataset
    Preconditions.checkArgument(
        (location == null) || (location.getScheme() != null),
        "Location URIs must be fully-qualified and have a FS scheme.");
    checkCompressionType(format, compressionType);

    this.schema = schema;
    this.schemaUri = schemaUri;
    this.schemaUrl = toURL(schemaUri);
    this.format = format;
    this.location = location;
    if (properties != null) {
      this.properties = ImmutableMap.copyOf(properties);
    } else {
      this.properties = ImmutableMap.of();
    }
    this.partitionStrategy = partitionStrategy;
    this.columnMappings = columnMapping;

    // if no compression format is present, get the default from the format
    this.compressionType = compressionType == null ?
        this.format.getDefaultCompressionType() : compressionType;
  }

  /**
   * Get the associated {@link Schema}. Depending on the underlying storage
   * system, this schema can be simple (that is, records made up of only scalar
   * types) or complex (that is, containing other records, lists, and so on).
   * Validation of the supported schemas is performed by the managing
   * repository, not the dataset or descriptor itself.
   *
   * @return the schema
   */
  public Schema getSchema() {
    return schema;
  }

  /**
   * Get a URL from which the {@link Schema} can be retrieved (optional). This
   * method might return {@code null} if the schema is not stored at a persistent
   * URL (for example, if it were constructed from a literal string).
   *
   * @return a URL from which the schema can be retrieved
   * @since 0.3.0
   */
  @Nullable
  public URL getSchemaUrl() {
    return schemaUrl;
  }

  /**
   * Get the associated {@link Format} the data is stored in.
   *
   * @return the format
   * @since 0.2.0
   */
  public Format getFormat() {
    return format;
  }

  /**
   * Get the URL location where the data for this {@link Dataset} is stored
   * (optional).
   *

   * Due to a bug in Hadoop's {@link Path}, the URI returned by this method
   * should not be used to create a path using its {@link URI} constructor.
   * Instead, use {@code new Path(desc.getLocation().toString())}.
   *
   * @return a location URL or null if one is not set
   *
   * @since 0.8.0
   */
  @Nullable
  public URI getLocation() {
    return location;
  }

  /**
   * Get a named property.
   *
   * @param name the String property name to get.
   * @return the String value of the property, or null if it does not exist.
   *
   * @since 0.8.0
   */
  @Nullable
  public String getProperty(String name) {
    return properties.get(name);
  }

  /**
   * Check if a named property exists.
   *
   * @param name the String property name.
   * @return true if the property exists, false otherwise.
   *
   * @since 0.8.0
   */
  public boolean hasProperty(String name) {
    return properties.containsKey(name);
  }

  /**
   * List the names of all custom properties set.
   *
   * @return a Collection of String property names.
   *
   * @since 0.8.0
   */
  public Collection<String> listProperties() {
    return properties.keySet();
  }

  /**
   * Get the {@link PartitionStrategy}, if this dataset is partitioned. Calling
   * this method on a non-partitioned dataset is an error. Instead, use the
   * {@link #isPartitioned()} method prior to invocation.
   */
  public PartitionStrategy getPartitionStrategy() {
    Preconditions
        .checkState(
            isPartitioned(),
            "Attempt to retrieve the partition strategy on a non-partitioned descriptor:%s",
            this);

    return partitionStrategy;
  }

  /**
   * Get the {@link ColumnMapping}.
   *
   * @return ColumnMapping
   *
   * @since 0.14.0
   */
  public ColumnMapping getColumnMapping() {
    return columnMappings;
  }

  /**
   * Get the {@link CompressionType}
   *
   * @return the compression format
   *
   * @since 0.17.0
   */
  public CompressionType getCompressionType() {
    return compressionType;
  }

  /**
   * Returns true if an associated dataset is partitioned (that is, has an
   * associated {@link PartitionStrategy}), false otherwise.
   */
  public boolean isPartitioned() {
    return partitionStrategy != null;
  }

  /**
   * Returns true if an associated dataset is column mapped (that is, has an
   * associated {@link ColumnMapping}), false otherwise.
   *
   * @since 0.14.0
   */
  public boolean isColumnMapped() {
    return columnMappings != null;
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(schema, format, location, properties,
        partitionStrategy, columnMappings, compressionType);
  }

  @Override
  @edu.umd.cs.findbugs.annotations.SuppressWarnings(
      value="NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION",
      justification="Default annotation is not correct for equals")
  public boolean equals(@Nullable Object obj) {
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    final DatasetDescriptor other = (DatasetDescriptor) obj;
    return (
        Objects.equal(schema, other.schema) &&
        Objects.equal(format, other.format) &&
        Objects.equal(location, other.location) &&
        Objects.equal(properties, other.properties) &&
        Objects.equal(partitionStrategy, other.partitionStrategy) &&
        Objects.equal(columnMappings, other.columnMappings) &&
        Objects.equal(compressionType, other.compressionType));
  }

  @Override
  public String toString() {
    Objects.ToStringHelper helper = Objects.toStringHelper(this)
        .add("format", format)
        .add("schema", schema)
        .add("location", location)
        .add("properties", properties)
        .add("partitionStrategy", partitionStrategy)
        .add("compressionType", compressionType);
    if (isColumnMapped()) {
      helper.add("columnMapping", columnMappings);
    }
    return helper.toString();
  }

  /**
   * A fluent builder to aid in the construction of {@link DatasetDescriptor}s.
   */
  public static class Builder {

    // used to match resource:schema.avsc URIs
    private static final String RESOURCE_URI_SCHEME = "resource";

    private Configuration conf;
    private URI defaultFS;

    private Schema schema;
    private URI schemaUri;
    private Format format = Formats.AVRO;
    private URI location;
    private Map<String, String> properties;
    private PartitionStrategy partitionStrategy;
    private ColumnMapping columnMapping;
    private ColumnMapping copiedMapping;
    private CompressionType compressionType;

    public Builder() {
      this.properties = Maps.newHashMap();
      this.conf = DefaultConfiguration.get();
      try {
        this.defaultFS = FileSystem.get(conf).getUri();
      } catch (IOException e) {
        throw new DatasetIOException("Cannot get the default FS", e);
      }
    }

    /**
     * Creates a Builder configured to copy {@code descriptor}, if it is not
     * modified. This is intended to help callers copy and update descriptors
     * even though they are {@link Immutable}.
     *
     * @param descriptor A {@link DatasetDescriptor} to copy settings from
     * @since 0.7.0
     */
    public Builder(DatasetDescriptor descriptor) {
      this();
      this.schema = descriptor.schema;
      this.schemaUri = descriptor.schemaUri;
      this.format = descriptor.format;
      this.location = descriptor.location;
      this.copiedMapping = descriptor.columnMappings;
      this.compressionType = descriptor.compressionType;
      this.partitionStrategy = descriptor.partitionStrategy;
      properties.putAll(descriptor.properties);
    }

    /**
     * Configure the dataset's schema. A schema is required, and can be set
     * using one of the methods: {@code schema}, {@code schemaLiteral},
     * {@code schemaUri}, or {@code schemaFromAvroDataFile}.
     *
     * @return An instance of the builder for method chaining.
     */
    public Builder schema(Schema schema) {
      Preconditions.checkNotNull(schema, "Schema cannot be null");
      this.schema = schema;
      return this;
    }

    /**
     * Configure the dataset's schema from a {@link File}. A schema is required,
     * and can be set using one of the methods {@code schema},
     * {@code schemaLiteral}, {@code schemaUri}, or
     * {@code schemaFromAvroDataFile}.
     *
     * @return An instance of the builder for method chaining.
     */
    public Builder schema(File file) throws IOException {
      this.schema = Schemas.fromAvsc(file);
      // don't set schema URL since it is a local file not on a DFS
      return this;
    }

    /**
     * Configure the dataset's schema from an {@link InputStream}. It is the
     * caller's responsibility to close the {@link InputStream}. A schema is
     * required, and can be set using one of the methods {@code schema},
     * {@code schemaLiteral}, {@code schemaUri}, or
     * {@code schemaFromAvroDataFile}.
     *
     * @return An instance of the builder for method chaining.
     */
    public Builder schema(InputStream in) throws IOException {
      this.schema = Schemas.fromAvsc(in);
      return this;
    }

    /**
     * Configure the {@link Dataset}'s schema from a URI. A schema is required,
     * and can be set using one of the methods {@code schema},
     * {@code schemaLiteral}, {@code schemaUri}, or
     * {@code schemaFromAvroDataFile}.
     *
     * @param uri a URI object for the schema's location.
     * @return An instance of the builder for method chaining.
     * @throws IOException
     *
     * @since 0.8.0
     */
    public Builder schemaUri(URI uri) throws IOException {
      this.schemaUri = qualifiedUri(uri);
      this.schema = Schemas.fromAvsc(conf, uri);
      return this;
    }

    /**
     * Configure the {@link Dataset}'s schema from a String URI. A schema is
     * required, and can be set using one of the methods {@code schema},
     * {@code schemaLiteral}, {@code schemaUri}, or
     * {@code schemaFromAvroDataFile}.
     *
     * @param uri a String URI
     * @return An instance of the builder for method chaining.
     * @throws IOException
     *
     * @since 0.8.0
     */
    public Builder schemaUri(String uri) throws IOException {
      return schemaUri(URI.create(uri));
    }

    /**
     * Configure the dataset's schema from a {@link String}. A schema is
     * required, and can be set using one of the methods {@code schema},
     * {@code schemaLiteral}, {@code schemaUri}, or
     * {@code schemaFromAvroDataFile}.
     *
     * @return An instance of the builder for method chaining.
     *
     * @since 0.8.0
     */
    public Builder schemaLiteral(String s) {
      this.schema = new Schema.Parser().parse(s);
      return this;
    }

    /**
     * Configure the dataset's schema via a Java class type. A schema is
     * required, and can be set using one of the methods {@code schema},
     * {@code schemaLiteral}, {@code schemaUri}, or
     * {@code schemaFromAvroDataFile}.
     *
     * @return An instance of the builder for method chaining.
     * @since 0.2.0
     */
    public <T> Builder schema(Class<T> type) {
      this.schema = ReflectData.get().getSchema(type);
      return this;
    }

    /**
     * Configure the dataset's schema by using the schema from an existing Avro
     * data file. A schema is required, and can be set using one of the methods
     * {@code schema}, {@code schemaLiteral}, {@code schemaUri}, or
     * {@code schemaFromAvroDataFile}.
     *
     * @return An instance of the builder for method chaining.
     */
    public Builder schemaFromAvroDataFile(File file) throws IOException {
      this.schema = Schemas.fromAvro(file);
      return this;
    }

    /**
     * Configure the dataset's schema by using the schema from an existing Avro
     * data file. It is the caller's responsibility to close the
     * {@link InputStream}. A schema is required, and can be set using one of
     * the methods  {@code schema},  {@code schemaLiteral}, {@code schemaUri},
     * or {@code schemaFromAvroDataFile}.
     *
     * @return An instance of the builder for method chaining.
     */
    public Builder schemaFromAvroDataFile(InputStream in) throws IOException {
      this.schema = Schemas.fromAvro(in);
      return this;
    }

    /**
     * Configure the dataset's schema by using the schema from an existing Avro
     * data file. A schema is required, and can be set using one of the methods
     * {@code schema}, {@code schemaLiteral}, {@code schemaUri}, or
     * {@code schemaFromAvroDataFile}.
     *
     * @return An instance of the builder for method chaining.
     */
    public Builder schemaFromAvroDataFile(URI uri) throws IOException {
      this.schema = Schemas.fromAvro(conf, uri);
      return this;
    }

    /**
     * Configure the dataset's format (optional). If not specified
     * {@link Formats#AVRO} is used by default.
     *
     * @return An instance of the builder for method chaining.
     * @since 0.2.0
     */
    public Builder format(Format format) {
      this.format = format;
      return this;
    }

    /**
     * Configure the dataset's format from a format name String (optional). If
     * not specified, {@link Formats#AVRO} is used by default.
     *
     * @param formatName a String format name
     * @return An instance of the builder for method chaining.
     * @throws UnknownFormatException if the format name is not recognized.
     *
     * @since 0.8.0
     */
    public Builder format(String formatName) {
      return this.format(Formats.fromString(formatName));
    }

    /**
     * Configure the dataset's location (optional).
     *
     * @param uri A URI location
     * @return An instance of the builder for method chaining.
     *
     * @since 0.8.0
     */
    public Builder location(@Nullable URI uri) {
      // URI can be null if the descriptor is configuring a new Dataset
      Preconditions.checkArgument((uri == null) || (uri.getScheme() != null),
          "Location URIs must be fully-qualified and have a FS scheme.");
      this.location = uri;
      return this;
    }

    /**
     * Configure the dataset's location (optional).
     *
     * @param path A location Path
     * @return An instance of the builder for method chaining.
     *
     * @since 0.8.0
     */
    public Builder location(Path path) {
      return location(path.toString());
    }

    /**
     * Configure the dataset's location (optional).
     *
     * @param uri A location String URI
     * @return An instance of the builder for method chaining.
     *
     * @since 0.8.0
     */
    public Builder location(String uri) {
      return location(URI.create(uri));
    }

    /**
     * Add a key-value property to the descriptor.
     *
     * @param name the property name
     * @param value the property value
     * @return An instance of the builder for method chaining.
     *
     * @since 0.8.0
     */
    public Builder property(String name, String value) {
      this.properties.put(name, value);
      return this;
    }

    /**
     * Configure the dataset's partitioning strategy (optional).
     *
     * @return An instance of the builder for method chaining.
     */
    public Builder partitionStrategy(
        @Nullable PartitionStrategy partitionStrategy) {
      this.partitionStrategy = partitionStrategy;
      return this;
    }

    /**
     * Configure the dataset's partition strategy from a File.
     *
     * The File contents must be a JSON-formatted partition strategy that is
     * produced by {@link PartitionStrategy#toString()}.
     *
     * @param file
     *          The File
     * @return
     *          An instance of the builder for method chaining.
     * @throws ValidationException
     *          If the file does not contain a valid JSON-encoded partition
     *          strategy
     * @throws DatasetIOException
     *          If there is an IOException accessing the file contents
     *
     * @since 0.14.0
     */
    public Builder partitionStrategy(File file) {
      this.partitionStrategy = PartitionStrategyParser.parse(file);
      return this;
    }

    /**
     * Configure the dataset's partition strategy from an InputStream.
     *
     * The InputStream contents must be a JSON-formatted partition strategy
     * that is produced by {@link PartitionStrategy#toString()}.
     *
     * @param in
     *          The input stream
     * @return An instance of the builder for method chaining.
     * @throws ValidationException
     *          If the stream does not contain a valid JSON-encoded partition
     *          strategy
     * @throws DatasetIOException
     *          If there is an IOException accessing the InputStream contents
     *
     * @since 0.14.0
     */
    public Builder partitionStrategy(InputStream in) {
      this.partitionStrategy = PartitionStrategyParser.parse(in);
      return this;
    }

    /**
     * Configure the dataset's partition strategy from a String literal.
     *
     * The String literal is a JSON-formatted partition strategy that can be
     * produced by {@link PartitionStrategy#toString()}.
     *
     * @param literal
     *          A partition strategy String literal
     * @return This builder for method chaining.
     * @throws ValidationException
     *          If the literal is not a valid JSON-encoded partition strategy
     *
     * @since 0.14.0
     */
    public Builder partitionStrategyLiteral(String literal) {
      this.partitionStrategy = PartitionStrategyParser.parse(literal);
      return this;
    }

    /**
     * Configure the dataset's partition strategy from a URI.
     *
     * @param uri
     *          A URI to a partition strategy JSON file.
     * @return This builder for method chaining.
     * @throws ValidationException
     *          If the literal is not a valid JSON-encoded partition strategy
     *
     * @since 0.14.0
     */
    public Builder partitionStrategyUri(URI uri) throws IOException {
      InputStream in = null;
      boolean threw = true;
      try {
        in = open(uri);
        partitionStrategy(in);
        threw = false;
      } finally {
        Closeables.close(in, threw);
      }
      return this;
    }

    /**
     * Configure the dataset's partition strategy from a String URI.
     *
     * @param uri
     *          A String URI to a partition strategy JSON file.
     * @return This builder for method chaining.
     * @throws ValidationException
     *          If the literal is not a valid JSON-encoded partition strategy
     *
     * @since 0.14.0
     */
    public Builder partitionStrategyUri(String uri) throws IOException {
      return partitionStrategyUri(URI.create(uri));
    }

    /**
     * Configure the dataset's column mapping descriptor (optional)
     *
     * @param columnMappings
     *          A ColumnMapping
     * @return This builder for method chaining
     *
     * @since 0.14.0
     */
    public Builder columnMapping(
        @Nullable ColumnMapping columnMappings) {
      this.columnMapping = columnMappings;
      return this;
    }

    /**
     * Configure the dataset's column mapping descriptor from a File.
     *
     * The File contents must be a JSON-formatted column mapping. This format
     * can produced by {@link ColumnMapping#toString()}.
     *
     * @param file
     *          The file
     * @return This builder for method chaining
     * @throws ValidationException
     *          If the literal is not valid JSON-encoded column mappings
     * @throws DatasetIOException
     *          If there is an IOException accessing the file contents
     *
     * @since 0.14.0
     */
    public Builder columnMapping(File file) {
      this.columnMapping = ColumnMappingParser.parse(file);
      return this;
    }

    /**
     * Configure the dataset's column mapping descriptor from an InputStream.
     *
     * The InputStream contents must be a JSON-formatted column mapping. This
     * format can produced by {@link ColumnMapping#toString()}.
     *
     * @param in
     *          The input stream
     * @return This builder for method chaining
     * @throws ValidationException
     *          If the literal is not valid JSON-encoded column mappings
     * @throws DatasetIOException
     *          If there is an IOException accessing the InputStream contents
     *
     * @since 0.14.0
     */
    public Builder columnMapping(InputStream in) {
      this.columnMapping = ColumnMappingParser.parse(in);
      return this;
    }

    /**
     * Configure the dataset's column mappings from a String literal.
     *
     * The String literal is a JSON-formatted representation that can be
     * produced by {@link ColumnMapping#toString()}.
     *
     * @param literal
     *          A column mapping String literal
     * @return This builder for method chaining
     * @throws ValidationException
     *          If the literal is not valid JSON-encoded column mappings
     *
     * @since 0.14.0
     */
    public Builder columnMappingLiteral(String literal) {
      this.columnMapping = ColumnMappingParser.parse(literal);
      return this;
    }

    /**
     * Configure the dataset's column mappings from a URI.
     *
     * @param uri
     *          A URI to a column mapping JSON file
     * @return This builder for method chaining
     * @throws ValidationException
     *          If the literal is not valid JSON-encoded column mappings
     * @throws java.io.IOException
     *          If accessing the URI results in an IOException
     *
     * @since 0.14.0
     */
    public Builder columnMappingUri(URI uri) throws IOException {
      InputStream in = null;
      boolean threw = true;
      try {
        in = open(uri);
        columnMapping(in);
        threw = false;
      } finally {
        Closeables.close(in, threw);
      }
      return this;
    }

    /**
     * Configure the dataset's column mappings from a String URI.
     *
     * @param uri
     *          A String URI to a column mapping JSON file
     * @return This builder for method chaining
     * @throws ValidationException
     *          If the literal is not valid JSON-encoded column mappings
     * @throws java.io.IOException
     *          If accessing the URI results in an IOException
     *
     * @since 0.14.0
     */
    public Builder columnMappingUri(String uri) throws IOException {
      return columnMappingUri(URI.create(uri));
    }

    /**
     * Configure the dataset's compression format (optional). If not set,
     * default to {@link CompressionType#Snappy}.
     *
     * @param compressionType the compression format
     *
     * @return This builder for method chaining
     *
     * @since 0.17.0
     */
    public Builder compressionType(CompressionType compressionType) {
      this.compressionType = compressionType;
      return this;
    }

    /**
     * Configure the dataset's compression format (optional). If not set,
     * default to {@link CompressionType#Snappy}.
     *
     * @param compressionTypeName  the name of the compression format
     *
     * @return This builder for method chaining
     *
     * @since 0.17.0
     */
    public Builder compressionType(String compressionTypeName) {
      return compressionType(CompressionType.forName(compressionTypeName));
    }

    /**
     * Build an instance of the configured dataset descriptor. Subsequent calls
     * produce new instances that are similarly configured.
     *
     * @since 0.9.0
     */
    public DatasetDescriptor build() {
      ValidationException.check(schema != null,
          "Descriptor schema is required and cannot be null");

      // if no partition strategy is defined, check for one in the schema
      if (partitionStrategy == null) {
        if (PartitionStrategyParser.hasEmbeddedStrategy(schema)) {
          this.partitionStrategy = PartitionStrategyParser.parseFromSchema(schema);
        }
      }

      // if no column mappings are present, check for them in the schema
      if (columnMapping == null) {
        if (ColumnMappingParser.hasEmbeddedColumnMapping(schema)) {
          this.columnMapping = ColumnMappingParser.parseFromSchema(schema);
        } else if (ColumnMappingParser.hasEmbeddedFieldMappings(schema)) {
          this.columnMapping = ColumnMappingParser.parseFromSchemaFields(schema);
          if (partitionStrategy == null) {
            // For backward-compatibility, build a strategy from key values
            this.partitionStrategy = buildPartitionStrategyForKeyMappings(
                ColumnMappingParser.parseKeyMappingsFromSchemaFields(schema));
          }
        }
      }

      // if we still don't have a column mapping, see if we had one copied from
      // another descriptor
      if (columnMapping == null && copiedMapping != null) {
        columnMapping = copiedMapping;
      }

      checkPartitionStrategy(schema, partitionStrategy);
      checkColumnMappings(schema, partitionStrategy, columnMapping);
      // TODO: verify that all fields have a mapping?

      return new DatasetDescriptor(
          schema, schemaUri, format, location, properties, partitionStrategy,
          columnMapping, compressionType);
    }

    private InputStream open(URI location) throws IOException {
      if (RESOURCE_URI_SCHEME.equals(location.getScheme())) {
        return Resources.getResource(location.getRawSchemeSpecificPart()).openStream();
      } else {
        Path filePath = new Path(qualifiedUri(location));
        // even though it was qualified using the default FS, it may not be in it
        FileSystem fs = filePath.getFileSystem(conf);
        return fs.open(filePath);
      }
    }

    private URI qualifiedUri(URI location) throws IOException {
      if (RESOURCE_URI_SCHEME.equals(location.getScheme())) {
        return null;
      } else {
        boolean useDefault = defaultFS.getScheme().equals(location.getScheme());
        // work around a bug in Path where the authority for a different scheme
        // will be used for the location.
        return new Path(location)
            .makeQualified(useDefault ? defaultFS : location, new Path("/"))
            .toUri();
      }
    }

    private static void checkPartitionStrategy(
        Schema schema, @Nullable PartitionStrategy strategy) {
      if (strategy == null) {
        return;
      }
      for (FieldPartitioner fp : strategy.getFieldPartitioners()) {
        if (fp instanceof ProvidedFieldPartitioner) {
          // provided partitioners are not based on the entity fields
          continue;
        }

        // check the entity is a record if there is a non-provided partitioner
        ValidationException.check(schema.getType() == Schema.Type.RECORD,
            "Cannot partition non-records: %s", schema);

        // the source name should be a field in the schema, but not necessarily
        // the record.
        Schema fieldSchema;
        try {
          fieldSchema = SchemaUtil.fieldSchema(schema, fp.getSourceName());
        } catch (IllegalArgumentException e) {
          throw new ValidationException(
              "Cannot partition on " + fp.getSourceName(), e);
        }
        ValidationException.check(
            SchemaUtil.isConsistentWithExpectedType(
                fieldSchema.getType(), fp.getSourceType()),
            "Field type %s does not match partitioner %s",
            fieldSchema.getType(), fp);
      }
    }
  }

  private static void checkCompressionType(Format format,
      @Nullable CompressionType compressionType) {

    if (compressionType == null) {
      return;
    }

    ValidationException.check(format.getSupportedCompressionTypes()
            .contains(compressionType),
        "Format %s doesn't support compression format %s", format.getName(),
        compressionType.getName());
  }

  private static void checkColumnMappings(Schema schema,
                                          @Nullable PartitionStrategy strategy,
                                          @Nullable ColumnMapping mappings) {
    if (mappings == null) {
      return;
    }
    ValidationException.check(schema.getType() == Schema.Type.RECORD,
        "Cannot map non-records: %s", schema);
    Set<String> keyMappedFields = Sets.newHashSet();
    for (FieldMapping fm : mappings.getFieldMappings()) {
      Schema fieldSchema = SchemaUtil.fieldSchema(schema, fm.getFieldName());
      ValidationException.check(
          SchemaUtil.isConsistentWithMappingType(
              fieldSchema.getType(), fm.getMappingType()),
          "Field type %s is not compatible with mapping %s",
          fieldSchema.getType(), fm);
      if (FieldMapping.MappingType.KEY == fm.getMappingType()) {
        keyMappedFields.add(fm.getFieldName());
      }
    }
    // verify that all key mapped fields have a corresponding id partitioner
    if (strategy != null) {
      for (FieldPartitioner fp : strategy.getFieldPartitioners()) {
        if (fp instanceof IdentityFieldPartitioner) {
          keyMappedFields.remove(fp.getSourceName());
        }
      }
    }
    // any remaining keyMappedFields are invalid
    if (keyMappedFields.size() > 0) {
      throw new ValidationException(
          "Fields are key-mapped without identity partitioners: " +
          Joiner.on(", ").join(keyMappedFields));
    }
  }

  private static PartitionStrategy buildPartitionStrategyForKeyMappings(
      Map<Integer, FieldMapping> keyMappings) {
    PartitionStrategy.Builder builder = new PartitionStrategy.Builder();
    for (Integer index : new TreeSet<Integer>(keyMappings.keySet())) {
      builder.identity(keyMappings.get(index).getFieldName());
    }
    return builder.build();
  }

  private static URI toURI(@Nullable URL url) {
    if (url == null) {
      return null;
    }
    // throw IllegalArgumentException if the URL is not a URI
    return URI.create(url.toExternalForm());
  }

  private static URL toURL(@Nullable URI uri) {
    if (uri == null) {
      return null;
    }
    try {
      // try with installed URLStreamHandlers first...
      return uri.toURL();
    } catch (MalformedURLException e) {
      try {
        // if that fails then try using the Hadoop protocol handler
        return new URL(null, uri.toString(), new HadoopFileSystemURLStreamHandler());
      } catch (MalformedURLException _) {
        return null; // can't produce a URL
      }
    }
  }
}


text:
@interface SPExampleSettings : NSObject

@property (nonatomic, assign, getter = isMagicEnabled) BOOL magicEnabled;

@end


text:
import xml.etree.ElementTree as ET

class Protocol:
    """Device protocol descrition/interface."""
    def __init__(self, protocolDescriptionPath):
        self._cmds = {}
        protocol = ET.parse(protocolDescriptionPath).getroot()
        for child in protocol:
            if child.tag == 'Cmd':
                self._cmds[child.attrib['NAME']] = child.attrib['VALUE']

    def getCmd(self, cmd, **args):
        """Return protocol command, try substitute argumens."""
        cmd = self._cmds[cmd]
        for key, val in args.items():
            fmt = "%s.%dX" % ("%", len(key), )
            cmd = cmd.replace(key, fmt % val)
        return cmd

    def hasCmd(self, cmd):
        return cmd in self._cmds


text:
import { Injectable, EventEmitter } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { FTHelperService } from '../shared/service/helper/ftHelper.service';
import { catchError } from 'rxjs/operators';

@Injectable()
export class GoogleMapService {
  isLoaded = new EventEmitter();
  map: google.maps.Map;

  constructor(private http: HttpClient, private ftHelperservice: FTHelperService) { }

  loadMap(mapDiv: Element, mapOptions: google.maps.MapOptions): google.maps.Map {
    this.map = null;
    if (mapDiv != null) {
      this.map = new google.maps.Map(mapDiv, mapOptions);
    }
    return this.map;
  }

  loadBoundries(areaTypeId: number, path: string): Observable<any> {
    const baseUrl: string = path + 'maps/' + areaTypeId + '/geojson/boundaries.js';
    return this.http.get(baseUrl).pipe(catchError(error => { return this.handleError(error) }));
  }

  private handleError(errorResponse: HttpErrorResponse) {
    console.error(errorResponse);
    return throwError(errorResponse.error.message);
  }
}


text:
<template id="dice-roller-2" >

</template>


text:
extern crate log;
extern crate env_logger;

extern crate mig;

use std::sync::{Arc};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::str;
use std::thread;

use mig::quic::threaded::QuicConnection;

fn main() {
    env_logger::init().unwrap();

    let args = ::std::env::args;
    if args().len() != 3 || args().nth(1) == Some("--help".to_string()) {
        println!("Usage: tunnel_client <serverip>:<port> <targetip>:<port>");
        return;
    }

    let address = args().nth(1).unwrap();
    let target = args().nth(2).unwrap();

    let listener = match TcpListener::bind(&*address) {
        Ok(listener) => {
            listener
        },
        Err(e) => {
            error!("Cannot bind to the address: {}", e);
            return;
        },
    };

    info!("Server on {}: listening for connections...", address);

    loop {
        let (mut connection, _) = match listener.accept() {
            Ok(connection) => {
                connection
            },
            Err(e) => {
                error!("Cannot accept a connection: {}", e);
                return;
            },
        };
        let mut connection_worker = connection.try_clone().unwrap();
        info!("Got a connection");

        let quic_own = Arc::new(QuicConnection::new(target.clone()).unwrap());
        let quic_writer = quic_own.clone();

        let mut stream_own = quic_own.get_stream(2);

        let target_writer = thread::spawn(move || {
            let mut quic_writer = quic_writer.get_stream(2);

            let mut buf = vec![0; 4096];
            loop {
                let size = connection_worker.read(&mut buf).unwrap();;

                if size == 0 {
                    break;
                }

                quic_writer.write(&mut buf[..size]).unwrap();
            }
        });

        let mut buf = vec![0; 4096];
        loop {
            let size = stream_own.read(&mut buf).unwrap();;

            if size == 0 {
                break;
            }

            connection.write(&mut buf[..size]).unwrap();
        }

        target_writer.join().unwrap();
    }
}