<commit_before># standard pylons controller imports
import os
import logging
log = logging.getLogger(__name__)

from pylons import request, response, session
try:
    from pylons import tmpl_context as c
except:
    from pylons import c
from pylons.controllers.util import redirect_to, url_for
import pylons.controllers.util as h

from sqlalchemy.orm import class_mapper
from formalchemy import *
from formalchemy.i18n import _, get_translator
from formalchemy.fields import _pk
from formalchemy.templates import TempitaEngine
from formalchemy.tempita import Template

__all__ = ['FormAlchemyAdminController']

# misc labels
_('Edit')
_('Delete')
_('Cancel')

# templates

template_dir = os.path.dirname(__file__)

def get_file_template(name, from_template):
    path = os.path.join(template_dir, '%s.tmpl' % name)
    return from_template.__class__.from_filename(
        path, namespace=from_template.namespace,
        get_template=from_template.get_template)

class TemplateEngine(TempitaEngine):
    directories = [template_dir]
    _templates = ['base', 'admin_index', 'admin_list', 'admin_edit']

engine = TemplateEngine(default_inherit='base', get_template=get_file_template)

def flash(msg):
    """Add 'msg' to the users flashest list in the users session"""
    flashes = session.setdefault('_admin_flashes', [])
    flashes.append(msg)
    session.save()

def get_forms(controller, model_module, forms):
    """scan model and forms"""
    if forms is not None:
        model_fieldsets = dict((form.model.__class__.__name__, form)
                               for form in forms.__dict__.itervalues()
                               if isinstance(form, FieldSet))
        model_grids = dict((form.model.__class__.__name__, form)
                           for form in forms.__dict__.itervalues()
                           if isinstance(form, Grid))
    else:
        model_fieldsets = dict()
        model_grids = dict()

    # generate missing forms, grids
    for key, obj in model_module.__dict__.iteritems():
        try:
            class_mapper(obj)
        except:
            continue
        if not isinstance(obj, type):
            continue
        if key not in model_fieldsets:
            model_fieldsets[key] = FieldSet(obj)
        if key not in model_grids:
            model_grids[key] = Grid(obj)
    # add Edit + Delete link to grids
    for modelname, grid in model_grids.iteritems():
        def get_linker(action, modelname=modelname):
            _ = get_translator().gettext
            label = action == 'edit' and _('edit') or _('delete')
            return lambda item: '%s' % (
                                h.url_for(modelname=modelname,
                                action=action,
                                id=_pk(item)),
                                label,
                                action,
                                label)
        old_include = grid.render_fields.values() # grab this now, or .add will change it if user didn't call configure yet
        for action in ['edit', 'delete']:
            grid.add(Field(action, types.String, get_linker(action)))
        grid.configure(include=old_include + [grid.edit, grid.delete], readonly=True)

    return {'_model_fieldsets':model_fieldsets, '_model_grids':model_grids}

class AdminController(object):
    """Base class to generate administration interface in Pylons"""
    _custom_css = _custom_js = ''

    def index(self):
        """List model types"""
        modelnames = sorted(self._model_grids.keys())
        return engine('admin_index', c=c, modelname=None,
                                     modelnames=modelnames,
                                     custom_css = self._custom_css,
                                     custom_js = self._custom_js)

    def list(self, modelname):
        """List instances of a model type"""
        grid = self._model_grids[modelname]
        S = self.Session()
        instances = S.query(grid.model.__class__).all()
        c.grid = grid.bind(instances)
        c.modelname = modelname
        return engine('admin_list', c=c,
                                    modelname=modelname,
                                    custom_css = self._custom_css,
                                    custom_js = self._custom_js)

    def edit(self, modelname, id=None):
        """Edit (or create, if `id` is None) an instance of the given model type"""
        F_ = get_translator().gettext
        fs = self._model_fieldsets[modelname]
        S = self.Session()
        if id:
            instance = S.query(fs.model.__class__).get(id)
            c.fs = fs.bind(instance)
            title = 'Edit'
        else:
            c.fs = fs.bind(fs.model.__class__, session=S)
            title = 'New object'
        if request.method == 'POST':
            c.fs = c.fs.bind(data=request.params)
            log.debug('saving %s w/ %s' % (c.fs.model.id, request.POST))
            if c.fs.validate():
                c.fs.sync()
                S.flush()
                if not id:
                    # needed if the object does not exist in db
                    S.save(c.fs.model)
                    message = _('Created %s %s')
                else:
                    S.refresh(c.fs.model)
                    message = _('Modified %s %s')
                S.commit()
                message = F_(message) % (modelname.encode('utf-8', 'ignore'),
                                         _pk(c.fs.model))
                flash(message)
                redirect_to(url_for(modelname=modelname,
                                    action='list', id=None))
        return engine('admin_edit', c=c,
                                    action=title, id=id,
                                    modelname=modelname,
                                    custom_css = self._custom_css,
                                    custom_js = self._custom_js)

    def delete(self, modelname, id):
        """Delete an instance of the given model type"""
        F_ = get_translator().gettext
        fs = self._model_fieldsets[modelname]
        S = self.Session()
        instance = S.query(fs.model.__class__).get(id)
        key = _pk(instance)
        S.delete(instance)
        S.commit()
        message = F_(_('Deleted %s %s')) % (modelname.encode('utf-8', 'ignore'),
                                            key)
        flash(message)
        redirect_to(url_for(modelname=modelname, action='list', id=None))

    def static(self, id):
        filename = os.path.basename(id)
        if filename not in os.listdir(template_dir):
            raise IOError('Invalid filename: %s' % filename)
        filepath = os.path.join(template_dir, filename)
        if filename.endswith('.css'):
            response.headers['Content-type'] = "text/css"
        elif filename.endswith('.js'):
            response.headers['Content-type'] = "text/javascript"
        elif filename.endswith('.png'):
            response.headers['Content-type'] = "image/png"
        else:
            raise IOError('Invalid filename: %s' % filename)
        fd = open(filepath, 'rb')
        data = fd.read()
        fd.close()
        return data

def FormAlchemyAdminController(cls):
    """
    Generate a controller that is a subclass of `AdminController`
    and the Pylons BaseController `cls`
    """
    controller = cls.__name__.lower().split('controller')[0]
    kwargs = get_forms(controller, cls.model, cls.forms)
    log.info('creating admin controller with args %s' % kwargs)
    return type(cls.__name__, (cls, AdminController), kwargs)
<commit_msg>don't call save() for exlir models.  fixes #76<commit_after># standard pylons controller imports
import os
import logging
log = logging.getLogger(__name__)

from pylons import request, response, session
try:
    from pylons import tmpl_context as c
except ImportError:
    from pylons import c
try:
    import elixir
    has_elixir = True
except ImportError:
    has_elixir = False

from pylons.controllers.util import redirect_to, url_for
import pylons.controllers.util as h

from sqlalchemy.orm import class_mapper
from formalchemy import *
from formalchemy.i18n import _, get_translator
from formalchemy.fields import _pk
from formalchemy.templates import TempitaEngine
from formalchemy.tempita import Template

__all__ = ['FormAlchemyAdminController']

# misc labels
_('Edit')
_('Delete')
_('Cancel')

# templates

template_dir = os.path.dirname(__file__)

def get_file_template(name, from_template):
    path = os.path.join(template_dir, '%s.tmpl' % name)
    return from_template.__class__.from_filename(
        path, namespace=from_template.namespace,
        get_template=from_template.get_template)

class TemplateEngine(TempitaEngine):
    directories = [template_dir]
    _templates = ['base', 'admin_index', 'admin_list', 'admin_edit']

engine = TemplateEngine(default_inherit='base', get_template=get_file_template)

def flash(msg):
    """Add 'msg' to the users flashest list in the users session"""
    flashes = session.setdefault('_admin_flashes', [])
    flashes.append(msg)
    session.save()

def get_forms(controller, model_module, forms):
    """scan model and forms"""
    if forms is not None:
        model_fieldsets = dict((form.model.__class__.__name__, form)
                               for form in forms.__dict__.itervalues()
                               if isinstance(form, FieldSet))
        model_grids = dict((form.model.__class__.__name__, form)
                           for form in forms.__dict__.itervalues()
                           if isinstance(form, Grid))
    else:
        model_fieldsets = dict()
        model_grids = dict()

    # generate missing forms, grids
    for key, obj in model_module.__dict__.iteritems():
        try:
            class_mapper(obj)
        except:
            continue
        if not isinstance(obj, type):
            continue
        if key not in model_fieldsets:
            model_fieldsets[key] = FieldSet(obj)
        if key not in model_grids:
            model_grids[key] = Grid(obj)
    # add Edit + Delete link to grids
    for modelname, grid in model_grids.iteritems():
        def get_linker(action, modelname=modelname):
            _ = get_translator().gettext
            label = action == 'edit' and _('edit') or _('delete')
            return lambda item: '%s' % (
                                h.url_for(modelname=modelname,
                                action=action,
                                id=_pk(item)),
                                label,
                                action,
                                label)
        old_include = grid.render_fields.values() # grab this now, or .add will change it if user didn't call configure yet
        for action in ['edit', 'delete']:
            grid.add(Field(action, types.String, get_linker(action)))
        grid.configure(include=old_include + [grid.edit, grid.delete], readonly=True)

    return {'_model_fieldsets':model_fieldsets, '_model_grids':model_grids}

class AdminController(object):
    """Base class to generate administration interface in Pylons"""
    _custom_css = _custom_js = ''

    def index(self):
        """List model types"""
        modelnames = sorted(self._model_grids.keys())
        return engine('admin_index', c=c, modelname=None,
                                     modelnames=modelnames,
                                     custom_css = self._custom_css,
                                     custom_js = self._custom_js)

    def list(self, modelname):
        """List instances of a model type"""
        grid = self._model_grids[modelname]
        S = self.Session()
        instances = S.query(grid.model.__class__).all()
        c.grid = grid.bind(instances)
        c.modelname = modelname
        return engine('admin_list', c=c,
                                    modelname=modelname,
                                    custom_css = self._custom_css,
                                    custom_js = self._custom_js)

    def edit(self, modelname, id=None):
        """Edit (or create, if `id` is None) an instance of the given model type"""
        F_ = get_translator().gettext
        fs = self._model_fieldsets[modelname]
        S = self.Session()
        if id:
            instance = S.query(fs.model.__class__).get(id)
            c.fs = fs.bind(instance)
            title = 'Edit'
        else:
            c.fs = fs.bind(fs.model.__class__, session=S)
            title = 'New object'
        if request.method == 'POST':
            c.fs = c.fs.bind(data=request.params)
            log.debug('saving %s w/ %s' % (c.fs.model.id, request.POST))
            if c.fs.validate():
                c.fs.sync()
                S.flush()
                if not id:
                    # needed if the object does not exist in db
                    if not has_elixir or not isinstance(c.fs.model, elixir.Entity):
                        S.save(c.fs.model)
                    message = _('Created %s %s')
                else:
                    S.refresh(c.fs.model)
                    message = _('Modified %s %s')
                S.commit()
                message = F_(message) % (modelname.encode('utf-8', 'ignore'),
                                         _pk(c.fs.model))
                flash(message)
                redirect_to(url_for(modelname=modelname,
                                    action='list', id=None))
        return engine('admin_edit', c=c,
                                    action=title, id=id,
                                    modelname=modelname,
                                    custom_css = self._custom_css,
                                    custom_js = self._custom_js)

    def delete(self, modelname, id):
        """Delete an instance of the given model type"""
        F_ = get_translator().gettext
        fs = self._model_fieldsets[modelname]
        S = self.Session()
        instance = S.query(fs.model.__class__).get(id)
        key = _pk(instance)
        S.delete(instance)
        S.commit()
        message = F_(_('Deleted %s %s')) % (modelname.encode('utf-8', 'ignore'),
                                            key)
        flash(message)
        redirect_to(url_for(modelname=modelname, action='list', id=None))

    def static(self, id):
        filename = os.path.basename(id)
        if filename not in os.listdir(template_dir):
            raise IOError('Invalid filename: %s' % filename)
        filepath = os.path.join(template_dir, filename)
        if filename.endswith('.css'):
            response.headers['Content-type'] = "text/css"
        elif filename.endswith('.js'):
            response.headers['Content-type'] = "text/javascript"
        elif filename.endswith('.png'):
            response.headers['Content-type'] = "image/png"
        else:
            raise IOError('Invalid filename: %s' % filename)
        fd = open(filepath, 'rb')
        data = fd.read()
        fd.close()
        return data

def FormAlchemyAdminController(cls):
    """
    Generate a controller that is a subclass of `AdminController`
    and the Pylons BaseController `cls`
    """
    controller = cls.__name__.lower().split('controller')[0]
    kwargs = get_forms(controller, cls.model, cls.forms)
    log.info('creating admin controller with args %s' % kwargs)
    return type(cls.__name__, (cls, AdminController), kwargs)
<|endoftext|>


<commit_before>#!/usr/bin/env python

import sys
import os
import git_visitor_base
from subprocess import check_output

def puaq():
    print("Usage: %s base_path." % os.path.basename(__file__))
    sys.exit(1)

def run_visitor_push(list_repos):
    for r in list_repos:
        out = check_output(["git", "--git-dir=%s" % r, "--work-tree=%s" % os.path.dirname(r), "push"])

if __name__ == "__main__":

    if len(sys.argv) < 2:
        puaq()

    basepath = sys.argv[1]
    if not os.path.exists(basepath):
        print("%s does not exist. Aborting." % basepath)
        sys.exit(1)

    repos = git_visitor_base.make_repo_list(basepath)
    run_visitor_push(repos)

<commit_msg>impl prototype git visitor push<commit_after>#!/usr/bin/env python

import sys
import os
import git_visitor_base
from subprocess import check_output

def puaq():
    print("Usage: %s base_path." % os.path.basename(__file__))
    sys.exit(1)

def run_visitor_push(list_repos):
    for rp in list_repos:
        remotes = git_visitor_base.get_remotes(rp)
        for rm in remotes:
            out = check_output(["git", "--git-dir=%s" % rp, "--work-tree=%s" % os.path.dirname(rp), "push", rm])

if __name__ == "__main__":

    if len(sys.argv) < 2:
        puaq()

    basepath = sys.argv[1]
    if not os.path.exists(basepath):
        print("%s does not exist. Aborting." % basepath)
        sys.exit(1)

    repos = git_visitor_base.make_repo_list(basepath)
    run_visitor_push(repos)

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# pyramid_auth documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 15 23:28:35 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'pyramid_auth'
copyright = u'2013, Aurélien Matouillot'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.2.1'
# The full version, including alpha/beta/rc tags.
release = '0.2.1'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'sphinxdoc'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'pyramid_authdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
  ('index', 'pyramid_auth.tex', u'pyramid\\_auth Documentation',
   u'Aurélien Matouillot', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'pyramid_auth', u'pyramid_auth Documentation',
     [u'Aurélien Matouillot'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'pyramid_auth', u'pyramid_auth Documentation',
   u'Aurélien Matouillot', 'pyramid_auth', 'One line description of project.',
   'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
<commit_msg>Use pyramid theme<commit_after># -*- coding: utf-8 -*-
#
# pyramid_auth documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 15 23:28:35 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'pyramid_auth'
copyright = u'2013, Aurélien Matouillot'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.2.1'
# The full version, including alpha/beta/rc tags.
release = '0.2.1'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'pyramid'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'pyramid_authdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
  ('index', 'pyramid_auth.tex', u'pyramid\\_auth Documentation',
   u'Aurélien Matouillot', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'pyramid_auth', u'pyramid_auth Documentation',
     [u'Aurélien Matouillot'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'pyramid_auth', u'pyramid_auth Documentation',
   u'Aurélien Matouillot', 'pyramid_auth', 'One line description of project.',
   'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# PyOEIS documentation build configuration file, created by
# sphinx-quickstart on Wed Jan 14 19:47:33 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../pyoeis'))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.intersphinx'
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'PyOEIS'
copyright = u'2015, Dylan Evans'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}

# If false, no module index is generated.
# html_domain_indices = True

# If false, no index is generated.
# html_use_index = True

# If true, the index is split into individual pages for each letter.
# html_split_index = False

# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'PyOEISdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {}
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
# 'preamble': '',

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [('index', 'PyOEIS.tex', u'PyOEIS Documentation',
                    u'Dylan Evans', 'manual'), ]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
# latex_appendices = []

# If false, no module index is generated.
# latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'pyoeis', u'PyOEIS Documentation',
     [u'Dylan Evans'], 1)
]

# If true, show URL addresses after external links.
# man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [('index', 'PyOEIS', u'PyOEIS Documentation',
                      u'Dylan Evans', 'PyOEIS',
                      'One line description of project.',
                      'Miscellaneous'), ]

# Documents to append as an appendix to all manuals.
# texinfo_appendices = []

# If false, no module index is generated.
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False

req_url = "http://docs.python-requests.org/en/latest/"
intersphinx_mapping = {'requests': (req_url, None)}
<commit_msg>Updated conf.py<commit_after># -*- coding: utf-8 -*-
#
# PyOEIS documentation build configuration file, created by
# sphinx-quickstart on Wed Jan 14 19:47:33 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, '/Users/dylan/Documents/Code/Python/pyoeis/pyoeis/')

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.intersphinx'
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'PyOEIS'
copyright = u'2015, Dylan Evans'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}

# If false, no module index is generated.
# html_domain_indices = True

# If false, no index is generated.
# html_use_index = True

# If true, the index is split into individual pages for each letter.
# html_split_index = False

# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'PyOEISdoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {}
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
# 'preamble': '',

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [('index', 'PyOEIS.tex', u'PyOEIS Documentation',
                    u'Dylan Evans', 'manual'), ]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
# latex_appendices = []

# If false, no module index is generated.
# latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'pyoeis', u'PyOEIS Documentation',
     [u'Dylan Evans'], 1)
]

# If true, show URL addresses after external links.
# man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [('index', 'PyOEIS', u'PyOEIS Documentation',
                      u'Dylan Evans', 'PyOEIS',
                      'One line description of project.',
                      'Miscellaneous'), ]

# Documents to append as an appendix to all manuals.
# texinfo_appendices = []

# If false, no module index is generated.
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False

req_url = "http://docs.python-requests.org/en/latest/"
intersphinx_mapping = {'requests': (req_url, None)}
<|endoftext|>


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

import sys
import re
import os
import settings
import git
import sqlite3
from time import time
import shlex, subprocess
from optparse import OptionParser

#optparse stuff
def config():
    """Definition for acceptable options with python's optparse library.
    """
    parser = OptionParser(usage='%prog [options] URL', description='Parse '
            'gitrepository at URL and generate commit-statistics to reward'
            'your users')
    parser.add_option('-b', '--branch', dest='branch', default='master',
        help="Branch you'd like to parse when checking out URL.")
    parser.add_option('-t', '--temp', dest='temp', default='tmp/',
        help="Temporary directory you'd like to make a mess in.")

    return parser.parse_args()

def main():
    # adding global vars to the sqlite connect
    # and the cursor, I imaging this isn't the greatest
    # implementation but it seems easy for me. Fee
    # free to re-write it better -- Eric J. Duran :)
    global conn
    global c
    (opts, args) = config()

    #sqlite db
    conn = sqlite3.connect('cores.db')
    conn.text_factory = str
    c = conn.cursor()

    # Set up the sqlite3 db
    setDatabase();

    #the repo we've been asked to parse
    #@TODO: install bleeding-edge gitpython (instead of old debian version),
    # maybe .clone will work, see:
    # - https://github.com/davvid/GitPython/blob/00c5497f190172765cc7a53ff9d8852a26b91676/CHANGES#L63-67

    #git.Git(opts.temp).clone(args[0])

    # close the cursor
    readLogs();
    c.close();

def setDatabase():
    # Set up the sqlite3 db
    c.execute('''create table if not exists users
    (username text, count real)''')
    c.execute('''create table if not exists hash
    (hash text, timestampt real)''')
    conn.commit()

def lastHash(hash):
    #Add the last has to the sqlite database
    c.execute('insert into hash values (?, ?)',[ hash, time()])
    conn.commit()

def readLogs():
    os.chdir('drupal')
    logs = subprocess.Popen(settings.GIT_LOG, stdout=subprocess.PIPE, shell=True).stdout.read()
    parseUsers(logs)

def parseUsers(logs):
    lines = logs.splitlines()
    for item in lines:
        item = item.strip().split(":")
        sha = item[0]
        users = item[1]
        if users.startswith(" Issue"):
            commit_message = users.strip()
            commit_message = re.sub('Issue #[0-9]* by ', '', commit_message)
            commit_users = commit_message.split(",")
            for user in commit_users:
                insertUser(user.strip(), sha)
                #lastHash(sha)

def insertUser(username, hash):
    count = getUserCount(username)
    count = count + 1
    if count == 1:
        c.execute('insert into users values (?, ?)',[username, count])
    else:
        c.execute('update users set count = ? where username = ?', [count, username])

    conn.commit()

def getUserCount(username):
    c.execute("select count from users where username = ?", [username])
    values = c.fetchone()
    if not values:
        return 0

    return values[0]

if __name__ == '__main__':
    main()

# vim: et:ts=4:sw=4:sts=4

<commit_msg>Adding basic writeHTML function, for now it just prints the results<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import re
import os
import settings
import git
import sqlite3
from time import time
import shlex, subprocess
from optparse import OptionParser

#optparse stuff
def config():
    """Definition for acceptable options with python's optparse library.
    """
    parser = OptionParser(usage='%prog [options] URL', description='Parse '
            'gitrepository at URL and generate commit-statistics to reward'
            'your users')
    parser.add_option('-b', '--branch', dest='branch', default='master',
        help="Branch you'd like to parse when checking out URL.")
    parser.add_option('-t', '--temp', dest='temp', default='tmp/',
        help="Temporary directory you'd like to make a mess in.")

    return parser.parse_args()

def main():
    # adding global vars to the sqlite connect
    # and the cursor, I imaging this isn't the greatest
    # implementation but it seems easy for me. Fee
    # free to re-write it better -- Eric J. Duran :)
    global conn
    global c
    (opts, args) = config()

    #sqlite db
    conn = sqlite3.connect('cores.db')
    conn.text_factory = str
    c = conn.cursor()

    # Set up the sqlite3 db
    setDatabase();

    #the repo we've been asked to parse
    #@TODO: install bleeding-edge gitpython (instead of old debian version),
    # maybe .clone will work, see:
    # - https://github.com/davvid/GitPython/blob/00c5497f190172765cc7a53ff9d8852a26b91676/CHANGES#L63-67

    #git.Git(opts.temp).clone(args[0])

    # close the cursor
    readLogs();
    writeHTML();
    c.close();

def setDatabase():
    # Set up the sqlite3 db
    c.execute('''create table if not exists users
    (username text, count real)''')
    c.execute('''create table if not exists hash
    (hash text, timestampt real)''')
    conn.commit()

def lastHash(hash):
    #Add the last has to the sqlite database
    c.execute('insert into hash values (?, ?)',[ hash, time()])
    conn.commit()

def readLogs():
    os.chdir('drupal')
    logs = subprocess.Popen(settings.GIT_LOG, stdout=subprocess.PIPE, shell=True).stdout.read()
    parseUsers(logs)

def parseUsers(logs):
    lines = logs.splitlines()
    for item in lines:
        item = item.strip().split(":")
        sha = item[0]
        users = item[1]
        if users.startswith(" Issue"):
            commit_message = users.strip()
            commit_message = re.sub('Issue #[0-9]* by ', '', commit_message)
            commit_users = commit_message.split(",")
            for user in commit_users:
                insertUser(user.strip(), sha)
                #lastHash(sha)

def insertUser(username, hash):
    count = getUserCount(username)
    count = count + 1
    if count == 1:
        c.execute('insert into users values (?, ?)',[username, count])
    else:
        c.execute('update users set count = ? where username = ?', [count, username])

    conn.commit()

def getUserCount(username):
    c.execute("select count from users where username = ?", [username])
    values = c.fetchone()
    if not values:
        return 0

    return values[0]

def writeHTML():
    c.execute("select * from users order by count desc")
    results = c.fetchall()
    print results

if __name__ == '__main__':
    main()

# vim: et:ts=4:sw=4:sts=4

<|endoftext|>


<commit_before>#-*- coding: utf-8 -*-

from random import randint
nsal_usuario = 0
nrec_usuario = 0
nsal_enemigo = 0
nrec_enemigo = 0
hpmb_usuario = (50)
hpmb_enemigo_facil = 20
hprec_enemigo = 1
salud_actual_usuario = 50
hprb_usuario= (50)
salud_actual_enemigo = 50
dificultad = 1
victorias = 0
lvl = 1
xp_ganada = 0
limite_xp = 50
xp_reiniciado = 0
randxp = 0
nivel = 1
xp_ganada = 1
nfuer_usuario = 0
#<seccion de salud>

def saludm_usuario():
	saludm = hpmb_usuario + (3*nsal_usuario)
	return saludm

def saludrec_usuario():
	saludrec = hprp_usuario + (2*nrec_usuario)
	return saludrec

def saludrec_usuario():
	saludrec_enemigo = hprp_enemigo + (2*nrec_enemigo)
	return saludrec_enemigo
#</seccion de salud>

def ataque_del_enemigo():
	global ataque_enemigo
	global salud_actual_usuario
	print("El enemigo ataca!")
	salud_actual_usuario -= ataque_enemigo
	print("Tu salud disminuye en ", ataque_enemigo)

def recuperacion_por_nivel():
	global salud_actual_usuario
	salud_actual_usuario = saludm_usuario()

def enemigo_facil():
	global ataque_enemigo
	global lvl_enemigo
	global saludm_enemigo
	global xp_ganada
	lvl_enemigo = randint(1,5)
	saludm_enemigo = hpmb_enemigo_facil + (3*lvl_enemigo)
	ataque_enemigo = 10 + lvl_enemigo
	xp_ganada = randint(15, 35)

def lvl_up():
	while 1:
		atributo_a_mejorar = input("¿Que atributo deseas mejorar?\n")
		if atributo_a_mejorar in['salud','Salud']:
			global nsal_usuario
			nsal_usuario = nsal_usuario + 1
			recuperacion_por_nivel()
			break
		elif atributo_a_mejorar in['recuperacion', 'Recuperacion', 'recuperación', 'recuperacion']:
			global nrec_usuario
			nrec_usuario = nrec_usuario + 1
			recuperacion_por_nivel()
			print(salud_actual_usuario)
			break
		elif atributo_a_mejorar in['fuerza', 'Fuerza']:
			global nfuer_usuario
			nfuer_usuario += 1
			break
		else:
			print("Ese no es un atributo disponible.")

def comprobacion_de_nivel():
	global xp_reiniciado
	global limite_xp
	global nivel
	while xp_reiniciado >= limite_xp:
		recuperacion_por_nivel()
		xp_reiniciado -= limite_xp
		limite_xp *= 1.5
		nivel += 1
		print("¡Has subido de nivel!\n¡Tu nuevo nivel es ", nivel, "!")
		lvl_up()

def combate():
	global nivel
	if 5 > nivel:
		enemigo_facil()
	global dificultad
	global salud_actual_enemigo
	global salud_actual_usuario
	salud_actual_enemigo = saludm_enemigo
	while 1:
		if salud_actual_usuario > 0 and salud_actual_enemigo > 0:
			print("\nTu salud es ", salud_actual_usuario, "\nLa salud del enemigo es, ", salud_actual_enemigo)
			print("1. Atacar \n2. Recuperarte")
			accion = input("¿Qué quieres hacer? \n")
			if accion in['atacar', 'Atacar']:
				salud_actual_enemigo -= 10 + 3*nfuer_usuario
				print("La salud enemiga ha disminuido", 10+3 * nfuer_usuario)
				if salud_actual_enemigo > 0:
					ataque_del_enemigo()
				elif accion == "10100":
					salud_actual_enemigo = 0
			elif accion in['recuperarme','Recuperarme', 'recuperarte', 'Recuperarte']:
				if salud_actual_usuario == saludm_usuario():
					print("Tu salud ya está al máximo, haz otra cosa.")
				else:
					recuperacion = (10 + 2*nrec_usuario)
					if salud_actual_usuario < (saludm_usuario() - recuperacion):
						salud_actual_usuario += recuperacion
						print("Recuperas", recuperacion, "puntos de salud.")
						ataque_del_enemigo()
					else:
						salud_actual_usuario = saludm_usuario()
						ataque_del_enemigo()
			else:
				print("Elije una opcion.")
		elif salud_actual_enemigo < 0 or salud_actual_enemigo == 0:
			print("El enemigo ha muerto")
			global xp_reiniciado
			global randxp
			global xp_ganada
			if dificultad == 1:
				xp_reiniciado += xp_ganada
				print("¡Has obtenido ", xp_ganada, " puntos de experiencia!")
				xp_ganada = 0
				comprobacion_de_nivel()
				break

print(nivel)
while True:
	combate()
<commit_msg>Update sots.py<commit_after>#-*- coding: utf-8 -*-

from random import randint
nsal_usuario = 0
nrec_usuario = 0
nsal_enemigo = 0
nrec_enemigo = 0
hpmb_usuario = (50)
hpmb_enemigo_facil = 20
hprec_enemigo = 1
salud_actual_usuario = 50
hprb_usuario= (50)
salud_actual_enemigo = 50
dificultad = 1
victorias = 0
lvl = 1
xp_ganada = 0
limite_xp = 50
xp_reiniciado = 0
randxp = 0
nivel = 1
xp_ganada = 1
nfuer_usuario = 0

def saludm_usuario():
	saludm = hpmb_usuario + (3*nsal_usuario)
	return saludm

def saludrec_usuario():
	saludrec = hprp_usuario + (2*nrec_usuario)
	return saludrec

def saludrec_usuario():
	saludrec_enemigo = hprp_enemigo + (2*nrec_enemigo)
	return saludrec_enemigo
#</seccion de salud>

def ataque_del_enemigo():
	global ataque_enemigo
	global salud_actual_usuario
	print("El enemigo ataca!")
	salud_actual_usuario -= ataque_enemigo
	print("Tu salud disminuye en ", ataque_enemigo)

def recuperacion_por_nivel():
	global salud_actual_usuario
	salud_actual_usuario = saludm_usuario()

def enemigo_facil():
	global ataque_enemigo
	global lvl_enemigo
	global saludm_enemigo
	global xp_ganada
	lvl_enemigo = randint(1,5)
	saludm_enemigo = hpmb_enemigo_facil + (3*lvl_enemigo)
	ataque_enemigo = 10 + lvl_enemigo
	xp_ganada = randint(15, 35)

def lvl_up():
	while 1:
		atributo_a_mejorar = input("¿Que atributo deseas mejorar?\n")
		if atributo_a_mejorar in['salud','Salud']:
			global nsal_usuario
			nsal_usuario = nsal_usuario + 1
			recuperacion_por_nivel()
			break
		elif atributo_a_mejorar in['recuperacion', 'Recuperacion', 'recuperación', 'recuperacion']:
			global nrec_usuario
			nrec_usuario = nrec_usuario + 1
			recuperacion_por_nivel()
			print(salud_actual_usuario)
			break
		elif atributo_a_mejorar in['fuerza', 'Fuerza']:
			global nfuer_usuario
			nfuer_usuario += 1
			break
		else:
			print("Ese no es un atributo disponible.")

def comprobacion_de_nivel():
	global xp_reiniciado
	global limite_xp
	global nivel
	while xp_reiniciado >= limite_xp:
		recuperacion_por_nivel()
		xp_reiniciado -= limite_xp
		limite_xp *= 1.5
		nivel += 1
		print("¡Has subido de nivel!\n¡Tu nuevo nivel es ", nivel, "!")
		lvl_up()

def combate():
	global nivel
	if 5 > nivel:
		enemigo_facil()
	global dificultad
	global salud_actual_enemigo
	global salud_actual_usuario
	salud_actual_enemigo = saludm_enemigo
	while 1:
		if salud_actual_usuario > 0 and salud_actual_enemigo > 0:
			print("\nTu salud es ", salud_actual_usuario, "\nLa salud del enemigo es, ", salud_actual_enemigo)
			print("1. Atacar \n2. Recuperarte")
			accion = input("¿Qué quieres hacer? \n")
			if accion in['atacar', 'Atacar']:
				salud_actual_enemigo -= 10 + 3*nfuer_usuario
				print("La salud enemiga ha disminuido", 10+3 * nfuer_usuario)
				if salud_actual_enemigo > 0:
					ataque_del_enemigo()
				elif accion == "10100":
					salud_actual_enemigo = 0
			elif accion in['recuperarme','Recuperarme', 'recuperarte', 'Recuperarte']:
				if salud_actual_usuario == saludm_usuario():
					print("Tu salud ya está al máximo, haz otra cosa.")
				else:
					recuperacion = (10 + 2*nrec_usuario)
					if salud_actual_usuario < (saludm_usuario() - recuperacion):
						salud_actual_usuario += recuperacion
						print("Recuperas", recuperacion, "puntos de salud.")
						ataque_del_enemigo()
					else:
						salud_actual_usuario = saludm_usuario()
						ataque_del_enemigo()
			else:
				print("Elije una opcion.")
		elif salud_actual_enemigo < 0 or salud_actual_enemigo == 0:
			print("El enemigo ha muerto")
			global xp_reiniciado
			global randxp
			global xp_ganada
			if dificultad == 1:
				xp_reiniciado += xp_ganada
				print("¡Has obtenido ", xp_ganada, " puntos de experiencia!")
				xp_ganada = 0
				comprobacion_de_nivel()
				break

print(nivel)
while True:
	combate()
#ADSFASDFA
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import pytz

from django.contrib.auth.models import AbstractBaseUser, UserManager
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils.functional import cached_property

from mailme.providers import provider_from_address
from mailme.utils.avatar import get_profile_image
from mailme.utils.db import MailmeModel
from mailme.utils.uri import parse_uri

class User(MailmeModel, AbstractBaseUser):
    username = models.CharField(_('Username'), unique=True, max_length=256)
    name = models.TextField(_('Name'), max_length=100, blank=True, null=True)
    is_active = models.BooleanField(
        _('active'), default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    # Required for django-admin
    is_staff = models.BooleanField(
        _('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_superuser = models.BooleanField(
        _('superuser status'), default=False,
        help_text=_('Designates that this user has all permissions without '
                    'explicitly assigning them.'))

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('User')
        verbose_name_plural = _('Users')

    def __str__(self):
        return self.username

    def has_module_perms(self, app_label):
        return self.is_superuser

    def has_perm(self, app_label):
        return self.is_superuser

    def get_absolute_url(self):
        return ''

    def get_display_name(self):
        return self.username

    def get_short_name(self):
        return self.get_display_name()

    @property
    def profile_image(self):
        return get_profile_image(self)

ALLOWED_MIMETYPES = {'text/plain', 'text/html'}

class MailboxFolder(models.Model):
    """Represents a folder in a mailbox.

    This is used purely for syncing purposes, we do store folders
    as flags on messages but don't represent a regular imap mailbox.
    """
    mailbox = models.ForeignKey('Mailbox', related_name='folders')
    name = models.CharField(_('Folder name'), max_length=256)

    # Imap sync related
    uidvalidity = models.BigIntegerField()
    highestmodseq = models.BigIntegerField(null=True, blank=True)
    uidnext = models.PositiveIntegerField(null=True, blank=True)

class Mailbox(models.Model):
    name = models.CharField(_(u'Name'), max_length=256)
    user = models.ForeignKey(User)

    uri = models.CharField(
        _(u'URI'), max_length=256,
        help_text=(_('Example: imap+ssl://myusername:mypassword@someserver')),
        blank=True, null=True, default=None)

    provider = models.CharField(
        _('Provider'), max_length=256, null=True, blank=True)

    from_email = models.CharField(
        _(u'From email'), max_length=255,
        blank=True, null=True, default=None)

    active = models.BooleanField(_(u'Active'), blank=True, default=True)

    objects = models.Manager()

    @cached_property
    def parsed_uri(self):
        return parse_uri(self.uri)

    def get_provider(self, email):
        try:
            return provider_from_address(email)
        except KeyError:
            return None

    def get_connection(self):
        """Returns the transport instance for this mailbox."""
        if not self.uri:
            return None

        # Circular imports
        from .transports.imap import ImapTransport

        uri = self.parsed_uri

        if uri.scheme == 'imap':
            conn = ImapTransport(
                uri.location,
                ssl=uri.use_ssl,
                provider=self.provider
            )
            conn.connect(uri.username, uri.password)
        return conn

    def sync(self, condition=None, folder=None):
        """Connect to this transport and fetch new messages."""
        new_mail = []
        connection = self.get_connection()
        if not connection:
            return new_mail

        messages = connection.get_messages(condition=condition, folder=folder)

        # TODO:
        # * handle attachments
        # * normalize html

        for message in messages:
            date = message['parsed_date']

            if timezone.is_naive(date):
                # If no timezone is given, UTC should be used
                date = timezone.make_aware(date, pytz.UTC)

            new_mail.append(Message(
                message_id=message['message_id'],
                original=message['original'],
                date=date,
                subject=message['subject'],
                plain_body=message['body']['plain'],
                html_body=message['body']['html'],
                sent_from=message['from'],
                to=message['to'],
                bcc=message['bcc'],
                cc=message['cc'],
                headers=message['headers'],
            ))

        Message.objects.bulk_create(new_mail)

        return new_mail

    def __str__(self):
        return self.name

class Thread(models.Model):
    mailbox = models.ForeignKey(Mailbox, related_name='threads')
    subject = models.CharField(max_length=256)

    # TODO:
    # * read (boolean, wether there are messages in the thread that are unread)
    # * starred (flagged)
    # * folders

class Message(models.Model):
    thread = models.ForeignKey(Thread, related_name='messages')

    from_address = JSONField(_('Sent from'), blank=True, default=[])
    to_address = JSONField(_('Sent to'), blank=True, default=[])
    cc_address = JSONField(_('CC'), blank=True, default=[])
    bcc_address = JSONField(_('BCC'), blank=True, default=[])
    reply_to = JSONField(_('Reply-To'), blank=True, null=True)
    in_reply_to = JSONField(_('In reply to'), blank=True, null=True)

    headers = JSONField(_('Headers'), blank=True, default={})
    subject = models.CharField(_('Subject'), max_length=255)
    original = models.TextField(_('Original (raw) text'))
    plain_body = models.TextField(_('Text'), blank=True)
    html_body = models.TextField(_('HTML'), blank=True)
    date = models.DateTimeField(_('Date'), blank=True)

    # From: http://tools.ietf.org/html/rfc4130, section 5.3.3,
    # max message_id_header is 998 characters
    message_id = models.CharField(max_length=998)
    references = JSONField(_('References'), blank=True, null=True)

    # Imap sync related metadata
    uid = models.BigIntegerField(db_index=True)

    # TODO:
    # * attachments
    # * read
    # * starred (flagged)

    def __str__(self):
        return self.subject

    def __repr__(self):
        return '<Message({})>'.format(self.subject)
<commit_msg>Add folder relation to message, more work on syncing<commit_after># -*- coding: utf-8 -*-
import pytz

from django.contrib.auth.models import AbstractBaseUser, UserManager
from django.contrib.postgres.fields import JSONField
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils.functional import cached_property

from mailme.providers import provider_from_address
from mailme.utils.avatar import get_profile_image
from mailme.utils.db import MailmeModel
from mailme.utils.uri import parse_uri

class User(MailmeModel, AbstractBaseUser):
    username = models.CharField(_('Username'), unique=True, max_length=256)
    name = models.TextField(_('Name'), max_length=100, blank=True, null=True)
    is_active = models.BooleanField(
        _('active'), default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    # Required for django-admin
    is_staff = models.BooleanField(
        _('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_superuser = models.BooleanField(
        _('superuser status'), default=False,
        help_text=_('Designates that this user has all permissions without '
                    'explicitly assigning them.'))

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('User')
        verbose_name_plural = _('Users')

    def __str__(self):
        return self.username

    def has_module_perms(self, app_label):
        return self.is_superuser

    def has_perm(self, app_label):
        return self.is_superuser

    def get_absolute_url(self):
        return ''

    def get_display_name(self):
        return self.username

    def get_short_name(self):
        return self.get_display_name()

    @property
    def profile_image(self):
        return get_profile_image(self)

ALLOWED_MIMETYPES = {'text/plain', 'text/html'}

class MailboxFolder(models.Model):
    """Represents a folder in a mailbox.

    This is used purely for syncing purposes, we do store folders
    as flags on messages but don't represent a regular imap mailbox.
    """
    mailbox = models.ForeignKey('Mailbox', related_name='folders')
    name = models.CharField(_('Folder name'), max_length=256)

    # Imap sync related
    uidvalidity = models.BigIntegerField()
    highestmodseq = models.BigIntegerField(null=True, blank=True)
    uidnext = models.PositiveIntegerField(null=True, blank=True)

class Mailbox(models.Model):
    name = models.CharField(_(u'Name'), max_length=256)
    user = models.ForeignKey(User)

    uri = models.CharField(
        _(u'URI'), max_length=256,
        help_text=(_('Example: imap+ssl://myusername:mypassword@someserver')),
        blank=True, null=True, default=None)

    provider = models.CharField(
        _('Provider'), max_length=256, null=True, blank=True)

    from_email = models.CharField(
        _(u'From email'), max_length=255,
        blank=True, null=True, default=None)

    active = models.BooleanField(_(u'Active'), blank=True, default=True)

    objects = models.Manager()

    @cached_property
    def parsed_uri(self):
        return parse_uri(self.uri)

    def get_provider(self, email):
        try:
            return provider_from_address(email)
        except KeyError:
            return None

    def get_connection(self):
        """Returns the transport instance for this mailbox."""
        if not self.uri:
            return None

        # Circular imports
        from .transports.imap import ImapTransport

        uri = self.parsed_uri

        if uri.scheme == 'imap':
            conn = ImapTransport(
                uri.location,
                ssl=uri.use_ssl,
                provider=self.provider
            )
            conn.connect(uri.username, uri.password)
        return conn

    def sync(self, condition=None, folder=None):
        """Connect to this transport and fetch new messages."""
        new_mail = []
        connection = self.get_connection()
        if not connection:
            return new_mail

        messages = connection.get_messages(condition=condition, folder=folder)

        # TODO:
        # * handle attachments
        # * normalize html

        for message in messages:
            date = message['parsed_date']

            if timezone.is_naive(date):
                # If no timezone is given, UTC should be used
                date = timezone.make_aware(date, pytz.UTC)

            new_mail.append(Message(
                message_id=message['message_id'],
                original=message['original'],
                date=date,
                subject=message['subject'],
                plain_body=message['body']['plain'],
                html_body=message['body']['html'],
                sent_from=message['from'],
                to=message['to'],
                bcc=message['bcc'],
                cc=message['cc'],
                headers=message['headers'],
            ))

        Message.objects.bulk_create(new_mail)

        return new_mail

    def __str__(self):
        return self.name

class Thread(models.Model):
    mailbox = models.ForeignKey(Mailbox, related_name='threads')
    subject = models.CharField(max_length=256)

    # TODO:
    # * read (boolean, wether there are messages in the thread that are unread)
    # * starred (flagged)
    # * folders

class Message(models.Model):
    thread = models.ForeignKey(Thread, related_name='messages')
    folder = models.ForeignKey(MailboxFolder, related_name='messages')

    from_address = JSONField(_('Sent from'), blank=True, default=[])
    to_address = JSONField(_('Sent to'), blank=True, default=[])
    cc_address = JSONField(_('CC'), blank=True, default=[])
    bcc_address = JSONField(_('BCC'), blank=True, default=[])
    reply_to = JSONField(_('Reply-To'), blank=True, null=True)
    in_reply_to = JSONField(_('In reply to'), blank=True, null=True)

    headers = JSONField(_('Headers'), blank=True, default={})
    subject = models.CharField(_('Subject'), max_length=255)
    original = models.TextField(_('Original (raw) text'))
    plain_body = models.TextField(_('Text'), blank=True)
    html_body = models.TextField(_('HTML'), blank=True)
    date = models.DateTimeField(_('Date'), blank=True)

    # From: http://tools.ietf.org/html/rfc4130, section 5.3.3,
    # max message_id_header is 998 characters
    message_id = models.CharField(max_length=998)
    references = JSONField(_('References'), blank=True, null=True)

    # Imap sync related metadata
    uid = models.BigIntegerField(db_index=True)

    # TODO:
    # * attachments
    # * read
    # * starred (flagged)

    def __str__(self):
        return self.subject

    def __repr__(self):
        return '<Message({})>'.format(self.subject)
<|endoftext|>


<commit_before>#
# zulip-contributor-docs documentation build configuration file, created by
# sphinx-quickstart on Mon Aug 17 16:24:04 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import sys
from typing import Any, Dict, Optional

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from version import LATEST_RELEASE_VERSION, ZULIP_VERSION

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    "myst_parser",
]

myst_enable_extensions = [
    "colon_fence",
    "substitution",
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The root toctree document.
root_doc = "index"

# General information about the project.
project = "Zulip"
copyright = "2012–2015 Dropbox, Inc., 2015–2021 Kandra Labs, Inc., and contributors"
author = "The Zulip Team"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ZULIP_VERSION
# The full version, including alpha/beta/rc tags.
release = ZULIP_VERSION

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language: Optional[str] = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build", "README.md"]

# The reST default role (used for this markup: `text`) to use for all
# documents.
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

myst_substitutions = {
    "LATEST_RELEASE_VERSION": LATEST_RELEASE_VERSION,
}

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.

# Read The Docs can't import sphinx_rtd_theme, so don't import it there.
on_rtd = os.environ.get("READTHEDOCS", None) == "True"

if not on_rtd:
    import sphinx_rtd_theme

    html_theme = "sphinx_rtd_theme"
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
else:
    html_theme = "sphinx_rtd_theme"
    html_style = None
    html_theme_options = {"collapse_navigation": False}
    using_rtd_theme = True

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
html_theme_options = {"collapse_navigation": False, "logo_only": True}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "images/zulip-logo.svg"

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}

# If false, no module index is generated.
# html_domain_indices = True

# If false, no index is generated.
# html_use_index = True

# If true, the index is split into individual pages for each letter.
# html_split_index = False

# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
# html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
# html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = "zulip-contributor-docsdoc"

# -- Options for LaTeX output ---------------------------------------------

latex_elements: Dict[str, str] = {
    # The paper size ('letterpaper' or 'a4paper').
    #'papersize': 'letterpaper',
    # The font size ('10pt', '11pt' or '12pt').
    #'pointsize': '10pt',
    # Additional stuff for the LaTeX preamble.
    #'preamble': '',
    # Latex figure (float) alignment
    #'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (root_doc, "zulip-contributor-docs.tex", "Zulip Documentation", "The Zulip Team", "manual"),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False

# If true, show page references after internal links.
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
# latex_appendices = []

# If false, no module index is generated.
# latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (root_doc, "zulip-contributor-docs", "Zulip Documentation", [author], 1),
]

# If true, show URL addresses after external links.
# man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (
        root_doc,
        "zulip-contributor-docs",
        "Zulip Documentation",
        author,
        "zulip-contributor-docs",
        "Documentation for contributing to Zulip.",
        "Miscellaneous",
    ),
]

# Documents to append as an appendix to all manuals.
# texinfo_appendices = []

# If false, no module index is generated.
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False

# The suffix(es) of source filenames. You can specify multiple suffix
# as a dictionary mapping file extensions to file types
# https://www.sphinx-doc.org/en/master/usage/markdown.html
source_suffix = {
    ".rst": "restructuredtext",
    ".md": "markdown",
}

suppress_warnings = [
    "myst.header",
]

def setup(app: Any) -> None:
    # overrides for wide tables in RTD theme
    app.add_css_file("theme_overrides.css")  # path relative to _static
<commit_msg>docs: Clean Sphinx configuration file.<commit_after># For documentation on Sphinx configuration options, see:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# https://myst-parser.readthedocs.io/en/latest/sphinx/reference.html
# https://sphinx-rtd-theme.readthedocs.io/en/stable/configuring.html

import os
import sys
from typing import Any

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from version import LATEST_RELEASE_VERSION, ZULIP_VERSION

on_rtd = os.environ.get("READTHEDOCS") == "True"

# General configuration

extensions = [
    "myst_parser",
]
templates_path = ["_templates"]
project = "Zulip"
copyright = "2012–2015 Dropbox, Inc., 2015–2021 Kandra Labs, Inc., and contributors"
author = "The Zulip Team"
version = ZULIP_VERSION
release = ZULIP_VERSION
exclude_patterns = ["_build", "README.md"]
suppress_warnings = [
    "myst.header",
]
pygments_style = "sphinx"

# Options for Markdown parser

myst_enable_extensions = [
    "colon_fence",
    "substitution",
]
myst_substitutions = {
    "LATEST_RELEASE_VERSION": LATEST_RELEASE_VERSION,
}

# Options for HTML output

html_theme = "sphinx_rtd_theme"
html_theme_options = {
    "collapse_navigation": False,
    "logo_only": True,
}
html_logo = "images/zulip-logo.svg"
html_static_path = ["_static"]

if not on_rtd:
    import sphinx_rtd_theme

    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

def setup(app: Any) -> None:
    # overrides for wide tables in RTD theme
    app.add_css_file("theme_overrides.css")  # path relative to _static
<|endoftext|>


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

import sys
import re
import os
import settings
import git
import HTML
import sqlite3
from time import time
import shlex, subprocess
from optparse import OptionParser

class DrupalCores():
    def __init__(self, opts, args):
        """Initial setup and config of database
        """
        self.opts = opts
        self.args = args

        # Set up the sqlite3 db
        self.setDatabase()

        #the repo we've been asked to parse
        # @TODO: shell out to clone a repo into self.opts.temp dir/
        #git.Git(dcores.opts.temp).clone(dcores.args[0])

    def setDatabase(self):
        """Set up the sqlite3 db"""
        self.conn = sqlite3.connect(self.opts.db)
        self.conn.text_factory = str
        self.c = self.conn.cursor()

        self.c.execute('''create table if not exists users
        (username text, count real)''')
        self.c.execute('''create table if not exists hash
        (hash text, timestampt real)''')
        self.conn.commit()

    def lastHash(self, hash):
        """Add the last has to the sqlite database"""
        self.c.execute('insert into hash values (?, ?)', [hash, time()])
        self.conn.commit()

    def readLogs(self):
        pushd = os.getcwd()
        os.chdir(self.opts.temp)
        logs = subprocess.Popen(settings.GIT_LOG, stdout=subprocess.PIPE, shell=True).stdout.read()
        os.chdir(pushd)
        self.parseUsers(logs)

    def parseUsers(self, logs):
        lines = logs.splitlines()
        for item in lines:
            item = item.strip().split(":")
            sha = item[0]
            users = item[1]
            if users.startswith(" Issue"):
                commit_message = users.strip()
                commit_message = re.sub('Issue #[0-9]* by ', '', commit_message)
                commit_users = commit_message.split(",")
                for user in commit_users:
                    self.insertUser(user.strip(), sha)
                    #self.lastHash(sha)

    def insertUser(self, username, hash):
        count = self.getUserCount(username)
        count = count + 1
        if count == 1:
            self.c.execute('insert into users values (?, ?)',[username, count])
        else:
            self.c.execute('update users set count = ? where username = ?', [count, username])

        self.conn.commit()

    def getUserCount(self, username):
        self.c.execute("select count from users where username = ?", [username])
        values = self.c.fetchone()
        if not values:
            return 0

        return values[0]

    def getAllUsers(self):
        self.c.execute("select * from users order by count desc")
        return self.c.fetchall()

#optparse stuff
def config():
    """Definition for acceptable options with python's optparse library.
    """
    parser = OptionParser(usage='%prog [options] URL', description='Parse '
            'gitrepository at URL and generate commit-statistics to reward'
            'your users')
    parser.add_option('-d', '--database', dest='db', default=':memory:',
        help="Database to use in counting user's commits.")
    parser.add_option('-b', '--branch', dest='branch', default='master',
        help="Branch you'd like to parse when checking out URL.")
    parser.add_option('-t', '--temp', dest='temp', default='drupal',
        help="Temporary directory you'd like to make a mess in.")
    parser.add_option('-o', '--output', dest='htmltable', default='pages/index.html',
        help="Filename that the HTML output should be written to.")

    return parser.parse_args()

def main():
    (opts, args) = config()
    dcores = DrupalCores(opts, args)

    #kick off the important leg work
    dcores.readLogs()

    #render our results
    writeHTML(dcores.getAllUsers(), dcores.opts.htmltable)

    #close sqlite3
    dcores.c.close()

def writeHTML(userCounts, tableName):
    htmlcode = "---\nlayout: default\n---\n\n\n"
    htmlcode += HTML.table(userCounts)
    f = open(tableName, 'w')
    f.writelines(htmlcode)
    f.close()

if __name__ == '__main__':
    main()

# vim: et:ts=4:sw=4:sts=4
<commit_msg>Adding date to output<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import re
import os
import settings
import git
import HTML
import sqlite3
import datetime
from time import time
import shlex, subprocess
from optparse import OptionParser

class DrupalCores():
    def __init__(self, opts, args):
        """Initial setup and config of database
        """
        self.opts = opts
        self.args = args

        # Set up the sqlite3 db
        self.setDatabase()

        #the repo we've been asked to parse
        # @TODO: shell out to clone a repo into self.opts.temp dir/
        #git.Git(dcores.opts.temp).clone(dcores.args[0])

    def setDatabase(self):
        """Set up the sqlite3 db"""
        self.conn = sqlite3.connect(self.opts.db)
        self.conn.text_factory = str
        self.c = self.conn.cursor()

        self.c.execute('''create table if not exists users
        (username text, count real)''')
        self.c.execute('''create table if not exists hash
        (hash text, timestampt real)''')
        self.conn.commit()

    def lastHash(self, hash):
        """Add the last has to the sqlite database"""
        self.c.execute('insert into hash values (?, ?)', [hash, time()])
        self.conn.commit()

    def readLogs(self):
        pushd = os.getcwd()
        os.chdir(self.opts.temp)
        logs = subprocess.Popen(settings.GIT_LOG, stdout=subprocess.PIPE, shell=True).stdout.read()
        os.chdir(pushd)
        self.parseUsers(logs)

    def parseUsers(self, logs):
        lines = logs.splitlines()
        for item in lines:
            item = item.strip().split(":")
            sha = item[0]
            users = item[1]
            if users.startswith(" Issue"):
                commit_message = users.strip()
                commit_message = re.sub('Issue #[0-9]* by ', '', commit_message)
                commit_users = commit_message.split(",")
                for user in commit_users:
                    self.insertUser(user.strip(), sha)
                    #self.lastHash(sha)

    def insertUser(self, username, hash):
        count = self.getUserCount(username)
        count = count + 1
        if count == 1:
            self.c.execute('insert into users values (?, ?)',[username, count])
        else:
            self.c.execute('update users set count = ? where username = ?', [count, username])

        self.conn.commit()

    def getUserCount(self, username):
        self.c.execute("select count from users where username = ?", [username])
        values = self.c.fetchone()
        if not values:
            return 0

        return values[0]

    def getAllUsers(self):
        self.c.execute("select * from users order by count desc")
        return self.c.fetchall()

#optparse stuff
def config():
    """Definition for acceptable options with python's optparse library.
    """
    parser = OptionParser(usage='%prog [options] URL', description='Parse '
            'gitrepository at URL and generate commit-statistics to reward'
            'your users')
    parser.add_option('-d', '--database', dest='db', default=':memory:',
        help="Database to use in counting user's commits.")
    parser.add_option('-b', '--branch', dest='branch', default='master',
        help="Branch you'd like to parse when checking out URL.")
    parser.add_option('-t', '--temp', dest='temp', default='drupal',
        help="Temporary directory you'd like to make a mess in.")
    parser.add_option('-o', '--output', dest='htmltable', default='pages/index.html',
        help="Filename that the HTML output should be written to.")

    return parser.parse_args()

def main():
    (opts, args) = config()
    dcores = DrupalCores(opts, args)

    #kick off the important leg work
    dcores.readLogs()

    #render our results
    writeHTML(dcores.getAllUsers(), dcores.opts.htmltable)

    #close sqlite3
    dcores.c.close()

def writeHTML(userCounts, tableName):
    htmlcode = "---\n"
    htmlcode += "layout: default\n"
    htmlcode += "date: " + str(datetime.datetime.now()) + "\n"
    htmlcode += "---\n\n\n"
    htmlcode += HTML.table(userCounts)
    f = open(tableName, 'w')
    f.writelines(htmlcode)
    f.close()

if __name__ == '__main__':
    main()

# vim: et:ts=4:sw=4:sts=4
<|endoftext|>