'Queries the DB for user jobs in error. Filters out monitor jobs.'

@web.expose
def errors_per_tool(self, trans, **kwd):

    message = ''
    PageSpec = namedtuple('PageSpec', ['entries', 'offset', 'page', 'pages_found'])
    params = util.Params(kwd)
    monitor_email = params.get('monitor_email', 'monitor@bx.psu.edu')
    specs = sorter('tool_id', kwd)
    sort_id = specs.sort_id
    order = specs.order
    arrow = specs.arrow
    _order = specs.exc_order
    time_period = kwd.get('spark_time')
    (time_period, _time_period) = get_spark_time(time_period)
    spark_limit = 30
    offset = 0
    limit = 10
    if ('entries' in kwd):
        entries = int(kwd.get('entries'))
    else:
        entries = 10
    limit = (entries * 4)
    if ('offset' in kwd):
        offset = int(kwd.get('offset'))
    else:
        offset = 0
    if ('page' in kwd):
        page = int(kwd.get('page'))
    else:
        page = 1
    monitor_user_id = get_monitor_id(trans, monitor_email)
    jobs_in_error_per_tool = sa.select((model.Job.table.c.tool_id.label('tool_id'), sa.func.count(model.Job.table.c.id).label('total_jobs')), whereclause=sa.and_((model.Job.table.c.state == 'error'), (model.Job.table.c.user_id != monitor_user_id)), from_obj=[model.Job.table], group_by=['tool_id'], order_by=[_order], offset=offset, limit=limit)
    all_jobs_per_tool_errors = sa.select((self.select_day(model.Job.table.c.create_time).label('date'), model.Job.table.c.id.label('id'), model.Job.table.c.tool_id.label('tool_id')), whereclause=sa.and_((model.Job.table.c.state == 'error'), (model.Job.table.c.user_id != monitor_user_id)), from_obj=[model.Job.table])
    currday = date.today()
    trends = dict()
    for job in all_jobs_per_tool_errors.execute():
        curr_tool = re.sub('\\W+', '', str(job.tool_id))
        try:
            day = (currday - job.date)
        except TypeError:
            day = (currday - datetime.date(job.date))
        day = day.days
        container = floor((day / _time_period))
        container = int(container)
        try:
            if (container < spark_limit):
                trends[curr_tool][container] += 1
        except KeyError:
            trends[curr_tool] = ([0] * spark_limit)
            if (day < spark_limit):
                trends[curr_tool][container] += 1
    jobs = []
    for row in jobs_in_error_per_tool.execute():
        jobs.append((row.total_jobs, row.tool_id))
    pages_found = ceil((len(jobs) / float(entries)))
    page_specs = PageSpec(entries, offset, page, pages_found)
    return trans.fill_template('/webapps/reports/jobs_errors_per_tool.mako', order=order, arrow=arrow, sort_id=sort_id, spark_limit=spark_limit, time_period=time_period, trends=trends, jobs=jobs, message=message, is_user_jobs_only=monitor_user_id, page_specs=page_specs)
