Example usage for org.apache.commons.lang3 ArrayUtils removeElement

List of usage examples for org.apache.commons.lang3 ArrayUtils removeElement

Introduction

In this page you can find the example usage for org.apache.commons.lang3 ArrayUtils removeElement.

Prototype

public static short[] removeElement(final short[] array, final short element) 

Source Link

Document

Removes the first occurrence of the specified element from the specified array.

Usage

From source file:TestRandomForest.java

public static void main(String[] args) throws Exception {

    SparkConf sparkConf = new SparkConf();
    sparkConf.setAppName("test-client").setMaster("local[2]");
    sparkConf.set("spark.driver.allowMultipleContexts", "true");
    JavaSparkContext javaSparkContext = new JavaSparkContext(sparkConf);
    SQLContext sqlContext = new SQLContext(javaSparkContext);

    DataFrame dataFrame = sqlContext.read().format("com.databricks.spark.csv").option("inferSchema", "true")
            .option("header", "true").load("/home/supun/Supun/MachineLearning/data/Iris/train.csv");

    double[] dataSplitWeights = { 0.7, 0.3 };
    DataFrame[] data = dataFrame.randomSplit(dataSplitWeights);

    // Create a vector from columns. Name the resulting vector as "features"
    String[] predictors = dataFrame.columns();
    predictors = ArrayUtils.removeElement(predictors, RESPONSE_VARIABLE);

    VectorAssembler vectorAssembler = new VectorAssembler();
    vectorAssembler.setInputCols(predictors).setOutputCol(FEATURES);

    MeanImputer meanImputer = new MeanImputer(predictors);

    // Index labels
    StringIndexerModel labelIndexer = new StringIndexer().setInputCol(RESPONSE_VARIABLE)
            .setOutputCol(INDEXED_RESPONSE_VARIABLE).fit(data[0]);

    /*/*from   w  ww  .  ja va 2  s. co  m*/
    // Automatically identify categorical features, and index them.
    // Set maxCategories so features with > 4 distinct values are treated as continuous.
    VectorIndexerModel featureIndexer = new VectorIndexer().setInputCol("features")
                                                        .setOutputCol("indexedFeatures")
                                                        .setMaxCategories(20)
                                                        .fit(data[0]);
     */

    // Train a RandomForest model.
    RandomForestClassifier randowmForest = new RandomForestClassifier().setLabelCol(INDEXED_RESPONSE_VARIABLE)
            .setFeaturesCol(FEATURES).setMaxBins(100).setNumTrees(10).setMaxDepth(10);

    KMeans kmeans = new KMeans().setK(10);

    // Convert indexed labels back to original labels.
    IndexToString labelConverter = new IndexToString().setInputCol(PREDICTION).setOutputCol(PREDICTION_LABEL)
            .setLabels(labelIndexer.labels());

    Pipeline pipeline = new Pipeline()
            .setStages(new PipelineStage[] { meanImputer, labelIndexer, vectorAssembler, kmeans });

    // Fit the pipeline to training documents.
    PipelineModel pipelineModel = pipeline.fit(data[0]);

    // ======================== Validate ========================
    DataFrame predictions = pipelineModel.transform(data[1]);
    predictions.show(200);

    // Confusion Matrix
    MulticlassMetrics metrics = new MulticlassMetrics(
            predictions.select(PREDICTION, INDEXED_RESPONSE_VARIABLE));
    Matrix confusionMatrix = metrics.confusionMatrix();

    // Accuracy Measures
    MulticlassClassificationEvaluator evaluator = new MulticlassClassificationEvaluator()
            .setLabelCol(INDEXED_RESPONSE_VARIABLE).setPredictionCol(PREDICTION).setMetricName("precision");
    double accuracy = evaluator.evaluate(predictions);

    System.out.println("===== Confusion Matrix ===== \n" + confusionMatrix + "\n============================");
    System.out.println("Accuracy = " + accuracy);

}

From source file:implementation.java

public static void main(String[] args) throws IOException {
    // Network Variables
    KUSOCKET ClientSocket = new KUSOCKET();
    ENDPOINT ClientAddress = new ENDPOINT("0.0.0.0", 0);
    ENDPOINT BroadcastAddress = new ENDPOINT("255.255.255.255", TokenAccess.SERVER_PORT_NUMBER);
    ENDPOINT AnyAddress = new ENDPOINT("0.0.0.0", 0);

    ENDPOINT ServerAddress = new ENDPOINT();
    MESSAGE OutgoingMessage = new MESSAGE();
    MESSAGE IncomingMessage = new MESSAGE();

    // Output variables         
    int CommentLength = TokenAccess.COMMENT_LENGTH;
    String Comment = new String();

    // Protocol variables
    Timer firstnode = new Timer();
    Timer tokentimer = new Timer();
    Timer tokenlost = new Timer();
    Timer exit = new Timer();
    int DialogueNumber = 0;
    int numRetries = 0;
    Integer addressIP[] = new Integer[2];
    int trigger = 0;
    String lanAddress = "192.168.1.67";
    // Create socket and await connection ///////////////////////////////////////

    // --------------------------------------------------------------------------
    // FINITE STATE MACHINE
    // --------------------------------------------------------------------------

    System.err.println("FSM Started ===================" + '\n');

    // FSM variables
    TokenAccess.STATES state = TokenAccess.STATES.STATE_INITIAL; // Initial STATE
    TokenAccess.STATES lastState = state; // Last STATE
    boolean bContinueEventWait = false;
    boolean bContinueStateLoop = true;
    String last = null;/*from w w  w .  ja v  a2 s  . c  om*/
    ClientSocket.CreateUDPSocket(ClientAddress);
    while (bContinueStateLoop) {

        switch (state) {
        case STATE_INITIAL:

            firstnode.Start(TokenAccess.firstnode);
            state = TokenAccess.STATES.STATE_STARTED;
            bContinueEventWait = false; // Stop Events loop
            break;

        case STATE_STARTED:

            ClientSocket.MakeConnection(AnyAddress);

            if (firstnode.isExpired()) {
                tokentimer.Start(TokenAccess.tokentimer);

                System.out.println("implementation.main()");
                // adding  local host ip to array
                String t = InetAddress.getLocalHost().getHostAddress();
                String[] split = t.split("\\.");
                addressIP[0] = Integer.parseInt(split[3]);
                System.out.println(split[3]);
                state = TokenAccess.STATES.STATE_TOKENED;
                bContinueEventWait = false;// Stop Events loop

            }
            boolean isMessageQueued = false;

            isMessageQueued = ClientSocket.RetrieveQueuedMessage(TokenAccess.READ_INTERVAL, IncomingMessage,
                    ServerAddress);

            if (isMessageQueued && (IncomingMessage.Type == TokenAccess.PDU_CONNECT)) {
                System.out.println("ring exists");
                //pdu_connect used instead of ring exisits 
                state = TokenAccess.STATES.STATE_tokenLess;
                bContinueEventWait = false;

            }

        case STATE_tokenLess:
            ClientSocket.MakeConnection(AnyAddress);
            while (state == TokenAccess.STATES.STATE_tokenLess) {
                // Instructs the socket to accept

                // building ip address message
                OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_CONNECT,
                        InetAddress.getLocalHost().getHostAddress(),
                        InetAddress.getLocalHost().getHostAddress().length());
                //broadcasting ip address
                ClientSocket.DeliverMessage(OutgoingMessage, BroadcastAddress);
                //     System.out.println("broadcasting address");

                isMessageQueued = ClientSocket.RetrieveQueuedMessage(TokenAccess.READ_INTERVAL, IncomingMessage,
                        ServerAddress);

                //will trigger if used on a 192 network i didnt know how to use regex for any number and a dot
                if (isMessageQueued == true && (IncomingMessage.Type == TokenAccess.PDU_CLOSE)) {
                    System.out.println("pdu close");
                    String ipaddress = IncomingMessage.Buffer;

                    for (int n : addressIP) {
                        if (addressIP[n] == Integer.parseInt(ipaddress)) {
                            String a;
                            a = Integer.toString(addressIP[n]);
                            OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_ACK,
                                    InetAddress.getLocalHost().getHostAddress(),
                                    InetAddress.getLocalHost().getHostAddress().length());
                            ENDPOINT exitAddress = new ENDPOINT(a, TokenAccess.SERVER_PORT_NUMBER);

                            ClientSocket.DeliverMessage(OutgoingMessage, exitAddress);
                            addressIP = ArrayUtils.removeElement(addressIP, n);
                        }

                    }
                }

                if (last != null && tokenlost.bRunning == false) {
                    tokenlost.Start(TokenAccess.tokenlost);
                    last = null;
                    System.out.println("token lost timer started");
                }

                if (isMessageQueued == true && (IncomingMessage.Type == TokenAccess.CMD_CONNECT)) {
                    System.out.println("token lost timer stopped");
                    tokenlost.Stop();
                }

                if (tokenlost.isExpired()) {

                    System.out.println("token lost");

                    for (int n = 0; n < addressIP.length; n++) {
                        String ipaddress = InetAddress.getLocalHost().toString();
                        int lastdot = ipaddress.lastIndexOf(".") + 1;
                        ipaddress = ipaddress.substring(lastdot, ipaddress.length());
                        System.out.println(n);
                        if (addressIP[n] == null) {

                        } else {
                            if (addressIP[n] == Integer.parseInt(ipaddress)) {

                                String a;
                                a = Integer.toString(addressIP[n]);
                                System.out.println("variable a " + a);
                                OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_ACK,
                                        InetAddress.getLocalHost().getHostAddress(),
                                        InetAddress.getLocalHost().getHostAddress().length());
                                ENDPOINT exitAddress = new ENDPOINT(lanAddress, TokenAccess.SERVER_PORT_NUMBER);

                                ClientSocket.DeliverMessage(OutgoingMessage, exitAddress);

                                OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_TOKEN,
                                        InetAddress.getLocalHost().getHostAddress(),
                                        InetAddress.getLocalHost().getHostAddress().length());
                                String b = Integer.toString(addressIP[n]);
                                b = lanAddress;
                                System.out.println(b);

                                ENDPOINT exitAddresss = new ENDPOINT(b, TokenAccess.SERVER_PORT_NUMBER);
                                ClientSocket.DeliverMessage(OutgoingMessage, exitAddresss);

                            }
                        }
                    }

                }

                if (exit.isExpired()) {
                    OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_CLOSE,
                            InetAddress.getLocalHost().getHostAddress(),
                            InetAddress.getLocalHost().getHostAddress().length());
                    exit.Start(30);
                }

                if (isMessageQueued && (IncomingMessage.Type == TokenAccess.PDU_TOKEN)) {
                    tokenlost.Stop();
                    System.out.println(IncomingMessage.Type);
                    state = TokenAccess.STATES.STATE_TOKENED;
                    tokentimer.Start(TokenAccess.tokentimer);
                    break;
                }

            }

        case STATE_TOKENED:
            while (state == TokenAccess.STATES.STATE_TOKENED) {

                //send data
                OutgoingMessage.BuildMessage(0, 0, "ALIVE", CommentLength);
                ClientSocket.DeliverMessage(OutgoingMessage, BroadcastAddress);
                tokenlost.Stop();
                while (trigger == 0) {
                    System.out.println("TOKENED");
                    trigger++;
                }

                if (tokentimer.isExpired()) {
                    trigger = 0;
                    System.out.println("token expired");
                    String ipaddress = InetAddress.getLocalHost().toString();
                    //  System.out.println( "System name : "+ipaddress);

                    for (int n = 0; n < addressIP.length; n++) {
                        // System.out.println(n);
                        int lastdot = ipaddress.lastIndexOf(".") + 1;
                        ipaddress = ipaddress.substring(lastdot, ipaddress.length());
                        // System.out.println("IP address: "+ipaddress);
                        int address1 = Integer.parseInt(ipaddress);

                        System.out.println("made it to line 214");
                        System.out.println(n);
                        System.out.println(addressIP[0]);

                        if (addressIP[n] == address1) {
                            String a;
                            a = Integer.toString(addressIP[n]);
                            System.out.println("variable a = " + a);

                            String ip = InetAddress.getLocalHost().getHostAddress();
                            System.out.println("line 226");
                            System.out.println(ip);

                            OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_TOKEN,
                                    InetAddress.getLocalHost().getHostAddress(),
                                    InetAddress.getLocalHost().getHostAddress().length());
                            String b;

                            System.out.println("line 222");
                            if (n + 1 >= addressIP.length) {
                                b = (ip);
                                //   System.out.println(b);
                            } else {
                                b = ip;

                            }

                            System.out.println(b);

                            //b = InetAddress.getLocalHost().toString().substring(0, lastdot); 
                            // int slash =   b.indexOf("/");
                            System.out.println(b);
                            ENDPOINT exitAddresss = new ENDPOINT(b, TokenAccess.SERVER_PORT_NUMBER);
                            ClientSocket.DeliverMessage(OutgoingMessage, exitAddresss);
                            System.out.println("exiting tokened state");
                            state = TokenAccess.STATES.STATE_tokenLess;
                            last = "1";
                        }
                        break;
                    }
                }
            }

        case STATE_EXIT:
            while (state == TokenAccess.STATES.STATE_EXIT) {
                System.exit(0);

            }

        }

    }

}

From source file:com.ericgithinji.java.algorithms.sort.MergeSort.java

public static int[] merge(int[] array1, int array2[]) {
    int[] mergedArray = new int[array1.length + array2.length];
    int i = mergedArray.length - 1;
    if (mergedArray.length <= 1)
        return mergedArray;
    if (mergedArray.length > 1) {
        if (array1[0] > array2[0]) {
            mergedArray[i] = array2[0];/*  w  w  w. ja v  a  2s  .  c  o m*/
            mergedArray = ArrayUtils.removeElement(array2, array2[0]);
            i--;
        } else {
            mergedArray[i] = array1[0];
            mergedArray = ArrayUtils.removeElement(array1, array1[0]);
            i--;
        }
    }
    if (array1.length > 0) {
        mergedArray[i] = array1[0];
        mergedArray = ArrayUtils.removeElement(array1, array1[0]);
        i--;
    }
    if (array2.length > 0) {
        mergedArray[i] = array2[0];
        mergedArray = ArrayUtils.removeElement(array2, array2[0]);
        i--;
    }
    return mergedArray;
}

From source file:de.linzn.leegianOS.internal.objectDatabase.skillType.SecondarySkill.java

public SecondarySkill(int subskill_id, String trigger, String[] inputArray, PrimarySkill parentskill,
        String java_class, String java_method, Map serial_data) {
    LeegianOSApp.logger(this.getClass().getSimpleName() + "->" + "creating Instance ", false);
    this.subskill_id = subskill_id;
    this.trigger = trigger;
    this.inputArray = ArrayUtils.removeElement(inputArray, trigger);
    this.parentskill = parentskill;
    this.java_class = java_class;
    this.java_method = java_method;
    this.serial_data = serial_data;
}

From source file:de.linzn.leegianOS.internal.objectDatabase.skillType.PrimarySkill.java

public PrimarySkill(int parentskill_id, boolean standalone, String trigger, String[] inputArray,
        String java_class, String java_method, Map serial_data) {
    LeegianOSApp.logger(this.getClass().getSimpleName() + "->" + "creating Instance ", false);
    this.parentskill_id = parentskill_id;
    this.standalone = standalone;
    this.trigger = trigger;
    this.inputArray = ArrayUtils.removeElement(inputArray, trigger);
    this.java_class = java_class;
    this.java_method = java_method;
    this.serial_data = serial_data;
}

From source file:com.outcastgeek.traversal.TraverseUtils.java

/**
 * @param pojo is the POJO to be traversed
 * @param pathSteps is traversal path//from   www .j a v  a 2  s . c  o  m
 * @return true or false
 * @throws TraverseException
 */
public static boolean isNullPath(Object pojo, String... pathSteps) throws TraverseException {

    boolean isNullPath = false;

    try {
        Class pojoClass = pojo.getClass();
        Method[] declaredMethods = pojoClass.getDeclaredMethods();
        int pathStepLength = pathSteps.length;
        logger.debug("Traversing {}...", pojo);
        for (int i = 0; i < pathStepLength; i++) {
            String step = pathSteps[i];
            logger.debug("Step: {}", step);
            Object value = null;
            for (Method method : declaredMethods) {
                String methodName = method.getName();
                if (StringUtils.containsIgnoreCase(methodName, step)) {
                    value = pojoClass.getDeclaredMethod(methodName).invoke(pojo);
                    break;
                }
            }
            if (value != null) {
                if (i == pathStepLength - 1) {
                    break;
                } else {
                    String[] followingSteps = ArrayUtils.removeElement(pathSteps, step);
                    return isNullPath(value, followingSteps);
                }
            } else {
                isNullPath = true;
                break;
            }
        }
    } catch (Exception e) {
        throw new TraverseException(e);
    }

    return isNullPath;
}

From source file:com.norconex.jefmon.instances.InstancesManager.java

public static void removeInstance(String url) {
    JEFMonConfig config = getConfig();//from  w  ww.j  a v  a 2 s .  c o  m
    synchronized (config) {
        config.setRemoteInstanceUrls(ArrayUtils.removeElement(config.getRemoteInstanceUrls(), url));
        try {
            ConfigurationDAO.saveConfig(config);
        } catch (IOException e) {
            throw new WicketRuntimeException("Config file not found: " + ConfigurationDAO.CONFIG_FILE, e);
        }
    }
}

From source file:com.outcastgeek.traversal.TraverseUtils.java

/**
 * @param pojo is the POJO to be traversed
 * @param pathSteps is traversal path//w  ww.  jav  a2  s  .co m
 * @return the object a the end of the path
 * @throws TraverseException
 */
public static Object getPath(Object pojo, String... pathSteps) throws TraverseException {

    Object value = null;

    try {
        Class pojoClass = pojo.getClass();
        Method[] declaredMethods = pojoClass.getDeclaredMethods();
        int pathStepLength = pathSteps.length;
        logger.debug("Traversing {}...", pojo);
        for (int i = 0; i < pathStepLength; i++) {
            String step = pathSteps[i];
            logger.debug("Step: {}", step);
            for (Method method : declaredMethods) {
                String methodName = method.getName();
                if (StringUtils.containsIgnoreCase(methodName, step)) {
                    value = pojoClass.getDeclaredMethod(methodName).invoke(pojo);
                    break;
                }
            }
            if (i == pathStepLength - 1) {
                break;
            } else {
                String[] followingSteps = ArrayUtils.removeElement(pathSteps, step);
                return getPath(value, followingSteps);
            }
        }
    } catch (Exception e) {
        throw new TraverseException(e);
    }

    return value;
}

From source file:hoot.services.utils.MultipartSerializer.java

private static void serializeUploadedFiles(List<BodyPart> fileItems, Map<String, String> uploadedFiles,
        Map<String, String> uploadedFilesPaths, String repFolderPath) {
    try {/* w  w w.  j  av  a  2 s  .c o m*/
        for (BodyPart fileItem : fileItems) {
            String fileName = fileItem.getContentDisposition().getFileName();

            if (fileName == null) {
                throw new RuntimeException("A valid file name was not specified.");
            }

            String uploadedPath = repFolderPath + "/" + fileName;

            boolean isPathSafe = validatePath(HOME_FOLDER + "/upload", uploadedPath);
            if (isPathSafe) {
                try (InputStream fileStream = fileItem.getEntityAs(InputStream.class)) {
                    File file = new File(uploadedPath);
                    FileUtils.copyInputStreamToFile(fileStream, file);
                }

                String[] nameParts = fileName.split("\\.");
                if (nameParts.length > 1) {
                    String extension = nameParts[nameParts.length - 1].toUpperCase();
                    String[] subArr = ArrayUtils.removeElement(nameParts, nameParts[nameParts.length - 1]);
                    String filename = StringUtils.join(subArr, '.');
                    if (extension.equalsIgnoreCase("OSM") || extension.equalsIgnoreCase("GEONAMES")
                            || extension.equalsIgnoreCase("SHP") || extension.equalsIgnoreCase("ZIP")
                            || extension.equalsIgnoreCase("PBF")) {
                        uploadedFiles.put(filename, extension);
                        uploadedFilesPaths.put(filename, fileName);
                        logger.debug("Saving uploaded:{}", filename);
                    }
                }
            } else {
                throw new IOException("Illegal path: " + uploadedPath);
            }
        }
    } catch (Exception ioe) {
        throw new RuntimeException("Error trying to serialize uploaded files!", ioe);
    }
}

From source file:code.elix_x.excore.utils.client.gui.elements.ListGuiElement.java

public void remove(ListElement element) {
    elements = ArrayUtils.removeElement(elements, element);
}