Parsing the output of iwlist, tool having a lot of different faces :-(
@param str output of the tool
@param callback
557938
function parseOutput(str, callback) {
  var err   = null;
  var wifis = [];

  try {
    var blocks = str.split(cellRegex);

    blocks.forEach(block => {
      var network = {};
      var lines   = block.split('\n');
      if (macRegex.exec(lines[0])) {
        // First line is the mac address (always! (?))
        network.mac = lines[0].trim();

        lines.forEach(line => {
          // SSID
          if (line.indexOf('ESSID:') > 0) {
            network.ssid = _.trim(line.split(':')[1], '"');
            if (_.startsWith(network.ssid, '\\x00')) {
              // The raspi 3 interprets a string terminator as character, it's an empty SSID
              network.ssid = '';
            }
          }

          // Channel, an ugly thing to get it
          else if (_.startsWith(line.trim(), 'Frequency:')) {
            network.channel = parseInt(_.trim(line, ' )').split(/Channel/)[1], 10);
          }
            
          // Another ugly thing, the signal which can have different formats, even worse als
          // having different identifiers
          else if (line.indexOf('Signal level') > -1) {
            if (line.indexOf('Quality') > -1) {
              // This is a "Quality=40/70  Signal level=-70 dBm" line
              network.rssi = parseInt(line.substr(line.indexOf('Signal level') + 13), 10);
            }
            else {
              // This is a "Signal level=60/100" line
              var elements = line.split('=');
              elements.forEach(e => {
                if (e.indexOf('/') > 0) {
                  // that's our part
                  var parts    = e.split('/');
                  var level    = Math.floor(100 * parseInt(parts[0], 10) / parseInt(parts[1], 10));
                  network.rssi = level / 2 - 100;
                }
              })
            }
          }
        });
        wifis.push(network);
      }
    });
  }
  catch (ex) {
    err = ex;
  }

  callback(err, wifis);
}
956372
function parseRawLines(rawText, extendedSyntax, parsedRawLinesCallback) {
        var entries = rawText.replace(reBlank, '').split(/[\r\n]+/);
        var currentLang = '*';
        var genericLang = lang.split('-', 1)[0];
        var skipLang = false;
        var match = '';

        function nextEntry() {
          // Use infinite loop instead of recursion to avoid reaching the
          // maximum recursion limit for content with many lines.
          while (true) {
            if (!entries.length) {
              parsedRawLinesCallback();
              return;
            }
            var line = entries.shift();

            // comment or blank line?
            if (reComment.test(line))
              continue;

            // the extended syntax supports [lang] sections and @import rules
            if (extendedSyntax) {
              match = reSection.exec(line);
              if (match) { // section start?
                // RFC 4646, section 4.4, "All comparisons MUST be performed
                // in a case-insensitive manner."

                currentLang = match[1].toLowerCase();
                skipLang = (currentLang !== '*') &&
                    (currentLang !== lang) && (currentLang !== genericLang);
                continue;
              } else if (skipLang) {
                continue;
              }
              match = reImport.exec(line);
              if (match) { // @import rule?
                loadImport(baseURL + match[1], nextEntry);
                return;
              }
            }

            // key-value pair
            var tmp = line.match(reSplit);
            if (tmp && tmp.length == 3) {
              dictionary[tmp[1]] = evalString(tmp[2]);
            }
          }
        }
        nextEntry();
      }
1228701
def debug_callback(event, *args, **kwds):
    '''
    '''
    l = ['event %s' % (event.type,)]
    if args:
        l.extend(map(str, args))
    if kwds:
        l.extend(sorted('%s=%s' % t for t in kwds.items()))
    print('Debug callback (%s)' % ', '.join(l))
338016
function saxParser(elem, callbacks){
	if(typeof callbacks !== 'object')
		throw 'please provide callbacks!';

	//todo: support further events, options for trim & space normalisation
	
	function parse(node){
		var name = node.tagName.toLowerCase(),
		    attributeNodes = node.attributes;
		
		callbacks.onopentagname(name);
		
		for(var i = 0, j = attributeNodes.length; i < j; i++){
			callbacks.onattribute(attributeNodes[i].name+'', attributeNodes[i].value);
		}
		
		var childs = node.childNodes,
		    num = childs.length, nodeType;
		
		for(var i = 0; i < num; i++){
			nodeType = childs[i].nodeType;
			if(nodeType === 3 /*text*/)
				callbacks.ontext(childs[i].textContent);
			else if(nodeType === 1 /*element*/) parse(childs[i]);
			/*else if(nodeType === 8) //comment
				if(callbacks.oncomment) callbacks.oncomment(childs[i].toString());
			[...]
			*/
		}
		callbacks.onclosetag(name);
	}
	
	parse(elem);
}
762700
function callbackHandler(callback) {
        return function(error, data) {
            if (data === 'OK') {
                callback();
                return;
            }

            callback(error, deserializeResponse(data));
        };
    }
140078
public static void parse(final String str, final ShortcodeParser.Handler handler) {
      ShortcodeParser.parse(str, handler);
   }
817997
function Parser(stdout) {
  this._name = null;
  this._description = null;
  this._version = "0.0.0";
  this._epilog = null;
  this._commands = { };
  this._short = { };
  this._default = this.showHelp.bind(this);
  this._hooks = { };
  this._width = 0;
  this._out = isFunction(stdout) ? stdout : console.log;
  this.option("H", "help", "show this help information", this.showHelp.bind(this));
  this.option("V", "version", "show version information", this.showVersion.bind(this));
  return this;
}
1206010
function callbackParser(err, out) {
	if (err) {
		error += err + '\n\n';
	} else {
		results[counter] = out;
	}

	counter++;
	if (counter === urlLength) {
		let result = {sources: [], feeds: []};
		let i = 0;
		_.each(results, feed => {
			feed.metadata.lastBuildDate = moment(feed.metadata.lastBuildDate).format('x');
			feed.metadata.update = moment(feed.metadata.update).format('x');
			result.sources.push({type: feed.type, metadata: feed.metadata});
			_.each(feed.items, function (item) {
				item.source = i;
				result.feeds.push(item);
			});
			i++;
		});

		// Sort value
		switch (allowSortValue[sortByDate]) {
			case allowSortValue.asc:
				result.feeds.sort((a, b) => (a.date > b.date) ? 1 : ((b.date > a.date) ? -1 : 0));
				break;
			case allowSortValue.desc:
				result.feeds.sort((a, b) => (a.date < b.date) ? 1 : ((b.date < a.date) ? -1 : 0));
				break;
			default:
				break;
		}

		if (error !== '') {
			finishCallback(error);
		} else {
			finishCallback(null, {feedRSSAtom: result});
		}
	}
}
1283562
def _lenstr(ins):
    ''' 
    '''
    (tmp1, output) = _str_oper(ins.quad[2], no_exaf=True)
    if tmp1:
        output.append('push hl')

    output.append('call __STRLEN')
    output.extend(_free_sequence(tmp1))
    output.append('push hl')
    REQUIRES.add('strlen.asm')
    return output
837151
def output_callback(self, line, kill_switch):
        """"""
        self.notifications += line + "\n"

        if "Initialization Sequence Completed" in line:
            self.started = True
        if "ERROR:" in line or "Cannot resolve host address:" in line:
            self.error = True
        if "process exiting" in line:
            self.stopped = True
29592
function parseOutput(str, callback) {
  var err = null;

  try {
    var lines      = str.split('\n');
    var wifis = [];
    
    for (var i = 1, l = lines.length; i < l; i++) {
      var mac = lines[i].match(macRegex);
      if (!mac) {
        continue;
      }
      var macStart = lines[i].indexOf(mac[0]);
      var elements = lines[i].substr(macStart).split(/[ ]+/);
      wifis.push({
        'ssid'    : lines[i].substr(0, macStart).trim(),
        'mac'     : elements[0].trim(),
        'channel' : parseInt(elements[2].trim(), 10),
        'rssi'    : parseInt(elements[1].trim(), 10)
      });
    }
  }
  catch (ex) {
    err = ex;
  }

  callback(err, wifis);
}
1230451
function CallbackHandler(callable) {
    CallbackHandler.super_.call(this);

    if (!_.isFunction(callable)) {
        throw new TypeError(
            'Argument  must be valid callable'
        );
    }

    this.__callable = callable;
}
1296461
function showInterfaceIdlMethod(method, html) {
    var line = "\n   "

    var allParameters = method.parameters.concat(method.callbackParameters)

    line += getIdlType(method.returns)
    line += " <span class='methodName'>" + method.name + "</span> (" + getIdlParameterList(allParameters) + ");"
    html.push(line)
}
45694
void parseArgs(String[] args) {
    int i = 0;
    while (true) {
      if (i >= args.length) {
        break;
      }

      String s = args[i];
      if (s.equals("-h") ||
              s.equals("help") ||
              s.equals("-help") ||
              s.equals("--help")) {
        usage();
      }
      else if (s.equals("-n") ||
              s.equals("-nodes")) {
        i++; if (i >= args.length) { usage(); }
        numNodes = Integer.parseInt(args[i]);
      }
      else if (s.equals("-o") ||
              s.equals("-output")) {
        i++; if (i >= args.length) { usage(); }
        outputPath = args[i];
      }
      else if (s.equals("-jobname")) {
        i++; if (i >= args.length) { usage(); }
        jobtrackerName = args[i];
      }
      else if (s.equals("-mapperXmx")) {
        i++; if (i >= args.length) { usage(); }
        mapperXmx = args[i];
      }
      else if (s.equals("-extramempercent")) {
        i++; if (i >= args.length) { usage(); }
        extraMemPercent = Integer.parseInt(args[i]);
      }
      else if (s.equals("-driverif")) {
        i++; if (i >= args.length) { usage(); }
        driverCallbackIp = args[i];
      }
      else if (s.equals("-driverport")) {
        i++; if (i >= args.length) { usage(); }
        driverCallbackPort = Integer.parseInt(args[i]);
      }
      else if (s.equals("-network")) {
        i++; if (i >= args.length) { usage(); }
        network = args[i];
      }
      else if (s.equals("-timeout")) {
        i++; if (i >= args.length) { usage(); }
        cloudFormationTimeoutSeconds = Integer.parseInt(args[i]);
      }
      else if (s.equals("-disown")) {
        disown = true;
      }
      else if (s.equals("-notify")) {
        i++; if (i >= args.length) { usage(); }
        clusterReadyFileName = args[i];
      }
      else if (s.equals("-nthreads")) {
        i++; if (i >= args.length) { usage(); }
        nthreads = Integer.parseInt(args[i]);
      }
      else if (s.equals("-many_cols")) {
        manyCols = true;
      }
      else if (s.equals("-chunk_bytes")) {
        i++; if (i >= args.length) { usage(); }
        chunk_bytes = Integer.parseInt(args[i]);
      }
      else if (s.equals("-data_max_factor_levels")) {
        i++; if (i >= args.length) { usage(); }
        data_max_factor_levels = Integer.parseInt(args[i]);
      }
      else if (s.equals("-baseport")) {
        i++; if (i >= args.length) { usage(); }
        basePort = Integer.parseInt(args[i]);
        if ((basePort < 0) || (basePort > 65535)) {
            error("Base port must be between 1 and 65535");
        }
      }
      else if (s.equals("-beta")) {
        beta = true;
      }
      else if (s.equals("-random_udp_drop")) {
        enableRandomUdpDrop = true;
      }
      else if (s.equals("-ea")) {
        enableExceptions = true;
      }
      else if (s.equals("-verbose:gc")) {
        enableVerboseGC = true;
      }
      else if (s.equals("-verbose:class")) {
        enableVerboseClass = true;
      }
      else if (s.equals("-XX:+PrintCompilation")) {
        enablePrintCompilation = true;
      }
      else if (s.equals("-exclude")) {
        enableExcludeMethods = true;
      }
      else if (s.equals("-Dlog4j.defaultInitOverride=true")) {
        enableLog4jDefaultInitOverride = true;
      }
      else if (s.equals("-debug")) {
        enableDebug = true;
      }
      else if (s.equals("-suspend")) {
        enableSuspend = true;
      }
      else if (s.equals("-debugport")) {
        i++; if (i >= args.length) { usage(); }
        debugPort = Integer.parseInt(args[i]);
        if ((debugPort < 0) || (debugPort > 65535)) {
          error("Debug port must be between 1 and 65535");
        }
      }
      else if (s.equals("-XX:+PrintGCDetails")) {
        enablePrintGCDetails = true;
      }
      else if (s.equals("-XX:+PrintGCTimeStamps")) {
        enablePrintGCTimeStamps = true;
      }
      else if (s.equals("-gc")) {
        enableVerboseGC = true;
        enablePrintGCDetails = true;
        enablePrintGCTimeStamps = true;
      }
      else if (s.equals("-license")) {
        i++; if (i >= args.length) { usage(); }
        licenseFileName = args[i];
      }
      else if (s.equals("-extraJavaOpts")) {
        i++; if (i >= args.length) { usage(); }
        extraJavaOpts = args[i];
      }
      else {
        error("Unrecognized option " + s);
      }

      i++;
    }

    // Check for mandatory arguments.
    if (numNodes < 1) {
      error("Number of H2O nodes must be greater than 0 (must specify -n)");
    }
    if (outputPath == null) {
      error("Missing required option -output");
    }
    if (mapperXmx == null) {
      error("Missing required option -mapperXmx");
    }

    // Check for sane arguments.
    if (! mapperXmx.matches("[1-9][0-9]*[mgMG]")) {
      error("-mapperXmx invalid (try something like -mapperXmx 4g)");
    }

    if (extraMemPercent < 0) {
      extraMemPercent = DEFAULT_EXTRA_MEM_PERCENT;
    }

    if (jobtrackerName == null) {
      Random rng = new Random();
      int num = rng.nextInt(99999);
      jobtrackerName = "H2O_" + num;
    }

    if (network == null) {
      network = "";
    }
    else {
      String[] networks;
      if (network.contains(",")) {
        networks = network.split(",");
      }
      else {
        networks = new String[1];
        networks[0] = network;
      }

      for (int j = 0; j < networks.length; j++) {
        String n = networks[j];
        Pattern p = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)/(\\d+)");
        Matcher m = p.matcher(n);
        boolean b = m.matches();
        if (! b) {
          error("network invalid: " + n);
        }

        for (int k = 1; k <=4; k++) {
          int o = Integer.parseInt(m.group(k));
          if ((o < 0) || (o > 255)) {
            error("network invalid: " + n);
          }

          int bits = Integer.parseInt(m.group(5));
          if ((bits < 0) || (bits > 32)) {
            error("network invalid: " + n);
          }
        }
      }
    }

    if (network == null) {
      error("Internal error, network should not be null at this point");
    }

    if ((nthreads >= 0) && (nthreads < 4)) {
      error("nthreads invalid (must be >= 4): " + nthreads);
    }

    if (licenseFileName != null) {
      try {
        licenseData = readFile(licenseFileName);
      }
      catch (Exception xe) {
        StringBuilder sb = new StringBuilder();
        sb.append("Failed to read license file: ");
        if (xe.getLocalizedMessage() != null) {
          sb.append(xe.getLocalizedMessage());
        }
        else {
          sb.append(licenseFileName);
        }

        error(sb.toString());
      }
    }
  }
706098
def _parsed_callback_wrapper(self, callback_parsed, callback_plain, foc, data):
        """"""
        # used by PointDataObjectHandler as reference
        if foc == R_FEED:
            point_ref = data['pid']
        else:  # R_CONTROL
            point_ref = Control(self, data[P_ENTITY_LID], data[P_LID], '0' * 32)

        try:
            data['parsed'] = self._get_point_data_handler_for(point_ref).get_template(data=data[P_DATA])
        except RefreshException:
            # No metadata available, do not produce warning
            if callback_plain:
                callback_plain(data)
        except:
            logger.warning('Failed to parse %s data for %s%s', foc_to_str(foc), point_ref,
                           '' if callback_plain else ', ignoring',
                           exc_info=DEBUG_ENABLED)
            if callback_plain:
                callback_plain(data)
        else:
            callback_parsed(data)
363476
function parse(str) {

  // find the prefix expressions and the main value
  var stringMatches = str.match(stringRegex)
  var allExpString = stringMatches[1] || ''
  var value = stringMatches[2]

  // parse each prefix expression
  var expressions = execAll(allExpressionsRegex, allExpString)
    // grab the expression content inside the braces
    .map(function (match) { return match[1] })
    .map(parseExpression)

  return {
    original:   str,
    value:      value,
    expressions: expressions
  }
}
916451
function json (program, callback) {
    var formatterRedux = formatter(jsonRedux())
    parse(program.stdin, program.stderr, printer(formatterRedux, program.stdout, program.stderr), callback)
}