def ad_hoc_queries() -> List[Dict[(str, str)]]:

    def get_page(query: Composable, cols: Sequence[str], title: str, totals_columns: Sequence[int]=[]) -> Dict[(str, str)]:
        cursor = connection.cursor()
        cursor.execute(query)
        rows = cursor.fetchall()
        rows = list(map(list, rows))
        cursor.close()

        def fix_rows(i: int, fixup_func: Union[(Callable[([Realm], mark_safe)], Callable[([datetime], str)])]) -> None:
            for row in rows:
                row[i] = fixup_func(row[i])
        total_row = []
        for (i, col) in enumerate(cols):
            if (col == 'Realm'):
                fix_rows(i, realm_activity_link)
            elif (col in ['Last time', 'Last visit']):
                fix_rows(i, format_date_for_activity_reports)
            elif (col == 'Hostname'):
                for row in rows:
                    row[i] = remote_installation_stats_link(row[0], row[i])
            if (len(totals_columns) > 0):
                if (i == 0):
                    total_row.append('Total')
                elif (i in totals_columns):
                    total_row.append(str(sum((row[i] for row in rows if (row[i] is not None)))))
                else:
                    total_row.append('')
        if (len(totals_columns) > 0):
            rows.insert(0, total_row)
        content = make_table(title, cols, rows)
        return dict(content=content, title=title)
    pages = []
    for mobile_type in ['Android', 'ZulipiOS']:
        title = f'{mobile_type} usage'
        query = SQL("\n            select\n                realm.string_id,\n                up.id user_id,\n                client.name,\n                sum(count) as hits,\n                max(last_visit) as last_time\n            from zerver_useractivity ua\n            join zerver_client client on client.id = ua.client_id\n            join zerver_userprofile up on up.id = ua.user_profile_id\n            join zerver_realm realm on realm.id = up.realm_id\n            where\n                client.name like {mobile_type}\n            group by string_id, up.id, client.name\n            having max(last_visit) > now() - interval '2 week'\n            order by string_id, up.id, client.name\n        ").format(mobile_type=Literal(mobile_type))
        cols = ['Realm', 'User id', 'Name', 'Hits', 'Last time']
        pages.append(get_page(query, cols, title))
    title = 'Desktop users'
    query = SQL("\n        select\n            realm.string_id,\n            client.name,\n            sum(count) as hits,\n            max(last_visit) as last_time\n        from zerver_useractivity ua\n        join zerver_client client on client.id = ua.client_id\n        join zerver_userprofile up on up.id = ua.user_profile_id\n        join zerver_realm realm on realm.id = up.realm_id\n        where\n            client.name like 'desktop%%'\n        group by string_id, client.name\n        having max(last_visit) > now() - interval '2 week'\n        order by string_id, client.name\n    ")
    cols = ['Realm', 'Client', 'Hits', 'Last time']
    pages.append(get_page(query, cols, title))
    title = 'Integrations by realm'
    query = SQL("\n        select\n            realm.string_id,\n            case\n                when query like '%%external%%' then split_part(query, '/', 5)\n                else client.name\n            end client_name,\n            sum(count) as hits,\n            max(last_visit) as last_time\n        from zerver_useractivity ua\n        join zerver_client client on client.id = ua.client_id\n        join zerver_userprofile up on up.id = ua.user_profile_id\n        join zerver_realm realm on realm.id = up.realm_id\n        where\n            (query in ('send_message_backend', '/api/v1/send_message')\n            and client.name not in ('Android', 'ZulipiOS')\n            and client.name not like 'test: Zulip%%'\n            )\n        or\n            query like '%%external%%'\n        group by string_id, client_name\n        having max(last_visit) > now() - interval '2 week'\n        order by string_id, client_name\n    ")
    cols = ['Realm', 'Client', 'Hits', 'Last time']
    pages.append(get_page(query, cols, title))
    title = 'Integrations by client'
    query = SQL("\n        select\n            case\n                when query like '%%external%%' then split_part(query, '/', 5)\n                else client.name\n            end client_name,\n            realm.string_id,\n            sum(count) as hits,\n            max(last_visit) as last_time\n        from zerver_useractivity ua\n        join zerver_client client on client.id = ua.client_id\n        join zerver_userprofile up on up.id = ua.user_profile_id\n        join zerver_realm realm on realm.id = up.realm_id\n        where\n            (query in ('send_message_backend', '/api/v1/send_message')\n            and client.name not in ('Android', 'ZulipiOS')\n            and client.name not like 'test: Zulip%%'\n            )\n        or\n            query like '%%external%%'\n        group by client_name, string_id\n        having max(last_visit) > now() - interval '2 week'\n        order by client_name, string_id\n    ")
    cols = ['Client', 'Realm', 'Hits', 'Last time']
    pages.append(get_page(query, cols, title))
    title = 'Remote Zulip servers'
    query = SQL("\n        with icount as (\n            select\n                server_id,\n                max(value) as max_value,\n                max(end_time) as max_end_time\n            from zilencer_remoteinstallationcount\n            where\n                property='active_users:is_bot:day'\n                and subgroup='false'\n            group by server_id\n            ),\n        remote_push_devices as (\n            select server_id, count(distinct(user_id)) as push_user_count from zilencer_remotepushdevicetoken\n            group by server_id\n        )\n        select\n            rserver.id,\n            rserver.hostname,\n            rserver.contact_email,\n            max_value,\n            push_user_count,\n            max_end_time\n        from zilencer_remotezulipserver rserver\n        left join icount on icount.server_id = rserver.id\n        left join remote_push_devices on remote_push_devices.server_id = rserver.id\n        order by max_value DESC NULLS LAST, push_user_count DESC NULLS LAST\n    ")
    cols = ['ID', 'Hostname', 'Contact email', 'Analytics users', 'Mobile users', 'Last update time']
    pages.append(get_page(query, cols, title, totals_columns=[3, 4]))
    return pages
def ad_hoc_queries() -> List[Dict[(str, str)]]:

    def get_page(query: Composable, cols: Sequence[str], title: str, totals_columns: Sequence[int]=[]) -> Dict[(str, str)]:
        cursor = connection.cursor()
        cursor.execute(query)
        rows = cursor.fetchall()
        rows = list(map(list, rows))
        cursor.close()

        def fix_rows(i: int, fixup_func: Union[(Callable[([Realm], mark_safe)], Callable[([datetime], str)])]) -> None:
            for row in rows:
                row[i] = fixup_func(row[i])
        total_row = []
        for (i, col) in enumerate(cols):
            if (col == 'Realm'):
                fix_rows(i, realm_activity_link)
            elif (col in ['Last time', 'Last visit']):
                fix_rows(i, format_date_for_activity_reports)
            elif (col == 'Hostname'):
                for row in rows:
                    row[i] = remote_installation_stats_link(row[0], row[i])
            if (len(totals_columns) > 0):
                if (i == 0):
                    total_row.append('Total')
                elif (i in totals_columns):
                    total_row.append(str(sum((row[i] for row in rows if (row[i] is not None)))))
                else:
                    total_row.append()
        if (len(totals_columns) > 0):
            rows.insert(0, total_row)
        content = make_table(title, cols, rows)
        return dict(content=content, title=title)
    pages = []
    for mobile_type in ['Android', 'ZulipiOS']:
        title = f'{mobile_type} usage'
        query = SQL("\n            select\n                realm.string_id,\n                up.id user_id,\n                client.name,\n                sum(count) as hits,\n                max(last_visit) as last_time\n            from zerver_useractivity ua\n            join zerver_client client on client.id = ua.client_id\n            join zerver_userprofile up on up.id = ua.user_profile_id\n            join zerver_realm realm on realm.id = up.realm_id\n            where\n                client.name like {mobile_type}\n            group by string_id, up.id, client.name\n            having max(last_visit) > now() - interval '2 week'\n            order by string_id, up.id, client.name\n        ").format(mobile_type=Literal(mobile_type))
        cols = ['Realm', 'User id', 'Name', 'Hits', 'Last time']
        pages.append(get_page(query, cols, title))
    title = 'Desktop users'
    query = SQL("\n        select\n            realm.string_id,\n            client.name,\n            sum(count) as hits,\n            max(last_visit) as last_time\n        from zerver_useractivity ua\n        join zerver_client client on client.id = ua.client_id\n        join zerver_userprofile up on up.id = ua.user_profile_id\n        join zerver_realm realm on realm.id = up.realm_id\n        where\n            client.name like 'desktop%%'\n        group by string_id, client.name\n        having max(last_visit) > now() - interval '2 week'\n        order by string_id, client.name\n    ")
    cols = ['Realm', 'Client', 'Hits', 'Last time']
    pages.append(get_page(query, cols, title))
    title = 'Integrations by realm'
    query = SQL("\n        select\n            realm.string_id,\n            case\n                when query like '%%external%%' then split_part(query, '/', 5)\n                else client.name\n            end client_name,\n            sum(count) as hits,\n            max(last_visit) as last_time\n        from zerver_useractivity ua\n        join zerver_client client on client.id = ua.client_id\n        join zerver_userprofile up on up.id = ua.user_profile_id\n        join zerver_realm realm on realm.id = up.realm_id\n        where\n            (query in ('send_message_backend', '/api/v1/send_message')\n            and client.name not in ('Android', 'ZulipiOS')\n            and client.name not like 'test: Zulip%%'\n            )\n        or\n            query like '%%external%%'\n        group by string_id, client_name\n        having max(last_visit) > now() - interval '2 week'\n        order by string_id, client_name\n    ")
    cols = ['Realm', 'Client', 'Hits', 'Last time']
    pages.append(get_page(query, cols, title))
    title = 'Integrations by client'
    query = SQL("\n        select\n            case\n                when query like '%%external%%' then split_part(query, '/', 5)\n                else client.name\n            end client_name,\n            realm.string_id,\n            sum(count) as hits,\n            max(last_visit) as last_time\n        from zerver_useractivity ua\n        join zerver_client client on client.id = ua.client_id\n        join zerver_userprofile up on up.id = ua.user_profile_id\n        join zerver_realm realm on realm.id = up.realm_id\n        where\n            (query in ('send_message_backend', '/api/v1/send_message')\n            and client.name not in ('Android', 'ZulipiOS')\n            and client.name not like 'test: Zulip%%'\n            )\n        or\n            query like '%%external%%'\n        group by client_name, string_id\n        having max(last_visit) > now() - interval '2 week'\n        order by client_name, string_id\n    ")
    cols = ['Client', 'Realm', 'Hits', 'Last time']
    pages.append(get_page(query, cols, title))
    title = 'Remote Zulip servers'
    query = SQL("\n        with icount as (\n            select\n                server_id,\n                max(value) as max_value,\n                max(end_time) as max_end_time\n            from zilencer_remoteinstallationcount\n            where\n                property='active_users:is_bot:day'\n                and subgroup='false'\n            group by server_id\n            ),\n        remote_push_devices as (\n            select server_id, count(distinct(user_id)) as push_user_count from zilencer_remotepushdevicetoken\n            group by server_id\n        )\n        select\n            rserver.id,\n            rserver.hostname,\n            rserver.contact_email,\n            max_value,\n            push_user_count,\n            max_end_time\n        from zilencer_remotezulipserver rserver\n        left join icount on icount.server_id = rserver.id\n        left join remote_push_devices on remote_push_devices.server_id = rserver.id\n        order by max_value DESC NULLS LAST, push_user_count DESC NULLS LAST\n    ")
    cols = ['ID', 'Hostname', 'Contact email', 'Analytics users', 'Mobile users', 'Last update time']
    pages.append(get_page(query, cols, title, totals_columns=[3, 4]))
    return pages