<commit_before>#
# INTEL CONFIDENTIAL
#
# Copyright 2013 Intel Corporation All Rights Reserved.
#
# The source code contained or described herein and all documents related
# to the source code ("Material") are owned by Intel Corporation or its
# suppliers or licensors. Title to the Material remains with Intel Corporation
# or its suppliers and licensors. The Material contains trade secrets and
# proprietary and confidential information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright and trade secret
# laws and treaty provisions. No part of the Material may be used, copied,
# reproduced, modified, published, uploaded, posted, transmitted, distributed,
# or disclosed in any way without Intel's prior express written permission.
#
# No license under any patent, copyright, trade secret or other intellectual
# property right is granted to or conferred upon you by disclosure or delivery
# of the Materials, either expressly, by implication, inducement, estoppel or
# otherwise. Any license under such intellectual property rights must be
# express and approved by Intel in writing.

from collections import defaultdict

import logging
import subprocess
from datetime import datetime, timedelta
import time
import argparse
import os

log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler())
log.setLevel(logging.INFO)
handler = logging.FileHandler("chroma-diagnostics.log")
handler.setFormatter(logging.Formatter('[%(asctime)s] %(message)s',
                                       '%d/%b/%Y:%H:%M:%S'))
log.addHandler(handler)

# Dictionary of parent path to array of logfiles
# that are rolled by logrotated such that when rotated
# the current file copied with the extendion -<date>.gz
# and the file is gzipped.
logrotate_logs = {
    '/var/log/chroma/': ['job_scheduler.log',
                         'http.log',
                         'corosync.log',
                         'http_agent.log',
                         'lustre_audit.log',
                         'plugin_runner.log',
                         'power_control.log',
                         'stats.log',
                         'supervisord.log',
                         'install.log',
                         'client_errors.log',
                         ],
    '/var/log/httpd': ['error_log',
                       'access_log',
                       'ssl_error_log',
                       ],
    '/var/log/': ['messages',
                  'chroma-agent.log',
                  'chroma-agent-console.log'
                  ]}

def run_command(cmd, out, err):

    try:
        p = subprocess.Popen(cmd,
                             stdout = out,
                             stderr = err)
    except OSError:
        #  The cmd in this case could not run on this platform, skipping
#        log.info("Skipping: %s" % cmd)
        return None
    else:
        p.wait()
        try:
            out.flush()
        except AttributeError:
            # doesn't do flush
            pass
        try:
            err.flush()
        except AttributeError:
            # doesn't do flush
            pass
        return p

def dump(fn, cmd, output_directory):

    out_fn = "%s.out" % fn
    err_fn = "%s.err" % fn
    out_path = os.path.join(output_directory, out_fn)
    err_path = os.path.join(output_directory, err_fn)

    with open(out_path, 'w') as out:
        with open(err_path, 'w') as err:
            result = run_command(cmd, out, err)

    # Remove meaningless zero lenth error files
    if os.path.getsize(err_path) <= 0:
        os.remove(err_path)

    return result

def execute(cmd):
    return run_command(cmd, subprocess.PIPE, subprocess.PIPE)

def copy_logrotate_logs(output_directory, days_back=1, verbose=0):
    """Go days_back to find compressed logrotate.d type log files to be copied.

    Note:  Chose to use nieve dates here, since this will run on the same
    host that the file was created they are likely to match.  The server is
    probably in UTC anyway.
    """

    if days_back < 0:
        return 0

    # Create a cutoff date by step back from now the requested number of days
    # and then setting the time to the beginning of that day.
    # For example, if you run it as 3pm today, and ask for 1 day back, the
    # default you get a cut off of the beginning of the day yesterday all 24
    # hours of yesterday, up to right now, today.
    cutoff_date = datetime.now() - timedelta(days=days_back)
    cutoff_date = cutoff_date.replace(hour=0, minute=0, second=0)
    cutoff_date_seconds = time.mktime(cutoff_date.timetuple())

    collected_files = defaultdict(list)

    # Collect all suitable files
    for path, log_names_to_collect in logrotate_logs.items():
        if os.path.exists(path):
            for file_name in os.listdir(path):
                _dash = file_name.rfind('-')
                if _dash < 0 or not file_name.endswith('gz'):
                    # chroma-agent.log should be matched as a file_name
                    root_file_name = file_name
                else:
                    root_file_name = file_name[0:_dash]

                if root_file_name in log_names_to_collect:
                    abs_path = os.path.join(path, file_name)
                    last_modified = os.path.getmtime(abs_path)
                    if last_modified >= cutoff_date_seconds:
                        collected_files[root_file_name].append((abs_path,
                                                                last_modified))
        else:
            if verbose > 0:
                log.info("%s does not exist." % path)

    # Copy all files into one file per filename
    for file_name, log_files in collected_files.items():
        ordered_log_files = [t[0] for t in sorted(log_files,
                             key=lambda file_tuple: file_tuple[1])]
        output_file_name = os.path.join(output_directory, file_name)
        for log_file in ordered_log_files:
            if log_file.endswith('gz'):
                cmd = ['zcat', log_file, '>>', output_file_name, ]
            else:
                cmd = ['cat', log_file, '>>', output_file_name, ]
            subprocess.Popen(' '.join(cmd), shell=True)
        if verbose > 1:
            log.info("copied logs: " % "\t\n".join(ordered_log_files))

    return len(collected_files)

DEFAULT_OUTPUT_DIRECTORY = '/var/log/'

PACKAGES = ['chroma-agent',
            'chroma-agent-management',
            'chroma-manager',
            'chroma-manager-cli',
            'chroma-manager-libs']

def main():

    desc = ("Run this save a tar gzipped collection of "
            "logs and diagnostic output.  "
            "Output:  %sdiagnostics_<date>_<fqdn>.tar.gz"
            % DEFAULT_OUTPUT_DIRECTORY)

    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument('--verbose', '-v', action='count', required=False,
                        help="More output for troubleshooting.")

    def _check_days_back(arg):
        try:
            days_back = int(arg)
        except ValueError:
            msg = "%s is not a valid number of days."
            raise argparse.ArgumentTypeError(msg % arg)
        else:
            if days_back < 0:
                msg = "Number of days must not be less than zero."
                raise argparse.ArgumentTypeError(msg)
            else:
                return days_back
    parser.add_argument('--days-back', '-d', required=False,
                        type=_check_days_back, default=1,
                        help="Number of days back to collect logs. "
                             "default is 1.  0 would mean today's logs only.")
    args = parser.parse_args()

    time_stamp = datetime.now().strftime("%Y%m%dT%H%M%S")
    output_fn = 'diagnostics_%s' % time_stamp

    hostname_process = execute(['hostname', '-f'])
    if hostname_process:
        output_fn = '%s_%s' % (output_fn, hostname_process.stdout.read().strip())

    output_directory = os.path.join(DEFAULT_OUTPUT_DIRECTORY, output_fn)
    os.mkdir(output_directory)

    log.info("\nCollecting diagnostic files\n")

    if dump('detected_devices', ['chroma-agent', 'device_plugin',
                                 '--plugin=linux'], output_directory):
        log.info("Detected devices")
    elif args.verbose > 0:
        log.info("Failed to Detected devices")

    if dump('rabbit_queue_status', ['rabbitmqctl', 'list_queues', '-p',
                                    'chromavhost'], output_directory):
        log.info("Inspected rabbit queues")
    elif args.verbose > 0:
        log.info("Failed to inspect rabbit queues")

    if dump('rpm_packges_installed', ['rpm', '-qa'], output_directory):
        log.info("Listed installed packages")
    elif args.verbose > 0:
        log.info("Failed to list installed packages")

    if dump('pacemaker-cib', ['cibadmin', '--query'], output_directory):
        log.info("Listed pacemaker configuration")
    elif args.verbose > 0:
        log.info("Failed to list Pacemaker configuration")

    if dump('chroma-config-validate', ['chroma-config',
                                       'validate'], output_directory):
        log.info("Validated chroma installation")
    elif args.verbose > 0:
        log.info("Failed to run chroma installation validation")

    if dump('finger-print', ['rpm', '-V', ] + PACKAGES, output_directory):
        log.info("Finger printed chroma installation")
    elif args.verbose > 0:
        log.info("Failed to finger print chroma installation")

    if dump('ps', ['ps', '-ef', '--forest'], output_directory):
        log.info("Listed running processes")
    elif args.verbose > 0:
        log.info("Failed to list running processes: ps")

    if dump('lspci', ['lspci', '-v'], output_directory):
        log.info("listed PCI devices")
    elif args.verbose > 0:
        log.info("Failed to list PCI devices: lspci")

    if dump('df', ['df', '--all'], output_directory):
        log.info("listed file system disk space.")
    elif args.verbose > 0:
        log.info("Failed to list file system disk space : df")

    for proc in ['cpuinfo', 'meminfo', 'mounts', 'partitions']:
        if dump(proc, ['cat', '/proc/%s' % proc], output_directory):
            log.info("listed cat /proc/%s" % proc)
        elif args.verbose > 0:
            log.info("Failed to list cat /proc/%s" % proc)

    if dump('etc_hosts', ['cat', '/etc/hosts', ], output_directory):
        log.info("Listed hosts")
    elif args.verbose > 0:
        log.info("Failed to list hosts: /etc/hosts")

    log_count = copy_logrotate_logs(output_directory, args.days_back, args.verbose)
    if log_count > 0:
        log.info("Copied %s log files." % log_count)
    elif args.verbose > 0:
        log.info("Failed to copy logs")

    tgz_path = '%s.tar.lzma' % output_directory
    #  Using -C to change to parent of dump dir,
    # then tgz'ing just the output dir
    execute(['tar', '--lzma', '-cf', tgz_path, '-C',
             DEFAULT_OUTPUT_DIRECTORY, output_fn])

    log.info("\nDiagnostic collection is completed.")
    log.info(tgz_path)

    log.info("\nThe diagnostic report tgz file can be "
             "emailed to Chroma support for analysis.")

if __name__ == "__main__":
    main()
<commit_msg>HYD-2653 - chroma-diagnostics should collect HA systems state in<commit_after>#
# INTEL CONFIDENTIAL
#
# Copyright 2013 Intel Corporation All Rights Reserved.
#
# The source code contained or described herein and all documents related
# to the source code ("Material") are owned by Intel Corporation or its
# suppliers or licensors. Title to the Material remains with Intel Corporation
# or its suppliers and licensors. The Material contains trade secrets and
# proprietary and confidential information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright and trade secret
# laws and treaty provisions. No part of the Material may be used, copied,
# reproduced, modified, published, uploaded, posted, transmitted, distributed,
# or disclosed in any way without Intel's prior express written permission.
#
# No license under any patent, copyright, trade secret or other intellectual
# property right is granted to or conferred upon you by disclosure or delivery
# of the Materials, either expressly, by implication, inducement, estoppel or
# otherwise. Any license under such intellectual property rights must be
# express and approved by Intel in writing.

from collections import defaultdict

import logging
import subprocess
from datetime import datetime, timedelta
import time
import argparse
import os

log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler())
log.setLevel(logging.INFO)
handler = logging.FileHandler("chroma-diagnostics.log")
handler.setFormatter(logging.Formatter('[%(asctime)s] %(message)s',
                                       '%d/%b/%Y:%H:%M:%S'))
log.addHandler(handler)

# Dictionary of parent path to array of logfiles
# that are rolled by logrotated such that when rotated
# the current file copied with the extendion -<date>.gz
# and the file is gzipped.
logrotate_logs = {
    '/var/log/chroma/': ['job_scheduler.log',
                         'http.log',
                         'corosync.log',
                         'http_agent.log',
                         'lustre_audit.log',
                         'plugin_runner.log',
                         'power_control.log',
                         'stats.log',
                         'supervisord.log',
                         'install.log',
                         'client_errors.log',
                         ],
    '/var/log/httpd': ['error_log',
                       'access_log',
                       'ssl_error_log',
                       ],
    '/var/log/': ['messages',
                  'chroma-agent.log',
                  'chroma-agent-console.log'
                  ]}

def run_command(cmd, out, err):

    try:
        p = subprocess.Popen(cmd,
                             stdout = out,
                             stderr = err)
    except OSError:
        #  The cmd in this case could not run on this platform, skipping
#        log.info("Skipping: %s" % cmd)
        return None
    else:
        p.wait()
        try:
            out.flush()
        except AttributeError:
            # doesn't do flush
            pass
        try:
            err.flush()
        except AttributeError:
            # doesn't do flush
            pass
        return p

def dump(fn, cmd, output_directory):

    out_fn = "%s.out" % fn
    err_fn = "%s.err" % fn
    out_path = os.path.join(output_directory, out_fn)
    err_path = os.path.join(output_directory, err_fn)

    with open(out_path, 'w') as out:
        with open(err_path, 'w') as err:
            result = run_command(cmd, out, err)

    # Remove meaningless zero lenth error files
    if os.path.getsize(err_path) <= 0:
        os.remove(err_path)

    return result

def execute(cmd):
    return run_command(cmd, subprocess.PIPE, subprocess.PIPE)

def copy_logrotate_logs(output_directory, days_back=1, verbose=0):
    """Go days_back to find compressed logrotate.d type log files to be copied.

    Note:  Chose to use nieve dates here, since this will run on the same
    host that the file was created they are likely to match.  The server is
    probably in UTC anyway.
    """

    if days_back < 0:
        return 0

    # Create a cutoff date by step back from now the requested number of days
    # and then setting the time to the beginning of that day.
    # For example, if you run it as 3pm today, and ask for 1 day back, the
    # default you get a cut off of the beginning of the day yesterday all 24
    # hours of yesterday, up to right now, today.
    cutoff_date = datetime.now() - timedelta(days=days_back)
    cutoff_date = cutoff_date.replace(hour=0, minute=0, second=0)
    cutoff_date_seconds = time.mktime(cutoff_date.timetuple())

    collected_files = defaultdict(list)

    # Collect all suitable files
    for path, log_names_to_collect in logrotate_logs.items():
        if os.path.exists(path):
            for file_name in os.listdir(path):
                _dash = file_name.rfind('-')
                if _dash < 0 or not file_name.endswith('gz'):
                    # chroma-agent.log should be matched as a file_name
                    root_file_name = file_name
                else:
                    root_file_name = file_name[0:_dash]

                if root_file_name in log_names_to_collect:
                    abs_path = os.path.join(path, file_name)
                    last_modified = os.path.getmtime(abs_path)
                    if last_modified >= cutoff_date_seconds:
                        collected_files[root_file_name].append((abs_path,
                                                                last_modified))
        else:
            if verbose > 0:
                log.info("%s does not exist." % path)

    # Copy all files into one file per filename
    for file_name, log_files in collected_files.items():
        ordered_log_files = [t[0] for t in sorted(log_files,
                             key=lambda file_tuple: file_tuple[1])]
        output_file_name = os.path.join(output_directory, file_name)
        for log_file in ordered_log_files:
            if log_file.endswith('gz'):
                cmd = ['zcat', log_file, '>>', output_file_name, ]
            else:
                cmd = ['cat', log_file, '>>', output_file_name, ]
            subprocess.Popen(' '.join(cmd), shell=True)
        if verbose > 1:
            log.info("copied logs: " % "\t\n".join(ordered_log_files))

    return len(collected_files)

DEFAULT_OUTPUT_DIRECTORY = '/var/log/'

PACKAGES = ['chroma-agent',
            'chroma-agent-management',
            'chroma-manager',
            'chroma-manager-cli',
            'chroma-manager-libs']

def main():

    desc = ("Run this save a tar gzipped collection of "
            "logs and diagnostic output.  "
            "Output:  %sdiagnostics_<date>_<fqdn>.tar.gz"
            % DEFAULT_OUTPUT_DIRECTORY)

    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument('--verbose', '-v', action='count', required=False,
                        help="More output for troubleshooting.")

    def _check_days_back(arg):
        try:
            days_back = int(arg)
        except ValueError:
            msg = "%s is not a valid number of days."
            raise argparse.ArgumentTypeError(msg % arg)
        else:
            if days_back < 0:
                msg = "Number of days must not be less than zero."
                raise argparse.ArgumentTypeError(msg)
            else:
                return days_back
    parser.add_argument('--days-back', '-d', required=False,
                        type=_check_days_back, default=1,
                        help="Number of days back to collect logs. "
                             "default is 1.  0 would mean today's logs only.")
    args = parser.parse_args()

    time_stamp = datetime.now().strftime("%Y%m%dT%H%M%S")
    output_fn = 'diagnostics_%s' % time_stamp

    hostname_process = execute(['hostname', '-f'])
    if hostname_process:
        output_fn = '%s_%s' % (output_fn, hostname_process.stdout.read().strip())

    output_directory = os.path.join(DEFAULT_OUTPUT_DIRECTORY, output_fn)
    os.mkdir(output_directory)

    log.info("\nCollecting diagnostic files\n")

    if dump('detected_devices', ['chroma-agent', 'device_plugin',
                                 '--plugin=linux'], output_directory):
        log.info("Detected devices")
    elif args.verbose > 0:
        log.info("Failed to Detected devices")

    if dump('rabbit_queue_status', ['rabbitmqctl', 'list_queues', '-p',
                                    'chromavhost'], output_directory):
        log.info("Inspected rabbit queues")
    elif args.verbose > 0:
        log.info("Failed to inspect rabbit queues")

    if dump('rpm_packges_installed', ['rpm', '-qa'], output_directory):
        log.info("Listed installed packages")
    elif args.verbose > 0:
        log.info("Failed to list installed packages")

    if dump('pacemaker-cib', ['cibadmin', '--query'], output_directory):
        log.info("Listed cibadmin --query")
    elif args.verbose > 0:
        log.info("Failed to list cibadmin --query")

    if dump('pacemaker-pcs-config-show', ['pcs', 'config', 'show'], output_directory):
        log.info("Listed: pcs config show")
    elif args.verbose > 0:
        log.info("Failed to list pcs config show")

    if dump('pacemaker-crm-mon-1', ['crm_mon', '-1r', ], output_directory):
        log.info("Listed: crm_mon -1r")
    elif args.verbose > 0:
        log.info("Failed to list crm_mon -1r")

    if dump('chroma-config-validate', ['chroma-config',
                                       'validate'], output_directory):
        log.info("Validated chroma installation")
    elif args.verbose > 0:
        log.info("Failed to run chroma installation validation")

    if dump('finger-print', ['rpm', '-V', ] + PACKAGES, output_directory):
        log.info("Finger printed chroma installation")
    elif args.verbose > 0:
        log.info("Failed to finger print chroma installation")

    if dump('ps', ['ps', '-ef', '--forest'], output_directory):
        log.info("Listed running processes")
    elif args.verbose > 0:
        log.info("Failed to list running processes: ps")

    if dump('lspci', ['lspci', '-v'], output_directory):
        log.info("listed PCI devices")
    elif args.verbose > 0:
        log.info("Failed to list PCI devices: lspci")

    if dump('df', ['df', '--all'], output_directory):
        log.info("listed file system disk space.")
    elif args.verbose > 0:
        log.info("Failed to list file system disk space : df")

    for proc in ['cpuinfo', 'meminfo', 'mounts', 'partitions']:
        if dump(proc, ['cat', '/proc/%s' % proc], output_directory):
            log.info("listed cat /proc/%s" % proc)
        elif args.verbose > 0:
            log.info("Failed to list cat /proc/%s" % proc)

    if dump('etc_hosts', ['cat', '/etc/hosts', ], output_directory):
        log.info("Listed hosts")
    elif args.verbose > 0:
        log.info("Failed to list hosts: /etc/hosts")

    log_count = copy_logrotate_logs(output_directory, args.days_back, args.verbose)
    if log_count > 0:
        log.info("Copied %s log files." % log_count)
    elif args.verbose > 0:
        log.info("Failed to copy logs")

    tgz_path = '%s.tar.lzma' % output_directory
    #  Using -C to change to parent of dump dir,
    # then tgz'ing just the output dir
    execute(['tar', '--lzma', '-cf', tgz_path, '-C',
             DEFAULT_OUTPUT_DIRECTORY, output_fn])

    log.info("\nDiagnostic collection is completed.")
    log.info(tgz_path)

    log.info("\nThe diagnostic report tgz file can be "
             "emailed to Chroma support for analysis.")

if __name__ == "__main__":
    main()
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# concise documentation build configuration file, created by
# sphinx-quickstart on Tue Jul  9 22:26:36 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('.'))

# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)

# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)

import concise

# -- 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.napoleon', 'sphinx.ext.viewcode']

autodoc_member_order = 'bysource'  # sort methods by source

# 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'CONCISE'
copyright = u"2016, Žiga Avsec"

# 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 = concise.__version__
# The full version, including alpha/beta/rc tags.
release = concise.__version__

# 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']

# 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 = 'concisedoc'

# -- 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]).
latex_documents = [
    ('index', 'concise.tex',
     u'CONCISE Documentation',
     u'Žiga Avsec', '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', 'concise',
     u'CONCISE Documentation',
     [u'Žiga Avsec'], 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', 'concise',
     u'CONCISE Documentation',
     u'Žiga Avsec',
     'concise',
     '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

from unittest.mock import MagicMock

class Mock(MagicMock):
    @classmethod
        def __getattr__(cls, name):
            return Mock()

MOCK_MODULES = ['builtins', 'pygtk', 'gtk', 'gobject', 'argparse', 'numpy', 'pandas']
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
<commit_msg>fixed synthax error read the docs<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# concise documentation build configuration file, created by
# sphinx-quickstart on Tue Jul  9 22:26:36 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('.'))

# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)

# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)

import concise

# -- 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.napoleon', 'sphinx.ext.viewcode']

autodoc_member_order = 'bysource'  # sort methods by source

# 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'CONCISE'
copyright = u"2016, Žiga Avsec"

# 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 = concise.__version__
# The full version, including alpha/beta/rc tags.
release = concise.__version__

# 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']

# 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 = 'concisedoc'

# -- 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]).
latex_documents = [
    ('index', 'concise.tex',
     u'CONCISE Documentation',
     u'Žiga Avsec', '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', 'concise',
     u'CONCISE Documentation',
     [u'Žiga Avsec'], 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', 'concise',
     u'CONCISE Documentation',
     u'Žiga Avsec',
     'concise',
     '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

from unittest.mock import MagicMock

class Mock(MagicMock):
    @classmethod
    def __getattr__(cls, name):
        return Mock()

MOCK_MODULES = ['builtins', 'pygtk', 'gtk', 'gobject', 'argparse', 'numpy', 'pandas']
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
<|endoftext|>


<commit_before>"""
Forms for LearningResources
"""

from __future__ import unicode_literals

from django.forms import ModelForm
from django.db import transaction

from .models import Course, Repository

# pylint: disable=no-init,missing-docstring
# pylint: disable=old-style-class,too-few-public-methods

class CourseForm(ModelForm):
    """
    Form for the Course object.
    """
    class Meta:
        model = Course
        fields = (
            "repository", "org", "course_number", "run", "imported_by"
        )

class RepositoryForm(ModelForm):
    """
    Form for the Course object.
    """
    class Meta:
        model = Repository
        fields = ("name", "description")

    # pylint: disable=signature-differs
    # The ModelForm.save() accepts "commit" and this doesn't, because
    # we always set commit=False then add the user because created_by is
    # not part of the form, and shouldn't be.
    @transaction.atomic
    def save(self, user):
        """
        Save a newly-created form.
        """
        repo = super(RepositoryForm, self).save(commit=False)
        repo.created_by = user
        repo.save()
        return repo
<commit_msg>Fix typo in docstring<commit_after>"""
Forms for LearningResources
"""

from __future__ import unicode_literals

from django.forms import ModelForm
from django.db import transaction

from .models import Course, Repository

# pylint: disable=no-init,missing-docstring
# pylint: disable=old-style-class,too-few-public-methods

class CourseForm(ModelForm):
    """
    Form for the Course object.
    """
    class Meta:
        model = Course
        fields = (
            "repository", "org", "course_number", "run", "imported_by"
        )

class RepositoryForm(ModelForm):
    """
    Form for the Repository object.
    """
    class Meta:
        model = Repository
        fields = ("name", "description")

    # pylint: disable=signature-differs
    # The ModelForm.save() accepts "commit" and this doesn't, because
    # we always set commit=False then add the user because created_by is
    # not part of the form, and shouldn't be.
    @transaction.atomic
    def save(self, user):
        """
        Save a newly-created form.
        """
        repo = super(RepositoryForm, self).save(commit=False)
        repo.created_by = user
        repo.save()
        return repo
<|endoftext|>


<commit_before># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest2
import mongoengine as me

from st2common.constants.types import ResourceType
from st2common.models.db import stormbase
import st2common.util.actionalias_matching as matching

class MemoryActionAliasDB(stormbase.StormFoundationDB, stormbase.ContentPackResourceMixin,
                          stormbase.UIDFieldMixin):
    """
    Database entity that represent an Alias for an action.

    Attribute:
        pack: Pack to which this alias belongs to.
        name: Alias name.
        ref: Alias reference (pack + name).
        enabled: A flag indicating whether this alias is enabled in the system.
        action_ref: Reference of an action this alias belongs to.
        formats: Alias format strings.
    """

    RESOURCE_TYPE = ResourceType.ACTION
    UID_FIELDS = ['pack', 'name']

    name = me.StringField(required=True)
    ref = me.StringField(required=True)
    description = me.StringField()
    pack = me.StringField(
        required=True,
        help_text='Name of the content pack.',
        unique_with='name')
    enabled = me.BooleanField(
        required=True, default=True,
        help_text='A flag indicating whether the action alias is enabled.')
    action_ref = me.StringField(
        required=True,
        help_text='Reference of the Action map this alias.')
    formats = me.ListField(
        help_text='Possible parameter formats that an alias supports.')
    ack = me.DictField(
        help_text='Parameters pertaining to the acknowledgement message.'
    )
    result = me.DictField(
        help_text='Parameters pertaining to the execution result message.'
    )
    extra = me.DictField(
        help_text='Additional parameters (usually adapter-specific) not covered in the schema.'
    )

    def __init__(self, *args, **values):
        super(MemoryActionAliasDB, self).__init__(*args, **values)

class ActionAliasTestCase(unittest2.TestCase):
    '''
    Test scenarios must consist of 80s movie quotes.
    '''
    def test_list_format_strings_from_aliases(self):
        ALIASES = [
            MemoryActionAliasDB(name="kyle_reese", ref="terminator.1",
                                formats=["Come with me if you want to live"]),
            MemoryActionAliasDB(name="terminator", ref="terminator.2",
                                formats=["I need your {{item}}, your {{item2}}"
                                         " and your {{vehicle}}"])
        ]
        result = matching.list_format_strings_from_aliases(ALIASES)

        self.assertEqual(len(result), 2)

        self.assertEqual(result[0][0], "Come with me if you want to live")
        self.assertEqual(result[1][0],
                         "I need your {{item}}, your {{item2}} and"
                         " your {{vehicle}}")

    def test_list_format_strings_from_aliases_with_display(self):
        ALIASES = [
            MemoryActionAliasDB(name="johnny_five_alive", ref="short_circuit.1", formats=[
                {'display': 'Number 5 is {{status}}',
                 'representation': ['Number 5 is {{status=alive}}']},
                'Hey, laser lips, your mama was a snow blower.']),
            MemoryActionAliasDB(name="i_feel_alive", ref="short_circuit.2",
                                formats=["How do I feel? I feel... {{status}}!"])
        ]
        result = matching.list_format_strings_from_aliases(ALIASES)

        self.assertEqual(len(result), 3)

        self.assertEqual(result[0][0], "Number 5 is {{status}}")
        self.assertEqual(result[0][1], "Number 5 is {{status=alive}}")
        self.assertEqual(result[1][0], "Hey, laser lips, your mama was a snow blower.")
        self.assertEqual(result[1][1], "Hey, laser lips, your mama was a snow blower.")
        self.assertEqual(result[2][0], "How do I feel? I feel... {{status}}!")
        self.assertEqual(result[2][1], "How do I feel? I feel... {{status}}!")

    def test_normalise_alias_format_string(self):
        result = matching.normalise_alias_format_string(
            'Quite an experience to live in fear, isn\'t it?')

        self.assertEqual([result[0]], result[1])
        self.assertEqual(result[0], "Quite an experience to live in fear, isn't it?")

    def test_matching(self):
        ALIASES = [
            MemoryActionAliasDB(name="spengler", ref="ghostbusters.1",
                                formats=["{{choice}} cross the {{target}}"]),
        ]
        COMMAND = "Don't cross the streams"
        match = matching.match_command_to_alias(COMMAND, ALIASES)
        self.assertEqual(len(match), 1)
        self.assertEqual(match[0][0].ref, "ghostbusters.1")
        self.assertEqual(match[0][2], "{{choice}} cross the {{target}}")

    # we need some more complex scenarios in here.
<commit_msg>update the unit tests to patch out the UID generator instead of creating an entire mock class<commit_after># Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest2
import mock

from st2common.models.db.actionalias import ActionAliasDB
import st2common.util.actionalias_matching as matching

MemoryActionAliasDB = ActionAliasDB

@mock.patch.object(MemoryActionAliasDB, 'get_uid')
class ActionAliasTestCase(unittest2.TestCase):
    '''
    Test scenarios must consist of 80s movie quotes.
    '''
    def test_list_format_strings_from_aliases(self, mock):
        ALIASES = [
            MemoryActionAliasDB(name="kyle_reese", ref="terminator.1",
                                formats=["Come with me if you want to live"]),
            MemoryActionAliasDB(name="terminator", ref="terminator.2",
                                formats=["I need your {{item}}, your {{item2}}"
                                         " and your {{vehicle}}"])
        ]
        result = matching.list_format_strings_from_aliases(ALIASES)

        self.assertEqual(len(result), 2)

        self.assertEqual(result[0][0], "Come with me if you want to live")
        self.assertEqual(result[1][0],
                         "I need your {{item}}, your {{item2}} and"
                         " your {{vehicle}}")

    def test_list_format_strings_from_aliases_with_display(self, mock):
        ALIASES = [
            MemoryActionAliasDB(name="johnny_five_alive", ref="short_circuit.1", formats=[
                {'display': 'Number 5 is {{status}}',
                 'representation': ['Number 5 is {{status=alive}}']},
                'Hey, laser lips, your mama was a snow blower.']),
            MemoryActionAliasDB(name="i_feel_alive", ref="short_circuit.2",
                                formats=["How do I feel? I feel... {{status}}!"])
        ]
        result = matching.list_format_strings_from_aliases(ALIASES)

        self.assertEqual(len(result), 3)

        self.assertEqual(result[0][0], "Number 5 is {{status}}")
        self.assertEqual(result[0][1], "Number 5 is {{status=alive}}")
        self.assertEqual(result[1][0], "Hey, laser lips, your mama was a snow blower.")
        self.assertEqual(result[1][1], "Hey, laser lips, your mama was a snow blower.")
        self.assertEqual(result[2][0], "How do I feel? I feel... {{status}}!")
        self.assertEqual(result[2][1], "How do I feel? I feel... {{status}}!")

    def test_normalise_alias_format_string(self, mock):
        result = matching.normalise_alias_format_string(
            'Quite an experience to live in fear, isn\'t it?')

        self.assertEqual([result[0]], result[1])
        self.assertEqual(result[0], "Quite an experience to live in fear, isn't it?")

    def test_matching(self, mock):
        ALIASES = [
            MemoryActionAliasDB(name="spengler", ref="ghostbusters.1",
                                formats=["{{choice}} cross the {{target}}"]),
        ]
        COMMAND = "Don't cross the streams"
        match = matching.match_command_to_alias(COMMAND, ALIASES)
        self.assertEqual(len(match), 1)
        self.assertEqual(match[0][0].ref, "ghostbusters.1")
        self.assertEqual(match[0][2], "{{choice}} cross the {{target}}")

    # we need some more complex scenarios in here.
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# pyfact documentation build configuration file, created by
# sphinx-quickstart on Thu Mar  1 15:16:15 2012.
#
# 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, os

# Add script parent directory to python search path to get access to the pyfact package
sys.path.append(os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/..'))
#sys.path.append(os.path.abspath('/Users/mraue/Stuff/work/cta/2011/fits/pyfact-trunk'))

# 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.todo',
    'sphinx.ext.pngmath',
    'sphinx.ext.mathjax',
    'sphinx.ext.ifconfig',
    'sphinx.ext.viewcode',
    'npdoc'
    ]

# Don't show summaries of the members in each class along with the
# class' docstring
numpydoc_show_class_members = False

# 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'pyfact'
copyright = u'2012, Martin Raue'

# 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.1.0'
# The full version, including alpha/beta/rc tags.
release = '0.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 = []

# -- 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']

# 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 = 'pyfactdoc'

# -- 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]).
latex_documents = [
  ('index', 'pyfact.tex', u'pyfact Documentation',
   u'Martin Raue', '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', 'pyfact', u'pyfact Documentation',
     [u'Martin Raue'], 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', 'pyfact', u'pyfact Documentation',
   u'Martin Raue', 'pyfact', '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'
<commit_msg>Mock libraries with C extensions for docs build.<commit_after># -*- coding: utf-8 -*-
#
# pyfact documentation build configuration file, created by
# sphinx-quickstart on Thu Mar  1 15:16:15 2012.
#
# 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, os

# Add script parent directory to python search path to get access to the pyfact package
sys.path.append(os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/..'))
#sys.path.append(os.path.abspath('/Users/mraue/Stuff/work/cta/2011/fits/pyfact-trunk'))

# 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.todo',
    'sphinx.ext.pngmath',
    'sphinx.ext.mathjax',
    'sphinx.ext.ifconfig',
    'sphinx.ext.viewcode',
    'npdoc'
    ]

# Don't show summaries of the members in each class along with the
# class' docstring
numpydoc_show_class_members = False

# 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'pyfact'
copyright = u'2012, Martin Raue'

# 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.1.0'
# The full version, including alpha/beta/rc tags.
release = '0.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 = []

# -- 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']

# 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 = 'pyfactdoc'

# -- 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]).
latex_documents = [
  ('index', 'pyfact.tex', u'pyfact Documentation',
   u'Martin Raue', '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', 'pyfact', u'pyfact Documentation',
     [u'Martin Raue'], 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', 'pyfact', u'pyfact Documentation',
   u'Martin Raue', 'pyfact', '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'

# Mock libraries with C extensions to be able to build the docs if
# they are not present. Copied from here:
# http://read-the-docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules

class Mock(object):
    def __init__(self, *args, **kwargs):
        pass

    def __call__(self, *args, **kwargs):
        return Mock()

    @classmethod
    def __getattr__(self, name):
        if name in ('__file__', '__path__'):
            return '/dev/null'
        elif name[0] == name[0].upper():
            return type(name, (), {})
        else:
            return Mock()

MOCK_MODULES = ['numpy', 'scipy', 'scipy.optimize', 'scipy.special',
                'scipy.ndimage', 'pyfits', 'matplotlib', 'kapteyn']
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = Mock()<|endoftext|>


<commit_before>import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.training import moving_averages

import config as cfg

def relu_block(x, alpha=0., max_value=None):
    negative_part = tf.nn.relu(-x)
    x = tf.nn.relu(x)
    if max_value is not None:
        x = tf.clip_by_value(x, tf.cast(0., dtype=tf.float32),
                             tf.cast(max_value, dtype=tf.float32))
    x -= tf.constant(alpha, dtype=tf.float32) * negative_part
    return x

def res_block(inp, is_training_cond):
    """ResNet B Block.
    TODO: decide whether bias is worth it
    """
    inp_shape = inp.get_shape()
    assert inp_shape[-1] == 64 # Must have 64 channels to start.

    with tf.variable_scope("resconv1"):
        h = conv_block(inp, relu=True, bn=True, is_training_cond=is_training_cond)

    with tf.variable_scope("resconv2"):
        h = conv_block(h, bn=True, is_training_cond=is_training_cond)

    return inp + h

def deconv_block(inp, relu=True, output_channels=64):
    """
    TODO: Decide whether or not to add bias.
        biases = tf.get_variable('biases', [output_shape[-1]], initializer=tf.constant_initializer(0.0))
        deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape())
    """
    inp_shape = inp.get_shape()
    kernel_shape = (3, 3, output_channels, inp_shape[-1])
    output_shape = (int(inp_shape[0]), int(inp_shape[1] * 2), int(inp_shape[2] * 2), output_channels)
    strides = [1, 2, 2, 1]

    weights = tf.get_variable('weights', kernel_shape,
        initializer=tf.random_normal_initializer(stddev=0.02))
    h = tf.nn.conv2d_transpose(inp, weights, output_shape, strides)

    if relu:
        h = tf.nn.relu(h)

    return h

def conv_block(inp, relu=False, leaky_relu=False, bn=False,
               output_channels=64, stride=1, is_training_cond=None):
    inp_shape = inp.get_shape()
    kernel_shape = (3, 3, inp_shape[-1], output_channels)
    strides = [1, stride, stride, 1]

    weights = tf.get_variable('weights', kernel_shape,
        initializer=tf.random_normal_initializer(stddev=0.02))
    h = tf.nn.conv2d(inp, weights, strides, padding='SAME')

    if leaky_relu:
        h = relu_block(h, alpha=0.1)

    if bn:
        params_shape = h.get_shape()[-1:]
        beta = tf.get_variable('beta', params_shape,
            initializer=tf.zeros_initializer)
        gamma = tf.get_variable('gamma', params_shape,
            initializer=tf.ones_initializer)
        moving_mean = tf.get_variable('moving_mean', params_shape,
            initializer=tf.zeros_initializer, trainable=False)
        moving_variance = tf.get_variable('moving_variance', params_shape,
            initializer=tf.ones_initializer, trainable=False)
        mean, variance = tf.nn.moments(h, [0, 1, 2])
        update_moving_mean = moving_averages.assign_moving_average(moving_mean,
            mean, cfg.BN_DECAY)
        update_moving_variance = moving_averages.assign_moving_average(moving_variance,
            variance, cfg.BN_DECAY)
        tf.add_to_collection(cfg.UPDATE_OPS_COLLECTION, update_moving_mean)
        tf.add_to_collection(cfg.UPDATE_OPS_COLLECTION, update_moving_variance)
        mean, variance = tf.cond(is_training_cond, lambda: (mean, variance),
            lambda: (moving_mean, moving_variance))
        h = tf.nn.batch_normalization(h, mean, variance, beta, gamma, cfg.BN_EPSILON)

    if relu:
        h = tf.nn.relu(h)

    return h

def dense_block(inp, leaky_relu=False, sigmoid=False,
                output_size=1024):
    inp_size = inp.get_shape()
    h = tf.reshape(inp, [int(inp_size[0]), -1])
    h_size = h.get_shape()[1]

    w = tf.get_variable("w", [h_size, output_size],
        initializer=tf.random_normal_initializer(stddev=0.02))
    b = tf.get_variable("b", [output_size],
        initializer=tf.constant_initializer(0.0))

    h = tf.matmul(h, w) + b

    if leaky_relu:
        h = relu_block(h, alpha=0.1)

    if sigmoid:
        h = tf.nn.sigmoid(h)

    return h

<commit_msg>Add bias to deconv layer.<commit_after>import tensorflow as tf
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.training import moving_averages

import config as cfg

def relu_block(x, alpha=0., max_value=None):
    negative_part = tf.nn.relu(-x)
    x = tf.nn.relu(x)
    if max_value is not None:
        x = tf.clip_by_value(x, tf.cast(0., dtype=tf.float32),
                             tf.cast(max_value, dtype=tf.float32))
    x -= tf.constant(alpha, dtype=tf.float32) * negative_part
    return x

def res_block(inp, is_training_cond):
    """ResNet B Block.
    TODO: decide whether bias is worth it
    """
    inp_shape = inp.get_shape()
    assert inp_shape[-1] == 64 # Must have 64 channels to start.

    with tf.variable_scope("resconv1"):
        h = conv_block(inp, relu=True, bn=True, is_training_cond=is_training_cond)

    with tf.variable_scope("resconv2"):
        h = conv_block(h, bn=True, is_training_cond=is_training_cond)

    return inp + h

def deconv_block(inp, relu=True, output_channels=64):
    """
    TODO: Decide whether or not to add bias.
        biases = tf.get_variable('biases', [output_shape[-1]], initializer=tf.constant_initializer(0.0))
        deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape())
    """
    inp_shape = inp.get_shape()
    kernel_shape = (3, 3, output_channels, inp_shape[-1])
    output_shape = (int(inp_shape[0]), int(inp_shape[1] * 2), int(inp_shape[2] * 2), output_channels)
    strides = [1, 2, 2, 1]

    weights = tf.get_variable('weights', kernel_shape,
        initializer=tf.random_normal_initializer(stddev=0.02))
    h = tf.nn.conv2d_transpose(inp, weights, output_shape, strides)

    bias = tf.get_variable('bias', [output_channels],
            initializer=tf.constant_initializer(0.0))
    h = tf.nn.bias_add(h, bias)

    if relu:
        h = tf.nn.relu(h)

    return h

def conv_block(inp, relu=False, leaky_relu=False, bn=False,
               output_channels=64, stride=1, is_training_cond=None):
    inp_shape = inp.get_shape()
    kernel_shape = (3, 3, inp_shape[-1], output_channels)
    strides = [1, stride, stride, 1]

    weights = tf.get_variable('weights', kernel_shape,
        initializer=tf.random_normal_initializer(stddev=0.02))
    h = tf.nn.conv2d(inp, weights, strides, padding='SAME')

    if leaky_relu:
        h = relu_block(h, alpha=0.1)

    if bn:
        params_shape = h.get_shape()[-1:]
        beta = tf.get_variable('beta', params_shape,
            initializer=tf.zeros_initializer)
        gamma = tf.get_variable('gamma', params_shape,
            initializer=tf.ones_initializer)
        moving_mean = tf.get_variable('moving_mean', params_shape,
            initializer=tf.zeros_initializer, trainable=False)
        moving_variance = tf.get_variable('moving_variance', params_shape,
            initializer=tf.ones_initializer, trainable=False)
        mean, variance = tf.nn.moments(h, [0, 1, 2])
        update_moving_mean = moving_averages.assign_moving_average(moving_mean,
            mean, cfg.BN_DECAY)
        update_moving_variance = moving_averages.assign_moving_average(moving_variance,
            variance, cfg.BN_DECAY)
        tf.add_to_collection(cfg.UPDATE_OPS_COLLECTION, update_moving_mean)
        tf.add_to_collection(cfg.UPDATE_OPS_COLLECTION, update_moving_variance)
        mean, variance = tf.cond(is_training_cond, lambda: (mean, variance),
            lambda: (moving_mean, moving_variance))
        h = tf.nn.batch_normalization(h, mean, variance, beta, gamma, cfg.BN_EPSILON)

    if relu:
        h = tf.nn.relu(h)

    return h

def dense_block(inp, leaky_relu=False, sigmoid=False,
                output_size=1024):
    inp_size = inp.get_shape()
    h = tf.reshape(inp, [int(inp_size[0]), -1])
    h_size = h.get_shape()[1]

    w = tf.get_variable("w", [h_size, output_size],
        initializer=tf.random_normal_initializer(stddev=0.02))
    b = tf.get_variable("b", [output_size],
        initializer=tf.constant_initializer(0.0))

    h = tf.matmul(h, w) + b

    if leaky_relu:
        h = relu_block(h, alpha=0.1)

    if sigmoid:
        h = tf.nn.sigmoid(h)

    return h

<|endoftext|>


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

"""

ZUGBRUECKE
Calling routines in Windows DLLs from Python scripts running on unixlike systems
https://github.com/pleiszenburg/zugbruecke

	docs/conf.py: Configures the documentation build process

	Required to run on platform / side: [UNIX]

	Copyright (C) 2017-2019 Sebastian M. Ernst <ernst@pleiszenburg.de>

<LICENSE_BLOCK>
The contents of this file are subject to the GNU Lesser General Public License
Version 2.1 ("LGPL" or "License"). You may not use this file except in
compliance with the License. You may obtain a copy of the License at
https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
https://github.com/pleiszenburg/zugbruecke/blob/master/LICENSE

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
specific language governing rights and limitations under the License.
</LICENSE_BLOCK>

"""

def fetch_version_string():

	f = open('../setup.py', 'r')
	setup_py = f.read()
	f.close()

	version = ''
	setup_py_lines = setup_py.split('\n')
	for line in setup_py_lines:
		if '_version_' in line:
			version = line.split("'")[1].split("'")[0]
			break

	return version

# 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.
#
# import os
# import sys
# 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 = []

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

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = 'zugbruecke'
copyright = '2017-2018 Sebastian M. Ernst'
author = 'Sebastian M. Ernst'

# 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 = fetch_version_string()
# The full version, including alpha/beta/rc tags.
release = fetch_version_string()

# 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 = None

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

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

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = 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 = 'alabaster'
html_theme = "sphinx_rtd_theme"

# 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 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']

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
    '**': [
        'about.html',
        'navigation.html',
        'relations.html',  # needs 'show_related': True theme option to display
        'searchbox.html',
        'donate.html',
    ]
}

# -- Options for HTMLHelp output ------------------------------------------

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

# -- 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': '',

    # 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 = [
    (master_doc, 'zugbruecke.tex', 'zugbruecke Documentation',
     'Sebastian M. Ernst', 'manual'),
]

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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'zugbruecke', 'zugbruecke Documentation',
     [author], 1)
]

# -- 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 = [
    (master_doc, 'zugbruecke', 'zugbruecke Documentation',
     author, 'zugbruecke', 'One line description of project.',
     'Miscellaneous'),
]
<commit_msg>push copyright in documentation<commit_after>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

ZUGBRUECKE
Calling routines in Windows DLLs from Python scripts running on unixlike systems
https://github.com/pleiszenburg/zugbruecke

	docs/conf.py: Configures the documentation build process

	Required to run on platform / side: [UNIX]

	Copyright (C) 2017-2019 Sebastian M. Ernst <ernst@pleiszenburg.de>

<LICENSE_BLOCK>
The contents of this file are subject to the GNU Lesser General Public License
Version 2.1 ("LGPL" or "License"). You may not use this file except in
compliance with the License. You may obtain a copy of the License at
https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
https://github.com/pleiszenburg/zugbruecke/blob/master/LICENSE

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
specific language governing rights and limitations under the License.
</LICENSE_BLOCK>

"""

def fetch_version_string():

	f = open('../setup.py', 'r')
	setup_py = f.read()
	f.close()

	version = ''
	setup_py_lines = setup_py.split('\n')
	for line in setup_py_lines:
		if '_version_' in line:
			version = line.split("'")[1].split("'")[0]
			break

	return version

# 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.
#
# import os
# import sys
# 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 = []

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

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = 'zugbruecke'
copyright = '2017-2019 Sebastian M. Ernst'
author = 'Sebastian M. Ernst'

# 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 = fetch_version_string()
# The full version, including alpha/beta/rc tags.
release = fetch_version_string()

# 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 = None

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

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

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = 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 = 'alabaster'
html_theme = "sphinx_rtd_theme"

# 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 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']

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
    '**': [
        'about.html',
        'navigation.html',
        'relations.html',  # needs 'show_related': True theme option to display
        'searchbox.html',
        'donate.html',
    ]
}

# -- Options for HTMLHelp output ------------------------------------------

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

# -- 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': '',

    # 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 = [
    (master_doc, 'zugbruecke.tex', 'zugbruecke Documentation',
     'Sebastian M. Ernst', 'manual'),
]

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

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (master_doc, 'zugbruecke', 'zugbruecke Documentation',
     [author], 1)
]

# -- 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 = [
    (master_doc, 'zugbruecke', 'zugbruecke Documentation',
     author, 'zugbruecke', 'One line description of project.',
     'Miscellaneous'),
]
<|endoftext|>