/*
The function performOpenAllScanIteration does...
18515
function getPerformOpenAllScanIteration(bundle) {
        return function performOpenAllScanIteration(scanMethod, cb) {
            var dt = scanMethod.deviceType;
            var ct = scanMethod.connectionType;
            var requiredInfo = scanMethod.addresses;

            function onErr(err) {
                cb();
            }
            function onSuccess(openAllData) {
                var erroniusDevices = parseOutErroniusDevices(openAllData);
                erroniusDevices.forEach(function(dev) {
                    bundle.erroniusDevices.push(dev);
                });

                debugOpenAllResults('OpenAll...', openAllData, dt, ct);
                var stopTime = new Date();
                var deltaTime = parseFloat(((stopTime - startTime)/1000).toFixed(2));
                debugSS('Successfully called OpenAll', deltaTime);
                debugLJMCalls('Successfully called OpenAll', deltaTime);
                debugOpenAll('Successfully called OpenAll', deltaTime);
                var openedHandles = openAllData.handles;

                var openedDevices = [];
                openedHandles.forEach(function(openedHandle) {
                    openedDevices.push({
                        'handle': openedHandle,
                    });
                });


                /* openedHandles is an array of objects aka [ {handle: 0}, {handle: 1}, ... ] */
                debugOpenAll('OpenAll Finished, in onSuccess, data:', dt, ct, openAllData);

                // Build an array of promises indicating when all opened devices are finished being opened.
                var promises = openedDevices.map(function(openedDevice) {
                    var openInfo = {
                        'deviceType': dt,
                        'connectionType': ct,
                        'identifier': 'LJM_idANY',
                    };
                    debugOpenAll('Managing device...', openedDevice);
                    var promise = self.deviceManager.addDevice(
                        openedDevice,
                        requiredInfo,
                        openInfo
                    );
                    return promise;
                });


                // When all devices have been added to the device manager we can return.
                q.allSettled(promises)
                .then(function() {
                    cb();
                }, function(err) {
                    console.error('Error in performOpenAllScanIteration', err);
                    cb();
                });
            }
            var startTime = new Date();
            debugLJMCalls('Calling OpenAll', dt, ct);

            if(LIVE_DEVICE_SCANNING_ENABLED) {
                // Execute the LJM openAll function.
                self.driver.openAll(dt, ct, onErr, onSuccess);
            } else {
                mockDeviceScanningLib.openAll(dt, ct, onErr, onSuccess);
            }
        }
    }
143927
public IToken evaluate(ICharacterScanner scanner)
	{
		offset = 0;
		int c = read(scanner);
		if (c != ICharacterScanner.EOF && fDetector.isWordStart((char) c))
		{
			if (fColumn == UNDEFINED || fColumn == scanner.getColumn() - 1)
			{
				fBuffer.setLength(0);
				fBuffer.append((char) c);

				for (int i = 0; i < getMaxPartCount(); i++)
				{
					// read a word for each part
					do
					{
						c = read(scanner);
						fBuffer.append((char) c);
						// System.out.println("Read: '"+c + "' - '"+(char)c+"'");
					} while (c != ICharacterScanner.EOF && c != ' '
							&& fDetector.isWordStart((char) c));
				}

				// we may have read EOF so unread it
				popEof(scanner);

				final char lastChar = fBuffer.charAt(fBuffer.length()-1);
				if (lastChar==' ' || lastChar=='\t'
						|| lastChar=='\n' || lastChar=='\r')
				{
					unread(scanner);// last space
					fBuffer.delete(fBuffer.length() - 1, fBuffer.length());
				}
				
				String text = fBuffer.toString().toString().replace('\n', ' ').replace('\r', ' ').replace('\t', ' ');
				String key = text;// text.substring(0, text.length() - 1);


				WordMatch match = checkMatch(key);
				if (match != null)
				{
					if (match.unMatchedLength > 0)
					{
						// unread unmatched parts
						for (int i = 0; i < match.unMatchedLength; i++)
						{
							unread(scanner);
						}
					}

					return match.token;
				}

				if (fDefaultToken.isUndefined())
				{
					unreadBuffer(scanner);
				}

				return returnEmpty(fDefaultToken);

			}
		}

		unread(scanner);
		return returnEmpty(Token.UNDEFINED);
	}
1026889
@Override
    public <T> Map<File, T> scanDirectoryWithResults(
            File directory, FileFilter fileFilter, Function<Resource, T> fileProcessor) {
        final ConcurrentMap<File, T> results = new ConcurrentHashMap<File, T>();
        this.scanDirectory(directory, results, fileFilter, fileProcessor);
        return results;
    }
968701
@Override
  public void scan(InH3Amp in, PathH3Amp path, Object[] values)
  {
    int ch = read();
    
    switch (ch) {
    case 0xd0:
      readDefinition(in);
      scan(in, path, values);
      return;
      
    case 0xd1: case 0xd2: case 0xd3: 
    case 0xd4: case 0xd5: case 0xd6: case 0xd7:
    case 0xd8: case 0xd9: case 0xda: case 0xdb:
    case 0xdc: case 0xdd: case 0xde: case 0xdf:
    {
      int id = ch - 0xd0;

      in.serializer(id).scan(this, path, in, values);
      return;
    }
      
    case 0xe0: case 0xe1: case 0xe2: case 0xe3: 
    case 0xe4: case 0xe5: case 0xe6: case 0xe7:
    case 0xe8: case 0xe9: case 0xea: case 0xeb:
    case 0xec: case 0xed: case 0xee: case 0xef:
    {
      int id = (int) readLong(ch - 0xe0, 4);
      
      in.serializer(id).scan(this, path, in, values);
      return;
    }
      
    default:
      throw error(L.l("Unexpected opcode 0x{0} while scanning for {1}",
                      Integer.toHexString(ch), path));
    }
  }
854137
@Override
    public R visitArrayAccess(ArrayAccessTree node, P p) {
        R r = scan(node.getExpression(), p);
        r = scanAndReduce(node.getIndex(), p, r);
        return r;
    }
1202994
@Override
	public Scan open() {
		// throws an exception if p is not a tableplan.
		TableScan ts = (TableScan) tp.open();
		Index idx = ii.open(tx);
		return new IndexSelectScan(idx, 
				new SearchRange(ii.fieldNames(), schema(), searchRanges), ts);
	}
971692
private Token scanIdentifier(int c) throws IOException {
        int startLine = mSource.getLineNumber();
        int startPos = mSource.getStartPosition();
        int endPos = mSource.getEndPosition();
        mWord.setLength(0);
        
        mWord.append((char)c);

    loop:
        while ( (c = mSource.peek()) != -1 ) {
            switch (c) {
            case 'a': case 'b': case 'c': case 'd': case 'e':
            case 'f': case 'g': case 'h': case 'i': case 'j':
            case 'k': case 'l': case 'm': case 'n': case 'o':
            case 'p': case 'q': case 'r': case 's': case 't':
            case 'u': case 'v': case 'w': case 'x': case 'y':
            case 'z':
            case 'A': case 'B': case 'C': case 'D': case 'E':
            case 'F': case 'G': case 'H': case 'I': case 'J':
            case 'K': case 'L': case 'M': case 'N': case 'O':
            case 'P': case 'Q': case 'R': case 'S': case 'T':
            case 'U': case 'V': case 'W': case 'X': case 'Y':
            case 'Z': case '_': case '$':
            case '0': case '1': case '2': case '3': case '4': 
            case '5': case '6': case '7': case '8': case '9':
                mSource.read();
                endPos = mSource.getEndPosition();
                mWord.append((char)c);
                continue loop;
            }
                
            if (Character.isLetterOrDigit((char)c)) {
                mSource.read();
                endPos = mSource.getEndPosition();
                mWord.append((char)c);
            }
            else {
                break;
            }
        }
        
        int id = Token.findReservedWordID(mWord);
        
        Token t;

        if (id != Token.UNKNOWN) {
            t = new Token(startLine, startPos, endPos, id);
        }
        else {
            t = new StringToken(startLine, startPos, endPos,
                                Token.IDENT, mWord.toString());
        }

        mWord.setLength(0);
        return t;
    }
1074309
function (checks) {
    this.from = this.char;

    // Move to the next non-space character.
    var start;
    if (/\s/.test(this.peek())) {
      start = this.char;

      while (/\s/.test(this.peek())) {
        this.from += 1;
        this.skip();
      }
    }

    // Methods that work with multi-line structures and move the
    // character pointer.

    var match = this.scanComments() ||
      this.scanStringLiteral(checks) ||
      this.scanTemplateLiteral();

    if (match) {
      return match;
    }

    // Methods that don't move the character pointer.

    match =
      this.scanRegExp() ||
      this.scanPunctuator() ||
      this.scanKeyword() ||
      this.scanIdentifier() ||
      this.scanNumericLiteral();

    if (match) {
      this.skip(match.value.length);
      return match;
    }

    // No token could be matched, give up.

    return null;
  }
305357
@Override
    public void scanDirectoryNoResults(
            File directory, FileFilter fileFilter, Function<Resource, ?> fileProcessor) {
        this.scanDirectory(directory, null, fileFilter, fileProcessor);
    }
217344
private void initOrderedIterator()
   {
      if (orderedNodes != null)
      {
         return;
      }
      long time = 0;
      if (LOG.isDebugEnabled())
      {
         time = System.currentTimeMillis();
      }
      ScoreNode[][] nodes = (ScoreNode[][])scoreNodes.toArray(new ScoreNode[scoreNodes.size()][]);

      final Set<String> invalidIDs = new HashSet<String>(2);

      /** Cache for Nodes obtainer during the order (comparator work) */
      final Map<String, NodeData> lcache = new HashMap<String, NodeData>();
      do
      {
         if (invalidIDs.size() > 0)
         {
            // previous sort run was not successful -> remove failed uuids
            List<ScoreNode[]> tmp = new ArrayList<ScoreNode[]>();
            for (int i = 0; i < nodes.length; i++)
            {
               if (!invalidIDs.contains(nodes[i][selectorIndex].getNodeId()))
               {
                  tmp.add(nodes[i]);
               }
            }
            nodes = (ScoreNode[][])tmp.toArray(new ScoreNode[tmp.size()][]);
            invalidIDs.clear();
         }

         try
         {
            // sort the uuids
            Arrays.sort(nodes, new ScoreNodeComparator(lcache, invalidIDs));
         }
         catch (SortFailedException e)
         {
            if (LOG.isTraceEnabled())
            {
               LOG.trace("An exception occurred: " + e.getMessage());
            }
         }

      }
      while (invalidIDs.size() > 0);

      if (LOG.isDebugEnabled())
      {
         LOG.debug("" + nodes.length + " node(s) ordered in " + (System.currentTimeMillis() - time) + " ms");
      }

      orderedNodes = new ScoreNodeIteratorImpl(nodes);
   }
131427
function completeOpen() {
      if (process.stdout.isTTY) {
        rl = readline.createInterface(process.stdin, process.stdout);
        rl.setPrompt(chalk.dim('TinyG# '), 'TinyG# '.length);
        rl.prompt();

        // WARNING WARNING WARNING -- using the internals of node readline!!
        //
        // We need to override the default behavior for a few keys.
        // So, we tell stdin to REMOVE all of the listeners to the 'keypress'
        // event, then we will be the only listener. If we don't have a special
        // behavior for the pressed key, then we pass it on to the readline.
        //
        // To avoid using internals too much, we'll snarf in the listeners,
        // store them away, and then call them ourselves.
        var old_keypress_listeners = process.stdin.listeners('keypress');

        process.stdin.removeAllListeners('keypress');
        process.stdin.on('keypress', function (ch, k) {
          if (k && k.ctrl) {
            if (k.name == 'd') {
              if (sendingFile) {
                log(util.format(">>^d\n"));
                g.write('\x04'); // send the ^d
              }
              return;
            }
            else if (k.name == 'c') {
              var e = util.format("## Received CTRL-C in State '%s' -- sending CTRL-D and exiting.\n", STAT_CODES[latestMotionStatus]);
              log(e);
              if (interactive) {
                process.stdout.write(chalk.dim(e));
              }

              tryToQuit()
              return;
            }

          // Single character commands get sent immediately
        } else if (ch && ch.match(/^[!~%]/)) {
            log(util.format(">>%s\n", ch));
            g.write(ch);
            return;
          }

          for (var i = 0; i < old_keypress_listeners.length; i++) {
            old_keypress_listeners[i](ch,k);
          }
        })

        rl.on('line', function(line) {
          parseCommand(line);
          if (rl !== null) {
            rl.prompt(true);
          }
        });

        rl.on('close', function() {
          g.close();
          rl = null;
        });

        var leftText = "Progress |";
        var rightText = "|   0% ";

        var status = {};

        g.on('statusChanged', function(st) {
          for(var prop in st) {
            status[prop] = st[prop];
          }

          if (status.stat) {
            latestMotionStatus = status.stat;
          }

          if (interactive) {
            readline.moveCursor(process.stdout, 0, -1);
            readline.clearLine(process.stdout, 0);

            process.stdout.write(
              sprintf("\rPos: X=%4.2f Y=%4.2f Z=%4.2f A=%4.2f Vel:%4.2f",
                status.posx||0,
                status.posy||0,
                status.posz||0,
                status.posa||0,
                status.vel||0
              )
            );
            if (status.he1t) {
              process.stdout.write(
                sprintf(" He1=%4.2fºC/%4.2fºC",
                  status.he1t||0,
                  status.he1st||0
                )
              );
            }
            process.stdout.write(
              sprintf(" (%s)\n",
                STAT_CODES[status.stat] || 'Stopped'
              )
            );

            if (!sendingFile) {
              process.stdout.write(
                JSON.stringify(status, null, 0) + "\n"
              );

              rl.prompt(true);
            }
          }


          if (st.line && sendingFile) {
            if (st.line > maxLineNumber) {
              maxLineNumber = st.line;
            }
            // clear the whole line.
            // readline.moveCursor(process.stdout, 0, -1);
            // readline.clearLine(process.stdout, 0);
            process.stdout.write("\r");

            var maxWidth = process.stdout.columns;
            var paddingWidth = leftText.length + rightText.length;
            var barWidth = (maxWidth - paddingWidth) * (st.line/maxLineNumber);
            var barLeft = (maxWidth - paddingWidth);

            process.stdout.write(leftText);
            // console.error("maxWidth: %d, paddingWidth: %d, sent: %d, lines: %d", maxWidth, paddingWidth, b.sent, b.lines);
            while (barWidth > 1.0) {
              process.stdout.write('=');
              barWidth = barWidth - 1.0;
              barLeft--;
            }
            if (barWidth > 0.6) {
              process.stdout.write('+');
              barLeft--;
            } else if (barWidth > 0.3) {
              process.stdout.write('-');
              barLeft--;
            }
            while (barLeft-- > 0) {
              process.stdout.write('_');
            }

            process.stdout.write("| ")
            var percent = ((st.line/maxLineNumber) * 100);
            process.stdout.write(sprintf("%3.0f%%", percent));

            // if (process.stderr.isTTY) {
            //   process.stdout.write("\n")
            // } else {
              process.stdout.write("\r")
            // }
          } // if st.line
          // rl.prompt(true);
        }); // g.on('statusChanged', ... )
      }

      if (args.gcode || !process.stdin.isTTY) {
        sendFile(args.gcode || process.stdin, true);
      }
    }
672029
static boolean allPositive(int[] input, int start, int length) {
        for (int i = length - 1, index = start; i >= 0; i--, index++) {
            if (input[index] <= 0) {
                return false;
            }
        }

        return true;
    }
526160
function scan(language) {
            var i;
            for (i = 0; i < availableLanguages.length; i += 1) {
                if (language.toLowerCase() === availableLanguages[i].toLowerCase()) {
                    return availableLanguages[i];
                }
            }
        }
999690
function perfFindInterlacedInserts(multiplier) {
  var start, end;
  var totalTimes = [];
  var totalMS = 0;

  var loopIterations = arraySize;
  if (typeof (multiplier) != "undefined") {
    loopIterations = loopIterations * multiplier;
  }

  for (var idx = 0; idx < loopIterations; idx++) {
    var customidx = Math.floor(Math.random() * arraySize) + 1;

    start = process.hrtime();
    var results = samplecoll.find({
      'customId': customidx
    });
    // insert junk record, now (outside timing routine) to force index rebuild
    var obj = samplecoll.insert({
        customId: 999,
        val: 999,
        val2: 999,
        val3: "more data 1234567890"
    });  
    
    end = process.hrtime(start);
    totalTimes.push(end);
    
  }

  for (var idx = 0; idx < totalTimes.length; idx++) {
    totalMS += totalTimes[idx][0] * 1e3 + totalTimes[idx][1] / 1e6;
  }

  totalMS = totalMS.toFixed(2);
  var rate = loopIterations * 1000 / totalMS;
  rate = rate.toFixed(2);
  console.log("interlaced inserts + coll.find() : " + totalMS + "ms (" + rate + " ops/s) " + loopIterations + " iterations");
  
}
1170336
private int doall(String cmd, String argv[], int startindex) {
    int exitCode = 0;
    int i = startindex;
    boolean rmSkipTrash = false;
    
    // Check for -skipTrash option in rm/rmr
    if(("-rm".equals(cmd) || "-rmr".equals(cmd)) 
        && "-skipTrash".equals(argv[i])) {
      rmSkipTrash = true;
      i++;
    }

    //
    // for each source file, issue the command
    //
    for (; i < argv.length; i++) {
      try {
        //
        // issue the command to the fs
        //
        if ("-cat".equals(cmd)) {
          cat(argv[i], true);
        } else if ("-du".equals(cmd)) {
          du(argv[i]);
        } else if ("-dus".equals(cmd)) {
          dus(argv[i]);
        } else if (Count.matches(cmd)) {
          new Count(argv, i, getConf()).runAll();
        } else if ("-text".equals(cmd)) {
          text(argv[i]);
        } else if ("-decompress".equals(cmd)) {
          decompress(argv[i]);
        }
      } catch (RemoteException e) {
        //
        // This is a error returned by hadoop server. Print
        // out the first line of the error message.
        //
        exitCode = -1;
        try {
          String[] content;
          content = e.getLocalizedMessage().split("\n");
          System.err.println(cmd.substring(1) + ": " +
                             content[0]);
        } catch (Exception ex) {
          System.err.println(cmd.substring(1) + ": " +
                             ex.getLocalizedMessage());
        }
      } catch (IOException e) {
        //
        // IO exception encountered locally.
        //
        exitCode = -1;
        String content = e.getLocalizedMessage();
        if (content != null) {
          content = content.split("\n")[0];
        }
        System.err.println(cmd.substring(1) + ": " +
                          content);
      }
    }
    return exitCode;
  }
1305904
private Iterator<MultiTableScanResult> scanMultiTableRows(
            final TableSet tables, final DeltaPlacement placement, final ByteBufferRange rowRange,
            final LimitCounter limit, final boolean includeDroppedTables, final boolean includeMirrorTables,
            final int largeRowThreshold, final ReadConsistency consistency, @Nullable final Instant cutoffTime) {

        // Avoiding pinning multiple decoded rows into memory at once.
        return limit.limit(new AbstractIterator<MultiTableScanResult>() {
            private PeekingIterator<Row<ByteBuffer, DeltaKey>> _iter = Iterators.peekingIterator(
                    rowScan(placement, rowRange, _maxColumnsRange, LimitCounter.max(), consistency));

            private long _lastTableUuid = -1;
            private AstyanaxTable _table = null;
            private boolean _droppedTable;
            private boolean _primaryTable;

            @Override
            protected MultiTableScanResult computeNext() {
                while (_iter.hasNext()) {
                    Row<ByteBuffer, DeltaKey> row = _iter.next();
                    ColumnList<DeltaKey> rowColumns = row.getColumns();

                    // Convert the results into a Record object, lazily fetching the rest of the columns as necessary.
                    ByteBuffer rowKey = row.getRawKey();

                    long tableUuid = AstyanaxStorage.getTableUuid(rowKey);
                    if (_lastTableUuid != tableUuid) {
                        _lastTableUuid = tableUuid;
                        try {
                            _table = (AstyanaxTable) tables.getByUuid(tableUuid);
                        } catch (UnknownTableException e) {
                            _table = AstyanaxTable.createUnknown(tableUuid, placement, e.getTable());
                        } catch (DroppedTableException e) {
                            _table = AstyanaxTable.createUnknown(tableUuid, placement, e.getPriorTable());
                        }
                        _droppedTable = _table.isUnknownTable();
                        _primaryTable = _table.getReadStorage().hasUUID(tableUuid);
                    }

                    // Skip dropped and mirror tables if configured
                    if ((!includeDroppedTables && _droppedTable) || (!includeMirrorTables && !_primaryTable)) {
                        _iter = skipToNextTable(tableUuid);
                        continue;
                    }

                    int shardId = AstyanaxStorage.getShardId(rowKey);
                    String key = AstyanaxStorage.getContentKey(rowKey);
                    Record record = newRecord(new Key(_table, key), rowKey, rowColumns, largeRowThreshold, consistency, cutoffTime);
                    return new MultiTableScanResult(rowKey, shardId, tableUuid, _droppedTable, record);
                }

                return endOfData();
            }

            private PeekingIterator<Row<ByteBuffer, DeltaKey>> skipToNextTable(long tableUuid) {
                // Iterate over the next 50 rows first to check for a table switch.  This avoids starting a new range
                // query if the number of rows in the undesired table is small.
                int skipLimit = 50;
                Row<ByteBuffer, DeltaKey> row = null;

                while (skipLimit != 0 && _iter.hasNext()) {
                    row = _iter.peek();
                    long nextTableUuid = AstyanaxStorage.getTableUuid(row.getRawKey());
                    if (nextTableUuid != tableUuid) {
                        // This is the first row of a new table
                        return _iter;
                    } else {
                        _iter.next();
                        skipLimit -= 1;
                    }
                }

                if (_iter.hasNext()) {
                    // Skip the table entirely by starting a new query on the next possible table
                    assert row != null;
                    int shardId = AstyanaxStorage.getShardId(row.getRawKey());
                    ByteBuffer nextPossibleTableStart = AstyanaxStorage.getRowKeyRaw(shardId, tableUuid + 1, "");
                    ByteBuffer end = rowRange.getEnd();

                    if (AstyanaxStorage.compareKeys(nextPossibleTableStart, end) < 0) {
                        // We haven't reached the last end boundary of the original range scan
                        ByteBufferRange updatedRange = new ByteBufferRangeImpl(nextPossibleTableStart, end, -1, false);
                        return Iterators.peekingIterator(
                                rowScan(placement, updatedRange, _maxColumnsRange, LimitCounter.max(), consistency));
                    }
                }

                return Iterators.peekingIterator(Iterators.<Row<ByteBuffer, DeltaKey>>emptyIterator());
            }
        });
    }
257534
protected function xxxScan($method, $str_key, &$i_iterator, $str_pattern = null, $i_count = null)
    {
        $argStrs = ['ARGV[1]', 'ARGV[2]'];
        $args = [$str_key, $i_iterator];

        $argvCounter = 2;

        if(null !== $str_pattern)
        {
            $argStrs[] = "'MATCH'";
            $argStrs[] = 'ARGV[' . (++$argvCounter) . ']';
            $args[] = $str_pattern;
        }

        if(null !== $i_count)
        {
            $argStrs[] = "'COUNT'";
            $argStrs[] = 'ARGV[' . (++$argvCounter) . ']';
            $args[] = $i_count;
        }

        $argStr = implode(',', $argStrs);

        $result = $this->eval(<<<STR
return redis.call('{$method}', {$argStr}) 
STR
        , $args);

        if(!$result)
        {
            return false;
        }

        $i_iterator = (int)$result[0];
        return 0 === $i_iterator && [] === $result[1] ? false : $result[1];
    }