initialization and opening of a spreadsheet file
 values for packed: :zip
 optional cell_max (int) parameter for early aborting attempts to parse
 enormous documents.
960244
def method_missing(method, *args)
      if (label = workbook.defined_names[method.to_s])
        safe_send(sheet_for(label.sheet).cells[label.key], :value)
      else
        # call super for methods like #a1
        super
      end
    end
685780
def import_from_xls(
    filename_or_fobj,
    sheet_name=None,
    sheet_index=0,
    start_row=None,
    start_column=None,
    end_row=None,
    end_column=None,
    *args,
    **kwargs
):
    """"""

    source = Source.from_file(filename_or_fobj, mode="rb", plugin_name="xls")
    source.fobj.close()
    book = xlrd.open_workbook(
        source.uri, formatting_info=True, logfile=open(os.devnull, mode="w")
    )

    if sheet_name is not None:
        sheet = book.sheet_by_name(sheet_name)
    else:
        sheet = book.sheet_by_index(sheet_index)
    # TODO: may re-use Excel data types

    # Get header and rows
    # xlrd library reads rows and columns starting from 0 and ending on
    # sheet.nrows/ncols - 1. rows accepts the same pattern
    # The xlrd library reads rows and columns starting from 0 and ending on
    # sheet.nrows/ncols - 1. rows also uses 0-based indexes, so no
    # transformation is needed
    min_row, min_column = get_table_start(sheet)
    max_row, max_column = sheet.nrows - 1, sheet.ncols - 1
    # TODO: consider adding a parameter `ignore_padding=True` and when it's
    # True, consider `start_row` starting from `min_row` and `start_column`
    # starting from `min_col`.
    start_row = max(start_row if start_row is not None else min_row, min_row)
    end_row = min(end_row if end_row is not None else max_row, max_row)
    start_column = max(
        start_column if start_column is not None else min_column, min_column
    )
    end_column = min(end_column if end_column is not None else max_column, max_column)

    table_rows = [
        [
            cell_value(sheet, row_index, column_index)
            for column_index in range(start_column, end_column + 1)
        ]
        for row_index in range(start_row, end_row + 1)
    ]

    meta = {"imported_from": "xls", "source": source, "name": sheet.name}
    return create_table(table_rows, meta=meta, *args, **kwargs)
435557
def fillNullValues(col, rows):
    ''
    lastval = None
    nullfunc = isNullFunc()
    n = 0
    rowsToFill = list(rows)
    for r in Progress(col.sheet.rows, 'filling'):  # loop over all rows
        try:
            val = col.getValue(r)
        except Exception as e:
            val = e

        if nullfunc(val) and r in rowsToFill:
            if lastval:
                col.setValue(r, lastval)
                n += 1
        else:
            lastval = val

    col.recalc()
    status("filled %d values" % n)
708516
function parse_XLSBCell(data)/*:any*/ {
	var col = data.read_shift(4);
	var iStyleRef = data.read_shift(2);
	iStyleRef += data.read_shift(1) <<16;
	data.l++; //var fPhShow = data.read_shift(1);
	return { c:col, iStyleRef: iStyleRef };
}
258446
public static int findMaxCol(Sheet sheet) {
        int maxCol = 0;
        for (int i = 0, ii = sheet.getLastRowNum(); i <= ii; ++i) {
            val row = sheet.getRow(i);
            if (row == null) continue;

            for (int j = row.getLastCellNum() - 1; j > maxCol; --j) {
                val cell = row.getCell(j);
                if (cell == null) continue;

                val value = getCellStringValue(cell);
                if (StringUtils.isNotEmpty(value)) {
                    maxCol = j;
                    break;
                }
            }
        }

        return maxCol;
    }
793828
function write_ws_biff8(idx, opts, wb) {
	var ba = buf_array();
	var s = wb.SheetNames[idx], ws = wb.Sheets[s] || {};
	var _WB = ((wb||{}).Workbook||{});
	var _sheet = ((_WB.Sheets||[])[idx]||{});
	var dense = Array.isArray(ws);
	var b8 = opts.biff == 8;
	var ref, rr = "", cols = [];
	var range = safe_decode_range(ws['!ref'] || "A1");
	var MAX_ROWS = b8 ? 65536 : 16384;
	if(range.e.c > 0xFF || range.e.r >= MAX_ROWS) {
		if(opts.WTF) throw new Error("Range " + (ws['!ref'] || "A1") + " exceeds format limit A1:IV16384");
		range.e.c = Math.min(range.e.c, 0xFF);
		range.e.r = Math.min(range.e.c, MAX_ROWS-1);
	}

	write_biff_rec(ba, 0x0809, write_BOF(wb, 0x10, opts));
	/* ... */
	write_biff_rec(ba, "CalcMode", writeuint16(1));
	write_biff_rec(ba, "CalcCount", writeuint16(100));
	write_biff_rec(ba, "CalcRefMode", writebool(true));
	write_biff_rec(ba, "CalcIter", writebool(false));
	write_biff_rec(ba, "CalcDelta", write_Xnum(0.001));
	write_biff_rec(ba, "CalcSaveRecalc", writebool(true));
	write_biff_rec(ba, "PrintRowCol", writebool(false));
	write_biff_rec(ba, "PrintGrid", writebool(false));
	write_biff_rec(ba, "GridSet", writeuint16(1));
	write_biff_rec(ba, "Guts", write_Guts([0,0]));
	/* ... */
	write_biff_rec(ba, "HCenter", writebool(false));
	write_biff_rec(ba, "VCenter", writebool(false));
	/* ... */
	write_biff_rec(ba, 0x200, write_Dimensions(range, opts));
	/* ... */

	if(b8) ws['!links'] = [];
	for(var R = range.s.r; R <= range.e.r; ++R) {
		rr = encode_row(R);
		for(var C = range.s.c; C <= range.e.c; ++C) {
			if(R === range.s.r) cols[C] = encode_col(C);
			ref = cols[C] + rr;
			var cell = dense ? (ws[R]||[])[C] : ws[ref];
			if(!cell) continue;
			/* write cell */
			write_ws_biff8_cell(ba, cell, R, C, opts);
			if(b8 && cell.l) ws['!links'].push([ref, cell.l]);
		}
	}
	var cname = _sheet.CodeName || _sheet.name || s;
	/* ... */
	if(b8 && _WB.Views) write_biff_rec(ba, "Window2", write_Window2(_WB.Views[0]));
	/* ... */
	if(b8 && (ws['!merges']||[]).length) write_biff_rec(ba, "MergeCells", write_MergeCells(ws['!merges']));
	/* ... */
	if(b8) write_ws_biff8_hlinks(ba, ws);
	/* ... */
	write_biff_rec(ba, "CodeName", write_XLUnicodeString(cname, opts));
	/* ... */
	if(b8) write_FEAT(ba, ws);
	/* ... */
	write_biff_rec(ba, "EOF");
	return ba.end();
}
1122218
def get_range_data(row_start, col_start, row_end, col_end) # :nodoc:
      # TODO. Check for worksheet limits.

      # Iterate through the table data.
      data = []
      (row_start .. row_end).each do |row_num|
        # Store nil if row doesn't exist.
        if !@cell_data_table[row_num]
          data << nil
          next
        end

        (col_start .. col_end).each do |col_num|
          if cell = @cell_data_table[row_num][col_num]
            data << cell.data
          else
            # Store nil if col doesn't exist.
            data << nil
          end
        end
      end

      return data
    end
564058
def process_workbook_options(*params)
      case params.size
      when 0
        [{}, {}]
      when 1 # one hash
        options_keys = [:tempdir, :date_1904, :optimization, :excel2003_style, :strings_to_urls]

        hash = params.first
        options = hash.reject{|k,v| !options_keys.include?(k)}

        default_format_properties =
          hash[:default_format_properties] ||
          hash.reject{|k,v| options_keys.include?(k)}

        [options, default_format_properties.dup]
      when 2 # array which includes options and default_format_properties
        options, default_format_properties = params
        default_format_properties ||= {}

        [options.dup, default_format_properties.dup]
      end
    end
5531
function validateMaxFileSize(pluginDir) {
  return (maxBytes, filePath) => {
    try {
      const stat = fs.statSync(path.join(pluginDir, filePath));
      return stat.size <= maxBytes;
    } catch (e) {
      return false;
    }
  };
}
1327321
def _open(self):
        
        self._sample = None

        formatting_parameters0 = {'encoding':        'auto',
                                  'delimiter':       'auto',
                                  'line_terminator': 'auto',
                                  'escape_char':     '\\',
                                  'quote_char':      '"'}
        formatting_parameters1 = self._helper.pass1(self._filename, formatting_parameters0)
        self._formatting_parameters = formatting_parameters1

        # Detect encoding.
        if formatting_parameters1['encoding'] == 'auto':
            self._get_sample('rb', None)
            self._detect_encoding()

        # Detect delimiter.
        if formatting_parameters1['delimiter'] == 'auto':
            self._get_sample('rt', formatting_parameters1['encoding'])
            self._detect_delimiter()

        # Detect line terminators.
        if formatting_parameters1['line_terminator'] == 'auto':
            if not self._sample:
                self._get_sample('rt', formatting_parameters1['encoding'])
            self._detect_line_ending()

        self._formatting_parameters = self._helper.pass2(self._filename,
                                                         self._formatting_parameters,
                                                         formatting_parameters1)

        self._open_file('rt', formatting_parameters1['encoding'])
        self._csv_reader = csv.reader(self._file,
                                      delimiter=self._formatting_parameters['delimiter'],
                                      escapechar=self._formatting_parameters['escape_char'],
                                      lineterminator=self._formatting_parameters['line_terminator'],
                                      quotechar=self._formatting_parameters['quote_char'])  # Ignored

        self._sample = None
548150
def excel():
    
    global files, cwd, settings
    _d = {}
    # Turn off verbose. We don't want to clutter the console with extra reading/writing output statements
    settings["verbose"] = False
    # Find excel files
    print("Found " + str(len(files[".xls"])) + " Excel files")
    logger_start.info("found excel files: {}".format(len(files[".xls"])))
    # Start the clock
    start = clock()
    # Loop for each excel file
    for file in files[".xls"]:
        # Convert excel file to LiPD
        dsn = excel_main(file)
        try:
            # Read the new LiPD file back in, to get fixes, inferred calculations, updates, etc.
            _d[dsn] = readLipd(os.path.join(file["dir"], dsn + ".lpd"))
            # Write the modified LiPD file back out again.
            writeLipd(_d[dsn], cwd)
        except Exception as e:
            logger_start.error("excel: Unable to read new LiPD file, {}".format(e))
            print("Error: Unable to read new LiPD file: {}, {}".format(dsn, e))
    # Time!
    end = clock()
    logger_benchmark.info(log_benchmark("excel", start, end))
    # Start printing stuff again.
    settings["verbose"] = True
    return _d
314623
def prep_fastq_inputs(in_files, data):
    
    if len(in_files) == 1 and _is_bam_input(in_files):
        out = _bgzip_from_bam(in_files[0], data["dirs"], data)
    elif len(in_files) == 1 and _is_cram_input(in_files):
        out = _bgzip_from_cram(in_files[0], data["dirs"], data)
    elif len(in_files) in [1, 2] and _ready_gzip_fastq(in_files, data):
        out = _symlink_in_files(in_files, data)
    else:
        if len(in_files) > 2:
            fpairs = fastq.combine_pairs(in_files)
            pair_types = set([len(xs) for xs in fpairs])
            assert len(pair_types) == 1
            fpairs.sort(key=lambda x: os.path.basename(x[0]))
            organized = [[xs[0] for xs in fpairs]]
            if len(fpairs[0]) > 1:
                organized.append([xs[1] for xs in fpairs])
            in_files = organized
        parallel = {"type": "local", "num_jobs": len(in_files),
                    "cores_per_job": max(1, data["config"]["algorithm"]["num_cores"] // len(in_files))}
        inputs = [{"in_file": x, "read_num": i, "dirs": data["dirs"], "config": data["config"],
                   "is_cwl": "cwl_keys" in data,
                   "rgnames": data["rgnames"]}
                  for i, x in enumerate(in_files) if x]
        out = run_multicore(_bgzip_from_fastq_parallel, [[d] for d in inputs], data["config"], parallel)
    return out
875469
def clr(args):
    
    p = OptionParser(clr.__doc__)
    opts, args = p.parse_args(args)

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

    blastfile = args[0]
    fastafiles = args[1:]

    sizes = {}
    for fa in fastafiles:
        f = Fasta(fa)
        sizes.update(f.itersizes())

    b = Blast(blastfile)
    for query, hits in b.iter_hits():

        qsize = sizes[query]
        vectors = list((x.qstart, x.qstop) for x in hits)
        vmin, vmax = range_minmax(vectors)

        left_size = vmin - 1
        right_size = qsize - vmax

        if left_size > right_size:
            clr_start, clr_end = 0, vmin
        else:
            clr_start, clr_end = vmax, qsize

        print("\t".join(str(x) for x in (query, clr_start, clr_end)))
        del sizes[query]

    for q, size in sorted(sizes.items()):
        print("\t".join(str(x) for x in (q, 0, size)))
171712
def set_file_limits(n):
    '''
    

    '''

    try:
        resource.setrlimit(resource.RLIMIT_NOFILE, (n, n))
        return True
    except ValueError:
        return False
1290257
def checkMax(row, col_name, arg, *args):
    
    cell_value = row[col_name]
    if not cell_value:
        return None
    elif isinstance(cell_value, float):
        if np.isnan(cell_value):
            return None
    try:
        arg_val = float(arg)
    except ValueError:
        if arg in row.index:
            arg_val = row[arg]
        else:
            return None
    if cb.is_null(arg_val):
        return None
    #arg = float(arg)
    try:
        if float(cell_value) <= float(arg_val):
            return None
        else:
            return "{} ({}) must be <= {} ({})".format(str(cell_value), col_name, str(arg_val), str(arg))
    # this happens when the value isn't a float (an error which will be caught elsewhere)
    except ValueError:
        return None
1016329
def set(row, col, value, sheet = nil) #:nodoc:
      key = normalize(row, col)
      cell_type = cell_type_by_value(value)
      sheet_for(sheet).cells[key] = Cell.new(value, cell_type, nil, cell_type, value, nil, nil, nil, Coordinate.new(row, col))
    end
157781
def readExcel(usr_path=""):
    
    global cwd, files
    start = clock()
    files[".xls"] = []
    __read(usr_path, ".xls")
    end = clock()
    logger_benchmark.info(log_benchmark("readExcel", start, end))
    return cwd