Generic cli app for bsseval results. Expects two folder with
424301
def bsseval(inargs=None):
    
    parser = argparse.ArgumentParser()

    parser.add_argument(
        'reference_dir',
        type=str
    )

    parser.add_argument(
        'estimates_dir',
        type=str
    )

    parser.add_argument('-o', help='output_dir')

    parser.add_argument(
        '--win', type=float, help='Window size in seconds', default=1.0
    )

    parser.add_argument(
        '--hop', type=float, help='Hop size in seconds', default=1.0
    )

    parser.add_argument(
        '-m', type=str, help='bss_eval version [`v3`, `v4`]', default='v4'
    )

    parser.add_argument(
        '--version', '-v',
        action='version',
        version='%%(prog)s %s' % util.__version__
    )

    args = parser.parse_args(inargs)

    if not args.o:
        output_dir = args.estimates_dir
    else:
        output_dir = args.o

    # evaluate an existing estimate folder with wav files
    data = eval_dir(
        args.reference_dir,
        args.estimates_dir,
        output_dir=output_dir,
        mode=args.m,
        win=args.win,
        hop=args.hop
    )

    print(data)
692744
def _run_bcbio_variation(vrn_file, rm_file, rm_interval_file, base_dir, sample, caller, data):
    
    val_config_file = _create_validate_config_file(vrn_file, rm_file, rm_interval_file,
                                                   base_dir, data)
    work_dir = os.path.join(base_dir, "work")
    out = {"summary": os.path.join(work_dir, "validate-summary.csv"),
           "grading": os.path.join(work_dir, "validate-grading.yaml"),
           "discordant": os.path.join(work_dir, "%s-eval-ref-discordance-annotate.vcf" % sample)}
    if not utils.file_exists(out["discordant"]) or not utils.file_exists(out["grading"]):
        bcbio_variation_comparison(val_config_file, base_dir, data)
    out["concordant"] = filter(os.path.exists,
                                [os.path.join(work_dir, "%s-%s-concordance.vcf" % (sample, x))
                                 for x in ["eval-ref", "ref-eval"]])[0]
    return out
1275263
function sassError(ctx /*, options*/) {
  if (ctx.line && ctx.message) { // libsass 3.x error object
    return new Error('Line ' + ctx.line + ': ' + ctx.message);
  }
  if (typeof ctx === 'string') { // libsass error string format: path:line: error: message
    var error = _.zipObject(
      [ 'path', 'line', 'level', 'message' ],
      ctx.split(':', 4).map(function (str) { return str.trim(); })
    );
    if (error.line && error.level && error.message) {
      return new Error('Line ' + error.line + ': ' + error.message);
    }
  }

  return new Error(ctx);
}
1330321
function error(path, e) {
    var status = void 0;
    var stdout = void 0;

    if (e.code === 'ENOENT' && e.syscall === 'scandir') {
      status = 1;
      stdout = 'ls: cannot access ' + path + ': No such file or directory';
    } else {
      status = 2;
      stdout = e.stack;
    }

    ls.self.log(stdout);
    return { status: status, stdout: stdout };
  }
1356989
def _bsd_bradd(br):
    '''
    
    '''
    kernel = __grains__['kernel']
    ifconfig = _tool_path('ifconfig')

    if not br:
        return False

    if __salt__['cmd.retcode']('{0} {1} create up'.format(ifconfig, br),
                               python_shell=False) != 0:
        return False

    # NetBSD is two cmds
    if kernel == 'NetBSD':
        brconfig = _tool_path('brconfig')
        if __salt__['cmd.retcode']('{0} {1} up'.format(brconfig, br),
                                   python_shell=False) != 0:
            return False

    return True
2373
def cli(ctx, **kwargs):
    
    if kwargs['add_sys_path']:
        sys.path.append(os.getcwd())

    logging.config.fileConfig(kwargs['logging_config'])

    # get db from env
    for db in ('taskdb', 'projectdb', 'resultdb'):
        if kwargs[db] is not None:
            continue
        if os.environ.get('MYSQL_NAME'):
            kwargs[db] = utils.Get(lambda db=db: connect_database(
                'sqlalchemy+mysql+%s://%s:%s/%s' % (
                    db, os.environ['MYSQL_PORT_3306_TCP_ADDR'],
                    os.environ['MYSQL_PORT_3306_TCP_PORT'], db)))
        elif os.environ.get('MONGODB_NAME'):
            kwargs[db] = utils.Get(lambda db=db: connect_database(
                'mongodb+%s://%s:%s/%s' % (
                    db, os.environ['MONGODB_PORT_27017_TCP_ADDR'],
                    os.environ['MONGODB_PORT_27017_TCP_PORT'], db)))
        elif ctx.invoked_subcommand == 'bench':
            if kwargs['data_path'] == './data':
                kwargs['data_path'] += '/bench'
                shutil.rmtree(kwargs['data_path'], ignore_errors=True)
                os.mkdir(kwargs['data_path'])
            if db in ('taskdb', 'resultdb'):
                kwargs[db] = utils.Get(lambda db=db: connect_database('sqlite+%s://' % (db)))
            elif db in ('projectdb', ):
                kwargs[db] = utils.Get(lambda db=db: connect_database('local+%s://%s' % (
                    db, os.path.join(os.path.dirname(__file__), 'libs/bench.py'))))
        else:
            if not os.path.exists(kwargs['data_path']):
                os.mkdir(kwargs['data_path'])
            kwargs[db] = utils.Get(lambda db=db: connect_database('sqlite+%s:///%s/%s.db' % (
                db, kwargs['data_path'], db[:-2])))
            kwargs['is_%s_default' % db] = True

    # create folder for counter.dump
    if not os.path.exists(kwargs['data_path']):
        os.mkdir(kwargs['data_path'])

    # message queue, compatible with old version
    if kwargs.get('message_queue'):
        pass
    elif kwargs.get('amqp_url'):
        kwargs['message_queue'] = kwargs['amqp_url']
    elif os.environ.get('RABBITMQ_NAME'):
        kwargs['message_queue'] = ("amqp://guest:guest@%(RABBITMQ_PORT_5672_TCP_ADDR)s"
                                   ":%(RABBITMQ_PORT_5672_TCP_PORT)s/%%2F" % os.environ)
    elif kwargs.get('beanstalk'):
        kwargs['message_queue'] = "beanstalk://%s/" % kwargs['beanstalk']

    for name in ('newtask_queue', 'status_queue', 'scheduler2fetcher',
                 'fetcher2processor', 'processor2result'):
        if kwargs.get('message_queue'):
            kwargs[name] = utils.Get(lambda name=name: connect_message_queue(
                name, kwargs.get('message_queue'), kwargs['queue_maxsize']))
        else:
            kwargs[name] = connect_message_queue(name, kwargs.get('message_queue'),
                                                 kwargs['queue_maxsize'])

    # phantomjs-proxy
    if kwargs.get('phantomjs_proxy'):
        pass
    elif os.environ.get('PHANTOMJS_NAME'):
        kwargs['phantomjs_proxy'] = os.environ['PHANTOMJS_PORT_25555_TCP'][len('tcp://'):]

    # puppeteer-proxy
    if kwargs.get('puppeteer_proxy'):
        pass
    elif os.environ.get('PUPPETEER_NAME'):
        kwargs['puppeteer_proxy'] = os.environ['PUPPETEER_PORT_22222_TCP'][len('tcp://'):]

    ctx.obj = utils.ObjectDict(ctx.obj or {})
    ctx.obj['instances'] = []
    ctx.obj.update(kwargs)

    if ctx.invoked_subcommand is None and not ctx.obj.get('testing_mode'):
        ctx.invoke(all)
    return ctx
1258001
function install(destination, prg, callback) {
  prompt.start();

  prompt.message = ':'.white.bold.bgBlack;
  prompt.delimiter = ': '.white.bold.bgBlack;

  var schema = {
    properties: {
      appName: {
        description: 'Application name'.white.bold.bgBlack,
        pattern: /^[a-zA-Z0-9\s\-]+$/,
        message: 'Application name must be only letters, spaces, or dashes',
        default: path.basename(destination),
        required: true
      },
      appEmail: {
        description: 'Application email address'.white.bold.bgBlack,
        conform: validator.isEmail,
        message: 'Enter a valid email',
        required: true
      },
      adminName: {
        description: 'Administrator username'.white.bold.bgBlack,
        conform: validator.isAlphanumeric,
        default: 'admin',
        message: 'Enter a valid username e.g. admin',
        required: true
      },
      adminPass: {
        description: 'Administrator password (at least 6 characters)'.white.bold.bgBlack,
        hidden: true,
        conform: function (pass) {
          return validator.isLength(pass, 6);
        },
        message: 'Password must have at least 6 characters.',
        required: true
      },
      adminEmail: {
        description: 'Administrator email address'.white.bold.bgBlack,
        conform: validator.isEmail,
        message: 'Enter a valid email',
        required: true
      },
      database: {
        description: 'Database URI'.white.bold.bgBlack,
        conform: function(uri) {
          return validator.isURL(uri, {
            protocols: ['mongodb'],
            require_protocol: true,
            allow_underscores: true
          });
        },
        default: 'mongodb://localhost/' + path.basename(destination),
        message: 'Enter a valid URI for your database e.g. mongodb://localhost/chokoapp',
        required: true
      }

    }
  };

  prompt.get(schema, function (error, result) {

    if (error) {
      return console.log('\nInstall aborted, no changes were made.');
    }

    doInstall({
      application: {
        name: result.appName,
        email: result.appEmail
      },
      database: result.database,
      sessionSecret: crypto.randomBytes(32).toString('base64')
    }, destination);

    var app = new Application(destination);
    app.start(prg.port, function(error, app) {
      if (error) {
        throw error;
      }

      createAdminUser(app, result, function(error, newAccount, errors) {
        // @todo: handle errors.
        util.log('Navigate to http://localhost:' + prg.port + ' to start building your new application.');
      });
    });
  });

}
497309
def _bse_cli_lookup_by_role(args):
    ''''''
    return api.lookup_basis_by_role(args.basis, args.role, args.data_dir)
62712
function parse_wb_bin(data, opts) {
	var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, xmlns: "" };
	var pass = false, z;

	if(!opts) opts = {};
	opts.biff = 12;

	var Names = [];
	var supbooks = ([]);
	supbooks.SheetNames = [];

	recordhopper(data, function hopper_wb(val, R_n, RT) {
		switch(RT) {
			case 0x009C: /* 'BrtBundleSh' */
				supbooks.SheetNames.push(val.name);
				wb.Sheets.push(val); break;

			case 0x0099: /* 'BrtWbProp' */
				wb.WBProps = val; break;

			case 0x0027: /* 'BrtName' */
				val.Ref = stringify_formula(val.Ptg, null, null, supbooks, opts);
				delete val.Ptg;
				Names.push(val);
				break;
			case 0x040C: /* 'BrtNameExt' */ break;

			case 0x0165: /* 'BrtSupSelf' */
			case 0x0166: /* 'BrtSupSame' */
			case 0x0163: /* 'BrtSupBookSrc' */
			case 0x029B: /* 'BrtSupAddin' */
			case 0x016A: /* 'BrtExternSheet' */
			case 0x0169: /* 'BrtPlaceholderName' */
				break;

			/* case 'BrtModelTimeGroupingCalcCol' */
			/* case 'BrtRevisionPtr' */
			/* case 'BrtUid' */
			case 0x0817: /* 'BrtAbsPath15' */
			case 0x0216: /* 'BrtBookProtection' */
			case 0x02A5: /* 'BrtBookProtectionIso' */
			case 0x009E: /* 'BrtBookView' */
			case 0x009D: /* 'BrtCalcProp' */
			case 0x0262: /* 'BrtCrashRecErr' */
			case 0x0802: /* 'BrtDecoupledPivotCacheID' */
			case 0x009B: /* 'BrtFileRecover' */
			case 0x0224: /* 'BrtFileSharing' */
			case 0x02A4: /* 'BrtFileSharingIso' */
			case 0x0080: /* 'BrtFileVersion' */
			case 0x0299: /* 'BrtFnGroup' */
			case 0x0850: /* 'BrtModelRelationship' */
			case 0x084D: /* 'BrtModelTable' */
			case 0x0225: /* 'BrtOleSize' */
			case 0x0805: /* 'BrtPivotTableRef' */
			case 0x0254: /* 'BrtSmartTagType' */
			case 0x081C: /* 'BrtTableSlicerCacheID' */
			case 0x081B: /* 'BrtTableSlicerCacheIDs' */
			case 0x0822: /* 'BrtTimelineCachePivotCacheID' */
			case 0x018D: /* 'BrtUserBookView' */
			case 0x009A: /* 'BrtWbFactoid' */
			case 0x045D: /* 'BrtWbProp14' */
			case 0x0229: /* 'BrtWebOpt' */
			case 0x082B: /* 'BrtWorkBookPr15' */
				break;

			case 0x0023: /* 'BrtFRTBegin' */
				pass = true; break;
			case 0x0024: /* 'BrtFRTEnd' */
				pass = false; break;
			case 0x0025: /* 'BrtACBegin' */ break;
			case 0x0026: /* 'BrtACEnd' */ break;

			case 0x0010: /* 'BrtFRTArchID$' */ break;

			default:
				if((R_n||"").indexOf("Begin") > 0){/* empty */}
				else if((R_n||"").indexOf("End") > 0){/* empty */}
				else if(!pass || opts.WTF) throw new Error("Unexpected record " + RT + " " + R_n);
		}
	}, opts);

	parse_wb_defaults(wb);

	// $FlowIgnore
	wb.Names = Names;

	return wb;
}
216999
function services(srv, callback) {

  // fallback - if only callback is given
  if (util.isFunction(srv) && !callback) {
    callback = srv;
    srv = '';
  }

  return new Promise((resolve) => {
    process.nextTick(() => {
      if (srv) {
        srv = srv.trim().toLowerCase().replace(/,+/g, ' ').replace(/  +/g, ' ').replace(/ +/g, '|');
        let srvs = srv.split('|');
        let result = [];
        let dataSrv = [];
        let allSrv = [];

        if (_linux || _freebsd || _openbsd || _darwin) {
          if ((_linux || _freebsd || _openbsd) && srv === '*') {
            srv = '';
            let tmpsrv = execSync('service --status-all 2> /dev/null').toString().split('\n');
            for (const s of tmpsrv) {
              const parts = s.split(']');
              if (parts.length === 2) {
                srv += (srv !== '' ? '|' : '') + parts[1].trim();
                allSrv.push({ name: parts[1].trim(), running: parts[0].indexOf('+') > 0 });
              }
            }
            srvs = srv.split('|');
          }
          let comm = (_darwin) ? 'ps -caxo pcpu,pmem,pid,command' : 'ps -axo pcpu,pmem,pid,command';
          if (srv !== '' && srvs.length > 0) {
            exec(comm + ' | grep -v grep | grep -iE "' + srv + '"', { maxBuffer: 1024 * 2000 }, function (error, stdout) {
              if (!error) {
                let lines = stdout.toString().replace(/ +/g, ' ').replace(/,+/g, '.').split('\n');
                srvs.forEach(function (srv) {
                  let ps;
                  if (_darwin) {
                    ps = lines.filter(function (e) {
                      return (e.toLowerCase().indexOf(srv) !== -1);
                    });

                  } else {
                    ps = lines.filter(function (e) {
                      return (e.toLowerCase().indexOf(' ' + srv + ':') !== -1) || (e.toLowerCase().indexOf('/' + srv) !== -1);
                    });
                  }
                  let singleSrv = allSrv.filter(item => { return item.name === srv; });
                  const pids = [];
                  for (const p of ps) {
                    pids.push(p.trim().split(' ')[2]);
                  }
                  result.push({
                    name: srv,
                    running: (allSrv.length && singleSrv.length ? singleSrv[0].running : ps.length > 0),
                    startmode: '',
                    pids: pids,
                    pcpu: parseFloat((ps.reduce(function (pv, cv) {
                      return pv + parseFloat(cv.trim().split(' ')[0]);
                    }, 0)).toFixed(2)),
                    pmem: parseFloat((ps.reduce(function (pv, cv) {
                      return pv + parseFloat(cv.trim().split(' ')[1]);
                    }, 0)).toFixed(2))
                  });
                });
                if (_linux) {
                  // calc process_cpu - ps is not accurate in linux!
                  let cmd = 'cat /proc/stat | grep "cpu "';
                  for (let i in result) {
                    for (let j in result[i].pids) {
                      cmd += (';cat /proc/' + result[i].pids[j] + '/stat');
                    }
                  }
                  exec(cmd, { maxBuffer: 1024 * 2000 }, function (error, stdout) {
                    let curr_processes = stdout.toString().split('\n');

                    // first line (all - /proc/stat)
                    let all = parseProcStat(curr_processes.shift());

                    // process
                    let list_new = {};
                    let resultProcess = {};
                    for (let i = 0; i < curr_processes.length; i++) {
                      resultProcess = calcProcStatLinux(curr_processes[i], all, _services_cpu);

                      if (resultProcess.pid) {
                        let listPos = -1;
                        for (let i in result) {
                          for (let j in result[i].pids) {
                            if (parseInt(result[i].pids[j]) === parseInt(resultProcess.pid)) {
                              listPos = i;
                            }
                          }
                        }
                        if (listPos >= 0) {
                          result[listPos].pcpu += resultProcess.pcpuu + resultProcess.pcpus;
                        }

                        // save new values
                        list_new[resultProcess.pid] = {
                          pcpuu: resultProcess.pcpuu,
                          pcpus: resultProcess.pcpus,
                          utime: resultProcess.utime,
                          stime: resultProcess.stime,
                          cutime: resultProcess.cutime,
                          cstime: resultProcess.cstime
                        };
                      }
                    }

                    // store old values
                    _services_cpu.all = all;
                    _services_cpu.list = list_new;
                    _services_cpu.ms = Date.now() - _services_cpu.ms;
                    _services_cpu.result = result;
                    if (callback) { callback(result); }
                    resolve(result);
                  });
                } else {
                  if (callback) { callback(result); }
                  resolve(result);
                }
              } else {
                exec('ps -o comm | grep -v grep | egrep "' + srv + '"', { maxBuffer: 1024 * 2000 }, function (error, stdout) {
                  if (!error) {
                    let lines = stdout.toString().replace(/ +/g, ' ').replace(/,+/g, '.').split('\n');
                    srvs.forEach(function (srv) {
                      let ps = lines.filter(function (e) {
                        return e.indexOf(srv) !== -1;
                      });
                      result.push({
                        name: srv,
                        running: ps.length > 0,
                        startmode: '',
                        pcpu: 0,
                        pmem: 0
                      });
                    });
                    if (callback) { callback(result); }
                    resolve(result);
                  } else {
                    srvs.forEach(function (srv) {
                      result.push({
                        name: srv,
                        running: false,
                        startmode: '',
                        pcpu: 0,
                        pmem: 0
                      });
                    });
                    if (callback) { callback(result); }
                    resolve(result);
                  }
                });
              }
            });
          } else {
            if (callback) { callback(result); }
            resolve(result);
          }
        }
        if (_windows) {
          try {
            util.wmic('service get /value').then((stdout, error) => {
              if (!error) {
                let serviceSections = stdout.split(/\n\s*\n/);
                for (let i = 0; i < serviceSections.length; i++) {
                  if (serviceSections[i].trim() !== '') {
                    let lines = serviceSections[i].trim().split('\r\n');
                    let srvName = util.getValue(lines, 'Name', '=', true).toLowerCase();
                    let started = util.getValue(lines, 'Started', '=', true);
                    let startMode = util.getValue(lines, 'StartMode', '=', true);
                    if (srv === '*' || srvs.indexOf(srvName) >= 0) {
                      result.push({
                        name: srvName,
                        running: (started === 'TRUE'),
                        startmode: startMode,
                        pcpu: 0,
                        pmem: 0
                      });
                      dataSrv.push(srvName);
                    }
                  }
                }
                if (srv !== '*') {
                  let srvsMissing = srvs.filter(function (e) {
                    return dataSrv.indexOf(e) === -1;
                  });
                  srvsMissing.forEach(function (srvName) {
                    result.push({
                      name: srvName,
                      running: false,
                      startmode: '',
                      pcpu: 0,
                      pmem: 0
                    });
                  });
                }
                if (callback) { callback(result); }
                resolve(result);
              } else {
                srvs.forEach(function (srvName) {
                  result.push({
                    name: srvName,
                    running: false,
                    startmode: '',
                    pcpu: 0,
                    pmem: 0
                  });
                });
                if (callback) { callback(result); }
                resolve(result);
              }
            });
          } catch (e) {
            if (callback) { callback(result); }
            resolve(result);
          }
        }
      } else {
        if (callback) { callback({}); }
        resolve({});
      }
    });
  });
}
544667
def sampe(args, opts):
    
    dbfile, read1file, read2file = args
    dbfile = check_index(dbfile)
    sai1file = check_aln(dbfile, read1file, cpus=opts.cpus)
    sai2file = check_aln(dbfile, read2file, cpus=opts.cpus)

    samfile, _, unmapped = get_samfile(read1file, dbfile,
                                       bam=opts.bam, unmapped=opts.unmapped)
    if not need_update((dbfile, sai1file, sai2file), samfile):
        logging.error("`{0}` exists. `bwa samse` already run.".format(samfile))
        return "", samfile

    cmd = "bwa sampe " + " ".join((dbfile, sai1file, sai2file,
                                   read1file, read2file))
    cmd += " " + opts.extra
    if opts.cutoff:
        cmd += " -a {0}".format(opts.cutoff)
    if opts.uniq:
        cmd += " -n 1"

    return cmd, samfile
1367895
def bes(args):
    
    from jcvi.apps.align import run_blat

    p = OptionParser(bes.__doc__)
    p.set_cpus()
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    bacfasta, clonename = args

    entrez([clonename, "--database=nucgss", "--skipcheck"])
    besfasta = clonename + ".fasta"
    blatfile = clonename + ".bes.blat"
    run_blat(infile=besfasta, outfile=blatfile, db=bacfasta, \
             pctid=95, hitlen=100, cpus=opts.cpus)

    aid, asize = next(Fasta(bacfasta).itersizes())

    width = 50
    msg = "=" * width
    msg += "  " + aid
    print(msg, file=sys.stderr)

    ratio = width * 1. / asize
    _ = lambda x: int(round(x * ratio, 0))
    blasts = [BlastLine(x) for x in open(blatfile)]
    for b in blasts:
        if b.orientation == '+':
            msg = " " * _(b.sstart) + "->"
        else:
            msg = " " * (_(b.sstop) - 2) + "<-"
        msg += " " * (width - len(msg) + 2)
        msg += b.query
        if b.orientation == '+':
            msg += " (hang={0})".format(b.sstart - 1)
        else:
            msg += " (hang={0})".format(asize - b.sstop)

        print(msg, file=sys.stderr)
602469
function bin (argv) {
  program.version(pkg.version)
  .usage('[options] <sourceURI> <destURI>')
  .parse(argv)

  var sourceURI = program.args[0]
  var destURI = program.args[1]

  if (!sourceURI || !destURI) {
    program.help()
  }

  shell.mv(sourceURI, destURI, function (err, res, uri) {
    if (!err) {
      debug(res)
    } else {
      console.error(err)
    }
  })
}
907690
def des(clas,keyblob,valblob):
    ""
    raise NotImplementedError("don't use tuples, it breaks __eq__. this function probably isn't used in real life")
    raw_keyvals=msgpack.loads(keyblob)
    (namespace,version),keyvals=raw_keyvals[:2],raw_keyvals[2:]
    if namespace!=clas.NAMESPACE or version!=clas.VERSION:
      raise TypeError('des_mismatch got %s want %s'%((namespace,version),(clas.NAMESPACE,clas.VERSION)))
    vals=tuple(msgpack.loads(valblob))
    clas.type_check(zip(*clas.KEY)[1],keyvals,'KEY')
    clas.type_check(zip(*clas.VALUE)[1],vals,'VALUE')
    return clas(tuple(keyvals),vals)
24800
function dumpTree(dirname, shouldPrune, cb) {
    var args = ['-type', 'f'];
    if(shouldPrune) {
        args = EXCLUDED_ARGS.concat(args);
    }

    find(dirname, args, cb);
}
965960
def main(args=sys.argv[1:]):
    
    parser = argparse.ArgumentParser(description="""Aggregate results of
            nestly runs""")
    subparsers = parser.add_subparsers()
    delim_parser = subparsers.add_parser('delim', help="""Combine control files
            with delimited files.""")
    delim_parser.set_defaults(func=delim)
    key_group = delim_parser.add_mutually_exclusive_group()
    key_group.add_argument('-k', '--keys', help="""Comma separated list of
            keys from the JSON file to include [default: all keys]""",
            type=comma_separated_values)
    key_group.add_argument('-x', '--exclude-keys', help="""Comma separated
            list of keys from the JSON file not to include [default:
            %(default)s]""", type=comma_separated_values)
    delim_parser.add_argument('-m', '--missing-action', choices=('fail',
        'warn'), help="""Action to take when a file is missing [default:
        %(default)s]""", default='fail')
    delim_parser.add_argument('file_template', help="""Template for the
            delimited file to read in each directory [e.g. '{run_id}.csv']""")
    delim_parser.add_argument('control_files', metavar="control.json",
            help="""Control files""", nargs="*")
    delim_parser.add_argument('-d', '--directory', help="""Run on all control
            files under %(metavar)s. May be used in place of specifying control
            files.""", metavar='DIR')
    delim_parser.add_argument('-s', '--separator', default=DEFAULT_SEP,
            help="""Separator [default: %(default)s]""")
    delim_parser.add_argument('-t', '--tab', action='store_const',
            dest='separator', const='\t', help="""Files are tab-separated""")
    delim_parser.add_argument('-o', '--output', default=sys.stdout,
        type=argparse.FileType('w'), help="""Output file [default: stdout]""")

    arguments = parser.parse_args()

    arguments.func(arguments)
231775
async function runProgram() {
    const args = minimist(process.argv.slice(2));

    if (args.prefix) {
        intercept(function(txt) {
            return `[${pkg.name}]\n${txt}`;
        });
    }

    let latest = await latestVersion(pkg.name, { version: `>${pkg.version}` })
                        .catch(error => pkg.version);
    if (semver.gt(latest, pkg.version)) {
        process.stderr.write(chalk.default.white(`\n     Update available `));
        process.stderr.write(chalk.default.grey(`${pkg.version}`));
        process.stderr.write(chalk.default.white(` -> `));
        process.stderr.write(chalk.default.greenBright(`${latest}\n`));
        process.stderr.write(chalk.default.white(`     Run `));
        process.stderr.write(chalk.default.blueBright(`npm i -g ${pkg.name} `));
        process.stderr.write(chalk.default.white(`to update.\n`));
    }

    if (args.version || args.v) {
        process.stdout.write(pkg.version);
        return 0;
    }

    if (args.h || args.help) {
        help(process.stdout);
        return 0;
    }

    if (args.f || args.folder) {
        let inputDir = args.f.trim();
        let outputDir = (args.o || args.out_folder) ? args.o.trim() : "./";
        if (outputDir.substr(0, 2) === "./") {
            outputDir = path.resolve(process.cwd(), outputDir.substr(2))
        }
        const len = await processFiles(inputDir, outputDir);
        process.stdout.write(chalk`{green Successfully wrote ${len} files}\n`);
        return len;
    }
    else {
        const fileContents = await getInput(args);
        if (fileContents) {
            const activities = await chatdown(fileContents, args);
            const writeConfirmation = await writeOut(activities, args);

            if (typeof writeConfirmation === 'string') {
                process.stdout.write(chalk`{green Successfully wrote file:} {blue ${writeConfirmation}}\n`);
            }
            return 0;
        }
        else {
            help();
            return -1;
        }
    }
}