<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import bottle

from bottle import SimpleTemplate, template
from bottle import route, run, request, redirect
from itertools import groupby

################
#  CONFIGURATION
#
#  These values can be overridden in a "local_settings.py" file so that
#  your local changes don't require merging into new versions of cony.
################

DEBUG = True
#  Stand-alone server running as a daemon on port 8080
SERVER_MODE = 'STANDALONE' # or 'WSGI', or 'CGI'
SERVER_PORT = 8080
SERVER_HOST = 'localhost'  # or '' to allow on all interfaces


##################
# Default commands
##################

def rich_help(help_argument = ''):
    '''Decorator for command functions to mark them as providing help,
    which causes the default cmd_help to link to them.  The optional
    `help_argument`, if set, is the argument passed to the linked command
    for help.'''
    def decorator(handler):
        handler.rich_help = help_argument
        return handler
    return decorator


def cmd_g(term):
    """Google search."""
    redirect('http://www.google.com/search?q=%s' % term)

cmd_fallback = cmd_g


def cmd_pypi(term):
    """Python package index search.

    If there is exact match, then redirects right to the package's page.
    """
    import urllib
    try:
        direct_url = 'http://pypi.python.org/pypi/%s/' % term
        result = urllib.urlopen(direct_url)
    except Exception, e:
        pass
    else:
        if result.code == 200:
            redirect(direct_url)

    redirect('http://pypi.python.org/pypi?:action=search&term=%s&submit=search' % term)


def cmd_p(term):
    """Python documentation search."""
    redirect('http://docs.python.org/search.html?q=%s&check_keywords=yes&area=default' % term)


def cmd_help(term):
    """Shows all available commands."""
    items = []

    # functions should be sorted by value
    # because we will group them lately
    functions = sorted(globals().items(), key=lambda x: x[1])

    commands = (
        (cmd, name)
        for name, cmd in functions
        if name != 'cmd_fallback' and name.startswith('cmd_') and callable(cmd)
    )

    commands = groupby(commands, lambda x: x[0])

    # "list" of (func, (cmd_example, cmd_exmpl, cmd_ex, ...)) tuples
    # names are sorted by length
    commands = (
        (cmd, sorted(map(lambda x: x[1][4:], values), key=lambda x: len(x), reverse=True))
        for cmd, values in commands
    )

    # and finally, sort by name
    commands = sorted(commands, key=lambda x: x[1])

    for cmd, names in commands:
        title = ', '.join(names)
        if cmd is cmd_fallback:
            title += ' (default)'
        has_rich_help = hasattr(cmd, 'rich_help')

        data = {
                'name' : names[0],
                'title' : title,
                'doc' : cmd.__doc__,
                'has_rich_help' : has_rich_help,
                }

        if has_rich_help:
            data['rich_help_cmd'] = names[0] + (
                    ' ' + rich_help if has_rich_help else '')
        items.append(data)

    return dict(items = items, title = u'Help — Cony')

########################
# Templates related part
########################

_TEMPLATES = dict( # {{{
    layout = """
<!DOCTYPE html>
<html>
    <head>
        <title>{{ title or u'Cony — Smart bookmarks' }}</title>
        <style>
        .container {
            margin: 2em 200px 2em 200px; background: #EEE;
            padding: 1em 1em 0.5em 1em;
        }
        .container header {
            border-bottom: 1px solid #BBB;
            margin-bottom: 2em;
        }
        .container dl.help dd {
            margin-bottom: 1em;
        }
        .container dl.help dt {
            font-weight: bold;
        }
        .container footer {
            border-top: 1px solid #BBB;
            text-align: center;
        }
        .container footer p {
            font-size: 0.75em;
            margin-top: 0.5em;
            margin-bottom: 0.2em;
        }
        </style>
    </head>
    <body>
        <div class="container">
            <header><h1>{{ title }}</h1></header>
            %include
            <footer>
                <p class="copyright">Opensource. By <a href="mailto:<EMAIL>"><NAME></a>. <a href="http://github.com/svetlyak40wt/cony/">Fork it</a> at the GitHub.</p>
                <p class="thanks">Idea was stolen from Facebook's <a href="https://github.com/facebook/bunny1/">bunny1</a>, many thanks to them.</p>
            </footer>
        </div>
    </body>
</html>
""",
    help = """
    <dl class="help">
    %for item in items:
        <dt>
        %if item['has_rich_help']:
            <a href="?s={{ item['rich_help_cmd'] }}">{{ item['title'] }}</a></dt>
        %else:
            {{ item['title'] }}
        %end
        </dt>
        <dd>{{ item['doc'] }}</dt>
    %end
    </dl>
%rebase layout title='Help — Cony'
"""
) # }}}


class VerySimpleTemplate(SimpleTemplate):
    """ A wrapper around Bottle templates, allows to
        define templates right in the same file keeping
        ability to use inheritance.
    """
    def __init__(self, source=None, name=None, **kwargs):
        if source is None and name is not None:
            source = _TEMPLATES[name]
        super(VerySimpleTemplate, self).__init__(
            source=source, name=name, **kwargs
        )


try:
    from local_settings import *
    if 'TEMPLATES' in locals():
        _TEMPLATES.update(TEMPLATES)
except ImportError:
    pass

<commit_msg>Replace inline 'if else' with readable code.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import bottle

from bottle import SimpleTemplate, template
from bottle import route, run, request, redirect
from itertools import groupby

################
#  CONFIGURATION
#
#  These values can be overridden in a "local_settings.py" file so that
#  your local changes don't require merging into new versions of cony.
################

DEBUG = True
#  Stand-alone server running as a daemon on port 8080
SERVER_MODE = 'STANDALONE' # or 'WSGI', or 'CGI'
SERVER_PORT = 8080
SERVER_HOST = 'localhost'  # or '' to allow on all interfaces


##################
# Default commands
##################

def rich_help(help_argument = ''):
    '''Decorator for command functions to mark them as providing help,
    which causes the default cmd_help to link to them.  The optional
    `help_argument`, if set, is the argument passed to the linked command
    for help.'''
    def decorator(handler):
        handler.rich_help = help_argument
        return handler
    return decorator


def cmd_g(term):
    """Google search."""
    redirect('http://www.google.com/search?q=%s' % term)

cmd_fallback = cmd_g


def cmd_pypi(term):
    """Python package index search.

    If there is exact match, then redirects right to the package's page.
    """
    import urllib
    try:
        direct_url = 'http://pypi.python.org/pypi/%s/' % term
        result = urllib.urlopen(direct_url)
    except Exception, e:
        pass
    else:
        if result.code == 200:
            redirect(direct_url)

    redirect('http://pypi.python.org/pypi?:action=search&term=%s&submit=search' % term)


def cmd_p(term):
    """Python documentation search."""
    redirect('http://docs.python.org/search.html?q=%s&check_keywords=yes&area=default' % term)


def cmd_help(term):
    """Shows all available commands."""
    items = []

    # functions should be sorted by value
    # because we will group them lately
    functions = sorted(globals().items(), key=lambda x: x[1])

    commands = (
        (cmd, name)
        for name, cmd in functions
        if name != 'cmd_fallback' and name.startswith('cmd_') and callable(cmd)
    )

    commands = groupby(commands, lambda x: x[0])

    # "list" of (func, (cmd_example, cmd_exmpl, cmd_ex, ...)) tuples
    # names are sorted by length
    commands = (
        (cmd, sorted(map(lambda x: x[1][4:], values), key=lambda x: len(x), reverse=True))
        for cmd, values in commands
    )

    # and finally, sort by name
    commands = sorted(commands, key=lambda x: x[1])

    for cmd, names in commands:
        title = ', '.join(names)
        if cmd is cmd_fallback:
            title += ' (default)'

        data = dict(
            name = names[0],
            title = title,
            doc = cmd.__doc__,
            rich_help = None,
        )

        rich_help = getattr(cmd, 'rich_help', None)
        if rich_help is not None:
            data['rich_help'] = names[0] + ' ' + rich_help

        items.append(data)

    return dict(items = items, title = u'Help — Cony')

########################
# Templates related part
########################

_TEMPLATES = dict( # {{{
    layout = """
<!DOCTYPE html>
<html>
    <head>
        <title>{{ title or u'Cony — Smart bookmarks' }}</title>
        <style>
        .container {
            margin: 2em 200px 2em 200px; background: #EEE;
            padding: 1em 1em 0.5em 1em;
        }
        .container header {
            border-bottom: 1px solid #BBB;
            margin-bottom: 2em;
        }
        .container dl.help dd {
            margin-bottom: 1em;
        }
        .container dl.help dt {
            font-weight: bold;
        }
        .container footer {
            border-top: 1px solid #BBB;
            text-align: center;
        }
        .container footer p {
            font-size: 0.75em;
            margin-top: 0.5em;
            margin-bottom: 0.2em;
        }
        </style>
    </head>
    <body>
        <div class="container">
            <header><h1>{{ title }}</h1></header>
            %include
            <footer>
                <p class="copyright">Opensource. By <a href="mailto:<EMAIL>"><NAME></a>. <a href="http://github.com/svetlyak40wt/cony/">Fork it</a> at the GitHub.</p>
                <p class="thanks">Idea was stolen from Facebook's <a href="https://github.com/facebook/bunny1/">bunny1</a>, many thanks to them.</p>
            </footer>
        </div>
    </body>
</html>
""",
    help = """
    <dl class="help">
    %for item in items:
        <dt>
        %if item['rich_help'] is None:
            {{ item['title'] }}
        %else:
            <a href="?s={{ item['rich_help'] }}">{{ item['title'] }}</a></dt>
        %end
        </dt>
        <dd>{{ item['doc'] }}</dt>
    %end
    </dl>
%rebase layout title='Help — Cony'
"""
) # }}}


class VerySimpleTemplate(SimpleTemplate):
    """ A wrapper around Bottle templates, allows to
        define templates right in the same file keeping
        ability to use inheritance.
    """
    def __init__(self, source=None, name=None, **kwargs):
        if source is None and name is not None:
            source = _TEMPLATES[name]
        super(VerySimpleTemplate, self).__init__(
            source=source, name=name, **kwargs
        )


try:
    from local_settings import *
    if 'TEMPLATES' in locals():
        _TEMPLATES.update(TEMPLATES)
except ImportError:
    pass


{'fraction_non_alphanumeric': 0.14810781377620474, 'fraction_numerical': 0.008893729013522098, 'mean_word_length': 2.2700296735905043, 'pattern_counts': {'":': 0, '<': 83, '<?xml version=': 0, '>': 83, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '267098', 'n_tokens_mistral': 3496, 'n_tokens_neox': 3314, 'n_words': 972}