Return a dash definitio of an HTML table for a Pandas dataframe
326733
def make_dash_table(df):
    '''  '''
    table = []
    for index, row in df.iterrows():
        html_row = []
        for i in range(len(row)):
            html_row.append(html.Td([row[i]]))
        table.append(html.Tr(html_row))
    return table
60811
def _repr_html_(self):
        
        # qtconsole doesn't report its line width, and also
        # behaves badly when outputting an HTML table
        # that doesn't fit the window, so disable it.
        # XXX: In IPython 3.x and above, the Qt console will not attempt to
        # display HTML, so this check can be removed when support for IPython 2.x
        # is no longer needed.

        if self._pandas and options.display.notebook_repr_widget:
            from .. import DataFrame
            from ..ui import show_df_widget
            show_df_widget(DataFrame(self._values, schema=self.schema))

        if self._pandas:
            return self._values._repr_html_()

        if in_qtconsole():
            # 'HTML output is disabled in QtConsole'
            return None

        if options.display.notebook_repr_html:
            max_rows = options.display.max_rows
            max_cols = options.display.max_columns
            show_dimensions = options.display.show_dimensions

            return self.to_html(max_rows=max_rows, max_cols=max_cols,
                                show_dimensions=show_dimensions,
                                notebook=True)
        else:
            return None
380388
def _preprocess(df):
    

    df = df.stack()

    df.index.rename(["id", "time"], inplace=True)  # .reset_index()
    df.name = "value"
    df = df.reset_index()

    return df
688925
def _get_processed_dataframe(self, dataframe):
        
        dataframe.index = pd.to_datetime(dataframe['epoch'], unit='s', utc=True)
        del dataframe['epoch']
        summary = dataframe.describe(percentiles=[.80, .90, .95]).transpose().loc['scriptrun_time']
        df_grp = dataframe.groupby(pd.TimeGrouper('{}S'.format(self.interval)))
        df_final = df_grp.apply(lambda x: x.describe(percentiles=[.80, .90, .95])['scriptrun_time'])

        return {
            "raw": dataframe.round(2),
            "compiled": df_final.round(2),
            "summary": summary.round(2)
        }
60726
def separator(self):
        
        cells = dict([(column, "-" * self.column_widths[column]) for column in self.columns])
        return ColorRow(self, **cells)
89337
def _fmt_tdelta(self, td):
        

        rel = dateutil.relativedelta.relativedelta(datetime.datetime.utcnow(), td)

        if rel.years:
            return "{} Years and {} Months Ago".format(rel.years, rel.months)
        if rel.months:
            return "{} Months Ago".format(rel.months)
        if rel.days:
            return "{} Days Ago".format(rel.days)
        if rel.hours:
            return "{} Hours Ago".format(rel.hours)

        return "{} Minutes Ago".format(rel.minutes)
1032727
def _pretty_time_delta(td):
    
    seconds = td.total_seconds()
    sign_string = '-' if seconds < 0 else ''
    seconds = abs(int(seconds))
    days, seconds = divmod(seconds, 86400)
    hours, seconds = divmod(seconds, 3600)
    minutes, seconds = divmod(seconds, 60)
    d = dict(sign=sign_string, days=days, hours=hours, minutes=minutes, seconds=seconds)
    if days > 0:
        return '{sign}{days}d{hours:02d}h{minutes:02d}m:{seconds:02d}s'.format(**d)
    elif hours > 0:
        return '{sign}{hours:02d}h{minutes:02d}m:{seconds:02d}s'.format(**d)
    elif minutes > 0:
        return '{sign}{minutes:02d}m:{seconds:02d}s'.format(**d)
    else:
        return '{sign}{seconds:02d}s'.format(**d)
216722
def from_df(data_frame):
        
        labels = data_frame.keys().tolist()
        data = data_frame.values.tolist()
        return SqlTable(labels, data, "{:.3f}", "\n")
743351
def add_table(self, dataframe, isStyled = False):
        """"""

        if isStyled :
            table_string = dataframe.render()
        else :
            table_string = dataframe.style.render()
            
        table_string = table_string.replace("\n", "").replace("<table", """<table class = "table table-sm table-hover" """).replace("<thead>", """<thead class="thead-inverse">""")
        self.table = table_string
289322
function ( i )
	{
		var
			that = this,
			column = this.s.dt.aoColumns[i],
			dt = this.s.dt;

		var title = this.s.fnLabel===null ?
			column.sTitle :
			this.s.fnLabel( i, column.sTitle, column.nTh );

		return $(
				'<li '+(dt.bJUI ? 'class="ui-button ui-state-default"' : '')+'>'+
					'<label>'+
						'<input type="checkbox" />'+
						'<span>'+title+'</span>'+
					'</label>'+
				'</li>'
			)
			.click( function (e) {
				var showHide = !$('input', this).is(":checked");
				if (  e.target.nodeName.toLowerCase() !== "li" )
				{
					if ( e.target.nodeName.toLowerCase() == "input" || that.s.fnStateChange === null )
					{
						showHide = ! showHide;
					}
				}

				/* Need to consider the case where the initialiser created more than one table - change the
				 * API index that DataTables is using
				 */
				var oldIndex = $.fn.dataTableExt.iApiIndex;
				$.fn.dataTableExt.iApiIndex = that._fnDataTablesApiIndex.call(that);

				// Optimisation for server-side processing when scrolling - don't do a full redraw
				if ( dt.oFeatures.bServerSide )
				{
					that.s.dt.oInstance.fnSetColumnVis( i, showHide, false );
					that.s.dt.oInstance.fnAdjustColumnSizing( false );
					if (dt.oScroll.sX !== "" || dt.oScroll.sY !== "" )
					{
						that.s.dt.oInstance.oApi._fnScrollDraw( that.s.dt );
					}
					that._fnDrawCallback();
				}
				else
				{
					that.s.dt.oInstance.fnSetColumnVis( i, showHide );
				}

				$.fn.dataTableExt.iApiIndex = oldIndex; /* Restore */

				if ( that.s.fnStateChange !== null )
				{
					if ( e.target.nodeName.toLowerCase() == "span" )
					{
						e.preventDefault();
					}
					that.s.fnStateChange.call( that, i, showHide );
				}
			} )[0];
	}
646004
def nth(self, n, *args, **kwargs):
        """"""
        # TODO: Stop collecting the entire frame for each key.
        self._prep_pandas_groupby()
        myargs = self._myargs
        mykwargs = self._mykwargs
        nthRDD = self._regroup_mergedRDD().mapValues(
            lambda r: r.nth(
                n, *args, **kwargs)).values()
        return DataFrame.fromDataFrameRDD(nthRDD, self.sql_ctx)
1345452
function dashCase(str) {
        var newStr = '';

        for (var i = 0, len = str.length; i < len; i++) {
            if (str[i] === str[i].toUpperCase()) { newStr += '-'; }
            newStr += str[i].toLowerCase();
        }

        return newStr;
    }
1161798
def _make_df(rows):
    """"""

    # Make DataFrame
    df = pd.DataFrame(rows).set_index('ts')

    # TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835
    for column in df.columns:
        if(df[column].dtype == 'timedelta64[ns]'):
            print('Converting timedelta column {:s}...'.format(column))
            df[column] = df[column].astype(str)
    return df
5903
def _repr_html_(self):
        """"""
        out = "<table class='taqltable' style='overflow-x:auto'>\n"

        # Print column names (not if they are all auto-generated)
        if not(all([colname[:4] == "Col_" for colname in self.colnames()])):
            out += "<tr>"
            for colname in self.colnames():
                out += "<th><b>"+colname+"</b></th>"
            out += "</tr>"

        cropped = False
        rowcount = 0
        for row in self:
            rowout = _format_row(row, self.colnames(), self)
            rowcount += 1
            out += rowout
            if "\n" in rowout:  # Double space after multiline rows
                out += "\n"
            out += "\n"
            if rowcount >= 20:
                cropped = True
                break

        if out[-2:] == "\n\n":
            out = out[:-1]

        out += "</table>"

        if cropped:
            out += ("<p style='text-align:center'>(" +
                    str(self.nrows()-20)+" more rows)</p>\n")

        return out
264017
function dashProperCase(str) {
        if ( !str.length ) {
            return str;
        }
        return str.split('-').map(function (piece) {
            if ( piece.length ) {
                return piece.substring(0, 1).toUpperCase() + piece.substring(1);
            }
            return piece;
        }).join('-');
    }
671976
def _marker_line(self):
        # type: () -> str
        
        output = ''
        for col in sorted(self.col_widths):
            line = self.COLUMN_MARK + (self.DASH * (self.col_widths[col] + self.PADDING * 2))
            output += line
        output += self.COLUMN_MARK + '\n'

        return output
907618
def to_html(self, show_mean=None, sortable=None, colorize=True, *args,
                **kwargs):
        """"""
        if show_mean is None:
            show_mean = self.show_mean
        if sortable is None:
            sortable = self.sortable
        df = self.copy()
        if show_mean:
            df.insert(0, 'Mean', None)
            df.loc[:, 'Mean'] = ['%.3f' % self[m].mean() for m in self.models]
        html = df.to_html(*args, **kwargs)  # Pandas method
        html, table_id = self.annotate(df, html, show_mean, colorize)
        if sortable:
            self.dynamify(table_id)
        return html