TODO: Allow plugin to support rendering pdf, xls or other binary types
512729
public void apply(ActionContext context) {
        Boolean hasTemplate = context.hasTemplate();
        if (null != hasTemplate && hasTemplate) {
            RenderTemplate.get(context.successStatus()).apply(context);
            return;
        }
        H.Format fmt = context.accept();
        if (fmt == UNKNOWN) {
            H.Request req = context.req();
            if (req.userAgent().isIE9Down()) {
                fmt = HTML;
            } else {
                H.Method method = req.method();
                String methodInfo = S.concat(method.name(), " method to ");
                String acceptHeader = req.header(H.Header.Names.ACCEPT);
                throw E.unsupport(S.concat(
                        "Unknown accept content type(",
                        acceptHeader,
                        "): ",
                        methodInfo,
                        req.url()));
            }
        }
        Result result = null;
        if (JSON == fmt) {
            List<String> varNames = context.__appRenderArgNames();
            Map<String, Object> map = new HashMap<>(context.renderArgs());
            if (null != varNames && !varNames.isEmpty()) {
                for (String name : varNames) {
                    map.put(name, context.renderArg(name));
                }
            }
            result = new RenderJSON(map);
        } else if (XML == fmt) {
            List<String> varNames = context.__appRenderArgNames();
            Map<String, Object> map = new HashMap<>();
            if (null != varNames && !varNames.isEmpty()) {
                for (String name : varNames) {
                    map.put(name, context.renderArg(name));
                }
            }
            result = new FilteredRenderXML(map, null, context);
        } else if (HTML == fmt || TXT == fmt || CSV == fmt) {
            if (!ignoreMissingTemplate) {
                throw E.unsupport("Template[%s] not found", context.templatePath());
            }
            context.nullValueResultIgnoreRenderArgs().apply(context.req(), context.prepareRespForResultEvaluation());
            return;
        } else if (PDF == fmt || XLS == fmt || XLSX == fmt || DOC == fmt || DOCX == fmt) {
            List<String> varNames = context.__appRenderArgNames();
            if (null != varNames && !varNames.isEmpty()) {
                Object firstVar = context.renderArg(varNames.get(0));
                String action = S.str(context.actionPath()).afterLast(".").toString();
                if (firstVar instanceof File) {
                    File file = (File) firstVar;
                    result = new RenderBinary(file, action);
                } else if (firstVar instanceof InputStream) {
                    InputStream is = (InputStream) firstVar;
                    result = new RenderBinary(is, action);
                } else if (firstVar instanceof ISObject) {
                    ISObject sobj = (ISObject) firstVar;
                    result = new RenderBinary(sobj.asInputStream(), action);
                }
                if (null == result) {
                    throw E.unsupport("Unknown render arg type [%s] for binary response", firstVar.getClass());
                }
            } else {
                throw E.unexpected("No render arg found for binary response");
            }
        }
        if (null != result) {
            ActResponse<?> resp = context.prepareRespForResultEvaluation();
            result.status(context.successStatus()).apply(context.req(), resp);
        } else {
            throw E.unexpected("Unknown accept content type: %s", fmt.contentType());
        }
    }
740499
private void addPdfTable(Table t) throws DocumentException {
        // before every table, we flush all lines
        flushLines();

    	PdfTable table = new PdfTable(t, indentLeft(), indentRight(), indentTop() - currentHeight);
        RenderingContext ctx = new RenderingContext();
        ctx.pagetop = indentTop();
        ctx.oldHeight = currentHeight;
        ctx.cellGraphics = new PdfContentByte(writer);
        ctx.rowspanMap = new HashMap();
        ctx.table = table;

		// initialization of parameters
		PdfCell cell;

		// drawing the table
		ArrayList headercells = table.getHeaderCells();
        ArrayList cells = table.getCells();
        ArrayList rows = extractRows(cells, ctx);
        boolean isContinue = false;
		while (!cells.isEmpty()) {
			// initialization of some extra parameters;
			ctx.lostTableBottom = 0;

			// loop over the cells
			boolean cellsShown = false;

            // draw the cells (line by line)
            Iterator iterator = rows.iterator();

            boolean atLeastOneFits = false;
            while (iterator.hasNext()) {
                ArrayList row = (ArrayList) iterator.next();
                analyzeRow(rows, ctx);
                renderCells(ctx, row, table.hasToFitPageCells() & atLeastOneFits);

                if (!mayBeRemoved(row)) {
                    break;
                }
                consumeRowspan(row, ctx);
                iterator.remove();
                atLeastOneFits = true;
            }

//          compose cells array list for subsequent code
            cells.clear();
            Set opt = new HashSet();
            iterator = rows.iterator();
            while (iterator.hasNext()) {
                ArrayList row = (ArrayList) iterator.next();

                Iterator cellIterator = row.iterator();
                while (cellIterator.hasNext()) {
                    cell = (PdfCell) cellIterator.next();

                    if (!opt.contains(cell)) {
                        cells.add(cell);
                        opt.add(cell);
                    }
                }
            }

			// we paint the graphics of the table after looping through all the cells
			Rectangle tablerec = new Rectangle(table);
			tablerec.setBorder(table.getBorder());
			tablerec.setBorderWidth(table.getBorderWidth());
			tablerec.setBorderColor(table.getBorderColor());
			tablerec.setBackgroundColor(table.getBackgroundColor());
			PdfContentByte under = writer.getDirectContentUnder();
			under.rectangle(tablerec.rectangle(top(), indentBottom()));
			under.add(ctx.cellGraphics);
			// bugfix by Gerald Fehringer: now again add the border for the table
			// since it might have been covered by cell backgrounds
			tablerec.setBackgroundColor(null);
			tablerec = tablerec.rectangle(top(), indentBottom());
			tablerec.setBorder(table.getBorder());
			under.rectangle(tablerec);
			// end bugfix

            ctx.cellGraphics = new PdfContentByte(null);
			// if the table continues on the next page

			if (!rows.isEmpty()) {
				isContinue = true;
				graphics.setLineWidth(table.getBorderWidth());
				if (cellsShown && (table.getBorder() & Rectangle.BOTTOM) == Rectangle.BOTTOM) {
					// Draw the bottom line

					// the color is set to the color of the element
					Color tColor = table.getBorderColor();
					if (tColor != null) {
						graphics.setColorStroke(tColor);
					}
					graphics.moveTo(table.getLeft(), Math.max(table.getBottom(), indentBottom()));
					graphics.lineTo(table.getRight(), Math.max(table.getBottom(), indentBottom()));
					graphics.stroke();
					if (tColor != null) {
						graphics.resetRGBColorStroke();
					}
				}

				// old page
				pageEmpty = false;
                float difference = ctx.lostTableBottom;

				// new page
				newPage();

				// G.F.: if something added in page event i.e. currentHeight > 0
				float heightCorrection = 0;
				boolean somethingAdded = false;
				if (currentHeight > 0) {
					heightCorrection = 6;
					currentHeight += heightCorrection;
					somethingAdded = true;
					newLine();
					flushLines();
					indentation.indentTop = currentHeight - leading;
					currentHeight = 0;
				}
				else {
                    flushLines();
				}

				// this part repeats the table headers (if any)
				int size = headercells.size();
				if (size > 0) {
					// this is the top of the headersection
					cell = (PdfCell) headercells.get(0);
					float oldTop = cell.getTop(0);
					// loop over all the cells of the table header
					for (int i = 0; i < size; i++) {
						cell = (PdfCell) headercells.get(i);
						// calculation of the new cellpositions
						cell.setTop(indentTop() - oldTop + cell.getTop(0));
						cell.setBottom(indentTop() - oldTop + cell.getBottom(0));
						ctx.pagetop = cell.getBottom();
						// we paint the borders of the cell
						ctx.cellGraphics.rectangle(cell.rectangle(indentTop(), indentBottom()));
						// we write the text of the cell
						ArrayList images = cell.getImages(indentTop(), indentBottom());
						for (Iterator im = images.iterator(); im.hasNext();) {
							cellsShown = true;
							Image image = (Image) im.next();
							graphics.addImage(image);
						}
						lines = cell.getLines(indentTop(), indentBottom());
						float cellTop = cell.getTop(indentTop());
						text.moveText(0, cellTop-heightCorrection);
						float cellDisplacement = flushLines() - cellTop+heightCorrection;
						text.moveText(0, cellDisplacement);
					}

					currentHeight = indentTop() - ctx.pagetop + table.cellspacing();
					text.moveText(0, ctx.pagetop - indentTop() - currentHeight);
				}
				else {
					if (somethingAdded) {
						ctx.pagetop = indentTop();
						text.moveText(0, -table.cellspacing());
					}
				}
				ctx.oldHeight = currentHeight - heightCorrection;

				// calculating the new positions of the table and the cells
				size = Math.min(cells.size(), table.columns());
				int i = 0;
				while (i < size) {
					cell = (PdfCell) cells.get(i);
					if (cell.getTop(-table.cellspacing()) > ctx.lostTableBottom) {
						float newBottom = ctx.pagetop - difference + cell.getBottom();
						float neededHeight = cell.remainingHeight();
						if (newBottom > ctx.pagetop - neededHeight) {
							difference += newBottom - (ctx.pagetop - neededHeight);
						}
					}
					i++;
				}
				size = cells.size();
				table.setTop(indentTop());
				table.setBottom(ctx.pagetop - difference + table.getBottom(table.cellspacing()));
				for (i = 0; i < size; i++) {
					cell = (PdfCell) cells.get(i);
					float newBottom = ctx.pagetop - difference + cell.getBottom();
					float newTop = ctx.pagetop - difference + cell.getTop(-table.cellspacing());
					if (newTop > indentTop() - currentHeight) {
						newTop = indentTop() - currentHeight;
					}

					cell.setTop(newTop );
					cell.setBottom(newBottom );
				}
			}
		}

        float tableHeight = table.getTop() - table.getBottom();
        // bugfix by Adauto Martins when have more than two tables and more than one page
        // If continuation of table in other page (bug report #1460051)
        if (isContinue) {
        	currentHeight = tableHeight;
        	text.moveText(0, -(tableHeight - (ctx.oldHeight * 2)));
        } else {
        	currentHeight = ctx.oldHeight + tableHeight;
        	text.moveText(0, -tableHeight);
        }
        // end bugfix
        pageEmpty = false;
    }
151442
function plugin(options){
  options = options || {};
  var keys = options.keys || [];

  return function(files, metalsmith, done){
    setImmediate(done);
    Object.keys(files).forEach(function(file){
      debug('checking file: %s', file);
      if (!isHtml(file)) return;
      var data = files[file];
      var dir = dirname(file);
      var html = basename(file, extname(file)) + '.html';
      if ('.' != dir) html = dir + '/' + html;

      debug('Encoding html entities in file: %s', file);

      var reg = /\`\`\`([\s\S]+?)\`\`\`/gi;
      var rep = function(match, group) {
        if (group) {
          return he.encode(group, {useNamedReferences: true});
        }
        else {
          return "";
        }
      };
      var encoded = data.contents.toString().replace(reg, rep);
      data.contents = new Buffer(encoded);

      keys.forEach(function(key) {
        data[key] = data[key].replace(reg, rep);
      });

      delete files[file];
      files[html] = data;
    });
  };
}
1167395
function encodeGlobal(output) {
    var book = output.getBook();
    var bookFS = book.getContentFS();
    var logger = output.getLogger();
    var outputFolder = output.getRoot();
    var plugins = output.getPlugins();
    var blocks = Plugins.listBlocks(plugins);

    var result = {
        log: logger,
        config: encodeConfig(output, book.getConfig()),
        summary: encodeSummary(output, book.getSummary()),

        /**
            Check if the book is a multilingual book

            @return {Boolean}
        */
        isMultilingual: function() {
            return book.isMultilingual();
        },

        /**
            Check if the book is a language book for a multilingual book

            @return {Boolean}
        */
        isLanguageBook: function() {
            return book.isLanguageBook();
        },

        /**
            Read a file from the book

            @param {String} fileName
            @return {Promise<Buffer>}
        */
        readFile: function(fileName) {
            return bookFS.read(fileName);
        },

        /**
            Read a file from the book as a string

            @param {String} fileName
            @return {Promise<String>}
        */
        readFileAsString: function(fileName) {
            return bookFS.readAsString(fileName);
        },

        /**
            Resolve a file from the book root

            @param {String} fileName
            @return {String}
        */
        resolve: function(fileName) {
            return path.resolve(book.getContentRoot(), fileName);
        },

        /**
            Resolve a page by it path

            @param {String} filePath
            @return {String}
        */
        getPageByPath: function(filePath) {
            var page = output.getPage(filePath);
            if (!page) return undefined;

            return encodePage(output, page);
        },

        /**
            Render a block of text (markdown/asciidoc)

            @param {String} type
            @param {String} text
            @return {Promise<String>}
        */
        renderBlock: function(type, text) {
            var parser = parsers.get(type);

            return parser.parsePage(text)
                .get('content');
        },

        /**
            Render an inline text (markdown/asciidoc)

            @param {String} type
            @param {String} text
            @return {Promise<String>}
        */
        renderInline: function(type, text) {
            var parser = parsers.get(type);

            return parser.parseInline(text)
                .get('content');
        },

        template: {
            /**
                Apply a templating block and returns its result

                @param {String} name
                @param {Object} blockData
                @return {Promise|Object}
            */
            applyBlock: function(name, blockData) {
                var block = blocks.get(name) || defaultBlocks.get(name);
                return Promise(block.applyBlock(blockData, result));
            }
        },

        output: {
            /**
                Name of the generator being used
                {String}
            */
            name: output.getGenerator(),

            /**
                Return absolute path to the root folder of output
                @return {String}
            */
            root: function() {
                return outputFolder;
            },

            /**
                Resolve a file from the output root

                @param {String} fileName
                @return {String}
            */
            resolve: function(fileName) {
                return path.resolve(outputFolder, fileName);
            },

            /**
                Convert a filepath into an url
                @return {String}
            */
            toURL: function(filePath) {
                return fileToURL(output, filePath);
            },

            /**
                Check that a file exists.

                @param {String} fileName
                @return {Promise}
            */
            hasFile: function(fileName, content) {
                return Promise()
                .then(function() {
                    var filePath = PathUtils.resolveInRoot(outputFolder, fileName);

                    return fs.exists(filePath);
                });
            },

            /**
                Write a file to the output folder,
                It creates the required folder

                @param {String} fileName
                @param {Buffer} content
                @return {Promise}
            */
            writeFile: function(fileName, content) {
                return Promise()
                .then(function() {
                    var filePath = PathUtils.resolveInRoot(outputFolder, fileName);

                    return fs.ensureFile(filePath)
                    .then(function() {
                        return fs.writeFile(filePath, content);
                    });
                });
            },

            /**
                Copy a file to the output folder
                It creates the required folder.

                @param {String} inputFile
                @param {String} outputFile
                @param {Buffer} content
                @return {Promise}
            */
            copyFile: function(inputFile, outputFile, content) {
                return Promise()
                .then(function() {
                    var outputFilePath = PathUtils.resolveInRoot(outputFolder, outputFile);

                    return fs.ensureFile(outputFilePath)
                    .then(function() {
                        return fs.copy(inputFile, outputFilePath);
                    });
                });
            }
        },

        gitbook: {
            version: gitbook.version
        }
    };

    // Deprecated properties

    deprecate.renamedMethod(output, 'this.isSubBook', result, 'isSubBook', 'isLanguageBook');
    deprecate.renamedMethod(output, 'this.contentLink', result, 'contentLink', 'output.toURL');

    deprecate.field(output, 'this.generator', result, 'generator',
        output.getGenerator(), '"this.generator" property is deprecated, use "this.output.name" instead');

    deprecate.field(output, 'this.navigation', result, 'navigation', function() {
        return encodeNavigation(output);
    }, '"navigation" property is deprecated');

    deprecate.field(output, 'this.book', result, 'book',
        result, '"book" property is deprecated, use "this" directly instead');

    deprecate.field(output, 'this.options', result, 'options',
        result.config.values, '"options" property is deprecated, use config.get(key) instead');

    return result;
}
1243985
def compile(options = {})

            load_all_objects unless loaded?

            #
            # A valid document must have at least one page.
            #
            append_page if pages.empty?

            #
            # Allocates object numbers and creates references.
            # Invokes object finalization methods.
            #
            physicalize(options)

            #
            # Sets the PDF version header.
            #
            version, level = version_required
            @header.major_version = version[0,1].to_i
            @header.minor_version = version[2,1].to_i

            set_extension_level(version, level) if level > 0

            self
        end
283511
def render_latex_text(input_text, nest_in_doc=False, preamb_extra=None,
                      appname='utool', verbose=None):
    
    import utool as ut
    if verbose is None:
        verbose = ut.VERBOSE
    dpath = ut.ensure_app_resource_dir(appname, 'latex_tmp')
    # put a latex framgent in a full document
    # print(input_text)
    fname = 'temp_render_latex'
    pdf_fpath = ut.compile_latex_text(
        input_text, dpath=dpath, fname=fname, preamb_extra=preamb_extra,
        verbose=verbose)
    ut.startfile(pdf_fpath)
    return pdf_fpath
227797
function parse_xlml_xml(d, _opts) {
	var opts = _opts || {};
	make_ssf(SSF);
	var str = debom(xlml_normalize(d));
	if(opts && opts.type == 'binary' && typeof cptable !== 'undefined') str = cptable.utils.decode(65001, char_codes(str));
	if(str.substr(0,1000).indexOf("<html") >= 0) return HTML_.to_workbook(str, opts);
	var Rn;
	var state = [], tmp;
	if(DENSE != null && opts.dense == null) opts.dense = DENSE;
	var sheets = {}, sheetnames = [], cursheet = (opts.dense ? [] : {}), sheetname = "";
	var table = {}, cell = ({}), row = {};
	var dtag = xlml_parsexmltag('<Data ss:Type="String">'), didx = 0;
	var c = 0, r = 0;
	var refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
	var styles = {}, stag = {};
	var ss = "", fidx = 0;
	var mergecells = [];
	var Props = {}, Custprops = {}, pidx = 0, cp = {};
	var comments = [], comment = {};
	var cstys = [], csty, seencol = false;
	var arrayf = [];
	var rowinfo = [], rowobj = {};
	var Workbook = ({ Sheets:[], WBProps:{date1904:false} }), wsprops = {};
	xlmlregex.lastIndex = 0;
	str = str.replace(/<!--([\s\S]*?)-->/mg,"");
	while((Rn = xlmlregex.exec(str))) switch(Rn[3]) {
		case 'Data':
			if(state[state.length-1][1]) break;
			if(Rn[1]==='/') parse_xlml_data(str.slice(didx, Rn.index), ss, dtag, state[state.length-1][0]=="Comment"?comment:cell, {c:c,r:r}, styles, cstys[c], row, arrayf, opts);
			else { ss = ""; dtag = xlml_parsexmltag(Rn[0]); didx = Rn.index + Rn[0].length; }
			break;
		case 'Cell':
			if(Rn[1]==='/'){
				if(comments.length > 0) cell.c = comments;
				if((!opts.sheetRows || opts.sheetRows > r) && cell.v !== undefined) {
					if(opts.dense) {
						if(!cursheet[r]) cursheet[r] = [];
						cursheet[r][c] = cell;
					} else cursheet[encode_col(c) + encode_row(r)] = cell;
				}
				if(cell.HRef) {
					cell.l = {Target:cell.HRef, Tooltip:cell.HRefScreenTip};
					delete cell.HRef; delete cell.HRefScreenTip;
				}
				if(cell.MergeAcross || cell.MergeDown) {
					var cc = c + (parseInt(cell.MergeAcross,10)|0);
					var rr = r + (parseInt(cell.MergeDown,10)|0);
					mergecells.push({s:{c:c,r:r},e:{c:cc,r:rr}});
				}
				if(!opts.sheetStubs) { if(cell.MergeAcross) c = cc + 1; else ++c; }
				else if(cell.MergeAcross || cell.MergeDown) {
for(var cma = c; cma <= cc; ++cma) {
						for(var cmd = r; cmd <= rr; ++cmd) {
							if(cma > c || cmd > r) {
								if(opts.dense) {
									if(!cursheet[cmd]) cursheet[cmd] = [];
									cursheet[cmd][cma] = {t:'z'};
								} else cursheet[encode_col(cma) + encode_row(cmd)] = {t:'z'};
							}
						}
					}
					c = cc + 1;
				}
				else ++c;
			} else {
				cell = xlml_parsexmltagobj(Rn[0]);
				if(cell.Index) c = +cell.Index - 1;
				if(c < refguess.s.c) refguess.s.c = c;
				if(c > refguess.e.c) refguess.e.c = c;
				if(Rn[0].slice(-2) === "/>") ++c;
				comments = [];
			}
			break;
		case 'Row':
			if(Rn[1]==='/' || Rn[0].slice(-2) === "/>") {
				if(r < refguess.s.r) refguess.s.r = r;
				if(r > refguess.e.r) refguess.e.r = r;
				if(Rn[0].slice(-2) === "/>") {
					row = xlml_parsexmltag(Rn[0]);
					if(row.Index) r = +row.Index - 1;
				}
				c = 0; ++r;
			} else {
				row = xlml_parsexmltag(Rn[0]);
				if(row.Index) r = +row.Index - 1;
				rowobj = {};
				if(row.AutoFitHeight == "0" || row.Height) {
					rowobj.hpx = parseInt(row.Height, 10); rowobj.hpt = px2pt(rowobj.hpx);
					rowinfo[r] = rowobj;
				}
				if(row.Hidden == "1") { rowobj.hidden = true; rowinfo[r] = rowobj; }
			}
			break;
		case 'Worksheet': /* TODO: read range from FullRows/FullColumns */
			if(Rn[1]==='/'){
				if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
				sheetnames.push(sheetname);
				if(refguess.s.r <= refguess.e.r && refguess.s.c <= refguess.e.c) cursheet["!ref"] = encode_range(refguess);
				if(mergecells.length) cursheet["!merges"] = mergecells;
				if(cstys.length > 0) cursheet["!cols"] = cstys;
				if(rowinfo.length > 0) cursheet["!rows"] = rowinfo;
				sheets[sheetname] = cursheet;
			} else {
				refguess = {s: {r:2000000, c:2000000}, e: {r:0, c:0} };
				r = c = 0;
				state.push([Rn[3], false]);
				tmp = xlml_parsexmltag(Rn[0]);
				sheetname = unescapexml(tmp.Name);
				cursheet = (opts.dense ? [] : {});
				mergecells = [];
				arrayf = [];
				rowinfo = [];
				wsprops = {name:sheetname, Hidden:0};
				Workbook.Sheets.push(wsprops);
			}
			break;
		case 'Table':
			if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
			else if(Rn[0].slice(-2) == "/>") break;
			else {
				table = xlml_parsexmltag(Rn[0]);
				state.push([Rn[3], false]);
				cstys = []; seencol = false;
			}
			break;

		case 'Style':
			if(Rn[1]==='/') process_style_xlml(styles, stag, opts);
			else stag = xlml_parsexmltag(Rn[0]);
			break;

		case 'NumberFormat':
			stag.nf = unescapexml(xlml_parsexmltag(Rn[0]).Format || "General");
			if(XLMLFormatMap[stag.nf]) stag.nf = XLMLFormatMap[stag.nf];
			for(var ssfidx = 0; ssfidx != 0x188; ++ssfidx) if(SSF._table[ssfidx] == stag.nf) break;
			if(ssfidx == 0x188) for(ssfidx = 0x39; ssfidx != 0x188; ++ssfidx) if(SSF._table[ssfidx] == null) { SSF.load(stag.nf, ssfidx); break; }
			break;

		case 'Column':
			if(state[state.length-1][0] !== 'Table') break;
			csty = xlml_parsexmltag(Rn[0]);
			if(csty.Hidden) { csty.hidden = true; delete csty.Hidden; }
			if(csty.Width) csty.wpx = parseInt(csty.Width, 10);
			if(!seencol && csty.wpx > 10) {
				seencol = true; MDW = DEF_MDW; //find_mdw_wpx(csty.wpx);
				for(var _col = 0; _col < cstys.length; ++_col) if(cstys[_col]) process_col(cstys[_col]);
			}
			if(seencol) process_col(csty);
			cstys[(csty.Index-1||cstys.length)] = csty;
			for(var i = 0; i < +csty.Span; ++i) cstys[cstys.length] = dup(csty);
			break;

		case 'NamedRange':
			if(!Workbook.Names) Workbook.Names = [];
			var _NamedRange = parsexmltag(Rn[0]);
			var _DefinedName = ({
				Name: _NamedRange.Name,
				Ref: rc_to_a1(_NamedRange.RefersTo.substr(1))
			});
			if(Workbook.Sheets.length>0) _DefinedName.Sheet=Workbook.Sheets.length-1;
Workbook.Names.push(_DefinedName);
			break;

		case 'NamedCell': break;
		case 'B': break;
		case 'I': break;
		case 'U': break;
		case 'S': break;
		case 'Sub': break;
		case 'Sup': break;
		case 'Span': break;
		case 'Border': break;
		case 'Alignment': break;
		case 'Borders': break;
		case 'Font':
			if(Rn[0].slice(-2) === "/>") break;
			else if(Rn[1]==="/") ss += str.slice(fidx, Rn.index);
			else fidx = Rn.index + Rn[0].length;
			break;
		case 'Interior':
			if(!opts.cellStyles) break;
			stag.Interior = xlml_parsexmltag(Rn[0]);
			break;
		case 'Protection': break;

		case 'Author':
		case 'Title':
		case 'Description':
		case 'Created':
		case 'Keywords':
		case 'Subject':
		case 'Category':
		case 'Company':
		case 'LastAuthor':
		case 'LastSaved':
		case 'LastPrinted':
		case 'Version':
		case 'Revision':
		case 'TotalTime':
		case 'HyperlinkBase':
		case 'Manager':
		case 'ContentStatus':
		case 'Identifier':
		case 'Language':
			if(Rn[0].slice(-2) === "/>") break;
			else if(Rn[1]==="/") xlml_set_prop(Props, Rn[3], str.slice(pidx, Rn.index));
			else pidx = Rn.index + Rn[0].length;
			break;
		case 'Paragraphs': break;

		case 'Styles':
		case 'Workbook':
			if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
			else state.push([Rn[3], false]);
			break;

		case 'Comment':
			if(Rn[1]==='/'){
				if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));
				xlml_clean_comment(comment);
				comments.push(comment);
			} else {
				state.push([Rn[3], false]);
				tmp = xlml_parsexmltag(Rn[0]);
				comment = {a:tmp.Author};
			}
			break;

		case 'AutoFilter':
			if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
			else if(Rn[0].charAt(Rn[0].length-2) !== '/') {
				var AutoFilter = xlml_parsexmltag(Rn[0]);
				cursheet['!autofilter'] = { ref:rc_to_a1(AutoFilter.Range).replace(/\$/g,"") };
				state.push([Rn[3], true]);
			}
			break;

		case 'Name': break;

		case 'ComponentOptions':
		case 'DocumentProperties':
		case 'CustomDocumentProperties':
		case 'OfficeDocumentSettings':
		case 'PivotTable':
		case 'PivotCache':
		case 'Names':
		case 'MapInfo':
		case 'PageBreaks':
		case 'QueryTable':
		case 'DataValidation':
		case 'Sorting':
		case 'Schema':
		case 'data':
		case 'ConditionalFormatting':
		case 'SmartTagType':
		case 'SmartTags':
		case 'ExcelWorkbook':
		case 'WorkbookOptions':
		case 'WorksheetOptions':
			if(Rn[1]==='/'){if((tmp=state.pop())[0]!==Rn[3]) throw new Error("Bad state: "+tmp.join("|"));}
			else if(Rn[0].charAt(Rn[0].length-2) !== '/') state.push([Rn[3], true]);
			break;

		default:
			/* FODS file root is <office:document> */
			if(state.length == 0 && Rn[3] == "document") return parse_fods(str, opts);
			/* UOS file root is <uof:UOF> */
			if(state.length == 0 && Rn[3] == "UOF") return parse_fods(str, opts);

			var seen = true;
			switch(state[state.length-1][0]) {
				/* OfficeDocumentSettings */
				case 'OfficeDocumentSettings': switch(Rn[3]) {
					case 'AllowPNG': break;
					case 'RemovePersonalInformation': break;
					case 'DownloadComponents': break;
					case 'LocationOfComponents': break;
					case 'Colors': break;
					case 'Color': break;
					case 'Index': break;
					case 'RGB': break;
					case 'PixelsPerInch': break; // TODO: set PPI
					case 'TargetScreenSize': break;
					case 'ReadOnlyRecommended': break;
					default: seen = false;
				} break;

				/* ComponentOptions */
				case 'ComponentOptions': switch(Rn[3]) {
					case 'Toolbar': break;
					case 'HideOfficeLogo': break;
					case 'SpreadsheetAutoFit': break;
					case 'Label': break;
					case 'Caption': break;
					case 'MaxHeight': break;
					case 'MaxWidth': break;
					case 'NextSheetNumber': break;
					default: seen = false;
				} break;

				/* ExcelWorkbook */
				case 'ExcelWorkbook': switch(Rn[3]) {
					case 'Date1904':
Workbook.WBProps.date1904 = true;
						break;
					case 'WindowHeight': break;
					case 'WindowWidth': break;
					case 'WindowTopX': break;
					case 'WindowTopY': break;
					case 'TabRatio': break;
					case 'ProtectStructure': break;
					case 'ProtectWindows': break;
					case 'ActiveSheet': break;
					case 'DisplayInkNotes': break;
					case 'FirstVisibleSheet': break;
					case 'SupBook': break;
					case 'SheetName': break;
					case 'SheetIndex': break;
					case 'SheetIndexFirst': break;
					case 'SheetIndexLast': break;
					case 'Dll': break;
					case 'AcceptLabelsInFormulas': break;
					case 'DoNotSaveLinkValues': break;
					case 'Iteration': break;
					case 'MaxIterations': break;
					case 'MaxChange': break;
					case 'Path': break;
					case 'Xct': break;
					case 'Count': break;
					case 'SelectedSheets': break;
					case 'Calculation': break;
					case 'Uncalced': break;
					case 'StartupPrompt': break;
					case 'Crn': break;
					case 'ExternName': break;
					case 'Formula': break;
					case 'ColFirst': break;
					case 'ColLast': break;
					case 'WantAdvise': break;
					case 'Boolean': break;
					case 'Error': break;
					case 'Text': break;
					case 'OLE': break;
					case 'NoAutoRecover': break;
					case 'PublishObjects': break;
					case 'DoNotCalculateBeforeSave': break;
					case 'Number': break;
					case 'RefModeR1C1': break;
					case 'EmbedSaveSmartTags': break;
					default: seen = false;
				} break;

				/* WorkbookOptions */
				case 'WorkbookOptions': switch(Rn[3]) {
					case 'OWCVersion': break;
					case 'Height': break;
					case 'Width': break;
					default: seen = false;
				} break;

				/* WorksheetOptions */
				case 'WorksheetOptions': switch(Rn[3]) {
					case 'Visible':
						if(Rn[0].slice(-2) === "/>"){/* empty */}
						else if(Rn[1]==="/") switch(str.slice(pidx, Rn.index)) {
							case "SheetHidden": wsprops.Hidden = 1; break;
							case "SheetVeryHidden": wsprops.Hidden = 2; break;
						}
						else pidx = Rn.index + Rn[0].length;
						break;
					case 'Header':
						if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
						cursheet['!margins'].header = parsexmltag(Rn[0]).Margin;
						break;
					case 'Footer':
						if(!cursheet['!margins']) default_margins(cursheet['!margins']={}, 'xlml');
						cursheet['!margins'].footer = parsexmltag(Rn[0]).Margin;
						break;
					case 'PageMargins':
						var pagemargins = parsexmltag(Rn[0]);
						if(!cursheet['!margins']) default_margins(cursheet['!margins']={},'xlml');
						if(pagemargins.Top) cursheet['!margins'].top = pagemargins.Top;
						if(pagemargins.Left) cursheet['!margins'].left = pagemargins.Left;
						if(pagemargins.Right) cursheet['!margins'].right = pagemargins.Right;
						if(pagemargins.Bottom) cursheet['!margins'].bottom = pagemargins.Bottom;
						break;
					case 'Unsynced': break;
					case 'Print': break;
					case 'Panes': break;
					case 'Scale': break;
					case 'Pane': break;
					case 'Number': break;
					case 'Layout': break;
					case 'PageSetup': break;
					case 'Selected': break;
					case 'ProtectObjects': break;
					case 'EnableSelection': break;
					case 'ProtectScenarios': break;
					case 'ValidPrinterInfo': break;
					case 'HorizontalResolution': break;
					case 'VerticalResolution': break;
					case 'NumberofCopies': break;
					case 'ActiveRow': break;
					case 'ActiveCol': break;
					case 'ActivePane': break;
					case 'TopRowVisible': break;
					case 'TopRowBottomPane': break;
					case 'LeftColumnVisible': break;
					case 'LeftColumnRightPane': break;
					case 'FitToPage': break;
					case 'RangeSelection': break;
					case 'PaperSizeIndex': break;
					case 'PageLayoutZoom': break;
					case 'PageBreakZoom': break;
					case 'FilterOn': break;
					case 'DoNotDisplayGridlines': break;
					case 'SplitHorizontal': break;
					case 'SplitVertical': break;
					case 'FreezePanes': break;
					case 'FrozenNoSplit': break;
					case 'FitWidth': break;
					case 'FitHeight': break;
					case 'CommentsLayout': break;
					case 'Zoom': break;
					case 'LeftToRight': break;
					case 'Gridlines': break;
					case 'AllowSort': break;
					case 'AllowFilter': break;
					case 'AllowInsertRows': break;
					case 'AllowDeleteRows': break;
					case 'AllowInsertCols': break;
					case 'AllowDeleteCols': break;
					case 'AllowInsertHyperlinks': break;
					case 'AllowFormatCells': break;
					case 'AllowSizeCols': break;
					case 'AllowSizeRows': break;
					case 'NoSummaryRowsBelowDetail': break;
					case 'TabColorIndex': break;
					case 'DoNotDisplayHeadings': break;
					case 'ShowPageLayoutZoom': break;
					case 'NoSummaryColumnsRightDetail': break;
					case 'BlackAndWhite': break;
					case 'DoNotDisplayZeros': break;
					case 'DisplayPageBreak': break;
					case 'RowColHeadings': break;
					case 'DoNotDisplayOutline': break;
					case 'NoOrientation': break;
					case 'AllowUsePivotTables': break;
					case 'ZeroHeight': break;
					case 'ViewableRange': break;
					case 'Selection': break;
					case 'ProtectContents': break;
					default: seen = false;
				} break;

				/* PivotTable */
				case 'PivotTable': case 'PivotCache': switch(Rn[3]) {
					case 'ImmediateItemsOnDrop': break;
					case 'ShowPageMultipleItemLabel': break;
					case 'CompactRowIndent': break;
					case 'Location': break;
					case 'PivotField': break;
					case 'Orientation': break;
					case 'LayoutForm': break;
					case 'LayoutSubtotalLocation': break;
					case 'LayoutCompactRow': break;
					case 'Position': break;
					case 'PivotItem': break;
					case 'DataType': break;
					case 'DataField': break;
					case 'SourceName': break;
					case 'ParentField': break;
					case 'PTLineItems': break;
					case 'PTLineItem': break;
					case 'CountOfSameItems': break;
					case 'Item': break;
					case 'ItemType': break;
					case 'PTSource': break;
					case 'CacheIndex': break;
					case 'ConsolidationReference': break;
					case 'FileName': break;
					case 'Reference': break;
					case 'NoColumnGrand': break;
					case 'NoRowGrand': break;
					case 'BlankLineAfterItems': break;
					case 'Hidden': break;
					case 'Subtotal': break;
					case 'BaseField': break;
					case 'MapChildItems': break;
					case 'Function': break;
					case 'RefreshOnFileOpen': break;
					case 'PrintSetTitles': break;
					case 'MergeLabels': break;
					case 'DefaultVersion': break;
					case 'RefreshName': break;
					case 'RefreshDate': break;
					case 'RefreshDateCopy': break;
					case 'VersionLastRefresh': break;
					case 'VersionLastUpdate': break;
					case 'VersionUpdateableMin': break;
					case 'VersionRefreshableMin': break;
					case 'Calculation': break;
					default: seen = false;
				} break;

				/* PageBreaks */
				case 'PageBreaks': switch(Rn[3]) {
					case 'ColBreaks': break;
					case 'ColBreak': break;
					case 'RowBreaks': break;
					case 'RowBreak': break;
					case 'ColStart': break;
					case 'ColEnd': break;
					case 'RowEnd': break;
					default: seen = false;
				} break;

				/* AutoFilter */
				case 'AutoFilter': switch(Rn[3]) {
					case 'AutoFilterColumn': break;
					case 'AutoFilterCondition': break;
					case 'AutoFilterAnd': break;
					case 'AutoFilterOr': break;
					default: seen = false;
				} break;

				/* QueryTable */
				case 'QueryTable': switch(Rn[3]) {
					case 'Id': break;
					case 'AutoFormatFont': break;
					case 'AutoFormatPattern': break;
					case 'QuerySource': break;
					case 'QueryType': break;
					case 'EnableRedirections': break;
					case 'RefreshedInXl9': break;
					case 'URLString': break;
					case 'HTMLTables': break;
					case 'Connection': break;
					case 'CommandText': break;
					case 'RefreshInfo': break;
					case 'NoTitles': break;
					case 'NextId': break;
					case 'ColumnInfo': break;
					case 'OverwriteCells': break;
					case 'DoNotPromptForFile': break;
					case 'TextWizardSettings': break;
					case 'Source': break;
					case 'Number': break;
					case 'Decimal': break;
					case 'ThousandSeparator': break;
					case 'TrailingMinusNumbers': break;
					case 'FormatSettings': break;
					case 'FieldType': break;
					case 'Delimiters': break;
					case 'Tab': break;
					case 'Comma': break;
					case 'AutoFormatName': break;
					case 'VersionLastEdit': break;
					case 'VersionLastRefresh': break;
					default: seen = false;
				} break;

				case 'Sorting':
				case 'ConditionalFormatting':
				case 'DataValidation':
				switch(Rn[3]) {
					case 'Range': break;
					case 'Type': break;
					case 'Min': break;
					case 'Max': break;
					case 'Sort': break;
					case 'Descending': break;
					case 'Order': break;
					case 'CaseSensitive': break;
					case 'Value': break;
					case 'ErrorStyle': break;
					case 'ErrorMessage': break;
					case 'ErrorTitle': break;
					case 'CellRangeList': break;
					case 'InputMessage': break;
					case 'InputTitle': break;
					case 'ComboHide': break;
					case 'InputHide': break;
					case 'Condition': break;
					case 'Qualifier': break;
					case 'UseBlank': break;
					case 'Value1': break;
					case 'Value2': break;
					case 'Format': break;
					default: seen = false;
				} break;

				/* MapInfo (schema) */
				case 'MapInfo': case 'Schema': case 'data': switch(Rn[3]) {
					case 'Map': break;
					case 'Entry': break;
					case 'Range': break;
					case 'XPath': break;
					case 'Field': break;
					case 'XSDType': break;
					case 'FilterOn': break;
					case 'Aggregate': break;
					case 'ElementType': break;
					case 'AttributeType': break;
				/* These are from xsd (XML Schema Definition) */
					case 'schema':
					case 'element':
					case 'complexType':
					case 'datatype':
					case 'all':
					case 'attribute':
					case 'extends': break;

					case 'row': break;
					default: seen = false;
				} break;

				/* SmartTags (can be anything) */
				case 'SmartTags': break;

				default: seen = false; break;
			}
			if(seen) break;
			/* CustomDocumentProperties */
			if(!state[state.length-1][1]) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
			if(state[state.length-1][0]==='CustomDocumentProperties') {
				if(Rn[0].slice(-2) === "/>") break;
				else if(Rn[1]==="/") xlml_set_custprop(Custprops, Rn, cp, str.slice(pidx, Rn.index));
				else { cp = Rn; pidx = Rn.index + Rn[0].length; }
				break;
			}
			if(opts.WTF) throw 'Unrecognized tag: ' + Rn[3] + "|" + state.join("|");
	}
	var out = ({});
	if(!opts.bookSheets && !opts.bookProps) out.Sheets = sheets;
	out.SheetNames = sheetnames;
	out.Workbook = Workbook;
	out.SSF = SSF.get_table();
	out.Props = Props;
	out.Custprops = Custprops;
	return out;
}
1046625
function styleToAll() {
    // sometimes, setStylesheet fails upon loading
    printStyleSheet = printStyleSheet || getPrintStyleSheet();
    $printStyleSheetLink = $printStyleSheetLink || getPrintStyleSheetLink();
    // Chrome:
    printStyleSheet.media.mediaText = 'all';
    // Firefox:
    $printStyleSheetLink.attr( 'media', 'all' );
    return !!printStyleSheet;
}
520577
function renderArbitraryAST(plugin, ref, deps) {
  const { hasOwn } = deps;
  const child = t.identifier("child");
  const type = t.identifier("type");
  const func = t.identifier("func");
  const args = t.identifier("args");
  const i = t.identifier("i");
  const prop = t.identifier("prop");

  /**
   * function _renderArbitrary(child) {
   *   var type = typeof child;
   *   if (type === "number" || (type === string || type === 'object' && child instanceof String)) {
   *     text(child);
   *   } else if (Array.isArray(child)) {
   *     for (var i = 0; i < child.length; i++) {
   *       _renderArbitrary(child[i]);
   *     }
   *   } else if (type === "object") {
   *     if (child.__jsxDOMWrapper) {
   *       var func = child.func, args = child.args;
   *       if (args) {
   *         func.apply(this, args);
   *       } else {
   *         func();
   *       }
   *     } else if (String(child) === "[object Object]") {
   *       for (var prop in child) {
   *         if (_hasOwn.call(child, prop)) {
   *           renderArbitrary(child[prop])
   *         }
   *       }
   *     }
   *   }
   * }
   */
  return t.functionExpression(
    ref,
    [child],
    t.blockStatement([
      t.variableDeclaration("var", [
        t.variableDeclarator(
          type,
          t.unaryExpression("typeof", child)
        )
      ]),
      t.IfStatement(
        isTextual(type, child),
        t.blockStatement([
          t.expressionStatement(toFunctionCall(iDOMMethod("text", plugin), [child]))
        ]),
        t.ifStatement(
          isArray(child),
          t.blockStatement([
            t.forStatement(
              t.variableDeclaration("var", [t.variableDeclarator(i, t.numericLiteral(0))]),
              t.binaryExpression("<", i, t.memberExpression(child, t.identifier("length"))),
              t.updateExpression("++", i),
              t.expressionStatement(toFunctionCall(ref, [
                t.memberExpression(child, i, true)
              ]))
            )
          ]),
          t.ifStatement(
            isObject(type),
            t.blockStatement([
              t.ifStatement(
                isDOMWrapper(child),
                t.blockStatement([
                  t.variableDeclaration("var", [
                    t.variableDeclarator(func, t.memberExpression(child, func)),
                    t.variableDeclarator(args, t.memberExpression(child, args))
                  ]),
                  t.ifStatement(
                    args,
                    t.blockStatement([
                      t.expressionStatement(
                        toFunctionCall(t.memberExpression(func, t.identifier("apply")), [t.thisExpression(), args]),
                      )
                    ]),
                    t.blockStatement([
                      t.expressionStatement(toFunctionCall(func, [])),
                    ]),
                  )
                ]),
                t.ifStatement(
                  isPlainObject(child),
                  t.blockStatement([
                    t.forInStatement(
                      t.variableDeclaration("var", [t.variableDeclarator(prop)]),
                      child,
                      t.ifStatement(
                        toFunctionCall(t.memberExpression(
                          hasOwn,
                          t.identifier("call")
                        ), [child, i]),
                        t.expressionStatement(toFunctionCall(ref, [
                          t.memberExpression(child, i, true)
                        ]))
                      )
                    )
                  ])
                )
              )
            ])
          )
        )
      )
    ])
  );
}
656859
function () {
    // render stylesheets
    var precss = fs.readFileSync(__dirname + '/themes/default/styl/default.styl', 'utf8');
    stylus.render(precss, { filename: 'default.css' }, function(err, css){
      if (err) {
        throw err;
      }

      this.styles = css;
    }.bind(this));

    // collect client js (to be inined later)
    this.js = fs.readFileSync(__dirname + '/themes/default/js/default.js', 'utf8');

    // register handlebars helpers
    Handlebars.registerHelper('roundNumber', function (number) {
      return Math.round(number * Math.pow(10, 2)) / Math.pow(10, 2);
    });

    // collect & compile templates
    this.templates = {};
    this.templates.test = Handlebars.compile(fs.readFileSync(__dirname + '/themes/default/hbs/test.hbs', 'utf8'));
    this.templates.wrapper = Handlebars.compile(fs.readFileSync(__dirname + '/themes/default/hbs/wrapper.hbs', 'utf8'));
    this.templates.testresult = Handlebars.compile(fs.readFileSync(__dirname + '/themes/default/hbs/tests.hbs', 'utf8'));
    this.templates.banner = Handlebars.compile(fs.readFileSync(__dirname + '/themes/default/hbs/banner.hbs', 'utf8'));
    this.templates.detail = Handlebars.compile(fs.readFileSync(__dirname + '/themes/default/hbs/detail.hbs', 'utf8'));

    return this;
  }
893823
function sheetifySass (filename, source, options, done) {
  const sassOpts = extend({
    data: source,
    file: filename,
    indentedSyntax: /\.sass$/i.test(filename)
  }, options)

  sass.render(sassOpts, function (err, res) {
    if (err) return done(err)
    done(null, {
      css: String(res.css),
      files: res.stats.includedFiles
    })
  })
}
924212
def render(self, xml, context, raise_on_errors=True):
        """"""

        if xml:
            self.xml = xml

            # render XSL
            self.render_xsl(self.root, context)

            # create root XSL sheet
            xsl_ns = self.namespaces['xsl']
            rootName = etree.QName(xsl_ns, 'stylesheet')
            root = etree.Element(rootName, nsmap={'xsl': xsl_ns})
            sheet = etree.ElementTree(root)
            template = etree.SubElement(root, etree.QName(xsl_ns, "template"), match='/')

            # put OpenOffice tree into XSLT sheet
            template.append(self.root)
            self.root = root

            # drop XSL styles
            self.remove_style()

            #self.debug(self.xml)

            try:
                # transform XSL
                xsl = etree.XSLT(self.root)
                self.root = xsl(context)

            except etree.Error as e:
                # log errors
                for l in e.error_log:
                    self.error("XSLT error at line %s col %s:" % (l.line, l.column))
                    self.error("    message: %s" % l.message)
                    self.error("    domain: %s (%d)" % (l.domain_name, l.domain))
                    self.error('    type: %s (%d)' % (l.type_name, l.type))
                    self.error('    level: %s (%d)' % (l.level_name, l.level))
                    self.error('    filename: %s' % l.filename)

                if raise_on_errors:
                    raise

            return self.xml

        else:
            return xml
1305186
function write_sty_bin(wb, opts) {
	var ba = buf_array();
	write_record(ba, "BrtBeginStyleSheet");
	write_FMTS_bin(ba, wb.SSF);
	write_FONTS_bin(ba, wb);
	write_FILLS_bin(ba, wb);
	write_BORDERS_bin(ba, wb);
	write_CELLSTYLEXFS_bin(ba, wb);
	write_CELLXFS_bin(ba, opts.cellXfs);
	write_STYLES_bin(ba, wb);
	write_DXFS_bin(ba, wb);
	write_TABLESTYLES_bin(ba, wb);
	write_COLORPALETTE_bin(ba, wb);
	/* FRTSTYLESHEET*/
	write_record(ba, "BrtEndStyleSheet");
	return ba.end();
}
82181
function renderToString(vnode, context, opts, inner, isSvgMode) {
	if (vnode==null || typeof vnode==='boolean') {
		return '';
	}

	let nodeName = vnode.type,
		attributes = vnode.props,
		isComponent = false;
	context = context || {};
	opts = opts || {};

	let pretty = opts.pretty,
		indentChar = typeof pretty==='string' ? pretty : '\t';

	// #text nodes
	if (typeof vnode!=='object' && !nodeName) {
		return encodeEntities(vnode);
	}

	// components
	if (typeof nodeName==='function') {
		isComponent = true;
		if (opts.shallow && (inner || opts.renderRootComponent===false)) {
			nodeName = getComponentName(nodeName);
		}
		else {
			let props = getNodeProps(vnode),
				rendered;

			if (!nodeName.prototype || typeof nodeName.prototype.render!=='function') {
				// stateless functional components
				rendered = nodeName(props, context);
			}
			else {
				// class-based components
				let c = new nodeName(props, context);
				// turn off stateful re-rendering:
				c._disable = c.__x = true;
				c.props = props;
				c.context = context;
				if (c.componentWillMount) c.componentWillMount();
				rendered = c.render(c.props, c.state, c.context);

				if (c.getChildContext) {
					context = assign(assign({}, context), c.getChildContext());
				}
			}

			return renderToString(rendered, context, opts, opts.shallowHighOrder!==false);
		}
	}

	// render JSX to HTML
	let s = '', html;

	if (attributes) {
		let attrs = objectKeys(attributes);

		// allow sorting lexicographically for more determinism (useful for tests, such as via preact-jsx-chai)
		if (opts && opts.sortAttributes===true) attrs.sort();

		for (let i=0; i<attrs.length; i++) {
			let name = attrs[i],
				v = attributes[name];
			if (name==='children') continue;

			if (name.match(/[\s\n\\/='"\0<>]/)) continue;

			if (!(opts && opts.allAttributes) && (name==='key' || name==='ref')) continue;

			if (name==='className') {
				if (attributes.class) continue;
				name = 'class';
			}
			else if (isSvgMode && name.match(/^xlink:?./)) {
				name = name.toLowerCase().replace(/^xlink:?/, 'xlink:');
			}

			if (name==='style' && v && typeof v==='object') {
				v = styleObjToCss(v);
			}

			let hooked = opts.attributeHook && opts.attributeHook(name, v, context, opts, isComponent);
			if (hooked || hooked==='') {
				s += hooked;
				continue;
			}

			if (name==='dangerouslySetInnerHTML') {
				html = v && v.__html;
			}
			else if ((v || v===0 || v==='') && typeof v!=='function') {
				if (v===true || v==='') {
					v = name;
					// in non-xml mode, allow boolean attributes
					if (!opts || !opts.xml) {
						s += ' ' + name;
						continue;
					}
				}
				s += ` ${name}="${encodeEntities(v)}"`;
			}
		}
	}

	// account for >1 multiline attribute
	let sub = s.replace(/^\n\s*/, ' ');
	if (sub!==s && !~sub.indexOf('\n')) s = sub;
	else if (pretty && ~s.indexOf('\n')) s += '\n';

	s = `<${nodeName}${s}>`;
	if (String(nodeName).match(/[\s\n\\/='"\0<>]/)) throw s;

	let isVoid = String(nodeName).match(VOID_ELEMENTS);
	if (isVoid) s = s.replace(/>$/, ' />');

	let pieces = [];
	if (html) {
		// if multiline, indent.
		if (pretty && isLargeString(html)) {
			html = '\n' + indentChar + indent(html, indentChar);
		}
		s += html;
	}
	else if (vnode.props.children) {
        let hasLarge = ~s.indexOf('\n');
        let children = vnode.props.children;
        if (!Array.isArray(children)) {
            children = [children]
        }
        for (let i=0; i< children.length; i++) {
            let child = children[i];
            if (child!=null && child!==false) {
                let childSvgMode = nodeName==='svg' ? true : nodeName==='foreignObject' ? false : isSvgMode,
                    ret = renderToString(child, context, opts, true, childSvgMode);
                if (!hasLarge && pretty && isLargeString(ret)) hasLarge = true;
                if (ret) pieces.push(ret);
            }
        }

		if (pretty && hasLarge) {
			for (let i=pieces.length; i--; ) {
				pieces[i] = '\n' + indentChar + indent(pieces[i], indentChar);
			}
		}
	}

	if (pieces.length) {
		s += pieces.join('');
	}
	else if (opts && opts.xml) {
		return s.substring(0, s.length-1) + ' />';
	}

	if (!isVoid) {
		if (pretty && ~s.indexOf('\n')) s += '\n';
		s += `</${nodeName}>`;
	}

	return s;
}
1224126
function Type1Font(name, file, properties) {
  // Some bad generators embed pfb file as is, we have to strip 6-byte headers.
  // Also, length1 and length2 might be off by 6 bytes as well.
  // http://www.math.ubc.ca/~cass/piscript/type1.pdf
  var PFB_HEADER_SIZE = 6;
  var headerBlockLength = properties.length1;
  var eexecBlockLength = properties.length2;
  var pfbHeader = file.peekBytes(PFB_HEADER_SIZE);
  var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01;
  if (pfbHeaderPresent) {
    file.skip(PFB_HEADER_SIZE);
    headerBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
                        (pfbHeader[3] << 8) | pfbHeader[2];
  }

  // Get the data block containing glyphs and subrs informations
  var headerBlock = new Stream(file.getBytes(headerBlockLength));
  var headerBlockParser = new Type1Parser(headerBlock);
  headerBlockParser.extractFontHeader(properties);

  if (pfbHeaderPresent) {
    pfbHeader = file.getBytes(PFB_HEADER_SIZE);
    eexecBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) |
                       (pfbHeader[3] << 8) | pfbHeader[2];
  }

  // Decrypt the data blocks and retrieve it's content
  var eexecBlock = new Stream(file.getBytes(eexecBlockLength));
  var eexecBlockParser = new Type1Parser(eexecBlock, true);
  var data = eexecBlockParser.extractFontProgram();
  for (var info in data.properties) {
    properties[info] = data.properties[info];
  }

  var charstrings = data.charstrings;
  var type2Charstrings = this.getType2Charstrings(charstrings);
  var subrs = this.getType2Subrs(data.subrs);

  this.charstrings = charstrings;
  this.data = this.wrap(name, type2Charstrings, this.charstrings,
                        subrs, properties);
  this.seacs = this.getSeacs(data.charstrings);
}
325393
function renderTypeFun(obj) {
    if (!this.isGridShow()) return;
    if (typeof obj == 'undefined') {
        var begin = null,
            length = null,
            field = '';
    } else {
        var begin = typeof obj.begin == 'undefined' ? null : obj.begin,
            length = typeof obj.length == 'undefined' ? null : obj.length,
            field = typeof obj.field == 'undefined' ? '' : obj.field;
    }
    var oThis = this,
        begin = parseInt(begin),
        length = parseInt(length),
        end = begin;
    if (length > 0) {
        end = parseInt(begin + length - 1);
    }
    if (field == '') {
        if (this.gridCompColumnFixedArr) $.each(this.gridCompColumnFixedArr, function (i) {
            oThis.renderTypeByColumn(this, i, begin, length, true);
        });
        $.each(this.gridCompColumnArr, function (i) {
            oThis.renderTypeByColumn(this, i, begin, length, false);
        });
    } else {
        var rendered = false;
        if (this.gridCompColumnFixedArr) $.each(this.gridCompColumnFixedArr, function (i) {
            if (this.options.field == field) {
                oThis.renderTypeByColumn(this, i, begin, length, true);
                rendered = true;
                return;
            }
        });
        if (!rendered) $.each(this.gridCompColumnArr, function (i) {
            if (this.options.field == field) {
                oThis.renderTypeByColumn(this, i, begin, length, false);
                return;
            }
        });
    }
}
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;
}