text:
package org.nd4j.linalg.util;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.nd4j.linalg.api.blas.Level1;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.shape.Shape;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.INDArrayIndex;
import org.nd4j.linalg.indexing.Indices;
import org.nd4j.linalg.ops.transforms.Transforms;

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

/**
 * Basic INDArray ops
 *
 * @author Adam Gibson
 */
public class NDArrayUtil {

    public static INDArray exp(INDArray toExp) {
        return expi(toExp.dup());
    }

    /**
     * Returns an exponential version of this ndarray
     *
     * @param toExp the INDArray to convert
     * @return the converted ndarray
     */
    public static INDArray expi(INDArray toExp) {
        INDArray flattened = toExp.ravel();
        for (int i = 0; i < flattened.length(); i++)
            flattened.put(i, Nd4j.scalar(Math.exp((double) flattened.getScalar(i).element())));
        return flattened.reshape(toExp.shape());
    }

    /**
     * Center an array
     *
     * @param arr   the arr to center
     * @param shape the shape of the array
     * @return the center portion of the array based on the
     * specified shape
     */
    public static INDArray center(INDArray arr, int[] shape) {
        if (arr.length() < ArrayUtil.prod(shape))
            return arr;
        for (int i = 0; i < shape.length; i++)
            if (shape[i] < 1)
                shape[i] = 1;

        INDArray shapeMatrix = ArrayUtil.toNDArray(shape);
        INDArray currShape = ArrayUtil.toNDArray(arr.shape());

        INDArray startIndex = Transforms.floor(currShape.sub(shapeMatrix).divi(Nd4j.scalar(2)));
        INDArray endIndex = startIndex.add(shapeMatrix);
        INDArrayIndex[] indexes = Indices.createFromStartAndEnd(startIndex, endIndex);

        if (shapeMatrix.length() > 1)
            return arr.get(indexes);

        else {
            INDArray ret = Nd4j.create(new int[]{(int) shapeMatrix.getDouble(0)});
            int start = (int) startIndex.getDouble(0);
            int end = (int) endIndex.getDouble(0);
            int count = 0;
            for (int i = start; i < end; i++) {
                ret.putScalar(count++, arr.getDouble(i));
            }

            return ret;
        }
    }

    /**
     * Truncates an INDArray to the specified shape.
     * If the shape is the same or greater, it just returns
     * the original array
     *
     * @param nd the INDArray to truncate
     * @param n  the number of elements to truncate to
     * @return the truncated ndarray
     */
    public static INDArray truncate(INDArray nd, final int n, int dimension) {

        if (nd.isVector()) {
            INDArray truncated = Nd4j.create(new int[]{n});
            for (int i = 0; i < n; i++)
                truncated.put(i, nd.getScalar(i));
            return truncated;
        }

        if (nd.size(dimension) > n) {
            int[] targetShape = ArrayUtil.copy(nd.shape());
            targetShape[dimension] = n;
            int numRequired = ArrayUtil.prod(targetShape);
            if (nd.isVector()) {
                INDArray ret = Nd4j.create(targetShape);
                int count = 0;
                for (int i = 0; i < nd.length(); i += nd.stride()[dimension]) {
                    ret.put(count++, nd.getScalar(i));

                }
                return ret;
            } else if (nd.isMatrix()) {
                List<Double> list = new ArrayList<>();
                //row
                if (dimension == 0) {
                    for (int i = 0; i < nd.rows(); i++) {
                        INDArray row = nd.getRow(i);
                        for (int j = 0; j < row.length(); j++) {
                            if (list.size() == numRequired)
                                return Nd4j.create(ArrayUtil.toArrayDouble(list), targetShape);

                            list.add((Double) row.getScalar(j).element());
                        }
                    }
                } else if (dimension == 1) {
                    for (int i = 0; i < nd.columns(); i++) {
                        INDArray row = nd.getColumn(i);
                        for (int j = 0; j < row.length(); j++) {
                            if (list.size() == numRequired)
                                return Nd4j.create(ArrayUtil.toArrayDouble(list), targetShape);

                            list.add((Double) row.getScalar(j).element());
                        }
                    }
                } else
                    throw new IllegalArgumentException("Illegal dimension for matrix " + dimension);

                return Nd4j.create(ArrayUtil.toArrayDouble(list), targetShape);

            }

            if (dimension == 0) {
                List<INDArray> slices = new ArrayList<>();
                for (int i = 0; i < n; i++) {
                    INDArray slice = nd.slice(i);
                    slices.add(slice);
                }

                return Nd4j.create(slices, targetShape);

            } else {
                List<Double> list = new ArrayList<>();
                int numElementsPerSlice = ArrayUtil.prod(ArrayUtil.removeIndex(targetShape, 0));
                for (int i = 0; i < nd.slices(); i++) {
                    INDArray slice = nd.slice(i).ravel();
                    for (int j = 0; j < numElementsPerSlice; j++)
                        list.add((Double) slice.getScalar(j).element());
                }

                assert list.size() == ArrayUtil.prod(targetShape) : "Illegal shape for length " + list.size();

                return Nd4j.create(ArrayUtil.toArrayDouble(list), targetShape);

            }

        }

        return nd;

    }

    /**
     * Pads an INDArray with zeros
     *
     * @param nd          the INDArray to pad
     * @param targetShape the the new shape
     * @return the padded ndarray
     */
    public static INDArray padWithZeros(INDArray nd, int[] targetShape) {
        if (Arrays.equals(nd.shape(), targetShape))
            return nd;
        //no padding required
        if (ArrayUtil.prod(nd.shape()) >= ArrayUtil.prod(targetShape))
            return nd;

        INDArray ret = Nd4j.create(targetShape);
        System.arraycopy(nd.data(), 0, ret.data(), 0, (int) nd.data().length());
        return ret;

    }

    /** Tensor1DStats, used to efficiently iterate through tensors on a matrix (2d NDArray) for element-wise ops
     */
    public static Tensor1DStats get1DTensorStats(INDArray array, int dimension){
        //As per BaseNDArray.tensorAlongDimension
        int tensorLength = ArrayUtil.prod(ArrayUtil.keep(array.shape(), dimension));

        //As per tensorssAlongDimension:
        int numTensors = array.length() / tensorLength;

        //First tensor always starts with the first element in the NDArray, regardless of dimension
        int firstTensorOffset = array.offset();

        //Next: Need to work out the separation between the start (first element) of each 1d tensor
        int tensorStartSeparation;
        int elementWiseStride;  //Separation in buffer between elements in the tensor
        if(numTensors == 1){
            tensorStartSeparation = -1; //Not applicable
            elementWiseStride = array.elementWiseStride();
        } else {
            INDArray secondTensor = array.tensorAlongDimension(1, dimension);
            tensorStartSeparation = secondTensor.offset() - firstTensorOffset;
            elementWiseStride = secondTensor.elementWiseStride();
        }

        return new Tensor1DStats(firstTensorOffset,tensorStartSeparation,
                numTensors,tensorLength,elementWiseStride);
    }

    @AllArgsConstructor @Data
    public static class Tensor1DStats {
        public final int firstTensorOffset;
        public final int tensorStartSeparation;
        public final int numTensors;
        public final int tensorLength;
        public final int elementWiseStride;
    }

    /** Do element-wise operation on two NDArrays.
     * Ops:
     * 'a': addi    first += second
     * 's': subi    first -= second
     * 'm': muli    first *= second
     * 'd': divi    first /= second
     * 'p': put     first =  second
     */
    public static void doElementWiseOp(INDArray first, INDArray second, char op) {
        if(canDoElementWiseOpDirectly(first, second)){
            doOpDirectly(first,second,op);
        } else {
            //Decide which dimension we want to split on
            int opAlongDimension = chooseElementWiseTensorDimension(first, second);

            if(first.rank() == 2) {
                //Certain optimizations are possible on 2d that are not always possible on 3+d
                Tensor1DStats fs = get1DTensorStats(first, opAlongDimension);
                Tensor1DStats ss = get1DTensorStats(second, opAlongDimension);
                if (fs.tensorStartSeparation == fs.getTensorLength() * fs.getElementWiseStride() &&
                        ss.tensorStartSeparation == ss.getTensorLength() * ss.getElementWiseStride()) {
                    //One tensor ends and the next begins at same element-wise interval for both
                    doOpDirectly(first, second, op);
                } else {
                    doOpOnMatrix(first, second, op, fs, ss);
                }
            } else {
                doElementWiseOpGeneral(first,second,op);
            }
        }
    }

    /** Can we do the element-wise op directly on the arrays without breaking them up into 1d tensors first? */
    private static boolean canDoElementWiseOpDirectly(INDArray first, INDArray second){
        if(first.isVector()) return true;

        //Full buffer + matching strides -> implies all elements are contiguous (and match)
        int l1 = first.length();
        int dl1 = first.data().length();
        int l2 = second.length();
        int dl2 = second.data().length();
        int[] strides1 = first.stride();
        int[] strides2 = second.stride();
        boolean equalStrides = Arrays.equals(strides1, strides2);
        if(l1==dl1 && l2==dl2 && equalStrides) return true;

        //Strides match + are same as a zero offset NDArray -> all elements are contiguous (and match)
        int[] shape1 = first.shape();
        int[] stridesAsInit = (first.ordering()=='c' ? ArrayUtil.calcStrides(shape1) : ArrayUtil.calcStridesFortran(shape1));
        boolean stridesSameAsInit = Arrays.equals(strides1, stridesAsInit);
        if(equalStrides && stridesSameAsInit) return true;

        return false;
    }

    private static int chooseElementWiseTensorDimension(INDArray first, INDArray second){
        //doing argMin(max(first.stride(i),second.stride(i))) minimizes the maximum
        //separation between elements (helps CPU cache) BUT might result in a huge number
        //of tiny ops - i.e., addi on NDArrays with shape [5,10^6]
        int opAlongDimensionMinStride = ArrayUtil.argMinOfMax(first.stride(), second.stride());

        //doing argMax on shape gives us smallest number of largest tensors
        //but may not be optimal in terms of element separation (for CPU cache etc)
        int opAlongDimensionMaxLength = ArrayUtil.argMax(first.shape());

        //Edge cases: shapes with 1s in them can have stride of 1 on the dimensions of length 1
        if(first.size(opAlongDimensionMinStride)==1) return opAlongDimensionMaxLength;

        //Using a heuristic approach here: basically if we get >= 10x as many tensors using the minimum stride
        //dimension vs. the maximum size dimension, use the maximum size dimension instead
        //The idea is to avoid choosing wrong dimension in cases like shape=[10,10^6]
        //Might be able to do better than this with some additional thought
        int nOpsAlongMinStride = ArrayUtil.prod(ArrayUtil.keep(first.shape(), opAlongDimensionMinStride));
        int nOpsAlongMaxLength = ArrayUtil.prod(ArrayUtil.keep(first.shape(), opAlongDimensionMaxLength));
        if(nOpsAlongMinStride <= 10*nOpsAlongMaxLength) return opAlongDimensionMinStride;
        else return opAlongDimensionMaxLength;
    }

    /** Do an operation on the entire NDArray instead of breaking it up into tensors.
     * Can do this when elements are contiguous in buffer and first/second arrays
     * have same stride - i.e., when canDoElementWiseOpDirectly(...) returns true
     * */
    private static void doOpDirectly(INDArray first, INDArray second, char op){
        switch(op){
            case 'a':
            case 's':
                //first.addi(second) or first.subi(second)
                double a = (op == 'a' ? 1.0 : -1.0);
                Nd4j.getBlasWrapper().level1().axpy(first.length(), a, second, first);
                break;
            case 'm':   //muli
            case 'd':   //divi
                int incrFirst = first.elementWiseStride();
                int incrSecond = second.elementWiseStride();
                int offsetFirst = first.offset();
                int offsetSecond = second.offset();
                int opLength = first.length();
                Object arrayFirst = first.data().array();
                Object arraySecond = second.data().array();

                if(arrayFirst instanceof float[]) {
                    float[] fArr1 = (float[]) arrayFirst;
                    float[] fArr2 = (float[]) arraySecond;
                    if(op=='m') {   //muli
                        if(incrFirst == 1 && incrSecond == 1) {
                            if(offsetFirst==0 && offsetSecond == 0) {
                                muliSimpleFloat(fArr1,fArr2,opLength);
                            } else {
                                muliOffsetUnitIncrementFloat(fArr1,fArr2,opLength,offsetFirst,offsetSecond);
                            }
                        } else {
                            if(offsetFirst == 0 && offsetSecond == 0 ) {
                                muliIncrementNoOffsetFloat(fArr1,fArr2,opLength,incrFirst,incrSecond);
                            } else {
                                muliIncrementOffsetFloat(fArr1,fArr2,opLength,offsetFirst,offsetSecond,incrFirst,incrSecond);
                            }
                        }
                    } else {    //divi
                        if(incrFirst == 1 && incrSecond == 1) {
                            if(offsetFirst == 0 && offsetSecond == 0) {
                                diviSimpleFloat(fArr1,fArr2,opLength);
                            } else {
                                diviOffsetUnitIncrementFloat(fArr1,fArr2,opLength,offsetFirst,offsetSecond);
                            }
                        } else {
                            if(offsetFirst == 0 && offsetSecond == 0) {
                                diviIncrementNoOffsetFloat(fArr1,fArr2,opLength,incrFirst,incrSecond);
                            } else {
                                diviIncrementOffsetFloat(fArr1,fArr2,opLength,offsetFirst,offsetSecond,incrFirst,incrSecond);
                            }
                        }
                    }
                } else {    //double ops
                    double[] dArr1 = (double[])arrayFirst;
                    double[] dArr2 = (double[])arraySecond;
                    if(op=='m') {   //muli
                        if(incrFirst == 1 && incrSecond == 1) {
                            if(offsetFirst==0 && offsetSecond == 0) {
                                muliSimpleDouble(dArr1, dArr2, opLength);
                            } else {
                                muliOffsetUnitIncrementDouble(dArr1, dArr2, opLength, offsetFirst, offsetSecond);
                            }
                        } else {
                            if(offsetFirst==0 && offsetSecond==0){
                                muliIncrementNoOffsetDouble(dArr1, dArr2, opLength, incrFirst, incrSecond);
                            } else {
                                muliIncrementOffsetDouble(dArr1, dArr2, opLength, offsetFirst, offsetSecond, incrFirst, incrSecond);
                            }
                        }
                    } else {    //divi
                        if(incrFirst == 1 && incrSecond == 1) {
                            if(offsetFirst==0 && offsetSecond == 0) {
                                diviSimpleDouble(dArr1, dArr2, opLength);
                            } else {
                                diviOffsetUnitIncrementDouble(dArr1, dArr2, opLength, offsetFirst, offsetSecond);
                            }
                        } else {
                            if(offsetFirst == 0 && offsetSecond == 0) {
                                diviIncrementNoOffsetDouble(dArr1, dArr2, opLength, incrFirst, incrSecond);
                            } else {
                                diviIncrementOffsetDouble(dArr1, dArr2, opLength, offsetFirst, offsetSecond, incrFirst, incrSecond);
                            }
                        }
                    }
                }
                break;
            case 'p':   //put / copy
                Nd4j.getBlasWrapper().level1().copy(second,first); //first = second
                break;
            default:
                throw new UnsupportedOperationException("Unknown op: " + op);
        }
    }

    /** For 2d arrays (matrices) we can utilize the fact that each 1d tensor is separated by a fixed amount.
     * This allows us to avoid the cost of multiple calls to tensorAlongDimension
     * This does not always hold for 3+d matrices
     */
    private static void doOpOnMatrix(INDArray first, INDArray second, char op, Tensor1DStats fs, Tensor1DStats ss) {
        DataBuffer df = first.data();
        DataBuffer ds = second.data();
        int n = fs.getTensorLength();
        int nTensors = fs.getNumTensors();
        int incrF = fs.getElementWiseStride();
        int incrS = ss.getElementWiseStride();
        Level1 l1Blas = Nd4j.getBlasWrapper().level1();
        switch(op){
            case 'a':
            case 's':
                //first.addi(second) or first.subi(second)
                double a = (op == 'a' ? 1.0 : -1.0);
                for(int i = 0; i<nTensors; i++) {
                    int offset1 = fs.getFirstTensorOffset() + i*fs.getTensorStartSeparation();
                    int offset2 = ss.getFirstTensorOffset() + i*ss.getTensorStartSeparation();
                    l1Blas.axpy(n, a, ds, offset2, incrS, df, offset1, incrF);
                }
                break;
            case 'm':
                //muli
                Object arrayFirst = first.data().array();
                Object arraySecond = second.data().array();
                if(arrayFirst instanceof float[]) {
                    float[] f1 = (float[])arrayFirst;
                    float[] f2 = (float[])arraySecond;
                    if (incrF == 1 && incrS == 1) {
                        for (int i = 0; i < nTensors; i++) {
                            int offset1 = fs.getFirstTensorOffset() + i * fs.getTensorStartSeparation();
                            int offset2 = ss.getFirstTensorOffset() + i * ss.getTensorStartSeparation();
                            muliOffsetUnitIncrementFloat(f1,f2,n,offset1,offset2);
                        }
                    } else {
                        for (int i = 0; i < nTensors; i++) {
                            int offset1 = fs.getFirstTensorOffset() + i * fs.getTensorStartSeparation();
                            int offset2 = ss.getFirstTensorOffset() + i * ss.getTensorStartSeparation();
                            muliIncrementOffsetFloat(f1,f2,n,offset1,offset2,incrF,incrS);
                        }
                    }
                } else {
                    double[] f1 = (double[])arrayFirst;
                    double[] f2 = (double[])arraySecond;
                    if (incrF == 1 && incrS == 1) {
                        for (int i = 0; i < nTensors; i++) {
                            int offset1 = fs.getFirstTensorOffset() + i * fs.getTensorStartSeparation();
                            int offset2 = ss.getFirstTensorOffset() + i * ss.getTensorStartSeparation();
                            muliOffsetUnitIncrementDouble(f1, f2, n, offset1, offset2);
                        }
                    } else {
                        for (int i = 0; i < nTensors; i++) {
                            int offset1 = fs.getFirstTensorOffset() + i * fs.getTensorStartSeparation();
                            int offset2 = ss.getFirstTensorOffset() + i * ss.getTensorStartSeparation();
                            muliIncrementOffsetDouble(f1, f2, n, offset1, offset2, incrF, incrS);
                        }
                    }
                }
                break;
            case 'd':
                //divi
                Object arrayFirstd = first.data().array();
                Object arraySecondd = second.data().array();
                if(arrayFirstd instanceof float[]) {
                    float[] f1 = (float[])arrayFirstd;
                    float[] f2 = (float[])arraySecondd;
                    if (incrF == 1 && incrS == 1) {
                        for (int i = 0; i < nTensors; i++) {
                            int offset1 = fs.getFirstTensorOffset() + i * fs.getTensorStartSeparation();
                            int offset2 = ss.getFirstTensorOffset() + i * ss.getTensorStartSeparation();
                            diviOffsetUnitIncrementFloat(f1,f2,n,offset1,offset2);
                        }
                    } else {
                        for (int i = 0; i < nTensors; i++) {
                            int offset1 = fs.getFirstTensorOffset() + i * fs.getTensorStartSeparation();
                            int offset2 = ss.getFirstTensorOffset() + i * ss.getTensorStartSeparation();
                            diviIncrementOffsetFloat(f1,f2,n,offset1,offset2,incrF,incrS);
                        }
                    }
                } else {
                    double[] f1 = (double[])arrayFirstd;
                    double[] f2 = (double[])arraySecondd;
                    if (incrF == 1 && incrS == 1) {
                        for (int i = 0; i < nTensors; i++) {
                            int offset1 = fs.getFirstTensorOffset() + i * fs.getTensorStartSeparation();
                            int offset2 = ss.getFirstTensorOffset() + i * ss.getTensorStartSeparation();
                            diviOffsetUnitIncrementDouble(f1,f2,n,offset1,offset2);
                        }
                    } else {
                        for (int i = 0; i < nTensors; i++) {
                            int offset1 = fs.getFirstTensorOffset() + i * fs.getTensorStartSeparation();
                            int offset2 = ss.getFirstTensorOffset() + i * ss.getTensorStartSeparation();
                            diviIncrementOffsetDouble(f1,f2,n,offset1,offset2,incrF,incrS);
                        }
                    }
                }
                break;
            case 'p':   //put / copy
                for(int i=0; i<nTensors; i++ ) {
                    int offset1 = fs.getFirstTensorOffset() + i*fs.getTensorStartSeparation();
                    int offset2 = ss.getFirstTensorOffset() + i*ss.getTensorStartSeparation();
                    l1Blas.copy(n,ds,offset2,incrS,df,offset1,incrF);
                }
                break;
            default:
                throw new RuntimeException("Unknown op: " + op);
        }
    }

    private static void doElementWiseOpGeneral(INDArray first, INDArray second, char op){
        //Decide which dimension we want to split on
        int opAlongDimension = chooseElementWiseTensorDimension(first, second);
        int nTensors = first.tensorssAlongDimension(opAlongDimension);

        DataBuffer df = first.data();
        DataBuffer ds = second.data();
        Level1 l1Blas = Nd4j.getBlasWrapper().level1();
        switch(op){
            case 'a':
            case 's':
                //first.addi(second) or first.subi(second)
                double a = (op == 'a' ? 1.0 : -1.0);
                for(int i=0; i<nTensors; i++ ) {
                    INDArray tad1 = first.tensorAlongDimension(i,opAlongDimension);
                    INDArray tad2 = second.tensorAlongDimension(i,opAlongDimension);
                    l1Blas.axpy(tad1.length(),a,ds,tad2.offset(),tad2.elementWiseStride(),df,tad1.offset(),tad1.elementWiseStride());
                }
                break;
            case 'm':
                //muli
                Object arrayFirst = df.array();
                Object arraySecond = ds.array();
                if(arrayFirst instanceof float[]) {
                    float[] f1 = (float[])arrayFirst;
                    float[] f2 = (float[])arraySecond;
                    for (int i = 0; i < nTensors; i++) {
                        INDArray tad1 = first.tensorAlongDimension(i,opAlongDimension);
                        INDArray tad2 = second.tensorAlongDimension(i,opAlongDimension);
                        muliIncrementOffsetFloat(f1,f2,tad1.length(),tad1.offset(),tad2.offset(),tad1.elementWiseStride(),tad2.elementWiseStride());
                    }
                } else {
                    double[] f1 = (double[])arrayFirst;
                    double[] f2 = (double[])arraySecond;
                    for (int i = 0; i < nTensors; i++) {
                        INDArray tad1 = first.tensorAlongDimension(i,opAlongDimension);
                        INDArray tad2 = second.tensorAlongDimension(i,opAlongDimension);
                        muliIncrementOffsetDouble(f1, f2, tad1.length(), tad1.offset(), tad2.offset(), tad1.elementWiseStride(), tad2.elementWiseStride());
                    }
                }
                break;
            case 'd':
                //divi
                Object arrayFirstd = first.data().array();
                Object arraySecondd = second.data().array();
                if(arrayFirstd instanceof float[]) {
                    float[] f1 = (float[])arrayFirstd;
                    float[] f2 = (float[])arraySecondd;
                    for (int i = 0; i < nTensors; i++) {
                        INDArray tad1 = first.tensorAlongDimension(i,opAlongDimension);
                        INDArray tad2 = second.tensorAlongDimension(i,opAlongDimension);
                        diviIncrementOffsetFloat(f1,f2,tad1.length(),tad1.offset(),tad2.offset(),tad1.elementWiseStride(),tad2.elementWiseStride());
                    }
                } else {
                    double[] f1 = (double[])arrayFirstd;
                    double[] f2 = (double[])arraySecondd;
                    for (int i = 0; i < nTensors; i++) {
                        INDArray tad1 = first.tensorAlongDimension(i,opAlongDimension);
                        INDArray tad2 = second.tensorAlongDimension(i,opAlongDimension);
                        diviIncrementOffsetDouble(f1,f2,tad1.length(),tad1.offset(),tad2.offset(),tad1.elementWiseStride(),tad2.elementWiseStride());
                    }
                }
                break;
            case 'p':   //put / copy
                for(int i=0; i<nTensors; i++ ) {
                    INDArray tad1 = first.tensorAlongDimension(i,opAlongDimension);
                    INDArray tad2 = second.tensorAlongDimension(i,opAlongDimension);
                    l1Blas.copy(tad1.length(),ds,tad2.offset(),tad2.elementWiseStride(),df,tad1.offset(),tad1.elementWiseStride());
                }
                break;
            default:
                throw new RuntimeException("Unknown op: " + op);
        }

    }

    /** Do element-wise vector operation on an NDArray (using a vector NDArray)
     * Ops:
     * When vector is a row vector:
     * 'a': addiRowVector    first.eachRow += second
     * 's': subiRowVector    first.eachRow -= second
     * 'm': muliRowVector    first.eachRow *= second
     * 'd': diviRowVector    first.eachRow /= second
     * 'p': putRowVector     first.eachRow =  second
     * 'h': rsubiRowVector   first.eachRow = second - first.eachRow
     * 't': rdiviRowVector   first.eachRow = second / first.eachRow
     *
     * When vector is a column vector: do column-wise instead of row-wise ops
     */
    public static void doVectorOp(INDArray array, INDArray vector, char op){
        if(array.rank() != 2) throw new IllegalArgumentException("Cannot do row/column operation on non-2d matrix");
        boolean rowOp = Shape.isRowVectorShape(vector.shape());
        //Edge case: 'vector' is actually a scalar
        if(vector.length() == 1){
            //Expect 'array' to be a vector also
            if(array.isRowVector()){
                rowOp = false;
            } else if(array.isColumnVector()){
                rowOp = true;
            } else throw new IllegalArgumentException("Invalid input: vector input is a scalar but array is not a vector");
        }

        Tensor1DStats tensorStats = get1DTensorStats(array, (rowOp ? 1 : 0));

        int incr = tensorStats.getElementWiseStride();
        int incrVec = vector.elementWiseStride();
        int offsetVec = vector.offset();
        int opLength = vector.length();
        int nTensors = tensorStats.getNumTensors();

        DataBuffer buffer = array.data();
        DataBuffer bufferVec = vector.data();

        Object dataArray = buffer.array();
        Object dataArrayVec = bufferVec.array();
        float[] dataFloat;
        float[] dataFloatVec;
        double[] dataDouble;
        double[] dataDoubleVec;
        if(dataArray instanceof float[]){
            dataFloat = (float[])dataArray;
            dataFloatVec = (float[])dataArrayVec;
            dataDouble = null;
            dataDoubleVec = null;
        } else {
            dataFloat = null;
            dataFloatVec = null;
            dataDouble = (double[])dataArray;
            dataDoubleVec = (double[])dataArrayVec;
        }

        Level1 l1Blas = Nd4j.getBlasWrapper().level1();
        switch(op){
            case 'a':   //addiXVector
            case 's':   //subiXVector
                double a = (op == 'a' ? 1.0 : -1.0);
                for( int i=0; i<nTensors; i++){
                    int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                    l1Blas.axpy(opLength, a, bufferVec, offsetVec, incrVec, buffer, tOffset, incr);
                }
                break;
            case 'm':   //muliXVector
                if(dataFloat != null){
                    if(incr==1 && incrVec==1){
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            muliOffsetUnitIncrementFloat(dataFloat,dataFloatVec,opLength,tOffset,offsetVec);
                        }
                    } else {
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            muliIncrementOffsetFloat(dataFloat, dataFloatVec, opLength, tOffset, offsetVec, incr, incrVec);
                        }
                    }
                } else {
                    if(incr==1 && incrVec==1){
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            muliOffsetUnitIncrementDouble(dataDouble, dataDoubleVec, opLength, tOffset, offsetVec);
                        }
                    } else {
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            muliIncrementOffsetDouble(dataDouble, dataDoubleVec, opLength, tOffset, offsetVec, incr, incrVec);
                        }
                    }
                }
                break;
            case 'd':   //diviXVector
                if(dataFloat != null){
                    if(incr==1 && incrVec==1){
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            diviOffsetUnitIncrementFloat(dataFloat, dataFloatVec, opLength, tOffset, offsetVec);
                        }
                    } else {
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            diviIncrementOffsetFloat(dataFloat, dataFloatVec, opLength, tOffset, offsetVec, incr, incrVec);
                        }
                    }
                } else {
                    if(incr==1 && incrVec==1){
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            diviOffsetUnitIncrementDouble(dataDouble, dataDoubleVec, opLength, tOffset, offsetVec);
                        }
                    } else {
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            diviIncrementOffsetDouble(dataDouble, dataDoubleVec, opLength, tOffset, offsetVec, incr, incrVec);
                        }
                    }
                }
                break;
            case 'p':   //putiXVector
                for(int i=0; i<nTensors; i++ ) {
                    int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                    l1Blas.copy(opLength,bufferVec,offsetVec,incrVec,buffer,tOffset,incr);
                }
                break;
            case 'h':   //rsubiXVector
                if(dataFloat != null){
                    if(incr==1 && incrVec==1){
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            rsubiOffsetUnitIncrementFloat(dataFloat, dataFloatVec, opLength, tOffset, offsetVec);
                        }
                    } else {
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            rsubiIncrementOffsetFloat(dataFloat, dataFloatVec, opLength, tOffset, offsetVec, incr, incrVec);
                        }
                    }
                } else {
                    if(incr==1 && incrVec==1){
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            rsubiOffsetUnitIncrementDouble(dataDouble, dataDoubleVec, opLength, tOffset, offsetVec);
                        }
                    } else {
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            rsubiIncrementOffsetDouble(dataDouble, dataDoubleVec, opLength, tOffset, offsetVec, incr, incrVec);
                        }
                    }
                }
                break;
            case 't':   //rdiviXVector
                if(dataFloat != null){
                    if(incr==1 && incrVec==1){
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            rdiviOffsetUnitIncrementFloat(dataFloat, dataFloatVec, opLength, tOffset, offsetVec);
                        }
                    } else {
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            rdiviIncrementOffsetFloat(dataFloat, dataFloatVec, opLength, tOffset, offsetVec, incr, incrVec);
                        }
                    }
                } else {
                    if(incr==1 && incrVec==1){
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            rdiviOffsetUnitIncrementDouble(dataDouble, dataDoubleVec, opLength, tOffset, offsetVec);
                        }
                    } else {
                        for( int i=0; i<nTensors; i++ ){
                            int tOffset = tensorStats.getFirstTensorOffset() + i*tensorStats.getTensorStartSeparation();
                            rdiviIncrementOffsetDouble(dataDouble, dataDoubleVec, opLength, tOffset, offsetVec, incr, incrVec);
                        }
                    }
                }
                break;
            default:
                throw new RuntimeException("Unknown op: " + op);
        }

    }

    //muli - float
    private static void muliIncrementOffsetFloat(float[] first, float[] second, int opLength, int offsetFirst, int offsetSecond, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            first[offsetFirst + i * incrFirst] *= second[offsetSecond + i * incrSecond];
        }
    }

    private static void muliIncrementNoOffsetFloat(float[] first, float[] second, int opLength, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            first[i * incrFirst] *= second[i * incrSecond];
        }
    }

    private static void muliOffsetUnitIncrementFloat(float[] first, float[] second, int opLength, int offsetFirst, int offsetSecond){
        for (int i = 0; i < opLength; i++) {
            first[offsetFirst + i] *= second[offsetSecond + i];
        }
    }

    private static void muliSimpleFloat(float[] first, float[] second, int opLength){
        for (int i = 0; i < opLength; i++) {
            first[i] *= second[i];
        }
    }

    //muli - double
    private static void muliIncrementOffsetDouble(double[] first, double[] second, int opLength, int offsetFirst, int offsetSecond, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            first[offsetFirst + i * incrFirst] *= second[offsetSecond + i * incrSecond];
        }
    }

    private static void muliIncrementNoOffsetDouble(double[] first, double[] second, int opLength, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            first[i * incrFirst] *= second[i * incrSecond];
        }
    }

    private static void muliOffsetUnitIncrementDouble(double[] first, double[] second, int opLength, int offsetFirst, int offsetSecond){
        for (int i = 0; i < opLength; i++) {
            first[offsetFirst + i] *= second[offsetSecond + i];
        }
    }

    private static void muliSimpleDouble(double[] first, double[] second, int opLength){
        for (int i = 0; i < opLength; i++) {
            first[i] *= second[i];
        }
    }

    //divi - float
    private static void diviIncrementOffsetFloat(float[] first, float[] second, int opLength, int offsetFirst, int offsetSecond, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            first[offsetFirst + i * incrFirst] /= second[offsetSecond + i * incrSecond];
        }
    }

    private static void diviIncrementNoOffsetFloat(float[] first, float[] second, int opLength, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            first[i * incrFirst] /= second[i * incrSecond];
        }
    }

    private static void diviOffsetUnitIncrementFloat(float[] first, float[] second, int opLength, int offsetFirst, int offsetSecond){
        for (int i = 0; i < opLength; i++) {
            first[offsetFirst + i] /= second[offsetSecond + i];
        }
    }

    private static void diviSimpleFloat(float[] first, float[] second, int opLength){
        for (int i = 0; i < opLength; i++) {
            first[i] /= second[i];
        }
    }

    //divi - double
    private static void diviIncrementOffsetDouble(double[] first, double[] second, int opLength, int offsetFirst, int offsetSecond, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            first[offsetFirst + i * incrFirst] /= second[offsetSecond + i * incrSecond];
        }
    }

    private static void diviIncrementNoOffsetDouble(double[] first, double[] second, int opLength, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            first[i * incrFirst] /= second[i * incrSecond];
        }
    }

    private static void diviOffsetUnitIncrementDouble(double[] first, double[] second, int opLength, int offsetFirst, int offsetSecond){
        for (int i = 0; i < opLength; i++) {
            first[offsetFirst + i] /= second[offsetSecond + i];
        }
    }

    private static void diviSimpleDouble(double[] first, double[] second, int opLength){
        for (int i = 0; i < opLength; i++) {
            first[i] /= second[i];
        }
    }

    //rsubi - float
    private static void rsubiIncrementOffsetFloat(float[] first, float[] second, int opLength, int offsetFirst, int offsetSecond, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            int fIdx = offsetFirst + i * incrFirst;
            first[fIdx] = second[offsetSecond + i * incrSecond] - first[fIdx];
        }
    }

    private static void rsubiOffsetUnitIncrementFloat(float[] first, float[] second, int opLength, int offsetFirst, int offsetSecond){
        for (int i = 0; i < opLength; i++) {
            int fIdx = offsetFirst + i;
            first[fIdx] = second[offsetSecond + i] - first[fIdx];
        }
    }

    //rsubi - double
    private static void rsubiIncrementOffsetDouble(double[] first, double[] second, int opLength, int offsetFirst, int offsetSecond, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            int fIdx = offsetFirst + i * incrFirst;
            first[fIdx] = second[offsetSecond + i * incrSecond] - first[fIdx];
        }
    }

    private static void rsubiOffsetUnitIncrementDouble(double[] first, double[] second, int opLength, int offsetFirst, int offsetSecond){
        for (int i = 0; i < opLength; i++) {
            int fIdx = offsetFirst + i;
            first[fIdx] = second[offsetSecond + i] - first[fIdx];
        }
    }

    //rdivi - float
    private static void rdiviIncrementOffsetFloat(float[] first, float[] second, int opLength, int offsetFirst, int offsetSecond, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            int fIdx = offsetFirst + i * incrFirst;
            first[fIdx] = second[offsetSecond + i * incrSecond] / first[fIdx];
        }
    }

    private static void rdiviOffsetUnitIncrementFloat(float[] first, float[] second, int opLength, int offsetFirst, int offsetSecond){
        for (int i = 0; i < opLength; i++) {
            int fIdx = offsetFirst + i;
            first[fIdx] = second[offsetSecond + i] / first[fIdx];
        }
    }

    //rdivi - double
    private static void rdiviIncrementOffsetDouble(double[] first, double[] second, int opLength, int offsetFirst, int offsetSecond, int incrFirst, int incrSecond){
        for (int i = 0; i < opLength; i++) {
            int fIdx = offsetFirst + i * incrFirst;
            first[fIdx] = second[offsetSecond + i * incrSecond] / first[fIdx];
        }
    }

    private static void rdiviOffsetUnitIncrementDouble(double[] first, double[] second, int opLength, int offsetFirst, int offsetSecond){
        for (int i = 0; i < opLength; i++) {
            int fIdx = offsetFirst + i;
            first[fIdx] = second[offsetSecond + i] / first[fIdx];
        }
    }

}


text:
var http = require('http'),
    connect = require('connect'),
    httpProxy = require('http-proxy');

var proxymap = new Object();

var RoutingInfo = require("../models/RoutingInfo");

function configuration(portnumber, configid, targeturl, proxyurl, originalstring, stringtoreplace) {

                this.portnumber = portnumber;
                this.configid   = configid;
                this.targeturl  = targeturl;
                this.proxyurl   = proxyurl;
                this.originalstring = originalstring;
                this.stringtoreplace = stringtoreplace;

}

//update a routing tabel entry with proxyurl  for a configuration
function updateRoutingInfowithUrl(configid, proxyport)
{
  var query = {'configid' : configid};
  var update = { $set : { 'proxyurl' : "localhost:"+proxyport, 'status' : true } };

  RoutingInfo.update(query, update, function(err, num){
    if(err)
      throw err;
    //console.log( (err === null) ? { msg: 'updated' } : { msg: err });

  });

}

exports.createChangeResponseProxy=function(req,res) {

  var portnumber = generatePortNumber();
  //create a configuration object
  var config = new configuration();
 // var app = connect();
 // var  proxy = 'http://localhost:9013'

  config.portnumber = portnumber;
  config.configid = req.body.configid;
  console.log(config);

  RoutingInfo.findOne({"configid" : config.configid}, function(err, routingdb){
    if(err)
      res.send(err);

    //get configuration from db
    config.targeturl = routingdb.targeturl;
    config.originalstring = routingdb.originalresponse;
    config.stringtoreplace = routingdb.modifiedresponse;

    console.log("Routing db: "  + routingdb);
    console.log("Got config: " + config.originalstring +  " " + config.stringtoreplace);

    res.json({msg : "Proxyserver running on " + "localhost:" + config.portnumber, port: "localhost" + config.portnumber });

    //create change response proxy using connect middleware
    buildProxyServer(config);

  });

}

//stop the server
exports.stopChangeResponseProxy = function(req, res){

  var server = proxymap[req.params.configid];
  if(server === undefined) {

    res.json({msg : "Server not running"});

  } else {
    server.close();
    delete proxymap[req.params.configid];
    res.json({msg : "Proxy Stopped"});

  }

  RoutingInfo.update({'configid' : req.params.configid}, { $set : {'status' : false, 'proxyurl' : null} }, function(err, data){
    if(err)
      throw err;
    console.log( (err === null) ? { msg: 'updated' + data } : { msg: err });
  });
}

function buildProxyServer(config)
{
  console.log("Building ProxyServer to alter response with: " + config);
  var app = connect();
  var proxy = httpProxy.createProxyServer({target: config.targeturl});

  app.use(

		  function(req, res, next) {
			  if(req.method === 'GET'){
				  var _write = res.write;
				  res.write = function(data) {

					  _write.call(res,data.toString().replace(config.originalstring, config.stringtoreplace));
				  }
				  proxy.web(req,res);
		         }
});
		  var port = generatePortNumber();
		  var connectserver = http.createServer(app).listen(config.portnumber);
		  proxymap[config.configid] = connectserver;
		  console.log(connectserver);
		  updateRoutingInfowithUrl(config.configid, config.portnumber);
		 }

/////////////////////////////////////
  //var connectserver = connect.createServer( function (req, res, next) {

  //   var _write = res.write;

    //disable favicon
   // if(req.url === '/favicon.ico')
   // {
   //   console.log("favicon disabled");
   //   res.end();
   //   return;
   // }

   // res.write = function (data) {

     // console.log("data is: " + data);
     // _write.call(res, data.toString().replace(config.originalstring, config.stringtoreplace));

   // }
   // next();
 // },
 // function (req, res) {
  //  proxy.web(req, res);
 // }

//)
  //  connectserver.listen(config.portnumber);

   // proxymap[config.configid] = connectserver;

 //   console.log("Connectserver : " + connectserver);

    //poll the database at defined interval
   // var polldb = setInterval(function(){

     // RoutingInfo.findOne({"configid" : config.configid}, function(err, routingdb){
      //  if(err)
        //  res.send(err)

       // if(routingdb === null)
        //{
         // clearInterval(poll);
        //}
       // if(!Boolean(routingdb.status))  // check the status of proxy-server, if not running dnt get data
       // {
         // flag = false;
         // console.log("Stopping the db Polling");
          //clearInterval(polldb);
        //}
        //else
       // {
        //  config.targeturl = routingdb.targeturl;
         // config.originalstring = routingdb.originalresponse;
         // config.modifiedresponse = routingdb.modifiedresponse;
         // console.log("Polling the db " + config.targeturl);
       // }
      //});

    //}, 10000);

/*   var proxy = httpProxy.createProxyServer({ target: config.targeturl });

    updateRoutingInfowithUrl(config.configid, config.portnumber);

    process.on('uncaughtException', function (err) {

      //assign a new port if previous one is alreay in use and update routing table
      if(err.errno === "EADDRINUSE")
      {
        var port =  generatePortNumber();
        console.log(port);
        config.portnumber = port;
        connectserver.listen(port);
        updateRoutingInfowithUrl(config.configid, port);
      }
        console.log("Error occured");
        console.log(err);

    });

}

*/
//generate port numbers to run proxy server on demand
function generatePortNumber()
{
  var proxyport = Math.floor(Math.random() * 16383) + 49152;
  return proxyport;
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from collections import namedtuple
from datetime import datetime
import csv

from django.contrib.gis.geos import Point
from django.core.management.base import BaseCommand
from django.db import transaction
import pytz

from ddsc_core.models import Location
from ddsc_core.utils import transform

ETRS89 = 4258  # European Terrestrial Reference System 1989

# The named fields below correspond to the 12 columns in Fugro's Excel sheet.
# Fugro did not process `real_geometry` and `srid_real_geometry` in their
# original code. Question: why would one need `srid_real_geometry` if
# `real_geometry` is in EWKT?

row = namedtuple(
    'LocationRow', 'uuid, name, x, y, z, srid, parent_uuid, real_geometry, '
    'srid_real_geometry, description, geometry_precision, relative_location'
)

# Apparently, `real_geometry` has not been missed in 2 years, so it may
# safely be regarded as obsolete.

class Command(BaseCommand):
    args = '<CSV file>'
    help = 'Imports a CSV file of locations into the database.'

    @transaction.commit_on_success
    def handle(self, *args, **options):
        with open(args[0], 'rU') as f:

            # Loop over each row (i.e. Location) in the CSV file.
            for r in map(row._make, csv.reader(f)):

                # Create a new instance of Location.
                if r.parent_uuid:
                    # It's a child node.
                    parent = Location.objects.get(uuid=r.parent_uuid)
                    location = parent.add_child(name=r.name)
                else:
                    # It's a root node.
                    location = Location.add_root(name=r.name)

                # Assign properties.
                location.description = r.description
                location.geometry_precision = str2float(r.geometry_precision)
                point_geometry = point(r)
                location.point_geometry = point_geometry
                location.show_on_map = True if point_geometry else False
                location.relative_location = r.relative_location
                location.uuid = r.uuid
                location.created = datetime.now(tz=pytz.utc)

                # Persist to database.
                self.stdout.write("Saving {}.".format(location))
                location.save()

def str2float(s):
    "Create a float from its string representation."
    try:
        f = float(s)
    except ValueError:
        f = None
    return f

def point(r):
    "Create an ETRS89 point from x, y, z and srid."
    try:
        p = Point([float(r.x), float(r.y), float(r.z)], srid=int(r.srid))
        p = transform(p, ETRS89, clone=True)
    except ValueError:
        p = None
    return p


text:
'use strict';

(function() {
    angular.module('sdm.upload.directives.sdmUploadAttachment',[
            'angularFileUpload', 'ngCookies',
            'sdm.authentication.services.sdmUserManager',
            'sdm.upload.services.SdmMD5'])
        .directive('sdmUploadAttachment', ['$q', '$upload', '$cookieStore', 'sdmUserManager', 'SdmMD5',
            function ($q, $upload, $cookieStore, sdmUserManager, SdmMD5) {
                return {
                    restrict: 'E',
                    scope: false,
                    replace: false, // Replace with the template below
                    transclude: false,// we want to insert custom content inside the directive
                    controller: function(){},
                    controllerAs: 'sdmULController',
                    link: function($scope, $element, $attrs, sdmULController) {
                        console.log('upload', sdmULController);
                        console.log($scope);
                        sdmULController.files = [];

                        sdmULController.addFiles = function() {
                            sdmULController.errorMessage = null;
                            addFilesToQueue(sdmULController.newFiles)
                            processQueue(false);
                        }
                        sdmULController.uploadInProgress = false;
                        sdmULController.queueLength = 0;
                        sdmULController.processedFiles = 0;
                        var processQueue = function(isIterating) {
                            if (sdmULController.uploadInProgress && !isIterating) {
                                return;
                            }
                            sdmULController.progressPercentage = 0;
                            if (!sdmULController.files.length) {
                                sdmULController.uploadInProgress = false;
                                sdmULController.processedFiles = 0;
                                sdmULController.queueLength = 0;
                                return;
                            } else {
                                sdmULController.uploadInProgress = true;
                                var file = sdmULController.files.shift();
                                sdmULController.processingFileName = file.name;
                                uploadFile(file).then(
                                    function() {
                                        sdmULController.processedFiles++;
                                        processQueue(true);
                                    }
                                );
                            }
                        }

                        var addFilesToQueue = function(newFiles) {
                            console.log(newFiles);
                            sdmULController.queueLength += newFiles.length;
                            angular.forEach(newFiles, function(file){
                                if (file.type !== 'directory') {
                                    sdmULController.files.push(file);
                                }
                            });
                        }
                        var currentShaPromise;
                        var sdmMD5;
                        var uploadFile = function(file) {
                            var deferred = $q.defer();
                            var url = BASE_URL + [$scope.node.level.name,
                                $scope.node.id,
                                'file',
                                file.name + '?flavor=attachment&site=' + $scope.node.site].join('/');
                            var accessData = $cookieStore.get(SDM_KEY_CACHED_ACCESS_DATA);
                            var accessToken = typeof accessData !== undefined? accessData.access_token:undefined;
                            sdmMD5 = new SdmMD5(file);
                            sdmULController.calculatingMD5 = true;
                            sdmMD5.promise.then(function(md5){
                                    console.log(md5);
                                    sdmULController.calculatingMD5 = false;
                                    sdmULController.progressPercentage = 0;
                                    sdmULController.currentFile = uploadToAPI(
                                        url,
                                        file,
                                        accessToken,
                                        md5,
                                        deferred
                                    );
                                },
                                null,
                                function(progress){
                                    sdmULController.progressPercentage = progress;
                                }
                            );
                            return deferred.promise;
                        }

                        var uploadToAPI = function(url, file, accessToken, md5, deferred, retry) {
                            return $upload.http({
                                url: url,
                                data: file,
                                headers: {
                                    'Content-Type': file.type,
                                    Authorization: accessToken,
                                    'Content-MD5': md5
                                },
                                method: 'POST'
                            }).progress(function (evt) {
                                sdmULController.progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                            }).success(function (data, status, headers, config) {
                                console.log(data);
                                sdmULController.progressPercentage = 100;
                                $scope.sdmIMController.updateAttachmentsAndFiles();
                                deferred.resolve();
                                sdmULController.currentFile = null;
                            }).error(function(data, status, headers, config){
                                sdmULController.currentFile = null
                                console.log(data, status);
                                if (sdmULController.abortedUpload) {
                                    sdmULController.abortedUpload = false;
                                    return;
                                } else if (status === 400) {
                                    addError('Received file was corrupted. Please retry.');
                                } else if ((status === 401) && (!retry || retry < 3)) {
                                    sdmUserManager.refreshToken().then(
                                        function(){
                                            var accessData = $cookieStore.get(SDM_KEY_CACHED_ACCESS_DATA);
                                            var accessToken = typeof accessData !== undefined? accessData.access_token:undefined;
                                            var retry = retry?(retry + 1):1;
                                            uploadToAPI(url, file, accessToken, md5, deferred, retry);
                                        });
                                } else {
                                    addError('Error during upload. Please contact an administrator.');
                                }
                                sdmULController.uploadInProgress = false;
                                sdmULController.processedFiles = 0;
                                sdmULController.queueLength = 0;
                                sdmULController.progressPercentage = 0;
                            });
                        };

                        sdmULController.clearUploadFiles = function($event) {
                            if (sdmULController.currentFile) {
                                sdmULController.currentFile.abort();
                            } else {
                                sdmMD5.abort();
                            }
                            addError('Upload aborted.');
                            sdmULController.abortedUpload = true;
                            sdmULController.files = [];
                            sdmULController.uploadInProgress = false;
                            sdmULController.processedFiles = 0;
                            sdmULController.queueLength = 0;
                        }
                        sdmULController.skipFile = function($event) {
                            if (sdmULController.currentFile) {
                                sdmULController.currentFile.abort();
                            } else {
                                sdmMD5.abort();
                            }
                            addError('Upload skipped.');
                            sdmULController.abortedUpload = true;
                            processQueue(true);
                        }
                        var clearError;
                        var addError = function(message) {
                            if (clearError) {
                                clearTimeout(clearError);
                            }
                            sdmULController.errorMessage = message;
                            clearError = setTimeout(function(){
                                sdmULController.errorMessage = null;
                                $scope.$apply();
                            }, 5000);
                        }

                    }
                }
            }]);
})()


text:
using MongoDB.Bson.Serialization.Attributes;

namespace FraudDetection.Models
{
    public class TransactionStatus
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }
}


text:
#wpadminbar * {
	font-family: Tahoma, Arial, Helvetica, sans-serif;
}

#wpadminbar {
	direction: rtl;
	font-family: Tahoma, Arial, Helvetica, sans-serif;
	left: auto;
	right: 0;
}

#wpadminbar .quicklinks ul {
	text-align: right;
}

#wpadminbar li {
	float: right;
}

#wpadminbar .quicklinks > ul > li {
	border-right: 0;
	border-left: 1px solid #555;
}

#wpadminbar .quicklinks > ul > li > a,
#wpadminbar .quicklinks > ul > li > .ab-empty-item {
	border-right: 0;
	border-left: 1px solid #333;
}

#wpadminbar .quicklinks .ab-top-secondary > li {
	border-left: 0;
	border-right: 1px solid #333;
	float: left;
}

#wpadminbar .quicklinks .ab-top-secondary > li > a,
#wpadminbar .quicklinks .ab-top-secondary > li > .ab-empty-item {
	border-right: 1px solid #555;
	border-left: 0;
}

#wpadminbar .menupop .ab-sub-wrapper,
#wpadminbar .shortlink-input {
	margin: 0 -1px 0 0;
}

#wpadminbar.ie7 .menupop .ab-sub-wrapper,
#wpadminbar.ie7 .shortlink-input {
	left: auto;
	right: 0;
}

#wpadminbar .ab-top-secondary .menupop .ab-sub-wrapper {
	right: auto;
	left: 0;
	margin: 0 0 0 -1px;
}

#wpadminbar .menupop li:hover > .ab-sub-wrapper,
#wpadminbar .menupop li.hover > .ab-sub-wrapper {
	margin-left: 0px;
	margin-right: 100%;
}

#wpadminbar .ab-top-secondary .menupop li:hover > .ab-sub-wrapper,
#wpadminbar .ab-top-secondary .menupop li.hover > .ab-sub-wrapper {
	margin-left: inherit;
	margin-right: 0;
	left: 100%;
	right: inherit;
}

#wpadminbar .menupop .menupop > .ab-item {
	background-position: 5% -46px;
	padding-left: 2em;
	padding-right: 1em;
}

#wpadminbar .ab-top-secondary .menupop .menupop > .ab-item {
	background-position: 95% -20px;
	padding-left: 1em;
	padding-right: 2em;
}

#wpadminbar .quicklinks .menupop ul.ab-sub-secondary {
	right: 0;
	left: auto;
}

#wpadminbar .ab-top-secondary {
	float: left;
	right: auto;
	left: 0;
}

#wpadminbar ul li:last-child,
#wpadminbar ul li:last-child .ab-item {
	border-left: 0;
}

#wpadminbar .screen-reader-shortcut:focus {
	left: auto;
	right: 6px;
}

/**
 * My Account
 */
#wpadminbar #wp-admin-bar-my-account.with-avatar #wp-admin-bar-user-actions > li {
	margin-right: 88px;
	margin-left: 16px;
}

#wp-admin-bar-user-actions > li > .ab-item {
	padding-left: 0;
	padding-right: 8px;
}

#wp-admin-bar-user-info .avatar {
	left: auto;
	right: -72px;
}

#wpadminbar .quicklinks li#wp-admin-bar-my-account.with-avatar > a img {
	margin-left: -1px;
	margin-right: 4px
}

/*
 * My Sites
 */
#wpadminbar .quicklinks li .blavatar {
	margin-right: 0px;
	margin-left: 4px;
}

/*
 * Search
 */
#wpadminbar #adminbarsearch .adminbar-input {
	font-family: Tahoma, Arial, Helvetica, sans-serif;
	padding: 0 24px 0 3px;
	margin: 0;
	background-position: 50% 2px;
}

#wpadminbar #adminbarsearch .adminbar-input:focus,
#wpadminbar.ie7 #adminbarsearch .adminbar-input {
	background-position: 99% 2px;
}

/**
 * Comments icon
 */
#wpadminbar .ab-icon {
	float: right;
}

.ie7 #wp-admin-bar-wp-logo > .ab-item .ab-icon {
	position: static;
}

#wpadminbar.ie7 .ab-icon {
	float: left;
	left: 12px;
}

#wpadminbar .ab-label {
	margin-left: 0px;
	margin-right: 4px;
	float: left;
}

#wpadminbar.ie7 .ab-label {
	margin-right: 0;
}

#wpadminbar.ie7 #wp-admin-bar-comments > a {
	min-width: 25px;
}

#wpadminbar a:hover .ab-comments-icon-arrow {
	border-right-color: #bbb;
}

#wpadminbar .menupop .ab-sub-wrapper,
#wpadminbar .shortlink-input {
	right: 0;
}

#wpadminbar .quicklinks .menupop ul li a {
	position: relative;
}

/**
 * IE 6-targeted rules
 */
* html #wpadminbar .quicklinks ul li a {
	float: right;
}


text:
namespace clang {
namespace driver {

class ObjCRuntime {
public:
  enum Kind { GNU, NeXT };
private:
  unsigned RuntimeKind : 1;
public:
  void setKind(Kind k) { RuntimeKind = k; }
  Kind getKind() const { return static_cast<Kind>(RuntimeKind); }

  /// True if the runtime provides native ARC entrypoints.  ARC may
  /// still be usable without this if the tool-chain provides a
  /// statically-linked runtime support library.
  unsigned HasARC : 1;

  /// True if the runtime supports ARC zeroing __weak.
  unsigned HasWeak : 1;

  /// \brief True if the runtime supports subscripting methods.
  unsigned HasSubscripting : 1;

  /// True if the runtime provides the following entrypoint:
  ///   void objc_terminate(void);
  /// If available, this will be called instead of abort() when an
  /// exception is thrown out of an EH cleanup.
  unsigned HasTerminate : 1;

  ObjCRuntime() : RuntimeKind(NeXT), HasARC(false), HasWeak(false),
    HasSubscripting(false), HasTerminate(false) {}
};

}
}

#endif


text:
from win32com.propsys import propsys, pscon
print "propsys was imported (sorry - that is the extent of the tests,"
print "but see the shell folder_view demo, which uses this module)"
# that's all folks!


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Text;
using Xunit;

namespace OpenTelemetry.Exporter.AzureMonitor.Tests
{
    public class NDJsonWriterTests
    {
        [Fact]
        public void CanWriteMultilineJson()
        {
            var writer = new NDJsonWriter();
            writer.JsonWriter.WriteStartObject();
            writer.JsonWriter.WriteString("property", "value");
            writer.JsonWriter.WriteEndObject();
            writer.WriteNewLine();
            writer.JsonWriter.WriteStartObject();
            writer.JsonWriter.WriteNumber("anotherProperty", 2);
            writer.JsonWriter.WriteEndObject();

            Assert.Equal("{\"property\":\"value\"}\n{\"anotherProperty\":2}", Encoding.UTF8.GetString(writer.ToBytes().Span.ToArray()));
        }
    }
}


text:
package fr.upem.requests;

public class NoRightToException extends Exception {

    public NoRightToException(){
        super();
    }

    public NoRightToException(String message){
        super(message);
    }

    public NoRightToException(Throwable cause){
        super(cause);
    }

    public NoRightToException(String message, Throwable cause){
        super(message, cause);
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Clerodendrum luembense subsp. niassense R.Fern.

### Remarks
null


text:
int
Semantic::removeBiconditionals()
{
	// check if done
	if (!isExpression())
		return(OK);

	// check left and right sides
	if (left != NULL && left->removeBiconditionals() != OK)
	{
		ERROR("removeBiconditionals failed.", EINVAL);
		return(NOTOK);
	}
	if (right != NULL && right->removeBiconditionals() != OK)
	{
		ERROR("removeBiconditionals failed.", EINVAL);
		return(NOTOK);
	}

	// update current node, if required
	if (type == Biconditional)
	{
		// save left and right records
		Semantic *plsr = left;
		Semantic *pduplsr = new Semantic(*left);
		MustBeTrue(pduplsr != NULL);
		Semantic *prsr = right;
		Semantic *pduprsr = new Semantic(*right);
		MustBeTrue(pduprsr != NULL);

		// create implication records
		left = new Semantic(Conditional, plsr, prsr);
		MustBeTrue(left != NULL);
		right = new Semantic(Conditional, pduprsr, pduplsr);
		MustBeTrue(right != NULL);

		// change operator type to AND
		type = And;
	}

	// all done
	return(OK);
}

// convert implications to ORs, use the following:
//	(A --> B) is identical to (~A || B)
int
Semantic::removeConditionals()
{
	// check if done
	if (!isExpression())
		return(OK);

	// check left and right sides
	if (left != NULL && left->removeConditionals() != OK)
	{
		ERROR("removeConditionals failed.", EINVAL);
		return(NOTOK);
	}
	if (right != NULL && right->removeConditionals() != OK)
	{
		ERROR("removeConditionals failed.", EINVAL);
		return(NOTOK);
	}

	// update current node, if required
	if (type == Conditional)
	{
		// save left record
		Semantic *plsr = left;

		// create NOT record
		left = new Semantic(Negation, NULL, plsr);
		MustBeTrue(left != NULL);

		// change operator type to OR
		type = Or;
	}

	// all done
	return(OK);
}

// remove multiple NOTs, use ~~A <--> A rule.
int
Semantic::removeExtraNots()
{
	// save if a conclusion
	int saveConclusion = conclusion;
	int saveSOS = setofsupport;
	int saveQuery = query;

	// loop and remove extra NOTs.
	Semantic *ps = this;
	while ( 1 )
	{
		// is it a negation record
		if (type != Negation)
			break;

		// check for extra NOT
		if (right->type != Negation)
			break;

		// we have two NOTs. remove them.
		Semantic *psr = right;
		Semantic *psrr = right->right;

		// copy saved data
		type = psrr->type;
		varisused = psrr->varisused;
		conclusion = psrr->conclusion;
		setofsupport = psrr->setofsupport;
		query = psrr->query;
		name = psrr->name;
		originalname = psrr->originalname;
		value = psrr->value;
		argnum = psrr->argnum;
		left = psrr->left;
		right = psrr->right;
		pargs = psrr->pargs;

		// clear links and delete
		psr->left = NULL;
		psr->right = NULL;
		psr->pargs = NULL;
		psrr->left = NULL;
		psrr->right = NULL;
		psrr->pargs = NULL;
		delete psr;
		delete psrr;
	}

	// restore original conclusion status
	conclusion = saveConclusion;
	setofsupport = saveSOS;
	query = saveQuery;

	// all done
	return(OK);
}

// push negation as far down as possible, use demorgan's laws
//	~(A && B) identical to (~A || ~B) and
//	~(A || B) identical to (~A && ~B) and
//	~<x>(F(x)) identical to [x](~F(x))
//	~[x](F(x)) identical to <x>(~F(x))
//
int
Semantic::demorgans()
{
	// if not an expression, don't bother.
	if (!isExpression())
		return(OK);

	// remove multiple NOTs,
	//	use ~~A <--> A and
	//	use ~~~A <--> ~A rules.
	//
	if (removeExtraNots() != OK)
	{
		ERROR("removeExtraNots failed.", EINVAL);
		return(NOTOK);
	}

	// check if we have a negated expression
	if (type != Negation)
	{
		// not a negated expression, check left and right
		if (left != NULL && left->demorgans() != OK)
		{
			ERROR("demorgans failed.", EINVAL);
			return(NOTOK);
		}
		if (right != NULL && right->demorgans() != OK)
		{
			ERROR("demorgans failed.", EINVAL);
			return(NOTOK);
		}
		return(OK);
	}

	// we have a negation, check if rhs is a predicate or an expression.
	Semantic *prs = right;
	if (!(prs->isExpression()))
	{
		// what is negated is NOT an expression, just return.
		return(OK);
	}

	// check if expression is an AND, OR, UNIVERSAL, or EXISTENTIAL
	switch (prs->type)
	{
	case Or:
	case And:
	{
		// we have a negated AND or OR expression, apply demorgans laws.
		Semantic *prsls = prs->left;
		Semantic *prsrs = prs->right;

		// create new negation records
		Semantic *pnegls = new Semantic(Negation, NULL, prsls);
		MustBeTrue(pnegls != NULL);
		Semantic *pnegrs = new Semantic(Negation, NULL, prsrs);
		MustBeTrue(pnegrs != NULL);

		// write over negation record with the new record info
		left = pnegls;
		right = pnegrs;
		switch (prs->type)
		{
		case Or:
			type = And;
			break;
		case And:
			type = Or;
			break;
		default:
			ERRORD("unexpected type", prs->type, NOTOK);
			MustBeTrue(0);
			break;
		}

		// delete old right semantic record
		prs->left = NULL;
		prs->right = NULL;
		delete prs;

		// check left and right sides
		if (left != NULL && left->demorgans() != OK)
		{
			ERROR("demorgans failed.", EINVAL);
			return(NOTOK);
		}
		if (right != NULL && right->demorgans() != OK)
		{
			ERROR("demorgans failed.", EINVAL);
			return(NOTOK);
		}
		break;
	}
	case Universal:
	case Existential:
	{
		// we have a negated UNIVERSAL or EXISTENTIAL expressions,
		// ~[] becomes <>~
		// ~<> becones []~
		//
		switch (prs->type)
		{
		case Existential:
			type = Universal;
			break;
		case Universal:
			type = Existential;
			break;
		default:
			ERRORD("unexpected type", prs->type, NOTOK);
			MustBeTrue(0);
			break;
		}
		prs->type = Negation;
		name = prs->name;
		originalname = prs->originalname;
		prs->name = String("");
		prs->originalname = String("");
		varisused = prs->varisused;
		prs->varisused = 0;

		// check left and right sides
		if (left != NULL && left->demorgans() != OK)
		{
			ERROR("demorgans failed.", EINVAL);
			return(NOTOK);
		}
		if (right != NULL && right->demorgans() != OK)
		{
			ERROR("demorgans failed.", EINVAL);
			return(NOTOK);
		}
		break;
	}
	default:
	{
		// not any of the above.
		if (left != NULL && left->demorgans() != OK)
		{
			ERROR("demorgans failed.", EINVAL);
			return(NOTOK);
		}
		if (right != NULL && right->demorgans() != OK)
		{
			ERROR("demorgans failed.", EINVAL);
			return(NOTOK);
		}
		break;
	}
	}

	// all done
	return(OK);
}

// rename all variable names to unique names.
int
Semantic::renameVariables(List<Symbol> &localscope)
{
	// check of predicate or expression
	if (isExpression())
	{
		// check if we have quantifier
		int popscope = 0;
		if (type == Universal)
		{
			// we have a quantifier, rename variable
			popscope = 1;
			String uname = uniqueName(String("_V"));
			localscope.insertAtFront(
				Symbol(name, uname, UniversalVariable));
			name = uname;
		}
		else if (type == Existential)
		{
			// we have a quantifier, rename variable
			popscope = 1;
			String uname = uniqueName(String("_V"));
			localscope.insertAtFront(
				Symbol(name, uname, ExistentialVariable));
			name = uname;
		}

		// follow left and right branches
		if (left != NULL && left->renameVariables(localscope) != OK)
		{
			ERROR("renameVariables failed.", EINVAL);
			return(NOTOK);
		}
		if (right != NULL && right->renameVariables(localscope) != OK)
		{
			ERROR("renameVariables failed.", EINVAL);
			return(NOTOK);
		}

		// pop scope variable if required
		if (popscope)
		{
			Symbol tmp;
			MustBeTrue(localscope.removeAtFront(tmp) == OK);
		}
	}
	else if (isPredicate())
	{
		// check if a function
		if ((type == PredicateFunction) || (type == PredicateEqual))
		{
			// we have a function, scan argument list
			ListIterator<Semantic *> pargsIter(*pargs);
			for ( ; !pargsIter.done(); pargsIter++)
			{
				Semantic *parg = pargsIter();
				if (parg != NULL &&
				    parg->renameVariables(localscope) != OK)
				{
					ERROR("renameVariables failed.",
						EINVAL);
					return(NOTOK);
				}
			}
		}
	}
	else if (isTerm())
	{
		// check if a variable, function or anything else
		if (type == Variable)
		{
			// find variable in scope
			Symbol usym(name);
			if (localscope.retrieve(usym) == OK)
			{
				name = usym.getUniqueName();
				MustBeTrue(name != String(""));
			}
		}
		else if (type == Function)
		{
			// we have a function, scan argument list
			ListIterator<Semantic *> pargsIter(*pargs);
			for ( ; !pargsIter.done(); pargsIter++)
			{
				Semantic *parg = pargsIter();
				if (parg != NULL &&
				    parg->renameVariables(localscope) != OK)
				{
					ERROR("renameVariables failed.",
						EINVAL);
					return(NOTOK);
				}
			}
		}
	}
	else
	{
		ERRORD("unexpected type", type, NOTOK);
		MustBeTrue(0);
	}

	// all done
	return(OK);
}

int
Semantic::renameVariables()
{
	List<Symbol> localscope;
	return(renameVariables(localscope));
}

// remove existential quantifier by using skolem functions. all skolem
// functions must be unique. remember that the skolem function is dependent
// on any universal variables that are in scope.
//
int
Semantic::skolemize(List<Symbol> &localscope)
{
	// check if expression or predicate
	if (isExpression())
	{
		// what type is it
		if (type == Universal)
		{
			// store universal variable
			localscope.insertAtEnd(
				Symbol(name, name, originalname,
					UniversalVariable, 0, 0));

			// follow right leg, left leg is null
			if (right->skolemize(localscope) != OK)
			{
				ERROR("skolemize failed.", EINVAL);
				return(NOTOK);
			}

			// remove universal variable
			Symbol tmp;
			localscope.removeAtEnd(tmp);
		}
		else if (type == Existential)
		{
			// store existential variable
			String uname = uniqueName(String("_SK"));
			localscope.insertAtEnd(
				Symbol(name, uname, originalname,
					ExistentialVariable, 0, 0));

			// follow right leg, left leg is null
			if (right->skolemize(localscope) != OK)
			{
				ERROR("skolemize failed.", EINVAL);
				return(NOTOK);
			}

			// remove existential variable
			Symbol tmp;
			localscope.removeAtEnd(tmp);
		}
		else
		{
			// follow down other expression operators
			if (left != NULL &&
			    left->skolemize(localscope) != OK)
			{
				ERROR("skolemize failed.", EINVAL);
				return(NOTOK);
			}
			if (right != NULL &&
			    right->skolemize(localscope) != OK)
			{
				ERROR("skolemize failed.", EINVAL);
				return(NOTOK);
			}
		}

	}
	else if (isPredicate())
	{
		// check for functions
		if ((type == PredicateFunction) || (type == PredicateEqual))
		{
			// cycle thru arguments
			ListIterator<Semantic * > pargsIter(*pargs);
			for ( ; !pargsIter.done(); pargsIter++)
			{
				Semantic *parg = pargsIter();
				if (parg != NULL &&
				    parg->skolemize(localscope) != OK)
				{
					ERROR("skolemize failed.", EINVAL);
					return(NOTOK);
				}
			}
		}
	}
	else if (isTerm())
	{
		// check type of term
		switch (type)
		{
		case Variable:
		{
			// check if an existential variable
			Symbol qvarsym(name);
			MustBeTrue(localscope.retrieve(qvarsym) == OK);
			if (qvarsym.getType() != ExistentialVariable)
				break;

			// we have an existential variable
			String skolemName(qvarsym.getUniqueName());

			// need to replace this variable with a
			// skolem function which is dependent on all
			// universal variables in scope at this time.
			//
			List<Semantic * > *npargs = new List<Semantic * >;
			MustBeTrue(npargs != NULL);
			ListIterator<Symbol> scopeIter(localscope);
			int nargs;
			for (nargs = 0; !scopeIter.done(); scopeIter++)
			{
				// get symbol
				Symbol uvar = scopeIter();

				// check if we found the current
				// symbol. this marks the end of
				// dependent variables for the
				// skolem function. all other
				// existential variables are skipped.
				//
				if (uvar.getType() == ExistentialVariable)
				{
					if (uvar == Symbol(name))
						break;
					else
						continue;
				}

				// we have a universal variable in
				// scope
				//
				MustBeTrue(
					uvar.getType() == UniversalVariable);
				Semantic *parg =
					new Semantic(uvar.getOriginalName(),
						uvar.getName(), Variable);
				MustBeTrue(parg != NULL);
				npargs->insertAtEnd(parg);
				nargs++;
			}
			if (nargs == 0)
			{
				// skolem constant
				type = Constant;
				name = skolemName;
				pargs = NULL;
				argnum = 0;

				// delete unused argument list
				delete pargs;
			}
			else
			{
				// skolem function
				type = Function;
				name = skolemName;
				pargs = npargs;
				argnum = nargs;
			}
			break;
		}

		case Function:
		{
			// we have a function, scan its arguments
			ListIterator<Semantic *> pargsIter(*pargs);
			for ( ; !pargsIter.done(); pargsIter++)
			{
				Semantic *parg = pargsIter();
				if (parg != NULL &&
				    parg->skolemize(localscope) != OK)
				{
					ERROR("skolemize failed.", EINVAL);
					return(NOTOK);
				}
			}
			break;
		}
		}
	}
	else
	{
		ERRORD("unexpected type", type, NOTOK);
		MustBeTrue(0);
	}

	// all done
	return(OK);
}

int
Semantic::skolemize()
{
	// check if expression or predicate
	// if it's a predicate, there is nothing to do
	// since we are at the beginning of the expression,
	// and quantifiers are expressions.
	//
	if (!isExpression())
		return(OK);

	// list of variables in scope
	List<Symbol> localscope;

	// what type is it
	if (type == Universal)
	{
		// store universal variable
		localscope.insertAtEnd(Symbol(name, name, originalname,
					UniversalVariable, 0, 0));

		// follow right leg, left leg is null
		if (right->skolemize(localscope) != OK)
		{
			ERROR("skolemize failed.", EINVAL);
			return(NOTOK);
		}

		// remove universal variable
		Symbol tmp;
		localscope.removeAtEnd(tmp);
	}
	else if (type == Existential)
	{
		// store existential variable
		String uname = uniqueName(String("_SK"));
		localscope.insertAtEnd(Symbol(name, uname, originalname,
					ExistentialVariable, 0, 0));

		// follow right leg, left leg is null
		if (right->skolemize(localscope) != OK)
		{
			ERROR("skolemize failed.", EINVAL);
			return(NOTOK);
		}

		// remove existential variable
		Symbol tmp;
		localscope.removeAtEnd(tmp);
	}
	else
	{
		// follow down other expression operators
		if (left != NULL && left->skolemize(localscope) != OK)
		{
			ERROR("skolemize failed.", EINVAL);
			return(NOTOK);
		}
		if (right != NULL && right->skolemize(localscope) != OK)
		{
			ERROR("skolemize failed.", EINVAL);
			return(NOTOK);
		}
	}

	// scan one more time to remove existential records
	return(removeExistentials());
}

// remove existential records once skolemizing is done.
int
Semantic::removeExistentials()
{
	// check if an expression
	if (!isExpression())
		return(OK);

	// save if a conclusion
	int saveConclusion = conclusion;
	int saveSOS = setofsupport;
	int saveQuery = query;

	// check if and universal record
	if (type == Existential)
	{
		// save right branch of expression record
		Semantic *prs = right;

		// copy all the data
		type = prs->type;
		varisused = prs->varisused;
		conclusion = prs->conclusion;
		setofsupport = prs->setofsupport;
		query = prs->query;
		name = prs->name;
		originalname = prs->originalname;
		value = prs->value;
		argnum = prs->argnum;
		left = prs->left;
		right = prs->right;
		pargs = prs->pargs;

		// delete old right record
		prs->left = NULL;
		prs->right = NULL;
		prs->pargs = NULL;
		delete prs;
	}

	// reassign since we may have a new expression pointer
	if (isExpression())
	{
		if (type == Existential && removeExistentials() != OK)
		{
			ERROR("removeExistentials failed.", EINVAL);
			return(NOTOK);
		}
		else
		{
			if (left != NULL && left->removeExistentials() != OK)
			{
				ERROR("removeExistentials failed.", EINVAL);
				return(NOTOK);
			}
			if (right != NULL && right->removeExistentials() != OK)
			{
				ERROR("removeExistentials failed.", EINVAL);
				return(NOTOK);
			}
		}
	}

	// restore conclusion status
	conclusion = saveConclusion;
	setofsupport = saveSOS;
	query = saveQuery;

	// all done
	return(OK);
}

// remove all universals. since all variables are unique, remove
// the universal quantifiers. it is assumed that all variables are
// universally quantified.
//
int
Semantic::removeUniversals()
{
	// check if an expression
	if (!isExpression())
		return(OK);

	// save if a conclusion
	int saveConclusion = conclusion;
	int saveSOS = setofsupport;
	int saveQuery = query;

	// check if and universal record
	if (type == Universal)
	{
		// save right branch of expression record
		Semantic *prs = right;

		// copy all the data
		type = prs->type;
		varisused = prs->varisused;
		conclusion = prs->conclusion;
		setofsupport = prs->setofsupport;
		query = prs->query;
		name = prs->name;
		originalname = prs->originalname;
		value = prs->value;
		argnum = prs->argnum;
		left = prs->left;
		right = prs->right;
		pargs = prs->pargs;

		// delete old right record
		prs->left = NULL;
		prs->right = NULL;
		prs->pargs = NULL;
		delete prs;
	}

	// reassign since we may have a new expression pointer
	if (isExpression())
	{
		if (type == Universal && removeUniversals() != OK)
		{
			ERROR("removeUniversals failed.", EINVAL);
			return(NOTOK);
		}
		else
		{
			if (left != NULL && left->removeUniversals() != OK)
			{
				ERROR("removeUniversals failed.", EINVAL);
				return(NOTOK);
			}
			if (right != NULL && right->removeUniversals() != OK)
			{
				ERROR("removeUniversals failed.", EINVAL);
				return(NOTOK);
			}
		}
	}

	// restore conclusion status
	conclusion = saveConclusion;
	setofsupport = saveSOS;
	query = saveQuery;
	return(OK);
}

// distribute AND over OR using the rule:
//	(A && B) || C <--> (A || C) && (B || C)
//
int
Semantic::distributeLeftAnd(int &changed)
{
	// check if we have an expression
	if (!isExpression())
		return(OK);

	// update change flag
	changed = 1;

	// left and right semantic/expression records
	Semantic *pls = left;
	Semantic *prs = right;

	// left branch data
	Semantic *plsls = pls->left;
	Semantic *plsrs = pls->right;

	// we have and OR with a left AND. we can distribute the
	// OR using the rule (A&&B)||C = (A||C)&&(B||C)
	//
	// create new right semantic record
	right = new Semantic(Or, plsrs, prs);
	MustBeTrue(right != NULL);

	// update AND right branch
	pls->right = new Semantic(*prs);
	MustBeTrue(pls->right != NULL);

	// update all operations
	type = And;
	pls->type = Or;

	// scan new branches
	if (left != NULL && left->distribution(changed) != OK)
	{
		ERROR("distribution failed.", EINVAL);
		return(NOTOK);
	}
	if (right != NULL && right->distribution(changed) != OK)
	{
		ERROR("distribution failed.", EINVAL);
		return(NOTOK);
	}

	// all done
	return(OK);
}

// distribute OR over ANDs using the rule:
//	A || (B && C) <--> (A || B) && (A || C)
//
int
Semantic::distributeRightAnd(int &changed)
{
	// check if we have an expression
	if (!isExpression())
		return(OK);

	// update change flag
	changed = 1;

	// left and right semantic/expression records
	Semantic *pls = left;
	Semantic *prs = right;

	// right branch data
	Semantic *prsls = prs->left;
	Semantic *prsrs = prs->right;

	// we have an OR with a right AND. we can distribute the
	// OR using the rule A||(B&&C) = (A||B)&&(A||C).
	//
	// create new left semantic record
	left = new Semantic(Or, pls, prsls);
	MustBeTrue(left != NULL);

	// update AND left branch
	prs->left = new Semantic(*pls);
	MustBeTrue(prs->left != NULL);

	// update all operations
	type = And;
	prs->type = Or;

	// scan new branches
	if (left != NULL && left->distribution(changed) != OK)
	{
		ERROR("distribution failed.", EINVAL);
		return(NOTOK);
	}
	if (right != NULL && right->distribution(changed) != OK)
	{
		ERROR("distribution failed.", EINVAL);
		return(NOTOK);
	}

	// all done
	return(OK);
}

// convert program to conjunctive normal form
// distribute OR over ANDs using the rules:
//	A || (B && C) <--> (A || B) && (A || C)
//	(A && B) || C <--> (A || C) && (B || C)
//
int
Semantic::distribution(int &changed)
{
	// check if we have an expression
	if (!isExpression())
		return(OK);

	// check type of expression
	if (type != Or)
	{
		// we don't have an OR, check left and right
		if (left != NULL && left->distribution(changed) != OK)
		{
			ERROR("distribution failed.", EINVAL);
			return(NOTOK);
		}
		if (right != NULL && right->distribution(changed) != OK)
		{
			ERROR("distribution failed.", EINVAL);
			return(NOTOK);
		}
		return(OK);
	}

	// we have an OR, check if left is an AND.
	if (left->isExpression() && left->type == And)
		return(distributeLeftAnd(changed));

	// we have an OR, check if right is an AND.
	if (right->isExpression() && right->type == And)
		return(distributeRightAnd(changed));

	// check both sides
	if (left != NULL && left->distribution(changed) != OK)
	{
		ERROR("distribution failed.", EINVAL);
		return(NOTOK);
	}
	if (right != NULL && right->distribution(changed) != OK)
	{
		ERROR("distribution failed.", EINVAL);
		return(NOTOK);
	}

	// all done
	return(OK);
}

int
Semantic::distribution()
{
	for (int changed = 1; changed ; )
	{
		changed = 0;
		if (distribution(changed) != OK)
		{
			ERROR("distribution failed.", EINVAL);
			return(NOTOK);
		}
	}
	return(OK);
}

// get clauses from CNF statement
int
Semantic::getClauses(List<Semantic *> &clist)
{
	return(getClauses(clist, conclusion, setofsupport, query));
}
int
Semantic::getClauses(List<Semantic *> &clist, int con, int sos, int qry)
{
	// check if expression is an AND
	if (type != And)
	{
		Semantic *pnew = new Semantic(*this);
		MustBeTrue(pnew != NULL);
		pnew->conclusion = con;
		pnew->setofsupport = sos;
		pnew->query = qry;
		clist.insertAtEnd(pnew);
		return(OK);
	}

	// keep tracing down the ANDs
	if (left->getClauses(clist, con, sos, qry) != OK)
	{
		ERROR("getClauses failed.", EINVAL);
		return(NOTOK);
	}
	if (right->getClauses(clist, con, sos, qry) != OK)
	{
		ERROR("getClauses failed.", EINVAL);
		return(NOTOK);
	}

	// all done
	return(OK);
}

// rename all variables to unique names.
int
Semantic::renameAgain(List<Symbol> &localscope)
{
	// check of predicate or expression
	if (isExpression())
	{
		// clauses, can not be an AND
		MustBeTrue(type != And)

		// follow left and right branches
		if (left != NULL && left->renameAgain(localscope) != OK)
		{
			ERROR("renameAgain failed.", EINVAL);
			return(NOTOK);
		}
		if (right != NULL && right->renameAgain(localscope) != OK)
		{
			ERROR("renameAgain failed.", EINVAL);
			return(NOTOK);
		}
	}
	else if (type == PredicateFunction || type == PredicateEqual)
	{
		// we have a function, scan argument list
		ListIterator<Semantic *> pargsIter(*pargs);
		for ( ; !pargsIter.done(); pargsIter++)
		{
			Semantic *parg = pargsIter();
			if (parg != NULL &&
			    parg->renameAgain(localscope) != OK)
			{
				ERROR("renameAgain failed.", EINVAL);
				return(NOTOK);
			}
		}
	}
	else if (type == Variable)
	{
		// rename variable
		Symbol varsym(name);
		if (localscope.retrieve(varsym) == OK)
		{
			name = varsym.getUniqueName();
		}
		else
		{
			String uname = uniqueName(String("_V"));
			Symbol varsym(name, uname, Variable);
			name = uname;
			localscope.insertAtEnd(varsym);
		}
	}
	else if (type == Function)
	{
		// we have a function, scan argument list
		ListIterator<Semantic *> pargsIter(*pargs);
		for ( ; !pargsIter.done(); pargsIter++)
		{
			Semantic *parg = pargsIter();
			if (parg != NULL &&
			    parg->renameAgain(localscope) != OK)
			{
				ERROR("renameAgain failed.", EINVAL);
				return(NOTOK);
			}
		}
	}

	// all done
	return(OK);
}

int
Semantic::renameAgain()
{
	List<Symbol> localscope;
	return(renameAgain(localscope));
}


text:
package sctp

import (
	"errors"
	"fmt"
)

type param interface {
	marshal() ([]byte, error)
	length() int
}

var errParamTypeUnhandled = errors.New("unhandled ParamType")

func buildParam(t paramType, rawParam []byte) (param, error) {
	switch t {
	case forwardTSNSupp:
		return (&paramForwardTSNSupported{}).unmarshal(rawParam)
	case supportedExt:
		return (&paramSupportedExtensions{}).unmarshal(rawParam)
	case ecnCapable:
		return (&paramECNCapable{}).unmarshal(rawParam)
	case random:
		return (&paramRandom{}).unmarshal(rawParam)
	case reqHMACAlgo:
		return (&paramRequestedHMACAlgorithm{}).unmarshal(rawParam)
	case chunkList:
		return (&paramChunkList{}).unmarshal(rawParam)
	case stateCookie:
		return (&paramStateCookie{}).unmarshal(rawParam)
	case heartbeatInfo:
		return (&paramHeartbeatInfo{}).unmarshal(rawParam)
	case outSSNResetReq:
		return (&paramOutgoingResetRequest{}).unmarshal(rawParam)
	case reconfigResp:
		return (&paramReconfigResponse{}).unmarshal(rawParam)
	default:
		return nil, fmt.Errorf("%w: %v", errParamTypeUnhandled, t)
	}
}


text:
package com.appleframework.core.log;

import static com.appleframework.core.lang.RuntimeUtility.printDataInformation;
import static org.springframework.util.Log4jConfigurer.initLogging;

import java.io.FileNotFoundException;
import java.util.Enumeration;

import org.apache.log4j.Appender;
import org.slf4j.LoggerFactory;

import com.appleframework.core.utils.Enumerator;

/**
 * Logger factory interface.
 *
 * @author Cruise.Xu
 */
@net.jcip.annotations.ThreadSafe
public final class LogFactory {
   static {
      System.setProperty("logging.type", "log4j");
   }

   /**
    * @return list of appenders.
    */
   @SuppressWarnings({ "unchecked" })
   public static Enumerator<Appender> getAllRootAppenders() {
      @SuppressWarnings("rawtypes")
      Enumeration allAppenders = org.apache.log4j.Logger.getRootLogger().getAllAppenders();
      return new Enumerator<Appender>(allAppenders);
   }

   /**
    * @param loggerName
    *           name of the logger.
    * @return all appenders for logger.
    */
   @SuppressWarnings({ "unchecked" })
   public static Enumerator<Appender> getAllAppenders(String loggerName) {
      org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(loggerName);
      if (logger != null) {
         return new Enumerator<Appender>(logger.getAllAppenders());
      }
      return null;
   }

   /**
    * Return a logger named according to the name parameter using the statically bound
    * {@link LogFactory} instance.
    *
    * @param name
    *           The name of the logger.
    * @return logger
    */
   public static Logger getLogger(final String name) {
      final org.slf4j.Logger logger = LoggerFactory.getLogger(name);
      return new LogFactoryDelegate(logger);
   }

   /**
    * Return a logger named corresponding to the class passed as parameter, using the statically
    * bound {@link LogFactory} instance.
    *
    * @param clazz
    *           the returned logger will be named after clazz
    * @return logger
    */
   public static Logger getLogger(final Class<?> clazz) {
      org.slf4j.Logger logger = LoggerFactory.getLogger(clazz.getName());
      return new LogFactoryDelegate(logger);
   }

   /**
    * performs configuration from given inputStream.
    *
    * @param location
    *           location of log4j.xml
    * @throws java.io.FileNotFoundException
    *            of file is not available.
    */
   public static void configure(String location) throws FileNotFoundException {
      initLogging(location);
      printDataInformation();
   }

   private LogFactory() {
   }
}


text:
#ifndef rtkCudaSplatImageFilter_h
#define rtkCudaSplatImageFilter_h

#include "rtkSplatWithKnownWeightsImageFilter.h"
#include "itkCudaImage.h"
#include "itkCudaInPlaceImageFilter.h"
#include "rtkWin32Header.h"

namespace rtk
{

/** \class CudaSplatImageFilter
 * \brief Implements the SplatWithKnownWeightsImageFilter on GPU.
 *
 *
 *
 * \author Cyril Mory
 *
 * \ingroup CudaImageToImageFilter
 */
class ITK_EXPORT CudaSplatImageFilter :
    public itk::CudaInPlaceImageFilter< itk::CudaImage<float,4>, itk::CudaImage<float,4>,
  SplatWithKnownWeightsImageFilter< itk::CudaImage<float,4>, itk::CudaImage<float,3> > >

{
public:
  /** Standard class typedefs. */
  typedef rtk::CudaSplatImageFilter                             Self;
  typedef rtk::SplatWithKnownWeightsImageFilter< OutputImageType, InputImageType > Superclass;
  typedef itk::SmartPointer<Self>                            Pointer;
  typedef itk::SmartPointer<const Self>                      ConstPointer;

  /** Standard New method. */
  itkNewMacro(Self)

  /** Runtime information support. */
  itkTypeMacro(CudaSplatImageFilter, SplatWithKnownWeightsImageFilter)

protected:
  rtkcuda_EXPORT CudaSplatImageFilter();
  ~CudaSplatImageFilter(){
  }

  virtual void GPUGenerateData();

private:
  CudaSplatImageFilter(const Self&); //purposely not implemented
  void operator=(const Self&);         //purposely not implemented

}; // end of class

} // end namespace rtk

#endif