Example usage for java.util ArrayList isEmpty

List of usage examples for java.util ArrayList isEmpty

Introduction

In this page you can find the example usage for java.util ArrayList isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:com.massabot.codesender.GrblController.java

@Override
public void returnToHome() throws Exception {
    if (this.isCommOpen()) {
        // Not using max for now, it was causing issue for many people.
        double max = 0;
        if (this.maxZLocationMM != -1) {
            max = this.maxZLocationMM;
        }/*w ww  .ja va2s  .co  m*/
        ArrayList<String> commands = GrblUtils.getReturnToHomeCommands(this.grblVersion, this.grblVersionLetter,
                this.workLocation.z);
        if (!commands.isEmpty()) {
            Iterator<String> iter = commands.iterator();
            // Perform the homing commands
            while (iter.hasNext()) {
                String gcode = iter.next();
                GcodeCommand command = createCommand(gcode);
                this.sendCommandImmediately(command);
            }
            return;
        }

        restoreParserModalState();
    }
    // Throw exception
    super.returnToHome();
}

From source file:com.ec.android.module.bluetooth40.base.BaseBluetoothControlWithProtocolActivity.java

/**
 * ?//from w  ww . jav  a2  s  .  c  om
 * TODO ?
 *
 * @param data
 */
private void onReceiveData(byte[] data) {
    if (data.length < 7) {
        //?7header??
        return;
    }
    //
    byte magic = data[0];

    if (magic != Packet.MAGIC_BYTE) {
        //?
        return;
    }
    //
    byte dataMuti = data[1];
    byte errFlag = (byte) (dataMuti & 0x08);
    //
    int payloadLength = data[2];

    if (payloadLength < 0) {
        payloadLength = 256 + payloadLength;
    }
    ////
    byte sequenceIdHigh8 = data[3];
    byte sequenceIdLow8 = data[4];
    //
    int sequenceIdHigh8Int = sequenceIdHigh8;
    int sequenceIdLow8Int = sequenceIdLow8;
    //
    if (sequenceIdHigh8 < 0) {
        sequenceIdHigh8Int = (256 + sequenceIdHigh8);
    }
    if (sequenceIdLow8 < 0) {
        sequenceIdLow8Int = (256 + sequenceIdLow8);
    }
    //
    //        short sequenceIdTemp = 0;
    //sequenceIdpacket
    short sequenceId = (short) ((sequenceIdHigh8Int << 8) + sequenceIdLow8Int);
    //
    if (errFlag == 0x08) {
        //??1
        mProtocolDataUtils.putErrFlag(sequenceId, true);
        return;
    } else {
        //???0
        mProtocolDataUtils.putErrFlag(sequenceId, false);
    }
    //
    byte ackFlag = (byte) (dataMuti & 0x04);
    if (ackFlag == 0x04) {
        //??1
        //packet?

    } else {
        //???
        //??
        //
        byte beginFlag = (byte) (dataMuti & 0x02);
        byte endFlag = (byte) (dataMuti & 0x01);
        //?packet
        //
        int myCrc = magic ^ data[1] ^ payloadLength ^ sequenceId;

        int crcHigh = data[5];
        int crcLow = data[6];

        if (crcHigh < 0) {
            crcHigh = 256 + crcHigh;
        }
        if (crcLow < 0) {
            crcLow = 256 + crcLow;
        }

        //            int crcTemp = 0x00;
        //
        int crc = (crcHigh << 8) + crcLow;

        if (crc != myCrc) {
            //?
            mProtocolDataUtils.removeGetDataMap(sequenceId);
            return;
        }
        //?
        byte[] bodyBytes = ArrayUtils.subarray(data, 7, data.length);
        //
        if (beginFlag == 0x02) {
            //??1?packet
            //packet??sequenceId??????
            mProtocolDataUtils.removeGetDataMap(sequenceId);
            mProtocolDataUtils.plusGetDataMap(sequenceId, ArrayUtils.toObject(bodyBytes));
        } else {
            //??0??packet
            //???sequenceId???
            ArrayList<Byte[]> getDataMapList = mProtocolDataUtils.getGetDataMap(sequenceId);
            if (getDataMapList == null || getDataMapList.isEmpty()) {
                return;
            } else {
                //??
                mProtocolDataUtils.plusGetDataMap(sequenceId, ArrayUtils.toObject(bodyBytes));
            }
        }
        //
        if (endFlag == 0x01) {
            //??1??packet
            //??
            ArrayList<Byte[]> getDataMapList = mProtocolDataUtils.getGetDataMap(sequenceId);

            if (getDataMapList != null) {
                Byte[] myAllBytes = null;
                for (Byte[] bytes : getDataMapList) {
                    myAllBytes = (Byte[]) ArrayUtils.addAll(myAllBytes, bytes);
                }
                //?
                mProtocolDataUtils.removeGetDataMap(sequenceId);
                //
                onActionDataAvailable(myAllBytes);
            }
        }
    }
    //
}

From source file:com.app.util.browser.BrowserSniffer.java

private void sniffBrowser() throws Exception {
    // eg: Camino/0.7
    // [0] = Camino/0.7
    // [1] = Camino
    // [2] = 0//from  w  w w.  j  a v a 2  s . c om
    // [3] = .7
    ArrayList matches = getMatches(BrowserTypePat, ua, 4);
    if (matches.isEmpty())
        return;

    // first find out whether it's msie hiding behind many different doors... 
    String[] browserParticulars = (String[]) CollectionUtils.find(matches, new Predicate() {
        public boolean evaluate(Object arg0) {
            final String[] pieces = (String[]) arg0;
            for (int i = 0; i < pieces.length; i++) {
                final String piece = pieces[i];
                if (StringUtils.contains(piece, MSIE_ID)) {
                    return true;
                }
            }
            return false;
        }
    });

    // if it's not msie but test for Opera because it can identify itself as msie...
    if (browserParticulars == null) {
        // get the position of the last browser key found
        int count = matches.size() - 1;
        browserParticulars = (String[]) matches.get(count);
    }

    longName = browserParticulars[0];
    browserName = browserParticulars[1];

    // get browserName from string
    Matcher nameMatcher = NameOnlyPat.matcher(browserName);
    if (nameMatcher.matches()) {
        browserName = nameMatcher.group(nameMatcher.groupCount());
    }

    majorVersion = browserParticulars[2];

    // parse the minor version string and look for alpha chars
    if (browserParticulars[3] != null) {
        // eg: .7b
        // [0] = .7b
        // [1] = .7
        // [2] = b
        matches = getMatches(MinorVersionPat, browserParticulars[3], 3);
        if (matches.isEmpty())
            return;

        int count = matches.size() - 1;
        browserParticulars = (String[]) matches.get(count);
        if (browserParticulars[1] != null)
            minorVersion = browserParticulars[1];
        else
            minorVersion = ".0";

        if (PunctuationOnlyPat.matcher(minorVersion).matches())
            minorVersion = StringUtils.EMPTY;

        if (browserParticulars[2] != null && !PunctuationOnlyPat.matcher(browserParticulars[2]).matches())
            revisionVersion = browserParticulars[2];
    }
}

From source file:Interfaz.VnServidorReportes.java

public void setTiempoPromedio(ArrayList lista) {
        int res = 0;
        for (int i = 0; i < lista.size(); i++) {
            Tickets temp = (Tickets) lista.get(i);
            res = res + this.getDuracion(temp.getTiempoSegundos());
        }//from w ww  . j  a  v  a2  s  .  c  o m
        if (lista.isEmpty()) {
            return;
        }
        res = res / lista.size();
        this.tiempopromedio.setText(res + "");

    }

From source file:com.strategicgains.docussandra.controller.perf.remote.mongo.PlayByPlayPerfMongo.java

@Test
@Override//  w  ww . j av a 2s  .c om
public void postQueryTestTwoField() {
    try {
        int numQueries = 50;
        Date start = new Date();
        MongoClient mongoClient = new MongoClient(uri);
        //mongoClient.setWriteConcern(WriteConcern.MAJORITY);
        DB db = mongoClient.getDB(this.getDb().name());
        final DBCollection coll = db.getCollection(this.getDb().name());
        for (int i = 0; i < numQueries; i++) {
            logger.debug("Query: " + i);
            ArrayList<String> res = new ArrayList<>();
            BasicDBObject query = new BasicDBObject();
            query.append("dwn", 4);
            query.append("ytg", 1);
            DBCursor curser = coll.find(query);
            int count = 0;
            while (curser.hasNext() && count++ < 10000) {
                DBObject o = curser.next();
                assertNotNull(o);
                assertTrue(o.toString().contains("4"));
                assertTrue(o.toString().contains("1"));
                res.add(o.toString());
            }
            assertFalse(res.isEmpty());
        }
        Date end = new Date();

        long executionTime = end.getTime() - start.getTime();
        double inSeconds = (double) executionTime / 1000d;
        double average = (double) inSeconds / (double) numQueries;
        output.info(
                "PBP-Mongo: Time to execute (two fields) for " + numQueries + " is: " + inSeconds + " seconds");
        output.info("PBP-Mongo: Averge time for two fields is: " + average);
    } catch (UnknownHostException e) {
        logger.error("Couldn't run test.", e);
        throw new RuntimeException(e);
    }
}

From source file:com.l2jfree.gameserver.geodata.pathfinding.PathFinding.java

public final Node[] searchByClosest2(Node start, Node end, int instanceId) {
    // Always continues checking from the closest to target non-blocked
    // node from to_visit list. There's extra length in path if needed
    // to go backwards/sideways but when moving generally forwards, this is extra fast
    // and accurate. And can reach insane distances (try it with 800 nodes..).
    // Minimum required node count would be around 300-400.
    // Generally returns a bit (only a bit) more intelligent looking routes than
    // the basic version. Not a true distance image (which would increase CPU
    // load) level of intelligence though.

    // List of Visited Nodes
    L2FastSet<Node> visited = L2Collections.newL2FastSet();
    // List of Nodes to Visit
    ArrayList<Node> to_visit = L2Collections.newArrayList();
    to_visit.add(start);//  w ww  .j a v a  2  s  . c  o  m
    try {
        int targetx = end.getNodeX();
        int targety = end.getNodeY();
        int dx, dy;
        boolean added;
        int i = 0;
        while (i < 550) {
            if (to_visit.isEmpty()) {
                // No Path found
                return null;
            }

            Node node = to_visit.remove(0);

            if (node.equals(end)) //path found!
                return constructPath2(node);
            else {
                i++;
                visited.add(node);
                node.attachNeighbors(instanceId);
                Node[] neighbors = node.getNeighbors();
                if (neighbors == null)
                    continue;
                for (Node n : neighbors) {
                    if (!visited.contains(n) && !to_visit.contains(n)) {
                        added = false;
                        n.setParent(node);
                        dx = targetx - n.getNodeX();
                        dy = targety - n.getNodeY();
                        n.setCost(dx * dx + dy * dy);
                        for (int index = 0; index < to_visit.size(); index++) {
                            // supposed to find it quite early..
                            if (to_visit.get(index).getCost() > n.getCost()) {
                                to_visit.add(index, n);
                                added = true;
                                break;
                            }
                        }
                        if (!added)
                            to_visit.add(n);
                    }
                }
            }
        }
        //No Path found
        return null;
    } finally {
        L2Collections.recycle(visited);
        L2Collections.recycle(to_visit);
    }
}

From source file:edu.stolaf.cs.wmrserver.HadoopEngine.java

public JobStatus getStatus(Submission submission) throws NotFoundException, InternalException {
    RunningJob job = getJob(submission);
    JobConf conf = loadJobConfiguration(job);

    JobStatus status = new JobStatus();
    status.setInfo(getInfo(submission, job, conf));

    try {/*from  w  w w  .  jav a2 s .co m*/
        JobClient client = new JobClient(new JobConf());

        // Get job state
        // Thanks to the mentally handicapped switch statement, we have
        // to use a chain of ifs. Fuck Java.
        int jobState = job.getJobState();
        if (jobState == org.apache.hadoop.mapred.JobStatus.FAILED)
            status.setState(State.FAILED);
        else if (jobState == org.apache.hadoop.mapred.JobStatus.SUCCEEDED)
            status.setState(State.SUCCESSFUL);
        else if (jobState == org.apache.hadoop.mapred.JobStatus.KILLED)
            status.setState(State.KILLED);
        else if (jobState == org.apache.hadoop.mapred.JobStatus.RUNNING)
            status.setState(State.RUNNING);
        else
            status.setState(State.PREP);

        // Get task counts
        TaskReport[] mapTaskReports = client.getMapTaskReports(job.getID());
        TaskReport[] reduceTaskReports = client.getReduceTaskReports(job.getID());

        // Get failed task logs
        TaskCompletionEvent[] events = job.getTaskCompletionEvents(0);
        Pair<ArrayList<TaskLog>, ArrayList<TaskLog>> failures;
        if (events != null)
            failures = getLogsFromCompletionEvents(events);
        else
            failures = getLogsFromHistory(job, new Configuration());
        ArrayList<TaskLog> mapFailures = failures.first;
        ArrayList<TaskLog> reduceFailures = failures.second;

        // Get other mapper info
        PhaseStatus mapStatus = new PhaseStatus();
        mapStatus.setProgress(job.mapProgress() * 100);
        if (!mapFailures.isEmpty())
            mapStatus.setErrors(getMeaningfulTaskLog(mapFailures));
        if (mapTaskReports != null)
            mapStatus.setTotalTasks(mapTaskReports.length);
        // TODO: Handle the state in a sane way
        mapStatus.setState(status.getState());
        status.setMapStatus(mapStatus);

        // Get other reducer info
        PhaseStatus reduceStatus = new PhaseStatus();
        reduceStatus.setProgress(job.reduceProgress() * 100);
        if (!reduceFailures.isEmpty())
            reduceStatus.setErrors(getMeaningfulTaskLog(reduceFailures));
        reduceStatus.setState(status.getState());
        if (reduceTaskReports != null)
            reduceStatus.setTotalTasks(reduceTaskReports.length);
        if (conf != null)
            reduceStatus.setOutputPath(FileOutputFormat.getOutputPath(conf).toString());
        status.setReduceStatus(reduceStatus);
    } catch (Exception ex) {
        throw JobServiceHandler.wrapException("Could not get job info.", ex);
    }

    return status;
}

From source file:com.strategicgains.docussandra.controller.perf.remote.mongo.PlayersRemotePerfMongo.java

/**
 * Tests that the POST /{databases}/{table}/query endpoint properly runs a
 * two field query with a set time./*from  w  w  w .  ja v a2 s  .  c om*/
 */
@Test
@Override
public void postQueryTestTwoField() {
    int numQueries = 50;
    Date start = new Date();
    try {
        MongoClient mongoClient = new MongoClient(uri);
        mongoClient.setWriteConcern(WriteConcern.MAJORITY);
        DB db = mongoClient.getDB(this.getDb().name());
        final DBCollection coll = db.getCollection(this.getDb().name());
        for (int i = 0; i < numQueries; i++) {
            logger.debug("Query: " + i);
            ArrayList<String> res = new ArrayList<>();
            BasicDBObject query = new BasicDBObject();
            query.append("NAMELAST", "Manning");
            query.append("NAMEFIRST", "Peyton");
            DBCursor curser = coll.find(query);
            int count = 0;
            while (curser.hasNext() && count++ < 10000) {
                DBObject o = curser.next();
                assertNotNull(o);
                assertTrue(o.toString().contains("Manning"));
                assertTrue(o.toString().contains("Peyton"));
                res.add(o.toString());
            }
            assertFalse(res.isEmpty());
        }
        Date end = new Date();

        long executionTime = end.getTime() - start.getTime();
        double inSeconds = (double) executionTime / 1000d;
        double average = (double) inSeconds / (double) numQueries;
        output.info("Players-Mongo: Time to execute (two fields) for " + numQueries + " is: " + inSeconds
                + " seconds");
        output.info("Players-Mongo: Averge time for two fields is: " + average);
    } catch (UnknownHostException e) {
        logger.error("Couldn't run test.", e);
        throw new RuntimeException(e);
    }
}

From source file:edu.isi.misd.scanner.network.registry.web.controller.AnalysisPolicyStatementController.java

@RequestMapping(value = BASE_PATH, method = { RequestMethod.GET,
        RequestMethod.HEAD }, produces = HEADER_JSON_MEDIA_TYPE)
public @ResponseBody List<AnalysisPolicyStatement> getAnalysisPolicyStatements(
        @RequestParam Map<String, String> paramMap) {
    Map<String, String> params = validateParameterMap(paramMap, REQUEST_PARAM_USER_NAME,
            REQUEST_PARAM_INSTANCE_ID, REQUEST_PARAM_ANALYSIS_TOOL_ID);

    if (!params.isEmpty()) {
        ArrayList<String> missingParams = new ArrayList<String>();
        String userName = params.get(REQUEST_PARAM_USER_NAME);
        if (userName == null) {
            missingParams.add(REQUEST_PARAM_USER_NAME);
        }//from  w  w w  .  ja  v  a2  s  .co m
        String instanceId = params.get(REQUEST_PARAM_INSTANCE_ID);
        if (instanceId == null) {
            missingParams.add(REQUEST_PARAM_INSTANCE_ID);
        }
        String toolId = params.get(REQUEST_PARAM_ANALYSIS_TOOL_ID);
        if (toolId == null) {
            missingParams.add(REQUEST_PARAM_ANALYSIS_TOOL_ID);
        }
        if (!missingParams.isEmpty()) {
            throw new BadRequestException("Required parameter(s) missing: " + missingParams);
        }
        return analysisPolicyStatementRepository.findAnalysisPolicyStatementByUserNameAndInstanceIdAndToolId(
                userName, validateIntegerParameter(REQUEST_PARAM_INSTANCE_ID, instanceId),
                validateIntegerParameter(REQUEST_PARAM_ANALYSIS_TOOL_ID, toolId));
    }

    List<AnalysisPolicyStatement> analysisPolicyStatements = new ArrayList<AnalysisPolicyStatement>();
    Iterator iter = analysisPolicyStatementRepository.findAll().iterator();
    CollectionUtils.addAll(analysisPolicyStatements, iter);

    return analysisPolicyStatements;
}

From source file:com.kbot2.scriptable.methods.data.Walking.java

private WalkerNode[] findPath(WalkerNode startNode, WalkerNode endNode) {
    try {//from   w  ww.  j  ava 2 s  .c  om
        if (!loadNodes || !loadLisks)
            load();
        ArrayList<WalkerNode> l = new ArrayList<WalkerNode>();
        for (int i = 0; i < nodes.size(); i++) {
            WalkerNode thisNode = nodes.get(i);
            thisNode.distance = 999999;
            thisNode.previous = null;
            l.add(thisNode);
        }
        startNode.distance = 0;
        while (l.isEmpty() == false) {
            WalkerNode nearestNode = l.get(0);
            for (int i = 0; i < l.size(); i++) {
                WalkerNode thisNode = l.get(i);
                if (thisNode.distance <= nearestNode.distance)
                    nearestNode = thisNode;

            }
            l.remove(l.indexOf(nearestNode));
            if (nearestNode == endNode)
                l.clear();
            else
                for (int i = 0; i < nearestNode.neighbours.size(); i++) {
                    WalkerNode neighbourNode = nearestNode.neighbours.get(i);
                    int alt = nearestNode.distance + nearestNode.distance(neighbourNode);
                    if (alt < neighbourNode.distance) {
                        neighbourNode.distance = alt;
                        neighbourNode.previous = nearestNode;
                    }
                }
        }
        ArrayList<WalkerNode> nodePath = new ArrayList<WalkerNode>();
        nodePath.add(endNode);
        WalkerNode previousNode = endNode.previous;
        while (previousNode != null) {
            nodePath.add(previousNode);
            previousNode = previousNode.previous;
        }
        if (nodePath.size() == 1)
            return null;
        WalkerNode[] nodeArray = new WalkerNode[nodePath.size()];
        for (int i = nodePath.size() - 1; i >= 0; i--)
            nodeArray[nodePath.size() - i - 1] = nodePath.get(i);
        return nodeArray;
    } catch (Exception e) {
    }
    return null;
}