<commit_before>from instagram.client import InstagramAPI
import os
import time
import cups
from xhtml2pdf import pisa
import sys

# Note this is heavily inspired from https://nicshackle.wordpress.com/2014/04/09/hashtag-activated-instagram-printer/

def addToPrintQueue(url):
    html = '
Your image:
\n'
    html += '

'
    pdf = pisa.CreatePDF(html, file("/tmp/instagram-print.pdf", "w"))

    if not pdf.err:
        pdf.dest.close()
        connection = cups.Connection()
        printer = connection.getDefault()

        if printer is None:
            print("failed to print as a default printer has not been set up in cups.")
        else:
            connection.printFile(printer, "/tmp/instagram-print.pdf", "instagram", {})
            print("added image document to print queue")
    else:
        print("failed to add image document to print queue")

api = InstagramAPI(client_id=os.environ['INSTAGRAM_CLIENT_ID'], client_secret=os.environ['INSTAGRAM_CLIENT_SECRET'])

mostRecentId = 0
url = ''
previous_url = ''

while True:
    try:
        sys.stdout.write('.')
        sys.stdout.flush()
        recent_media = api.tag_recent_media(1, mostRecentId, 'soccer')

        for media in recent_media[0]:
            url = media.images['standard_resolution'].url
            mostRecentId = media.id

            if (url != previous_url):
                print "\n---received an image---"
                print str(media.user)
                print str(media.caption)
                print "url: " + str(url)
                previous_url = url
                addToPrintQueue(url)
                print "\n"

    except Exception, e:
        print "failed to retrieve recent media due to"
        print e

    # lets not go mental, rate limit seems to be 5000 / hr. (5 secs = 720 requests per hr)
    time.sleep(5)
<commit_msg>print to the first printer we find<commit_after>from instagram.client import InstagramAPI
import os
import time
import cups
from xhtml2pdf import pisa
import sys

# Note this is heavily inspired from https://nicshackle.wordpress.com/2014/04/09/hashtag-activated-instagram-printer/

def addToPrintQueue(url):
    html = '
Your image:
\n'
    html += '

'
    pdf = pisa.CreatePDF(html, file("/tmp/instagram-print.pdf", "w"))

    if not pdf.err:
        pdf.dest.close()
        connection = cups.Connection()
        printer = connection.getDefault()

        printers = connection.getPrinters()
        for printer in printers:
            print printer, printers[printer]["device-uri"]
            printer_name = printers.keys()[0] #use first printer in list

            connection.printFile(printer_name, "/tmp/instagram-print.pdf", "instagram", {})
            print("added image document to print queue")
    else:
        print("failed to add image document to print queue")

api = InstagramAPI(client_id=os.environ['INSTAGRAM_CLIENT_ID'], client_secret=os.environ['INSTAGRAM_CLIENT_SECRET'])

mostRecentId = 0
url = ''
previous_url = ''

while True:
    try:
        sys.stdout.write('.')
        sys.stdout.flush()
        recent_media = api.tag_recent_media(1, mostRecentId, 'soccer')

        for media in recent_media[0]:
            url = media.images['standard_resolution'].url
            mostRecentId = media.id

            if (url != previous_url):
                print "\n---received an image---"
                print str(media.user)
                print str(media.caption)
                print "url: " + str(url)
                previous_url = url
                addToPrintQueue(url)
                print "\n"

    except Exception, e:
        print "failed to retrieve recent media due to"
        print e

    # lets not go mental, rate limit seems to be 5000 / hr. (5 secs = 720 requests per hr)
    time.sleep(5)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# image_registration documentation build configuration file, created by
# sphinx-quickstart on Mon Sep  3 08:57:59 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

try:
    import numpy
except ImportError:
    pass
try:
    import scipy
except ImportError:
    pass
try:
    import image_registration
except ImportError:
    pass
try:
    import numpydoc
    print "numpydoc path is ",numpydoc.__file__
except ImportError:
    print "Failed to import numpydoc"

# 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('.'))
rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, rootpath)
#import numpydoc
#sys.path.insert(0, os.path.split(numpydoc.__file__)[0])
sys.path.insert(0, rootpath+"/doc/sphinxext/")
sys.path.append(os.path.abspath('sphinxext'))
sys.path.append(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.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage',
'sphinx.ext.pngmath', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig',
'sphinx.ext.viewcode','numpydoc','edit_on_github']

# 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'image_registration'
copyright = u'2012, Adam Ginsburg'

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

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

# -- 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', 'image_registration.tex', u'image\\_registration Documentation',
   u'Adam Ginsburg', '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', 'image_registration', u'image_registration Documentation',
     [u'Adam Ginsburg'], 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', 'image_registration', u'image_registration Documentation',
   u'Adam Ginsburg', 'image_registration', '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'

todo_include_todos = True

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}

# Don't import the module as "version" or it will override the
# "version" configuration parameter
from astropy import version as versionmod
edit_on_github_project = "keflavich/image_registration"
edit_on_github_branch = "master"
edit_on_github_source_root = ""
edit_on_github_doc_root = "doc"

# read the docs mocks
import sys

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

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

    @classmethod
    def __getattr__(cls, 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', 'pyfits', 'astropy', 'pytest', 'astropy.wcs',
    'astropy.io', 'astropy.io.fits', 'astropy.nddata', 'scipy.ndimage', 'pywcs',
    'matplotlib', 'matplotlib.pyplot']
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = Mock()
<commit_msg>removed an unnecessary line<commit_after># -*- coding: utf-8 -*-
#
# image_registration documentation build configuration file, created by
# sphinx-quickstart on Mon Sep  3 08:57:59 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

try:
    import numpy
except ImportError:
    pass
try:
    import scipy
except ImportError:
    pass
try:
    import image_registration
except ImportError:
    pass
try:
    import numpydoc
    print "numpydoc path is ",numpydoc.__file__
except ImportError:
    print "Failed to import numpydoc"

# 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('.'))
rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, rootpath)
#import numpydoc
#sys.path.insert(0, os.path.split(numpydoc.__file__)[0])
sys.path.insert(0, rootpath+"/doc/sphinxext/")
sys.path.append(os.path.abspath('sphinxext'))
sys.path.append(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.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage',
'sphinx.ext.pngmath', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig',
'sphinx.ext.viewcode','numpydoc','edit_on_github']

# 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'image_registration'
copyright = u'2012, Adam Ginsburg'

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

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

# -- 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', 'image_registration.tex', u'image\\_registration Documentation',
   u'Adam Ginsburg', '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', 'image_registration', u'image_registration Documentation',
     [u'Adam Ginsburg'], 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', 'image_registration', u'image_registration Documentation',
   u'Adam Ginsburg', 'image_registration', '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'

todo_include_todos = True

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}

# Don't import the module as "version" or it will override the
# "version" configuration parameter
edit_on_github_project = "keflavich/image_registration"
edit_on_github_branch = "master"
edit_on_github_source_root = ""
edit_on_github_doc_root = "doc"

# read the docs mocks
import sys

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

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

    @classmethod
    def __getattr__(cls, 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', 'pyfits', 'astropy', 'pytest', 'astropy.wcs',
    'astropy.io', 'astropy.io.fits', 'astropy.nddata', 'scipy.ndimage', 'pywcs',
    'matplotlib', 'matplotlib.pyplot']
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = Mock()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# QuTiP documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 25 14:08:15 2011.
#
# 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

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

# 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'QuTiP'
copyright = u'2011, P.D. Nation, J.R. Johansson'

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

# 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 = "haiku"

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

# -- 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', 'QuTiP.tex', u'QuTiP Documentation',
   u'P.D. Nation, J.R. Johansson', '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', 'qutip', u'QuTiP Documentation',
     [u'P.D. Nation, J.R. Johansson'], 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', 'QuTiP', u'QuTiP Documentation', u'P.D. Nation, J.R. Johansson',
   'QuTiP', '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>needed flag for sphinx 1.1+ since we use mathjax<commit_after># -*- coding: utf-8 -*-
#
# QuTiP documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 25 14:08:15 2011.
#
# 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

# 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.1'

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

# 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'QuTiP'
copyright = u'2011, P.D. Nation, J.R. Johansson'

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

# 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 = "haiku"

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

# -- 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', 'QuTiP.tex', u'QuTiP Documentation',
   u'P.D. Nation, J.R. Johansson', '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', 'qutip', u'QuTiP Documentation',
     [u'P.D. Nation, J.R. Johansson'], 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', 'QuTiP', u'QuTiP Documentation', u'P.D. Nation, J.R. Johansson',
   'QuTiP', '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'<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# giddy documentation build configuration file, created by
# sphinx-quickstart on Wed Jun  6 15:54:22 2018.
#
# 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.

# 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 sys, os
import sphinx_bootstrap_theme
import matplotlib as mpl
mpl.use("Agg")

sys.path.insert(0, os.path.abspath('../../'))

import giddy

# -- 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_gallery.gen_gallery',
              'sphinx.ext.autodoc',
              'sphinx.ext.autosummary',
              'sphinx.ext.viewcode',
              'sphinxcontrib.bibtex',
              'sphinx.ext.mathjax',
              'sphinx.ext.doctest',
              'sphinx.ext.intersphinx',
              'numpydoc',]
              #'matplotlib.sphinxext.plot_directive']
              #"sphinx.ext.napoleon"]

# sphinx_gallery_conf = {
#      # path to your examples scripts
#      'examples_dirs': '../examples',
#      # path where to save gallery generated examples
#      'gallery_dirs': 'auto_examples',
#      'backreferences_dir': False,
# }

# 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 = 'giddy'
copyright = '2018, pysal developers'
author = 'pysal developers'

# 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 full version.
version = giddy.__version__
release = giddy.__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 = 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', 'tests/*']

# 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 = 'bootstrap'
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()
html_title = "%s v%s Manual" % (project, version)

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

    # Navigation bar title. (Default: ``project`` value)
    'navbar_title': "giddy",

    # Render the next and previous page links in navbar. (Default: true)
    'navbar_sidebarrel': False,

    # Render the current pages TOC in the navbar. (Default: true)
    #'navbar_pagenav': True,
    #'navbar_pagenav': False,

    # No sidebar
    'nosidebar': True,

    # Tab name for the current pages TOC. (Default: "Page")
    #'navbar_pagenav_name': "Page",

    # Global TOC depth for "site" navbar tab. (Default: 1)
    # Switching to -1 shows all levels.
    'globaltoc_depth': 2,

    # Include hidden TOCs in Site navbar?
    #
    # Note: If this is "false", you cannot have mixed ``:hidden:`` and
    # non-hidden ``toctree`` directives in the same page, or else the build
    # will break.
    #
    # Values: "true" (default) or "false"
    'globaltoc_includehidden': "true",

    # HTML navbar class (Default: "navbar") to attach to <div> element.
    # For black navbar, do "navbar navbar-inverse"
    #'navbar_class': "navbar navbar-inverse",

    # Fix navigation bar to top of page?
    # Values: "true" (default) or "false"
    'navbar_fixed_top': "true",

    # Location of link to source.
    # Options are "nav" (default), "footer" or anything else to exclude.
    'source_link_position': 'footer',

    # Bootswatch (http://bootswatch.com/) theme.
    #
    # Options are nothing (default) or the name of a valid theme
    # such as "amelia" or "cosmo", "yeti", "flatly".
    'bootswatch_theme': "yeti",

    # Choose Bootstrap version.
    # Values: "3" (default) or "2" (in quotes)
    'bootstrap_version': "3",

    'navbar_links': [
                     #("Gallery", "auto_examples/index"),
                     # ("Tutorial", "tutorial"),
                     ("API", "api"),
                     ("Reference", "reference"),
                     ],

}

# 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 = ['source']

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# html_sidebars = {'sidebar': ['localtoc.html', 'sourcelink.html', 'searchbox.html']}

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

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

# -- 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, 'giddy.tex', u'giddy Documentation',
     u'pysal developers', '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, 'giddy', u'giddy 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, 'giddy', u'giddy Documentation',
     author, 'giddy', 'One line description of project.',
     'Miscellaneous'),
]

# -----------------------------------------------------------------------------
# Napoleon configuration
# -----------------------------------------------------------------------------
# numpydoc_show_class_members = True
# numpydoc_class_members_toctree = False
#
# napoleon_use_ivar = True

# Generate the API documentation when building
autosummary_generate = True
numpydoc_show_class_members = False
numpydoc_use_plots = True

def setup(app):
    app.add_stylesheet("source/_static/style.css")

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/3.6/': None}<commit_msg>no matplotlib<commit_after># -*- coding: utf-8 -*-
#
# giddy documentation build configuration file, created by
# sphinx-quickstart on Wed Jun  6 15:54:22 2018.
#
# 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.

# 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 sys, os
import sphinx_bootstrap_theme

sys.path.insert(0, os.path.abspath('../../'))

import giddy

# -- 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_gallery.gen_gallery',
              'sphinx.ext.autodoc',
              'sphinx.ext.autosummary',
              'sphinx.ext.viewcode',
              'sphinxcontrib.bibtex',
              'sphinx.ext.mathjax',
              'sphinx.ext.doctest',
              'sphinx.ext.intersphinx',
              'numpydoc',]
              #'matplotlib.sphinxext.plot_directive']
              #"sphinx.ext.napoleon"]

# sphinx_gallery_conf = {
#      # path to your examples scripts
#      'examples_dirs': '../examples',
#      # path where to save gallery generated examples
#      'gallery_dirs': 'auto_examples',
#      'backreferences_dir': False,
# }

# 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 = 'giddy'
copyright = '2018, pysal developers'
author = 'pysal developers'

# 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 full version.
version = giddy.__version__
release = giddy.__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 = 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', 'tests/*']

# 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 = 'bootstrap'
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()
html_title = "%s v%s Manual" % (project, version)

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

    # Navigation bar title. (Default: ``project`` value)
    'navbar_title': "giddy",

    # Render the next and previous page links in navbar. (Default: true)
    'navbar_sidebarrel': False,

    # Render the current pages TOC in the navbar. (Default: true)
    #'navbar_pagenav': True,
    #'navbar_pagenav': False,

    # No sidebar
    'nosidebar': True,

    # Tab name for the current pages TOC. (Default: "Page")
    #'navbar_pagenav_name': "Page",

    # Global TOC depth for "site" navbar tab. (Default: 1)
    # Switching to -1 shows all levels.
    'globaltoc_depth': 2,

    # Include hidden TOCs in Site navbar?
    #
    # Note: If this is "false", you cannot have mixed ``:hidden:`` and
    # non-hidden ``toctree`` directives in the same page, or else the build
    # will break.
    #
    # Values: "true" (default) or "false"
    'globaltoc_includehidden': "true",

    # HTML navbar class (Default: "navbar") to attach to <div> element.
    # For black navbar, do "navbar navbar-inverse"
    #'navbar_class': "navbar navbar-inverse",

    # Fix navigation bar to top of page?
    # Values: "true" (default) or "false"
    'navbar_fixed_top': "true",

    # Location of link to source.
    # Options are "nav" (default), "footer" or anything else to exclude.
    'source_link_position': 'footer',

    # Bootswatch (http://bootswatch.com/) theme.
    #
    # Options are nothing (default) or the name of a valid theme
    # such as "amelia" or "cosmo", "yeti", "flatly".
    'bootswatch_theme': "yeti",

    # Choose Bootstrap version.
    # Values: "3" (default) or "2" (in quotes)
    'bootstrap_version': "3",

    'navbar_links': [
                     #("Gallery", "auto_examples/index"),
                     # ("Tutorial", "tutorial"),
                     ("API", "api"),
                     ("Reference", "reference"),
                     ],

}

# 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 = ['source']

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# html_sidebars = {'sidebar': ['localtoc.html', 'sourcelink.html', 'searchbox.html']}

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

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

# -- 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, 'giddy.tex', u'giddy Documentation',
     u'pysal developers', '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, 'giddy', u'giddy 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, 'giddy', u'giddy Documentation',
     author, 'giddy', 'One line description of project.',
     'Miscellaneous'),
]

# -----------------------------------------------------------------------------
# Napoleon configuration
# -----------------------------------------------------------------------------
# numpydoc_show_class_members = True
# numpydoc_class_members_toctree = False
#
# napoleon_use_ivar = True

# Generate the API documentation when building
autosummary_generate = True
numpydoc_show_class_members = False
numpydoc_use_plots = True

def setup(app):
    app.add_stylesheet("source/_static/style.css")

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/3.6/': None}<|endoftext|>


<commit_before>__version__ = "1.0.29"
<commit_msg>Update __init__.py<commit_after>__version__ = "1.0.30"
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division

codec_registry = dict()

def get_codec(config):
    """Obtain a codec for the given configuration.

    Parameters
    ----------
    config : dict-like
        Configuration object.

    Returns
    -------
    codec : Codec

    """
    codec_id = config.pop('id', None)
    cls = codec_registry.get(codec_id, None)
    if cls is None:
        raise ValueError('codec not available: %r' % codec_id)
    return cls.from_config(config)

try:
    from numcodecs.blosc import Blosc
except ImportError:
    pass
else:
    codec_registry[Blosc.codec_id] = Blosc
<commit_msg>add zlib to registry<commit_after># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, division

codec_registry = dict()

def get_codec(config):
    """Obtain a codec for the given configuration.

    Parameters
    ----------
    config : dict-like
        Configuration object.

    Returns
    -------
    codec : Codec

    """
    codec_id = config.pop('id', None)
    cls = codec_registry.get(codec_id, None)
    if cls is None:
        raise ValueError('codec not available: %r' % codec_id)
    return cls.from_config(config)

try:
    from numcodecs.blosc import Blosc
except ImportError:
    pass
else:
    codec_registry[Blosc.codec_id] = Blosc

from numcodecs.zlib import Zlib
codec_registry[Zlib.codec_id] = Zlib
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# xhistogram documentation build configuration file, created by
# sphinx-quickstart on Sat Aug 29 00:18:20 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
import xhistogram

# 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(os.path.abspath('..'))

print "python exec:", sys.executable
print "sys.path:", sys.path

# -- 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.mathjax', 'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.extlinks',
    'sphinx.ext.viewcode',
    'sphinx.ext.intersphinx',
    'numpydoc',
    'nbsphinx',
    'IPython.sphinxext.ipython_directive',
    'IPython.sphinxext.ipython_console_highlighting',
]

# never execute notebooks: avoids lots of expensive imports on rtd
# https://nbsphinx.readthedocs.io/en/0.2.14/never-execute.html
# nbsphinx_execute = 'never'

# http://stackoverflow.com/questions/5599254/how-to-use-sphinxs-autodoc-to-document-a-classs-init-self-method
def skip(app, what, name, obj, skip, options):
    if name == "__init__":
        return False
    return skip

def setup(app):
    app.connect("autodoc-skip-member", skip)

# link to github issues
extlinks = {'issue': ('https://github.com/xgcm/xhistogram/issues/%s', 'GH')}

autosummary_generate = True
numpydoc_class_members_toctree = True
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'xhistogram'
copyright = u'2016-2019, xhistogram developers'

# 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 full version, including alpha/beta/rc tags.
release = xhistogram.__version__
# The short X.Y version.
version = '.'.join(release.split('.')[:2])

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

on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

if not on_rtd:  # only import and set the theme if we're building docs locally
    import sphinx_rtd_theme
    html_theme = 'sphinx_rtd_theme'
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#tml_theme = 'default'
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 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 = 'xhistogramdoc'

# -- 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', 'xhistogram.tex', u'xhistogram Documentation',
   u'xhistogram developers', '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', 'xhistogram', u'xhistogram Documentation',
     [u'xhistogram developers'], 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', 'xhistogram', u'xhistogram Documentation',
   u'xhistogram developers', 'xhistogram', 'Fast, flexible, label-aware histograms for numpy and xarray.',
   '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

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
    'python': ('https://docs.python.org/3/', None),
    'xarray': ('http://xarray.pydata.org/en/stable/', None)
}
<commit_msg>increase timeout<commit_after># -*- coding: utf-8 -*-
#
# xhistogram documentation build configuration file, created by
# sphinx-quickstart on Sat Aug 29 00:18:20 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
import xhistogram

# 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(os.path.abspath('..'))

print "python exec:", sys.executable
print "sys.path:", sys.path

# -- 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.mathjax', 'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.extlinks',
    'sphinx.ext.viewcode',
    'sphinx.ext.intersphinx',
    'numpydoc',
    'nbsphinx',
    'IPython.sphinxext.ipython_directive',
    'IPython.sphinxext.ipython_console_highlighting',
]

# never execute notebooks: avoids lots of expensive imports on rtd
# https://nbsphinx.readthedocs.io/en/0.2.14/never-execute.html
# nbsphinx_execute = 'never'

# give cells 10 minutes to run before timeout
nbsphinx_timeout = 600

# http://stackoverflow.com/questions/5599254/how-to-use-sphinxs-autodoc-to-document-a-classs-init-self-method
def skip(app, what, name, obj, skip, options):
    if name == "__init__":
        return False
    return skip

def setup(app):
    app.connect("autodoc-skip-member", skip)

# link to github issues
extlinks = {'issue': ('https://github.com/xgcm/xhistogram/issues/%s', 'GH')}

autosummary_generate = True
numpydoc_class_members_toctree = True
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'xhistogram'
copyright = u'2016-2019, xhistogram developers'

# 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 full version, including alpha/beta/rc tags.
release = xhistogram.__version__
# The short X.Y version.
version = '.'.join(release.split('.')[:2])

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

on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

if not on_rtd:  # only import and set the theme if we're building docs locally
    import sphinx_rtd_theme
    html_theme = 'sphinx_rtd_theme'
    html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#tml_theme = 'default'
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 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 = 'xhistogramdoc'

# -- 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', 'xhistogram.tex', u'xhistogram Documentation',
   u'xhistogram developers', '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', 'xhistogram', u'xhistogram Documentation',
     [u'xhistogram developers'], 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', 'xhistogram', u'xhistogram Documentation',
   u'xhistogram developers', 'xhistogram', 'Fast, flexible, label-aware histograms for numpy and xarray.',
   '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

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
    'python': ('https://docs.python.org/3/', None),
    'xarray': ('http://xarray.pydata.org/en/stable/', None)
}
<|endoftext|>


<commit_before># coding=utf-8
from typing import List

import networkx as nx
import pyisemail
from recordclass import recordclass
from toolz import *
from fuzzywuzzy import fuzz

from analysis import split_name_by_character_type, empty_dict

PARSED_EMAIL_FIELDS = ['email', 'valid', 'name', 'domain', 'parsed_name']

ParsedEmail = recordclass('ParsedEmail', PARSED_EMAIL_FIELDS)

PARSED_NAME_FIELDS = ['name', 'name_type']

ParsedName = recordclass('ParsedName', PARSED_NAME_FIELDS)

def proper(name: ParsedName):
    return name.name_type == 'proper' or name.name_type == 'personal'

class Actor:
    name: str
    email: str
    actor_id: str
    parsed_email: ParsedEmail
    parsed_name: ParsedName

    def __init__(self, name: str, email: str):
        self.name = name
        self.email = email
        self.actor_id = '{} <{}>'.format(name, email).lower()
        self.parsed_email = None
        self.parsed_name = None

class ActorParser:
    role_names = None

    _transform = compose(' '.join,
                         partial(filter, lambda s: s.isalpha()),
                         split_name_by_character_type)

    def __init__(self):
        self.role_names = dict()

    def add_role_names(self, name_roles):
        for name, role in name_roles:
            self.role_names[name] = role

    def parse_name(self, name: str) -> List[str]:
        """
        splits a name into parts separated by ., _, camel casing and
        similar
        :param name: potentially human name
        :return: list of name parts
        """
        parsed_name = ParsedName(**empty_dict(PARSED_NAME_FIELDS))
        lower_name = name.lower()
        if lower_name in self.role_names:
            parsed_name.name_type = self.role_names[lower_name]
            parsed_name.name = lower_name
        else:
            parsed_name.name_type = 'proper'
            parsed_name.name = self._transform(lower_name)
        return parsed_name

    def parse_email(self, email: str) -> ParsedEmail:
        parsed_email = ParsedEmail(**empty_dict(PARSED_EMAIL_FIELDS))
        parsed_email.email = email
        parsed_email.valid = pyisemail.is_email(email)
        email_parts = email.split('@')
        parsed_email.name = email_parts[0]
        if len(email_parts) == 2:
            parsed_email.domain = email_parts[1]
        else:
            parsed_email.domain = ''
        parsed_email.parsed_name  = self.parse_name(parsed_email.name)
        return parsed_email

    def parse_actor(self, name: str, email: str) -> Actor:
        actor = Actor(name, email)
        actor.parsed_name = self.parse_name(name)
        actor.parsed_email = self.parse_email(email)
        return actor

ACTOR_SIMILARITY_FIELDS = ['possible',
                           'identical',
                           'same_name',
                           'same_email',
                           'same_email_name',
                           'name_ratio',
                           'email_name_ratio',
                           'email_domain_ratio',
                           'name1_email_ratio',
                           'name2_email_ratio',
                           'proper_name1',
                           'proper_name2',
                           'proper_email_name1',
                           'proper_email_name2']
ActorSimilarity = recordclass('ActorSimilarity', ACTOR_SIMILARITY_FIELDS)

ACTOR_SIMILARITY_SETTINGS_FIELDS = ['min_name_ratio',
                                    'min_email_domain_ratio',
                                    'min_email_name_ratio',
                                    'min_name_email_ratio']
ActorSimilaritySettings = recordclass('ActorSimilaritySettings',
                                      ACTOR_SIMILARITY_SETTINGS_FIELDS)

class ActorSimilarityGraph:
    actor_graph: nx.Graph
    settings: ActorSimilaritySettings

    def __init__(self, settings=None):
        self.actor_graph = nx.Graph()
        self.similarity_checks = [self.identical_actors,
                                  self.similar_emails,
                                  self.similar_proper_names]
        if settings is None:
            settings = ActorSimilaritySettings(min_name_ratio=50,
                                               min_email_domain_ratio=50,
                                               min_email_name_ratio=50,
                                               min_name_email_ratio=50)
        self.settings = settings

    def add_actor(self, actor: Actor):
        if self.actor_graph.has_node(actor.actor_id):
            return
        self.actor_graph.add_node(actor.actor_id, actor=actor)
        for actor_id, actor_attrs in self.actor_graph.nodes_iter(data=True):
            if actor.actor_id == actor_id:
                continue
            other_actor = actor_attrs['actor']
            similarity = self.compute_similarity(actor, other_actor)
            if similarity.possible:
                self.actor_graph.add_edge(actor.actor_id,
                                          other_actor.actor_id,
                                          similarity=similarity)

    def evaluate_similarity(self, actor: Actor,
                            other_actor: Actor) -> ActorSimilarity:
        similarity = self.build_similarity(actor, other_actor)
        checks = list(self.similarity_checks)
        while not similarity.possible or len(checks):
            check = checks.pop()
            similarity.possible = check(similarity)
        return similarity

    def build_similarity(self, actor, other_actor):
        similarity = ActorSimilarity(**empty_dict(ACTOR_SIMILARITY_FIELDS))
        # run comparisons for similarity
        similarity.identical = (actor.actor_id == other_actor.actor_id)
        similarity.proper_name1 = proper(actor.parsed_name)
        similarity.proper_name2 = proper(other_actor.parsed_name)
        similarity.proper_email_name1 = proper(actor.parsed_email.parsed_name)
        similarity.proper_email_name2 = proper(
            other_actor.parsed_email.parsed_name)
        similarity.same_name = (actor.parsed_name.name ==
                                other_actor.parsed_name.name)
        similarity.name_ratio = self.compare_names(actor.parsed_name,
                                                   other_actor.parsed_name)
        similarity.same_email = (actor.parsed_email.email ==
                                 other_actor.parsed_email.email)
        similarity.email_domain_ratio = fuzz.ratio(
            actor.parsed_email.domain,
            other_actor.parsed_email.domain)
        similarity.same_email_name = (actor.parsed_email.parsed_name.name ==
                                      other_actor.parsed_email.parsed_name.name)
        similarity.email_name_ratio = self.compare_names(
            actor.parsed_email.parsed_name,
            other_actor.parsed_email.parsed_name)
        similarity.name1_email_ratio = self.compare_names(
            actor.parsed_name,
            other_actor.parsed_email.parsed_name)
        similarity.name2_email_ratio = self.compare_names(
            actor.parsed_email.parsed_name,
            other_actor.parsed_name)
        return similarity

    @staticmethod
    def compare_names(name1: ParsedName, name2: ParsedName):
        if proper(name1) and proper(name2):
            compare = fuzz.token_set_ratio
        else:
            compare = fuzz.ratio
        return compare(name1.name, name2.name)

    def similar_emails(self, s: ActorSimilarity):
        return (s.same_email or
                (s.email_domain_ratio >= self.settings.min_email_domain_ratio
                 and
                 s.email_name_ratio >= self.settings.min_email_name_ratio))

    def similar_proper_names(self, s: ActorSimilarity):
        return (s.proper_name1 and s.proper_name2 and
                (s.same_name or s.name_ratio >= self.settings.min_name_ratio))

    def similar_name_to_email(self, s: ActorSimilarity):
        return (s.name1_email_ratio >= self.settings.min_name_email_ratio or
                s.name2_email_ratio >= self.settings.min_name_email_ratio)

    @staticmethod
    def identical_actors(s: ActorSimilarity):
        return s.identical
<commit_msg>added forced actor links<commit_after># coding=utf-8
from typing import List

import networkx as nx
import pyisemail
from recordclass import recordclass
from toolz import *
from fuzzywuzzy import fuzz

from analysis import split_name_by_character_type, empty_dict

PARSED_EMAIL_FIELDS = ['email', 'valid', 'name', 'domain', 'parsed_name']

ParsedEmail = recordclass('ParsedEmail', PARSED_EMAIL_FIELDS)

PARSED_NAME_FIELDS = ['name', 'name_type']

ParsedName = recordclass('ParsedName', PARSED_NAME_FIELDS)

def proper(name: ParsedName):
    return name.name_type == 'proper' or name.name_type == 'personal'

class Actor:
    name: str
    email: str
    actor_id: str
    parsed_email: ParsedEmail
    parsed_name: ParsedName

    def __init__(self, name: str, email: str):
        self.name = name
        self.email = email
        self.actor_id = '{} <{}>'.format(name, email).lower()
        self.parsed_email = None
        self.parsed_name = None

class ActorParser:
    role_names = None

    _transform = compose(' '.join,
                         partial(filter, lambda s: s.isalpha()),
                         split_name_by_character_type)

    def __init__(self):
        self.role_names = dict()

    def add_role_names(self, name_roles):
        for name, role in name_roles:
            self.role_names[name] = role

    def parse_name(self, name: str) -> List[str]:
        """
        splits a name into parts separated by ., _, camel casing and
        similar
        :param name: potentially human name
        :return: list of name parts
        """
        parsed_name = ParsedName(**empty_dict(PARSED_NAME_FIELDS))
        lower_name = name.lower()
        if lower_name in self.role_names:
            parsed_name.name_type = self.role_names[lower_name]
            parsed_name.name = lower_name
        else:
            parsed_name.name_type = 'proper'
            parsed_name.name = self._transform(lower_name)
        return parsed_name

    def parse_email(self, email: str) -> ParsedEmail:
        parsed_email = ParsedEmail(**empty_dict(PARSED_EMAIL_FIELDS))
        parsed_email.email = email
        parsed_email.valid = pyisemail.is_email(email)
        email_parts = email.split('@')
        parsed_email.name = email_parts[0]
        if len(email_parts) == 2:
            parsed_email.domain = email_parts[1]
        else:
            parsed_email.domain = ''
        parsed_email.parsed_name  = self.parse_name(parsed_email.name)
        return parsed_email

    def parse_actor(self, name: str, email: str) -> Actor:
        actor = Actor(name, email)
        actor.parsed_name = self.parse_name(name)
        actor.parsed_email = self.parse_email(email)
        return actor

ACTOR_SIMILARITY_FIELDS = ['possible',
                           'identical',
                           'same_name',
                           'same_email',
                           'same_email_name',
                           'name_ratio',
                           'email_name_ratio',
                           'email_domain_ratio',
                           'name1_email_ratio',
                           'name2_email_ratio',
                           'proper_name1',
                           'proper_name2',
                           'proper_email_name1',
                           'proper_email_name2',
                           'explicit']
ActorSimilarity = recordclass('ActorSimilarity', ACTOR_SIMILARITY_FIELDS)

ACTOR_SIMILARITY_SETTINGS_FIELDS = ['min_name_ratio',
                                    'min_email_domain_ratio',
                                    'min_email_name_ratio',
                                    'min_name_email_ratio']
ActorSimilaritySettings = recordclass('ActorSimilaritySettings',
                                      ACTOR_SIMILARITY_SETTINGS_FIELDS)

class ActorSimilarityGraph:
    actor_graph: nx.Graph
    settings: ActorSimilaritySettings

    def __init__(self, settings=None):
        self.actor_graph = nx.Graph()
        self.similarity_checks = [self.identical_actors,
                                  self.similar_emails,
                                  self.similar_proper_names]
        if settings is None:
            settings = ActorSimilaritySettings(min_name_ratio=50,
                                               min_email_domain_ratio=50,
                                               min_email_name_ratio=50,
                                               min_name_email_ratio=50)
        self.settings = settings

    def add_actor(self, actor: Actor, link_similar=True):
        if self.actor_graph.has_node(actor.actor_id):
            return
        self.actor_graph.add_node(actor.actor_id, actor=actor)
        for actor_id, actor_attrs in self.actor_graph.nodes_iter(data=True):
            if actor.actor_id == actor_id:
                continue
            other_actor = actor_attrs['actor']
            if link_similar:
                similarity = self.evaluate_similarity(actor, other_actor)
                if similarity.possible:
                    self.actor_graph.add_edge(actor.actor_id,
                                              other_actor.actor_id,
                                              similarity=similarity,
                                              confidence=None)

    def link_same_actor(self, actor_id1: str, actor_id2: str,
                        confidence: float = 1):
        self.actor_graph.add_edge(actor_id1, actor_id2, confidence=confidence)
        if 'similarity' not in self.actor_graph[actor_id1][actor_id2]:
            self.actor_graph[actor_id1][actor_id2]['similarity'] = None

    def evaluate_similarity(self, actor: Actor,
                            other_actor: Actor) -> ActorSimilarity:
        similarity = self.build_similarity(actor, other_actor)
        checks = list(self.similarity_checks)
        while not similarity.possible or len(checks):
            check = checks.pop()
            similarity.possible = check(similarity)
        return similarity

    def build_similarity(self, actor, other_actor):
        similarity = ActorSimilarity(**empty_dict(ACTOR_SIMILARITY_FIELDS))
        # run comparisons for similarity
        similarity.identical = (actor.actor_id == other_actor.actor_id)
        similarity.proper_name1 = proper(actor.parsed_name)
        similarity.proper_name2 = proper(other_actor.parsed_name)
        similarity.proper_email_name1 = proper(actor.parsed_email.parsed_name)
        similarity.proper_email_name2 = proper(
            other_actor.parsed_email.parsed_name)
        similarity.same_name = (actor.parsed_name.name ==
                                other_actor.parsed_name.name)
        similarity.name_ratio = self.compare_names(actor.parsed_name,
                                                   other_actor.parsed_name)
        similarity.same_email = (actor.parsed_email.email ==
                                 other_actor.parsed_email.email)
        similarity.email_domain_ratio = fuzz.ratio(
            actor.parsed_email.domain,
            other_actor.parsed_email.domain)
        similarity.same_email_name = (actor.parsed_email.parsed_name.name ==
                                      other_actor.parsed_email.parsed_name.name)
        similarity.email_name_ratio = self.compare_names(
            actor.parsed_email.parsed_name,
            other_actor.parsed_email.parsed_name)
        similarity.name1_email_ratio = self.compare_names(
            actor.parsed_name,
            other_actor.parsed_email.parsed_name)
        similarity.name2_email_ratio = self.compare_names(
            actor.parsed_email.parsed_name,
            other_actor.parsed_name)
        return similarity

    @staticmethod
    def compare_names(name1: ParsedName, name2: ParsedName):
        if proper(name1) and proper(name2):
            compare = fuzz.token_set_ratio
        else:
            compare = fuzz.ratio
        return compare(name1.name, name2.name)

    def similar_emails(self, s: ActorSimilarity):
        return (s.same_email or
                (s.email_domain_ratio >= self.settings.min_email_domain_ratio
                 and
                 s.email_name_ratio >= self.settings.min_email_name_ratio))

    def similar_proper_names(self, s: ActorSimilarity):
        return (s.proper_name1 and s.proper_name2 and
                (s.same_name or s.name_ratio >= self.settings.min_name_ratio))

    def similar_name_to_email(self, s: ActorSimilarity):
        return (s.name1_email_ratio >= self.settings.min_name_email_ratio or
                s.name2_email_ratio >= self.settings.min_name_email_ratio)

    @staticmethod
    def identical_actors(s: ActorSimilarity):
        return s.identical
<|endoftext|>