pull this OR.SHEET into a real book/sheet in Origin
342072
def push(self,bookName=None,sheetName=None,overwrite=False):
        """"""
        # tons of validation
        if bookName: self.bookName=bookName
        if sheetName: self.sheetName=sheetName
        if not self.sheetName in OR.sheetNames(bookName):
            print("can't find [%s]%s!"%(bookName,sheetName))
            return

        # clear out out sheet by deleting EVERY column
        poSheet=OR.getSheet(bookName,sheetName) # CPyWorksheetPageI
        if not poSheet:
            print("WARNING: didn't get posheet",poSheet,bookName,sheetName)
        for poCol in [x for x in poSheet if x.IsValid()]:
            poCol.Destroy()

        # create columns and assign properties to each
        for i in range(len(self.colNames)):
            poSheet.InsertCol(i,self.colNames[i])
            poSheet.Columns(i).SetName(self.colNames[i])
            poSheet.Columns(i).SetLongName(self.colDesc[i])
            poSheet.Columns(i).SetUnits(self.colUnits[i])
            poSheet.Columns(i).SetComments(self.colComments[i])
            poSheet.Columns(i).SetType(self.colTypes[i])
            poSheet.Columns(i).SetData(self.colData[i])
498000
def source_start(base='', book_id='book'):
    
    repo_htm_path = "{book_id}-h/{book_id}-h.htm".format(book_id=book_id)
    possible_paths = ["book.asciidoc",
                      repo_htm_path,
                      "{}-0.txt".format(book_id),
                      "{}-8.txt".format(book_id),
                      "{}.txt".format(book_id),
                      "{}-pdf.pdf".format(book_id),
                     ]

    # return the first match

    for path in possible_paths:
        fullpath = os.path.join(base, path)
        if os.path.exists(fullpath):
            return path

    return None
205048
def create_book(self, name):
        """"""
        name = name.strip()
        if not len(name):
            self.error("Cannot have a blank book name")
        # The next could be relaxed, if users want commas in book names, but
        # I prefer to keep it, in case later there could be a syntax for multiple
        # book names, using comma.
        if name.find(",") >= 0:
            self.error("Cannot have a ',' in a book name")
        existing = self.list_books()
        nexisting = len(existing)
        if name in existing:
            self.error("Already have a book named '%s'" % name)
        try:
            self.cur.execute("INSERT INTO book (number, name) VALUES(?, ?);", (nexisting, name))
            self.con.commit()
        except:
            self.fyi("Error adding a book named '%s'" % name)
986765
def get_surface(shifts, orig_text, item, text):
    """"""
    span = item.span()
    logging.debug(u'\tInitial span: %s ("%s")', span, text[span[0]:span[1]])

    real_span = (span[0] - shifts[span[0]], span[1] - shifts[span[1] - 1])
    surface = orig_text[real_span[0]:real_span[1]]
    logging.debug(u'\tShifted span: %s ("%s")', real_span, surface)

    while any(surface.endswith(i) for i in [' ', '-']):
        surface = surface[:-1]
        real_span = (real_span[0], real_span[1] - 1)

    while surface.startswith(' '):
        surface = surface[1:]
        real_span = (real_span[0] + 1, real_span[1])

    logging.debug(u'\tFinal span: %s ("%s")', real_span, surface)
    return surface, real_span
1124361
function (books, context, options) {
      kb.fetcher.load(books).then(function (xhr) {
        renderThreeColumnBrowser2(books, context, options)
      }).catch(function (err) { complain(err) })
    }
4634
def exportTree(self, tree, filename):
        
        book = xlwt.Workbook()
        
        # determine the title for the sheet to export
        title = nativestring(tree.windowTitle())
        if not title:
            title = nativestring(tree.objectName())
        if not title:
            title = 'Sheet 1'
        
        sheet = book.add_sheet(title)
        
        # determine visible columns to export
        cols = [c for c in range(tree.columnCount()) \
                if not tree.isColumnHidden(c)]
        
        # export the column headers
        hitem = tree.headerItem()
        for c, col in enumerate(cols):
            sheet.write(0, c, nativestring(hitem.text(col)))
        
        self._currrow = 1
        for i in range(tree.topLevelItemCount()):
            self.exportTreeItem(sheet, cols, tree.topLevelItem(i))
        
        book.save(filename)
        return True
1279893
def sheetToHTML(sheet):
    

    assert "SHEET" in str(type(sheet))
    #data,names=None,units=None,bookName=None,sheetName=None,xCol=None
    #sheet=OR.SHEET()
    data=sheet.data
    names=sheet.colDesc
    units=sheet.colUnits
    bookName=sheet.bookName
    sheetName=sheet.sheetName

    def htmlListToTR(l,trClass=None,tdClass=None,td1Class=None):
        """
        turns a list into a <tr><td>something</td></tr>
        call this when generating HTML tables dynamically.
        """
        html="<tr>"
        for item in l:
            html+="<td>%s</td>"%item
        html+="</tr>"
        if trClass:
            html=html.replace("<tr>",'<tr class="%s">'%trClass)
        if td1Class:
            html=html.replace("<td>",'<td class="%s">'%td1Class,1)
        if tdClass:
            html=html.replace("<td>",'<td class="%s">'%tdClass)
        return html

    htmlFname = os.path.expanduser("~")+"/WKS-%s.%s.html"%(bookName,sheetName)
    html="""<body>
    <style>
    body {
          background-color: #ababab;
          padding:20px;
          }
    table {
           font-size:12px;
           border-spacing: 0;
           border-collapse: collapse;
           }
    .name {background-color:#fafac8;text-align:center;}
    .units {background-color:#fafac8;text-align:center;}
    .data0 {background-color:#FFFFFF;font-family: monospace;text-align:center;}
    .data1 {background-color:#FAFAFA;font-family: monospace;text-align:center;}
    .labelRow {background-color:#e0dfe4; text-align:right;border:1px solid #000000;}
    .labelCol {background-color:#e0dfe4; text-align:center;border:1px solid #000000;  padding-left: 20px; padding-right: 20px;}
    td {
        border:1px solid #c0c0c0; padding:5px;
        font-family: Arial, Helvetica, sans-serif;
        }
    </style>
    <html>"""
    html+="<h1>FauxRigin</h1>"
    if bookName or sheetName:
        html+='<code><b>%s / %s</b></code><br><br>'%(bookName,sheetName)
    html+="<table>"
    colNames=['']
    for i in range(len(units)):
        shortName=chr(i%26+ord('A'))
        if i>=26:
            shortName=chr(int(i/26-1)+ord('A'))+shortName
        label="%s(%s)"%(shortName,"X" if sheet.colTypes[i]==3 else "Y")
        colNames.append(label)
    html+=htmlListToTR(colNames,'labelCol','labelCol')
    html+=htmlListToTR(['Long Name']+list(names),'name',td1Class='labelRow')
    html+=htmlListToTR(['Units']+list(units),'units',td1Class='labelRow')
    cutOff=False
    for y in range(len(data)):
        html+=htmlListToTR([y+1]+list(data[y]),trClass='data%d'%(y%2),td1Class='labelRow')
        if y>=200:
            cutOff=True
            break
    html+="</table>"
    html=html.replace(">nan<",">--<")
    html=html.replace(">None<","><")
    if cutOff:
        html+="<h3>... showing only %d of %d rows ...</h3>"%(y,len(data))
    html+="</body></html>"
    with open(htmlFname,'w') as f:
        f.write(html)
    import webbrowser
    webbrowser.open(htmlFname)
    return
675974
def toxls(tbl, filename, sheet, encoding=None, style_compression=0,
          styles=None):
    

    import xlwt
    if encoding is None:
        encoding = locale.getpreferredencoding()
    wb = xlwt.Workbook(encoding=encoding, style_compression=style_compression)
    ws = wb.add_sheet(sheet)

    if styles is None:
        # simple version, don't worry about styles
        for r, row in enumerate(tbl):
            for c, v in enumerate(row):
                ws.write(r, c, label=v)
    else:
        # handle styles
        it = iter(tbl)
        hdr = next(it)
        flds = list(map(str, hdr))
        for c, f in enumerate(flds):
            ws.write(0, c, label=f)
            if f not in styles or styles[f] is None:
                styles[f] = xlwt.Style.default_style
        # convert to list for easy zipping
        styles = [styles[f] for f in flds]
        for r, row in enumerate(it):
            for c, (v, style) in enumerate(izip_longest(row, styles,
                                                        fillvalue=None)):
                ws.write(r+1, c, label=v, style=style)

    wb.save(filename)
480251
def from_code_array(self):
        """"""

        worksheets = []
        self._shape2xls(worksheets)

        self._code2xls(worksheets)

        self._row_heights2xls(worksheets)
        self._col_widths2xls(worksheets)

        return self.workbook
1037412
function createCssRule(selector, ...rules) {
    let styles = document.getElementById(styleId);

    if (!styles) {
        styles = document.createElement('style');
        styles.type = 'text/css';
        styles.id = styleId;
        document.getElementsByTagName('head')[0].appendChild(styles);
    }

    const sheet = styles.sheet;

    // add each rule via 'insertRule' if that rule doesn't already exist
    // (needed due to storybook / webpack hot reloading)
    for (let i = 0; i < rules.length; i++) {
        const rule = rules[i];
        const cssText = `${selector} { ${rule}; }`;
        let found = false;

        for (let j = 0; j < sheet.cssRules.length; j++) {
            const existingRule = sheet.cssRules[j];
            if (cssText === existingRule.cssText) {
                found = true;
                break;
            }
        }

        if (!found) {
            // insertRule won't allow semicolons
            sheet.insertRule(cssText.replace(';', ''), 0);
        }
    }
}
346699
def get_linenos(obj):
    """"""
    try:
        lines, start = inspect.getsourcelines(obj)
    except TypeError:
        return None, None
    else:
        return start, start + len(lines) - 1
234701
def from_text(text, origin = root):
    

    if not isinstance(text, str):
        if isinstance(text, unicode) and sys.hexversion >= 0x02030000:
            return from_unicode(text, origin)
        else:
            raise ValueError("input to from_text() must be a string")
    if not (origin is None or isinstance(origin, Name)):
        raise ValueError("origin must be a Name or None")
    labels = []
    label = ''
    escaping = False
    edigits = 0
    total = 0
    if text == '@':
        text = ''
    if text:
        if text == '.':
            return Name([''])
        for c in text:
            if escaping:
                if edigits == 0:
                    if c.isdigit():
                        total = int(c)
                        edigits += 1
                    else:
                        label += c
                        escaping = False
                else:
                    if not c.isdigit():
                        raise BadEscape
                    total *= 10
                    total += int(c)
                    edigits += 1
                    if edigits == 3:
                        escaping = False
                        label += chr(total)
            elif c == '.':
                if len(label) == 0:
                    raise EmptyLabel
                labels.append(label)
                label = ''
            elif c == '\\':
                escaping = True
                edigits = 0
                total = 0
            else:
                label += c
        if escaping:
            raise BadEscape
        if len(label) > 0:
            labels.append(label)
        else:
            labels.append('')
    if (len(labels) == 0 or labels[-1] != '') and not origin is None:
        labels.extend(list(origin.labels))
    return Name(labels)
883399
function prepareSheet(opts, data, columns, idx) {
		/** Default options for sheet */
		var opt = {sheetid: 'Sheet ' + idx, headers: true};
		alasql.utils.extend(opt, opts);

		var dataLength = Object.keys(data).length;

		// Generate columns if they are not defined
		if ((!columns || columns.length == 0) && dataLength > 0) {
			columns = Object.keys(data[0]).map(function(columnid) {
				return {columnid: columnid};
			});
		}

		var cells = {};

		if (wb.SheetNames.indexOf(opt.sheetid) > -1) {
			cells = wb.Sheets[opt.sheetid];
		} else {
			wb.SheetNames.push(opt.sheetid);
			wb.Sheets[opt.sheetid] = {};
			cells = wb.Sheets[opt.sheetid];
		}

		var range = 'A1';
		if (opt.range) range = opt.range;

		var col0 = alasql.utils.xlscn(range.match(/[A-Z]+/)[0]);
		var row0 = +range.match(/[0-9]+/)[0] - 1;

		if (wb.Sheets[opt.sheetid]['!ref']) {
			var rangem = wb.Sheets[opt.sheetid]['!ref'];
			var colm = alasql.utils.xlscn(rangem.match(/[A-Z]+/)[0]);
			var rowm = +rangem.match(/[0-9]+/)[0] - 1;
		} else {
			var colm = 1,
				rowm = 1;
		}
		var colmax = Math.max(col0 + columns.length, colm);
		var rowmax = Math.max(row0 + dataLength + 2, rowm);

		//		console.log(col0,row0);
		var i = row0 + 1;

		wb.Sheets[opt.sheetid]['!ref'] = 'A1:' + alasql.utils.xlsnc(colmax) + rowmax;
		//		var i = 1;

		if (opt.headers) {
			columns.forEach(function(col, idx) {
				cells[alasql.utils.xlsnc(col0 + idx) + '' + i] = {v: col.columnid.trim()};
			});
			i++;
		}

		for (var j = 0; j < dataLength; j++) {
			columns.forEach(function(col, idx) {
				var cell = {v: data[j][col.columnid]};
				if (typeof data[j][col.columnid] == 'number') {
					cell.t = 'n';
				} else if (typeof data[j][col.columnid] == 'string') {
					cell.t = 's';
				} else if (typeof data[j][col.columnid] == 'boolean') {
					cell.t = 'b';
				} else if (typeof data[j][col.columnid] == 'object') {
					if (data[j][col.columnid] instanceof Date) {
						cell.t = 'd';
					}
				}
				cells[alasql.utils.xlsnc(col0 + idx) + '' + i] = cell;
			});
			i++;
		}
	}
991464
function onPage(output, page) {
    var options   = output.getOptions();
    var prefix    = options.get('prefix');

    var file      = page.getFile();

    var book      = output.getBook();
    var plugins   = output.getPlugins();
    var state     = output.getState();
    var resources = state.getResources();

    var engine = createTemplateEngine(output, page.getPath());

    // Output file path
    var filePath = fileToOutput(output, file.getPath());

    // Calcul relative path to the root
    var outputDirName = path.dirname(filePath);
    var basePath = LocationUtils.normalize(path.relative(outputDirName, './'));

    return Modifiers.modifyHTML(page, getModifiers(output, page))
    .then(function(resultPage) {
        // Generate the context
        var context = JSONUtils.encodeOutputWithPage(output, resultPage);
        context.plugins = {
            resources: Plugins.listResources(plugins, resources).toJS()
        };

        context.template = {
            getJSContext: function() {
                return {
                    page: omit(context.page, 'content'),
                    config: context.config,
                    file: context.file,
                    gitbook: context.gitbook,
                    basePath: basePath,
                    book: {
                        language: book.getLanguage()
                    }
                };
            }
        };

        // We should probabbly move it to "template" or a "site" namespace
        context.basePath = basePath;

        // Render the theme
        return Templating.renderFile(engine, prefix + '/page.html', context)

        // Write it to the disk
        .then(function(tplOut) {
            return writeFile(output, filePath, tplOut.getContent());
        });
    });
}
1268903
def open_book(self, for_writing=False) -> piecash.Book:
        
        filename = None

        # check if the file path is already a URL.
        file_url = urllib.parse.urlparse(self.filename)
        if file_url.scheme == "file" or file_url.scheme == "sqlite":
            filename = file_url.path[1:]
        else:
            filename = self.filename

        if not os.path.isfile(filename):
            log(WARN, "Database %s requested but not found. Creating an in-memory book.", filename)
            return self.create_book()

        access_type = "read/write" if for_writing else "readonly"
        log(INFO, "Using %s in %s mode.", filename, access_type)
        # file_path = path.relpath(self.filename)
        file_path = path.abspath(filename)

        if not for_writing:
            book = piecash.open_book(file_path, open_if_lock=True)
        else:
            book = piecash.open_book(file_path, open_if_lock=True, readonly=False)
        # book = create_book()
        return book
871184
def create_or_open_table_at index
      t = self[index]
      t = self[index] = Workbook::Table.new if t == nil
      t.sheet = self
      t
    end
56431
function loadForBook(book) {
    var logger = book.getLogger();

    // List the dependencies
    var requirements = listDepsForBook(book);

    // List all plugins installed in the book
    return findForBook(book)
    .then(function(installedMap) {
        var missing = [];
        var plugins = requirements.reduce(function(result, dep) {
            var name = dep.getName();
            var installed = installedMap.get(name);

            if (installed) {
                var deps = installedMap
                    .filter(function(plugin) {
                        return plugin.getParent() === name;
                    })
                    .toArray();

                result = result.concat(deps);
                result.push(installed);
            } else {
                missing.push(name);
            }

            return result;
        }, []);

        // Convert plugins list to a map
        plugins = Immutable.List(plugins)
            .map(function(plugin) {
                return [
                    plugin.getName(),
                    plugin
                ];
            });
        plugins = Immutable.OrderedMap(plugins);

        // Log state
        logger.info.ln(installedMap.size + ' plugins are installed');
        if (requirements.size != installedMap.size) {
            logger.info.ln(requirements.size + ' explicitly listed');
        }

        // Verify that all plugins are present
        if (missing.length > 0) {
            throw new Error('Couldn\'t locate plugins "' + missing.join(', ') + '", Run \'gitbook install\' to install plugins from registry.');
        }

        return Promise.map(plugins, function(plugin) {
            return loadPlugin(book, plugin);
        });
    });
}