<commit_before>"""
Django settings for testsite project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os, sys
from django.contrib.messages import constants as messages

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

def load_config(confpath):
    '''
    Given a path to a file, parse its lines in ini-like format, and then
    set them in the current namespace.
    '''
    # todo: consider using something like ConfigObj for this:
    # http://www.voidspace.org.uk/python/configobj.html
    import re
    if os.path.isfile(confpath):
        sys.stderr.write('config loaded from %s\n' % confpath)
        with open(confpath) as conffile:
            line = conffile.readline()
            while line != '':
                if not line.startswith('#'):
                    look = re.match(r'(\w+)\s*=\s*(.*)', line)
                    if look:
                        value = look.group(2) \
                            % {'LOCALSTATEDIR': BASE_DIR + '/var'}
                        # Once Django 1.5 introduced ALLOWED_HOSTS (a tuple
                        # definitely in the site.conf set), we had no choice
                        # other than using eval. The {} are here to restrict
                        # the globals and locals context eval has access to.
                        # pylint: disable=eval-used
                        setattr(sys.modules[__name__],
                            look.group(1).upper(), eval(value, {}, {}))
                line = conffile.readline()
    else:
        sys.stderr.write('warning: config file %s does not exist.\n' % confpath)

load_config(os.path.join(BASE_DIR, 'credentials'))

if not hasattr(sys.modules[__name__], "SECRET_KEY"):
    from random import choice
    SECRET_KEY = "".join([choice(
        "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^*-_=+") for i in range(50)])

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'captcha',
    'signup',
    'testsite'
)

AUTHENTICATION_BACKENDS = (
    'signup.backends.auth.UsernameOrEmailModelBackend',
    'django.contrib.auth.backends.ModelBackend'
)

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite'),
    }
}

MIDDLEWARE = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'signup.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

MIDDLEWARE_CLASSES = MIDDLEWARE

ROOT_URLCONF = 'testsite.urls'

WSGI_APPLICATION = 'testsite.wsgi.application'

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': (os.path.join(BASE_DIR, 'testsite', 'templates'),
             os.path.join(BASE_DIR, 'signup', 'templates')),
    'OPTIONS': {
        'context_processors': [
            'django.contrib.auth.context_processors.auth', # because of admin/
            'django.template.context_processors.request',
            'django.template.context_processors.media',
        ],
        'loaders': [
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader'
        ],
    }
}]

# Messages
# --------

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
MESSAGE_TAGS = {
    messages.ERROR: 'danger'
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

ACCOUNT_ACTIVATION_DAYS = 2

# Mail server and accounts for notifications.
# Host, port, TLS for sending email.
EMAIL_HOST = ""
EMAIL_PORT = 587
EMAIL_USE_TLS = False

# Default email address to use for various automated correspondence from
# the site managers (also django-registration settings)
DEFAULT_FROM_EMAIL = "admin@example.com"

# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = '/app/'

# Applications settings

REST_FRAMEWORK = {
    'PAGE_SIZE': 25,
    'DEFAULT_PAGINATION_CLASS':
        'rest_framework.pagination.PageNumberPagination',
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'signup.authentication.JWTAuthentication',
        'signup.authentication.APIKeyAuthentication',
        # `rest_framework.authentication.SessionAuthentication` is the last
        # one in the list because it will raise a PermissionDenied if the CSRF
        # is absent.
        'rest_framework.authentication.SessionAuthentication',
    )
}

# Debug toolbar and panel
# -----------------------
DEBUG_TOOLBAR_PATCH_SETTINGS = False
DEBUG_TOOLBAR_CONFIG = {
    'JQUERY_URL': '/static/vendor/jquery.js',
    'SHOW_COLLAPSED': True,
    'SHOW_TEMPLATE_CONTEXT': True,
}

INTERNAL_IPS = ('127.0.0.1', '::1')

NOCAPTCHA = True
<commit_msg>uses test smtp server<commit_after>"""
Django settings for testsite project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os, sys
from django.contrib.messages import constants as messages

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

def load_config(confpath):
    '''
    Given a path to a file, parse its lines in ini-like format, and then
    set them in the current namespace.
    '''
    # todo: consider using something like ConfigObj for this:
    # http://www.voidspace.org.uk/python/configobj.html
    import re
    if os.path.isfile(confpath):
        sys.stderr.write('config loaded from %s\n' % confpath)
        with open(confpath) as conffile:
            line = conffile.readline()
            while line != '':
                if not line.startswith('#'):
                    look = re.match(r'(\w+)\s*=\s*(.*)', line)
                    if look:
                        value = look.group(2) \
                            % {'LOCALSTATEDIR': BASE_DIR + '/var'}
                        # Once Django 1.5 introduced ALLOWED_HOSTS (a tuple
                        # definitely in the site.conf set), we had no choice
                        # other than using eval. The {} are here to restrict
                        # the globals and locals context eval has access to.
                        # pylint: disable=eval-used
                        setattr(sys.modules[__name__],
                            look.group(1).upper(), eval(value, {}, {}))
                line = conffile.readline()
    else:
        sys.stderr.write('warning: config file %s does not exist.\n' % confpath)

load_config(os.path.join(BASE_DIR, 'credentials'))

if not hasattr(sys.modules[__name__], "SECRET_KEY"):
    from random import choice
    SECRET_KEY = "".join([choice(
        "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^*-_=+") for i in range(50)])

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',
    'captcha',
    'signup',
    'testsite'
)

AUTHENTICATION_BACKENDS = (
    'signup.backends.auth.UsernameOrEmailModelBackend',
    'django.contrib.auth.backends.ModelBackend'
)

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite'),
    }
}

MIDDLEWARE = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'signup.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

MIDDLEWARE_CLASSES = MIDDLEWARE

ROOT_URLCONF = 'testsite.urls'

WSGI_APPLICATION = 'testsite.wsgi.application'

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': (os.path.join(BASE_DIR, 'testsite', 'templates'),
             os.path.join(BASE_DIR, 'signup', 'templates')),
    'OPTIONS': {
        'context_processors': [
            'django.contrib.auth.context_processors.auth', # because of admin/
            'django.template.context_processors.request',
            'django.template.context_processors.media',
        ],
        'loaders': [
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader'
        ],
    }
}]

# Messages
# --------

MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
MESSAGE_TAGS = {
    messages.ERROR: 'danger'
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

ACCOUNT_ACTIVATION_DAYS = 2

# Mail server and accounts for notifications.
# Host, port, TLS for sending email.
EMAIL_HOST = "localhost"
EMAIL_PORT = 1025
EMAIL_USE_TLS = False

# Default email address to use for various automated correspondence from
# the site managers (also django-registration settings)
DEFAULT_FROM_EMAIL = "admin@example.com"

# Optional SMTP authentication information for EMAIL_HOST.
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = '/app/'

# Applications settings

REST_FRAMEWORK = {
    'PAGE_SIZE': 25,
    'DEFAULT_PAGINATION_CLASS':
        'rest_framework.pagination.PageNumberPagination',
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'signup.authentication.JWTAuthentication',
        'signup.authentication.APIKeyAuthentication',
        # `rest_framework.authentication.SessionAuthentication` is the last
        # one in the list because it will raise a PermissionDenied if the CSRF
        # is absent.
        'rest_framework.authentication.SessionAuthentication',
    )
}

# Debug toolbar and panel
# -----------------------
DEBUG_TOOLBAR_PATCH_SETTINGS = False
DEBUG_TOOLBAR_CONFIG = {
    'JQUERY_URL': '/static/vendor/jquery.js',
    'SHOW_COLLAPSED': True,
    'SHOW_TEMPLATE_CONTEXT': True,
}

INTERNAL_IPS = ('127.0.0.1', '::1')

NOCAPTCHA = True
<|endoftext|>


<commit_before># coding: utf-8
from unittest.mock import patch

from django.conf import settings
from django.core.cache import caches

from django_th.tests.test_main import MainTest
from th_evernote.models import Evernote
from th_evernote.forms import EvernoteProviderForm, EvernoteConsumerForm
from th_evernote.my_evernote import ServiceEvernote
from th_evernote.evernote_mgr import EvernoteMgr
from th_evernote.sanitize import sanitize
from evernote.api.client import EvernoteClient
try:
    from unittest import mock
except ImportError:
    import mock

cache = caches['th_evernote']

class EvernoteTest(MainTest):

    """
        EvernoteTest Model
    """

    def create_evernote(self):
        trigger = self.create_triggerservice(consumer_name='ServiceEvernote')
        tag = 'test'
        notebook = 'my notebook'
        title = 'a new note'
        status = True
        return Evernote.objects.create(tag=tag, title=title,
                                       notebook=notebook, trigger=trigger,
                                       status=status)

class EvernoteView(EvernoteTest):

    def test_evernote(self):
        ev = self.create_evernote()
        self.assertIsInstance(ev, Evernote)
        self.assertEqual(ev.show(), "My Evernote {}".format(ev.title))
        self.assertEqual(ev.__str__(), ev.title)

    """
        Form
    """
    # provider

    def test_valid_provider_form(self):
        ev = self.create_evernote()
        data = {'tag': ev.tag, 'notebook': ev.notebook}
        form = EvernoteProviderForm(data=data)
        self.assertTrue(form.is_valid())

    def test_invalid_provider_form(self):
        form = EvernoteProviderForm(data={})
        self.assertFalse(form.is_valid())

    # consumer
    def test_valid_consumer_form(self):
        ev = self.create_evernote()
        data = {'tag': ev.tag, 'notebook': ev.notebook}
        form = EvernoteConsumerForm(data=data)
        self.assertTrue(form.is_valid())

    def test_invalid_consumer_form(self):
        form = EvernoteConsumerForm(data={})
        self.assertFalse(form.is_valid())

    def test_get_config_th(self):
        """
            does this settings exists ?
        """
        self.assertTrue(settings.TH_EVERNOTE)

    def test_get_services_list(self):
        th_service = ('th_evernote.my_evernote.ServiceEvernote',)
        for service in th_service:
            self.assertIn(service, settings.TH_SERVICES)

class ServiceEvernoteTest(EvernoteTest):
    """
       ServiceEvernoteTest
    """

    def setUp(self):
        super(ServiceEvernoteTest, self).setUp()
        self.ev = self.create_evernote()
        self.data = {'link': 'http://foo.bar/some/thing/else/what/else',
                     'title': 'what else',
                     'content': 'A nice content with a nice '
                                'foobar link',
                     'summary_detail': 'summary foobar',
                     'description': 'description foobar'}
        self.token = 'AZERTY123'
        self.trigger_id = 1
        self.service = ServiceEvernote(self.token)

    def test_read_data(self):
        kwargs = dict({'date_triggered': '2013-05-11 13:23:58+00:00',
                       'trigger_id': self.trigger_id})

        with patch.object(EvernoteClient, 'get_note_store') as mock_ev:
            se = ServiceEvernote(self.token)
            se.read_data(**kwargs)
        mock_ev.assert_called_once_with()

    @patch.object(EvernoteClient, 'get_note_store')
    # @patch.object(EvernoteMgr, 'create_note')
    # def test_save_data(self, mock1, mock2):
    def test_save_data(self, mock1):
        self.assertTrue(self.token)
        self.assertIsInstance(self.trigger_id, int)
        self.assertIn('content', self.data)
        self.assertIn('summary_detail', self.data)
        self.assertIn('description', self.data)
        self.assertIn('title', self.data)
        self.assertIsNotNone(self.data['link'])
        self.assertNotEqual(self.data['title'], '')
        self.assertIn('sandbox', settings.TH_EVERNOTE)

        se = ServiceEvernote(self.token)
        se.save_data(self.trigger_id, **self.data)
        mock1.assert_called_once()
        # mock2.assert_called_once()

    def test_get_config_th(self):
        """
            does this settings exists ?
        """
        self.assertTrue(settings.TH_EVERNOTE)
        self.assertIn('consumer_key', settings.TH_EVERNOTE)
        self.assertIn('consumer_secret', settings.TH_EVERNOTE)
        self.assertIn('sandbox', settings.TH_EVERNOTE)

    def test_get_config_th_cache(self):
        self.assertIn('th_evernote', settings.CACHES)

    def test_get_evernote_client(self, token=None):
        """
            get the token from evernote
        """
        sandbox = settings.TH_EVERNOTE['sandbox']
        client = mock.Mock(return_value=True)
        client.method(token=token, sandbox=sandbox)
        client.method.assert_called_with(token=token, sandbox=sandbox)

        sandbox = settings.TH_EVERNOTE['sandbox']
        consumer_key = settings.TH_EVERNOTE['consumer_key']
        consumer_secret = settings.TH_EVERNOTE['consumer_secret']

        client = mock.Mock(return_value=True)
        client.method(consumer_key=consumer_key,
                      consumer_secret=consumer_secret, sandbox=sandbox)
        client.method.assert_called_with(consumer_key=consumer_key,
                                         consumer_secret=consumer_secret,
                                         sandbox=sandbox)

    def test_auth(self):
        pass

    def test_callback(self):
        pass

    def test_sanitize(self):
        html = "" \
               "
coucou
" \
               "<dir>foobar</dir>" \
               "
foobar2
" \
               "dropped" \
               "kept" \
               ""
        html = sanitize(html)
        self.assertTrue("dir" not in html)
        self.assertTrue("ftp" not in html)
        self.assertTrue("data-foobar" not in html)
        self.assertTrue("http" in html)

    def test_set_header(self):
        header = EvernoteMgr.set_header()
        self.assertTrue('DOCTYPE en-note SYSTEM "http://xml.evernote.'
                        'com/pub/enml2.dtd' in header)

    def test_footer(self):
        content = ''
        se = ServiceEvernote(self.token)
        footer = se._footer(self.ev, self.data, content)
        self.assertIsInstance(footer, str)

    def test_cleaning_content(self):
        se = ServiceEvernote(self.token)
        self.assertIsInstance(se._cleaning_content('foobar'), str)
<commit_msg>Dropped get config cache and replaced variable<commit_after># coding: utf-8
from unittest.mock import patch

from django.conf import settings
from django.core.cache import caches

from django_th.tests.test_main import MainTest
from th_evernote.models import Evernote
from th_evernote.forms import EvernoteProviderForm, EvernoteConsumerForm
from th_evernote.my_evernote import ServiceEvernote
from th_evernote.evernote_mgr import EvernoteMgr
from th_evernote.sanitize import sanitize
from evernote.api.client import EvernoteClient
try:
    from unittest import mock
except ImportError:
    import mock

cache = caches['django_th']

class EvernoteTest(MainTest):

    """
        EvernoteTest Model
    """

    def create_evernote(self):
        trigger = self.create_triggerservice(consumer_name='ServiceEvernote')
        tag = 'test'
        notebook = 'my notebook'
        title = 'a new note'
        status = True
        return Evernote.objects.create(tag=tag, title=title,
                                       notebook=notebook, trigger=trigger,
                                       status=status)

class EvernoteView(EvernoteTest):

    def test_evernote(self):
        ev = self.create_evernote()
        self.assertIsInstance(ev, Evernote)
        self.assertEqual(ev.show(), "My Evernote {}".format(ev.title))
        self.assertEqual(ev.__str__(), ev.title)

    """
        Form
    """
    # provider

    def test_valid_provider_form(self):
        ev = self.create_evernote()
        data = {'tag': ev.tag, 'notebook': ev.notebook}
        form = EvernoteProviderForm(data=data)
        self.assertTrue(form.is_valid())

    def test_invalid_provider_form(self):
        form = EvernoteProviderForm(data={})
        self.assertFalse(form.is_valid())

    # consumer
    def test_valid_consumer_form(self):
        ev = self.create_evernote()
        data = {'tag': ev.tag, 'notebook': ev.notebook}
        form = EvernoteConsumerForm(data=data)
        self.assertTrue(form.is_valid())

    def test_invalid_consumer_form(self):
        form = EvernoteConsumerForm(data={})
        self.assertFalse(form.is_valid())

    def test_get_config_th(self):
        """
            does this settings exists ?
        """
        self.assertTrue(settings.TH_EVERNOTE)

    def test_get_services_list(self):
        th_service = ('th_evernote.my_evernote.ServiceEvernote',)
        for service in th_service:
            self.assertIn(service, settings.TH_SERVICES)

class ServiceEvernoteTest(EvernoteTest):
    """
       ServiceEvernoteTest
    """

    def setUp(self):
        super(ServiceEvernoteTest, self).setUp()
        self.ev = self.create_evernote()
        self.data = {'link': 'http://foo.bar/some/thing/else/what/else',
                     'title': 'what else',
                     'content': 'A nice content with a nice '
                                'foobar link',
                     'summary_detail': 'summary foobar',
                     'description': 'description foobar'}
        self.token = 'AZERTY123'
        self.trigger_id = 1
        self.service = ServiceEvernote(self.token)

    def test_read_data(self):
        kwargs = dict({'date_triggered': '2013-05-11 13:23:58+00:00',
                       'trigger_id': self.trigger_id})

        with patch.object(EvernoteClient, 'get_note_store') as mock_ev:
            se = ServiceEvernote(self.token)
            se.read_data(**kwargs)
        mock_ev.assert_called_once_with()

    @patch.object(EvernoteClient, 'get_note_store')
    # @patch.object(EvernoteMgr, 'create_note')
    # def test_save_data(self, mock1, mock2):
    def test_save_data(self, mock1):
        self.assertTrue(self.token)
        self.assertIsInstance(self.trigger_id, int)
        self.assertIn('content', self.data)
        self.assertIn('summary_detail', self.data)
        self.assertIn('description', self.data)
        self.assertIn('title', self.data)
        self.assertIsNotNone(self.data['link'])
        self.assertNotEqual(self.data['title'], '')
        self.assertIn('sandbox', settings.TH_EVERNOTE)

        se = ServiceEvernote(self.token)
        se.save_data(self.trigger_id, **self.data)
        mock1.assert_called_once()
        # mock2.assert_called_once()

    def test_get_config_th(self):
        """
            does this settings exists ?
        """
        self.assertTrue(settings.TH_EVERNOTE)
        self.assertIn('consumer_key', settings.TH_EVERNOTE)
        self.assertIn('consumer_secret', settings.TH_EVERNOTE)
        self.assertIn('sandbox', settings.TH_EVERNOTE)

    def test_get_evernote_client(self, token=None):
        """
            get the token from evernote
        """
        sandbox = settings.TH_EVERNOTE['sandbox']
        client = mock.Mock(return_value=True)
        client.method(token=token, sandbox=sandbox)
        client.method.assert_called_with(token=token, sandbox=sandbox)

        sandbox = settings.TH_EVERNOTE['sandbox']
        consumer_key = settings.TH_EVERNOTE['consumer_key']
        consumer_secret = settings.TH_EVERNOTE['consumer_secret']

        client = mock.Mock(return_value=True)
        client.method(consumer_key=consumer_key,
                      consumer_secret=consumer_secret, sandbox=sandbox)
        client.method.assert_called_with(consumer_key=consumer_key,
                                         consumer_secret=consumer_secret,
                                         sandbox=sandbox)

    def test_auth(self):
        pass

    def test_callback(self):
        pass

    def test_sanitize(self):
        html = "" \
               "
coucou
" \
               "<dir>foobar</dir>" \
               "
foobar2
" \
               "dropped" \
               "kept" \
               ""
        html = sanitize(html)
        self.assertTrue("dir" not in html)
        self.assertTrue("ftp" not in html)
        self.assertTrue("data-foobar" not in html)
        self.assertTrue("http" in html)

    def test_set_header(self):
        header = EvernoteMgr.set_header()
        self.assertTrue('DOCTYPE en-note SYSTEM "http://xml.evernote.'
                        'com/pub/enml2.dtd' in header)

    def test_footer(self):
        content = ''
        se = ServiceEvernote(self.token)
        footer = se._footer(self.ev, self.data, content)
        self.assertIsInstance(footer, str)

    def test_cleaning_content(self):
        se = ServiceEvernote(self.token)
        self.assertIsInstance(se._cleaning_content('foobar'), str)
<|endoftext|>


<commit_before>"""
Shimmed Graph utilities:
   graph compilation, traversal, listing inputs...
"""
import collections
import itertools
from . import core
from .config import config as cf

# Custom exceptions
class TooCostly(Exception):
    pass
# Theano exceptions
class _MissingInputError(Exception):
    pass
MissingInputError = _MissingInputError
def load_exceptions():
    if cf.use_theano:
        import theano.gof as gof
        MissingInputError = gof.MissingInputError
    else:
        MissingInputError = _MissingInputError

######################
# Graph manipulation

def clone(output, replace=None, *args, **kwargs):
    """
    Use as theano.clone().
    TODO: Something useful with non-symbolic output ?
    """
    if not core.is_theano_variable(output):
        raise ValueError("`shim.graph.clone()` is undefined for non-symbolic outputs")
    return core.theano.clone(output, replace, *args, **kwargs)

#####################
# Graph compilation

def compile(inputs, outputs, *args, **kwargs):
    """
    Use as theano.function().
    TODO: Something useful with non-symbolic output ?
    """
    if not any(core.is_theano_variable(arg)
               for arg in itertools.chain([inputs, outputs], args, kwargs.values())):
        raise ValueError("`shim.graph.function()` is undefined for non-symbolic outputs")
    return core.theano.function(inputs, outputs, *args, **kwargs)

def eval(expr, givens=None, max_cost=10, if_too_costly='raise', inputs=None):
    """
    Obtain a numerical value by evaluating an expression's graph.

    If expr is shared (or shimmed shared) variable, its `get_value()` method is
    called and the result returned.
    Otherwise, a function is compiled and evaluated. `givens` can be used
    to replace symbolic and shared variables during compilation.

    If it's not a symbolic expression at all, `expr` is simply returned.

    Parameters
    ----------
    expr: Theano graph | slice | iterable (TODO)
        The theano expression we want to evaluate. If a slice, each component
        of the slice ('start', 'stop', 'step') is evaluated.
        TODO: iterable
    givens: dict (optional; default: {})
        Dictionary of inputs to be past to `eval`.
    max_cost: int (optional; default: 10)
        Maximum allowable 'cost' of the expression: if `expr` is estimated to
        be more costly than this, an error is raised instead. The value `None`
        deactivates this check.
        Cost is estimated by a proxy, specifically the number of ancestors to
        `expr` in the Theano graph. By default, only expressions with 10 ancestors
        or less are evaluated.
    if_too_costly: 'ignore'  |  'raise'
        What to do if an expression is too costly to compute.
        'ignore': do nothing, return symbolic expression.
        'raise' : raise a TooCostly exception.
    inputs: Deprecated
        Synonym for `givens`.

    Returns
    -------
    Pure Python variable of same type as `expr`.
    """
    # Bypassing code paths
    if core.isshared(expr):
        return expr.get_value()
    elif not core.is_theano_object(expr):
        return expr
    elif isinstance(expr, slice):
        return slice(eval(expr.start), eval(expr.stop), eval(expr.step))

    # "Standard" code path
    cost = len(core.gettheano().gof.graph.ancestors([expr]))
    if max_cost is not None and cost > max_cost:
        if if_too_costly == 'raise':
            raise TooCostly("Expression has {} ancestors, which exceeds the "
                            "limit of {}.".format(cost, max_cost))
        else:
            return expr
    else:
        if inputs is None: inputs = {}  # TODO: Remove `inputs`
        if givens is None: givens = {}
        givens = {**inputs, **givens}
        for k, v in givens.items():
            givens[k] = core.cast(v, k.dtype)
        f = core.gettheano().function(
            [], expr, givens=givens, on_unused_input='ignore')
        return f()

######################
# Graph inspection

def is_computable(varlist, with_inputs=None):
    """
    Returns True if the variables in varlist can be numerically evaluated
    using only the inputs in `with_inputs`. In other words, the computational
    graph associated to varlist is composed only of constants and shared variables,
    along with the symbolic variables in `with_inputs`.
    If varlist is not a Theano graph, it is always computable.
    """
    if ( not isinstance(varlist, collections.Iterable)
         or isinstance(varlist, str) ):
        raise ValueError("theano_shim.is_computable requires a list as first argument.")
    if with_inputs is None:
        with_inputs = []
    computable = True
    for var in varlist:
        if isinstance(var, slice):
            # Must come before `is_theano_variable`
            if not is_computable([var.start, var.stop, var.step]):
                computable = False
                break
        elif core.is_theano_variable(var): # Required because varlist may contain non-Theano objects
            if core.is_theano_variable( set(core.gettheano().gof.graph.inputs([var])).difference(with_inputs) ):
                computable = False
                break
    return computable

def inputs(varlist, *args, **kwargs):
    """
    Wrapper for theano.gof.graph.inputs.
    Returns an empty list for non symbolic variables
    """
    if ( not isinstance(varlist, collections.Iterable)
         or isinstance(varlist, str) ):
        raise ValueError("theano_shim.graph.inputs requires a list as first argument.")
    if core.is_theano_object(varlist):
        return core._gettheano().gof.graph.inputs(varlist, *args, **kwargs)
    else:
        return []

def variables(i, o=None):
    """
    Wrapper for theano.gof.graph.variables.
    Returns an empty list for non symbolic variables
    If given only one argument, returns all variables it depends on.
    """
    if o is None:
        o = i
        i = inputs(o)
    if ( not isinstance(i, collections.Iterable)
         or isinstance(i, str) ):
        raise ValueError(
            "Arguments to theano_shim.graph.variables must be lists.")
    if core.is_theano_object(i, o):
        return core._gettheano().gof.graph.variables(i, o)
    else:
        return []

def symbolic_inputs(varlist, *args, **kwargs):
    return [v for v in inputs(varlist, *args, **kwargs) if core.is_theano_variable(v)]

def is_same_graph(var1, var2, givens=None, debug=False):
    """
    Wraps theano.gof.graph.is_same_graph().
    Returns True if `var1` and `var2` perform the same computation.
    If either `var1` or `var2` is not a graph object, returns the result of
    `var1 == var2`.
    """
    if not (core.is_theano_object(var1) and core.is_theano_object(var2)):
        return var1 == var2
    else:
        return core._gettheano().gof.graph.is_same_graph(var1, var2,
                                                         givens, debug)
<commit_msg>[graph] Add hash function for graphs.<commit_after>"""
Shimmed Graph utilities:
   graph compilation, traversal, listing inputs...
"""
import collections
from collections import Iterable
import itertools
import builtins
from . import core
from .config import config as cf

# Custom exceptions
class TooCostly(Exception):
    pass
# Theano exceptions
class _MissingInputError(Exception):
    pass
MissingInputError = _MissingInputError
def load_exceptions():
    if cf.use_theano:
        import theano.gof as gof
        MissingInputError = gof.MissingInputError
    else:
        MissingInputError = _MissingInputError

######################
# Graph manipulation

def clone(output, replace=None, *args, **kwargs):
    """
    Use as theano.clone().
    TODO: Something useful with non-symbolic output ?
    """
    if not core.is_theano_object(output):
        raise ValueError("`shim.graph.clone()` is undefined for non-symbolic outputs")
    return core.theano.clone(output, replace, *args, **kwargs)

#####################
# Graph compilation

def compile(inputs, outputs, *args, **kwargs):
    """
    Use as theano.function().
    TODO: Something useful with non-symbolic output ?
    """
    if not any(core.is_theano_object(arg)
               for arg in itertools.chain([inputs, outputs], args, kwargs.values())):
        raise ValueError("`shim.graph.function()` is undefined for non-symbolic outputs")
    return core.theano.function(inputs, outputs, *args, **kwargs)

def eval(expr, givens=None, max_cost=10, if_too_costly='raise', inputs=None):
    """
    Obtain a numerical value by evaluating an expression's graph.

    If expr is shared (or shimmed shared) variable, its `get_value()` method is
    called and the result returned.
    Otherwise, a function is compiled and evaluated. `givens` can be used
    to replace symbolic and shared variables during compilation.

    If it's not a symbolic expression at all, `expr` is simply returned.

    Parameters
    ----------
    expr: Theano graph | slice | iterable (TODO)
        The theano expression we want to evaluate. If a slice, each component
        of the slice ('start', 'stop', 'step') is evaluated.
        TODO: iterable
    givens: dict (optional; default: {})
        Dictionary of inputs to be past to `eval`.
    max_cost: int (optional; default: 10)
        Maximum allowable 'cost' of the expression: if `expr` is estimated to
        be more costly than this, an error is raised instead. The value `None`
        deactivates this check.
        Cost is estimated by a proxy, specifically the number of ancestors to
        `expr` in the Theano graph. By default, only expressions with 10 ancestors
        or less are evaluated.
    if_too_costly: 'ignore'  |  'raise'
        What to do if an expression is too costly to compute.
        'ignore': do nothing, return symbolic expression.
        'raise' : raise a TooCostly exception.
    inputs: Deprecated
        Synonym for `givens`.

    Returns
    -------
    Pure Python variable of same type as `expr`.
    """
    # Bypassing code paths
    if core.isshared(expr):
        return expr.get_value()
    elif not core.is_theano_object(expr):
        return expr
    elif isinstance(expr, slice):
        return slice(eval(expr.start), eval(expr.stop), eval(expr.step))

    # "Standard" code path
    cost = len(core.gettheano().gof.graph.ancestors([expr]))
    if max_cost is not None and cost > max_cost:
        if if_too_costly == 'raise':
            raise TooCostly("Expression has {} ancestors, which exceeds the "
                            "limit of {}.".format(cost, max_cost))
        else:
            return expr
    else:
        if inputs is None: inputs = {}  # TODO: Remove `inputs`
        if givens is None: givens = {}
        givens = {**inputs, **givens}
        for k, v in givens.items():
            givens[k] = core.cast(v, k.dtype)
        f = core.gettheano().function(
            [], expr, givens=givens, on_unused_input='ignore')
        return f()

######################
# Graph inspection

# _stablehash and _tobytes also in `mackelab.utils`
def _stablehash(o):
    """
    Builtin `hash` is not stable across sessions for security reasons.
    """
    import hashlib
    return hashlib.sha1(_tobytes(o)).hexdigest()

def _tobytes(o):
    if isinstance(o, Iterable) and not isinstance(o, cf.TerminatingTypes):
        return b''.join(_tobytes(oi) for oi in o)
    elif isinstance(o, str):
        return o.encode('utf8')
    elif isinstance(o, bytes):
        return o
    else:
        return bytes(o)

def hash(graph):
    """
    Return a value which is consistent on equivalent graphs.

    ..Note: The implementation may change. Hashes can be used for memoization,
    but should not be used for long term storage.
    FIXME: Current implementation works by hashing the result of `shim.pprint`.
    This is not ideal, because using the same name for different variables
    might not be resolved, and shape/dtype is not included.

    Parameters
    ----------
    graph: symbolic | list of symbolics
        If a list, a single value is returned, wich is dependent on the order.
        Nested lists also work, but note that `hash([a, b]) != hash([a, [b]])`.
    """

    if (isinstance(graph, collections.Iterable)
        and not isinstance(graph, cf.TerminatingTypes)):
        return _stablehash(tuple(hash(g) for g in graph))
    else:
        return _stablehash(core.pprint(graph))

def is_computable(varlist, with_inputs=None):
    """
    Returns True if the variables in varlist can be numerically evaluated
    using only the inputs in `with_inputs`. In other words, the computational
    graph associated to varlist is composed only of constants and shared variables,
    along with the symbolic variables in `with_inputs`.
    If varlist is not a Theano graph, it is always computable.
    """
    if ( not isinstance(varlist, collections.Iterable)
         or isinstance(varlist, str) ):
        raise ValueError("theano_shim.is_computable requires a list as first argument.")
    if with_inputs is None:
        with_inputs = []
    computable = True
    for var in varlist:
        if isinstance(var, slice):
            # Must come before `is_theano_variable`
            if not is_computable([var.start, var.stop, var.step]):
                computable = False
                break
        elif core.is_theano_variable(var): # Required because varlist may contain non-Theano objects
            if core.is_theano_variable( set(core.gettheano().gof.graph.inputs([var])).difference(with_inputs) ):
                computable = False
                break
    return computable

def inputs(varlist, *args, **kwargs):
    """
    Wrapper for theano.gof.graph.inputs.
    Returns an empty list for non symbolic variables
    """
    if isinstance(varlist, cf.GraphType):
        # Wrap calls on single variables with a list
        varlist = [varlist]
    elif ( not isinstance(varlist, collections.Iterable)
         or isinstance(varlist, str) ):
        raise ValueError("theano_shim.graph.inputs requires a list as first argument.")
    if core.is_theano_object(varlist):
        return core._gettheano().gof.graph.inputs(varlist, *args, **kwargs)
    else:
        return []

def symbolic_inputs(varlist, *args, **kwargs):
    return [v for v in inputs(varlist, *args, **kwargs) if core.is_symbolic(v)]

def shared_inputs(varlist, *args, **kwargs):
    return [v for v in inputs(varlist, *args, **kwargs)
              if isinstance(v, cf.SharedType)]

def pure_symbolic_inputs(varlist, *args, **kwargs):
    return [v for v in inputs(varlist, *args, **kwargs) if core.is_pure_symbolic(v)]

def variables(i, o=None):
    """
    Wrapper for theano.gof.graph.variables.
    Returns an empty list for non symbolic variables
    If given only one argument, returns all variables it depends on.
    """
    if o is None:
        o = i
        i = inputs(o)
    if isinstance(i, cf.GraphType):
        i = [i]
    if isinstance(o, cf.GraphType):
        o = [o]
    if ( not isinstance(i, collections.Iterable)
         or isinstance(i, str) ):
        raise ValueError(
            "Arguments to theano_shim.graph.variables must be lists.")
    if core.is_theano_object(i, o):
        return core._gettheano().gof.graph.variables(i, o)
    else:
        return []

def is_same_graph(var1, var2, givens=None, debug=False):
    """
    Wraps theano.gof.graph.is_same_graph().
    Returns True if `var1` and `var2` perform the same computation.
    If either `var1` or `var2` is not a graph object, returns the result of
    `var1 == var2`.
    """
    if not (core.is_theano_object(var1) and core.is_theano_object(var2)):
        return var1 == var2
    else:
        return core._gettheano().gof.graph.is_same_graph(var1, var2,
                                                         givens, debug)
<|endoftext|>


<commit_before>#MoReqquiem 2015
<commit_msg>Final Calculator for Python Interpreter<commit_after>#MoRequiem 2015
#The following line will make you insert the cost of your meal, not including taxes.
meal = float(input("-What is the cost of the meal? \n"))

#The tax is set on kenosha restaurant tax, edit if needed; also tip is 15 percent, later will add question for increase or decrease in tip
tax = 0.055
tip = 0.15

#The following two lines will calculate the tax on your meal, and the total with taxes
tax = meal * tax
meal = meal + tax

#The following two lines calculate the tip to give and the subtotal
tip = meal * tip
total = meal + tip

#The following set of lines displays the finished calculations in: total, tip, and subtotal
print ("""-Total: ${0:10.2f}
-Tip: ${1:10.2f}
-Subtotal: ${2:10.2f}""".format(meal, tip, total))
<|endoftext|>


<commit_before>"""
This module extracts the information provided in "Third millenium
Ideal Gas and Condensed Phase Thermochemical Database for Combustion
with Updates from Active Thermochemical Tables. A. Burcat and B
Ruscic. It needs the actual database BURCAT_THR.xml (xml format) to
run.
"""

# TODO: Introduce the exception in all try-except clauses

from __future__ import division
from __future__ import print_function
import os
try:
    from xml.etree.ElementTree import parse
except ImportError:
    from elementtree import parse
from numpy import empty, array, dot, log

# Universal gas constant R
R = 8.314472

class Element(object):

    """
    This is a helper class.  It is intended to be created via an
    Elementdb object but you can use it by your own. Take a look at
    Elementdb class.

    Units are K, J, kg... conversion functions are provided in the
    external units module.

    One extra feature not explained in Elementdb documentation is that
    it contains the number of each atom, useful for computing chemical
    reactions.

    >>> db = Elementdb()
    >>> weird = db.getelementdata("C8H6O2")
    >>> print(weird.elements)
    [('C', 8), ('H', 6), ('O', 2)]
    """

    def __init__(self, formula, Tmin_, _Tmax, mm, hfr, elements):
        self.formula = formula
        self.Tmin_ = Tmin_
        self._Tmax = _Tmax
        self.mm = mm
        self.hfr = hfr
        self.elements = elements

    def density(self, p, T):
        """
        Density in kg/m3.
        """
        return p * self.mm / R / T

    def cpo(self, T):
        """
        Calculates the specific heat capacity in J/mol K
        """
        # I know perfectly that the most efficient way of evaluatin
        # polynomials is recursively but I want the implementation to
        # be as explicit as possible
        Ta = array([1, T, T ** 2, T ** 3, T ** 4], 'd')
        if T > 200 and T <= 1000:
            return dot(self.Tmin_[:5], Ta) * R
        elif T > 1000 and T < 6000:
            return dot(self._Tmax[:5], Ta) * R
        else:
            raise ValueError("Temperature out of range")

    def cp_(self, T):
        """
        Computes the specific heat capacity in J/kg K for a given temperature
        """
        return self.cpo(T) / self.mm

    @property
    def cp(self):
        """
        Computes the specific heat capacity in J/kg K at 298 K (Reference T)
        """
        return self.cp_(298)

    def ho(self, T):
        """
        Computes the sensible enthalpy in J/mol
        """
        Ta = array([1, T / 2, T ** 2 / 3, T ** 3 / 4, T ** 4 / 5, 1 / T], 'd')
        if T > 200 and T <= 1000:
            return dot(self.Tmin_[:6], Ta) * R * T
        elif T > 1000 and T < 6000:
            return dot(self._Tmax[:6], Ta) * R * T
        else:
            raise ValueError("Temperature out of range")

    def h(self, T):
        """
        Computes the total enthalpy in J/kg
        """
        return self.cp_(T) * T

    def so(self, T):
        """
        Computes enthropy in J/mol K
        """
        Ta = array([log(T), T, T ** 2 / 2, T ** 3 / 3, T ** 4 / 4, 0, 1], 'd')
        if T > 200 and T <= 1000:
            return dot(self.Tmin_, Ta) * R
        elif T > 1000 and T < 6000:
            return dot(self._Tmax, Ta) * R
        else:
            raise ValueError("Temperature out of range")

    def go(self, T):
        """
        Computes the Gibbs free energy from the sensible enthalpy in
        J/mol
        """
        if T > 200 and T < 6000:
            return self.ho(T) - self.so(T) * T
        else:
            raise ValueError("Temperature out of range")

    def __repr__(self):
        return """<element> %s""" % (self.formula)

    def __str__(self):
        return """<element> %s""" % (self.formula)

    def __unicode__(self):
        return u"""<element> %s""" % (self.formula)

class Mixture(object):

    """
    Class that models a gas mixture. By now only volume (molar)
    composition is supported.

    You can iterate through all its elements.  The item returned is a
    tuple containing the element and the amount.

    >>> db = Elementdb()
    >>> mix = db.getmixturedata([("O2 REF ELEMENT",20.9476),\
    ("N2  REF ELEMENT",78.084),\
    ("CO2",0.0319),\
    ("AR REF ELEMENT",0.9365),\
    ])
    >>> mix_list = [(e[0], round(e[1], 6)) for e in mix]
    >>> for e in mix_list: print(e)
    (<element> O2 REF ELEMENT, 20.9476)
    (<element> N2  REF ELEMENT, 78.084)
    (<element> CO2, 0.0319)
    (<element> AR REF ELEMENT, 0.9365)

    You can get elements either by index or by value.

    >>> print(mix['CO2'])
    (<element> CO2, 0.0319)

    You can also delete components of a mixture.  Needed by the
    MoistAir class

    >>> mix.delete('CO2')
    >>> print(mix)
    <Mixture>:
        O2 REF ELEMENT at 20.9476
        N2  REF ELEMENT at 78.084
        AR REF ELEMENT at 0.9365
    """

    def __init__(self, config='vol'):
        self.mix = list()
        self.config = config
        self.idx = 0

    # The following two functions are an iterator. Its purpose is to
    # be able to iterate through all the elements of a mix.
    def __iter__(self):
        return self

    def __next__(self):
        return self.next()

    def next(self):
        try:
            rv = self.mix[self.idx]
            self.idx += 1
            return rv

        except:
            self.idx = 0
            raise StopIteration

    def __getitem__(self, i):
        if isinstance(i, int):
            return self.mix[i]

        if isinstance(i, str):
            elem = (None, None)
            for e in self.mix:
                if i == e[0].formula:
                    elem = e

            return elem

    def add(self, component, prop):
        """Add a component to the mixture"""
        self.mix.append((component, prop))

    def delete(self, formula):
        """Delete a formula from the mixture"""
        erased = False
        for e in self.mix:
            if e[0].formula == formula:
                self.mix.remove(e)
                erased = True

        if not erased:
            raise ValueError("Not a component")

    @property
    def mm(self):
        """
        Computes the equivalent molar mass for a mix

        .. math::

          M_m = \\frac{1}{N_m} \\sum_i N_i M_i
        """
        if self.config == 'vol':
            Nm = 0
            Mm = 0
            for comp in self.mix:
                Nm += comp[1]

            for comp in self.mix:
                Mm += comp[1] * comp[0].mm

            return Mm / Nm

    def density(self, p, T):
        """
        Computes the density for a given mix of gases in kg/m3

        The equivalent R for a mix is :math:`R_m = \\frac{R_u}{M_n}`,
        where :math:`M_n` is the equivalent molar mass for the mix.
        """
        return p * self.mm / R / T

    def extensive(self, attr, T):
        """
        Computes the extensive value for a mix.  Remember that an
        extensive value depends on the amount of matter. Enthalpy and
        volume are extensive values.

        .. math::

          ext = \\frac{1}{N_m M_m} \\sum_i N_i M_i ext_i
        """
        if self.config == 'vol':
            Nm = 0
            Mm = 0
            ext = 0
            for comp in self.mix:
                Nm += comp[1]

            for comp in self.mix:
                Mm += comp[1] * comp[0].mm

            Mm = Mm / Nm

            for comp in self.mix:
                # Tricky use of getattr function to avoid cutting and
                # pasting several times the very same code
                iattr = getattr(comp[0], attr)
                ext += comp[1] * comp[0].mm * iattr(T)

            return ext / Nm / Mm

    def cp_(self, T):
        """
        Computes the heat capacity at a given temperature

        """
        return self.extensive('cp_', T)

    @property
    def cp(self):
        """
        Computes the heat capacity
        """
        return self.extensive('cp_', 298.15)

    def ho(self, T):
        return self.extensive('ho', T)

    def h(self, T):
        return self.cp_(T) * T

    def so(self, T):
        return self.extensive('so', T)

    def go(self, T):
        return self.extensive('go', T)

    def __repr__(self):
        repr_str = "<Mixture>:"
        for comp in self.mix:
            repr_str += "\n    %s at %s" % (comp[0].formula, comp[1])
        return repr_str

    def __str__(self):
        return self.__repr__()

    def __unicode__(self):
        repr_str = u"<Mixture>:"
        for comp in self.mix:
            repr_str += u"\n    %s at %s" % (comp[0].formula, comp[1])

        return repr_str

class Elementdb(object):

    """
    Class that reads the Alexander Burcat's thermochemical database
    for combustion.

    >>> db = Elementdb()
    >>> oxygen = db.getelementdata("O2 REF ELEMENT")
    >>> print(oxygen)
    <element> O2 REF ELEMENT
    >>> print('molar mass',oxygen.mm)
    molar mass 0.0319988
    >>> print('heat capacity',oxygen.cp)
    heat capacity 918.078952423

    The reference temperature for enthalpy is 298.15 K

    >>> print('enthropy',oxygen.so(298))
    enthropy 205.133745795
    >>> print('gibbs free energy',oxygen.go(298))
    gibbs free energy -61134.2629008

    There's a search function.  It is very useful because some names
    are a bit tricky.  Well, not this one.

    >>> db.search("AIR")
    ['AIR']
    >>> air = db.getelementdata("AIR")
    >>> print('air molar mass',air.mm)
    air molar mass 0.02896518
    >>> print('heat capacity',air.cp)
    heat capacity 1004.77625096
    >>> print(round(air.density(101325,298), 6))
    1.184519

    The element database can create also mixtures.  It returns an
    instance of Mixture object that can give you the same as the
    Element class for any mixture.

    >>> mix = db.getmixturedata([("O2 REF ELEMENT",20.9476),\
    ("N2  REF ELEMENT",78.084),\
    ("CO2",0.0319),\
    ("AR REF ELEMENT",0.9365),\
    ])
    >>> print(mix)
    <Mixture>:
        O2 REF ELEMENT at 20.9476
        N2  REF ELEMENT at 78.084
        CO2 at 0.0319
        AR REF ELEMENT at 0.9365
    >>> print(mix.cp)
    1004.72217065
    >>> print(round(mix.mm, 6))
    0.028965
    """

    def __init__(self):
        """
        The database file is read when the class is instantiated.
        This is terribly slow as the database is more than 2MB.
        Create the instance and the elements at boot, otherwise be
        prepared to face huge computation times.
        """
        dirname = os.path.dirname(__file__)
        burcat = os.path.join(dirname, 'BURCAT_THR.xml')
        with open(burcat, 'r') as database:
            tree = parse(database)
        self.db = tree.getroot()

    def search(self, formula):
        """
        List all the species containing a string. Helpful for
        interactive use of the database.
        """
        matches = []
        for specie in self.db:
            try:
                for element in specie:
                    try:
                        if element.tag == "phase":
                            if formula in element.find("formula").text:
                                matches.append(element.find("formula").text)
                    except:
                        pass
            except:
                pass

        return matches

    def getelementdata(self, formula):
        """
        Returns an element instance given the name of the element.
        """
        Tmin_ = empty((7), 'd')
        _Tmax = empty((7), 'd')
        comp = []
        for specie in self.db:
            try:
                for element in specie:
                    try:
                        if element.tag == "phase":
                            if formula == element.find("formula").text:
                                phase = element
                                coefficients = phase.find("coefficients")
                                low = coefficients.find("range_Tmin_to_1000")
                                for (i, c) in zip(range(7), low):
                                    Tmin_[i] = float(c.text)

                                high = coefficients.find("range_1000_to_Tmax")
                                for (i, c) in zip(range(7), high):
                                    _Tmax[i] = float(c.text)

                                elements = phase.find("elements")
                                elements = elements.getchildren()
                                for elem in elements:
                                    it = elem.items()
                                    # First is name of element, second is number
                                    # of atoms
                                    comp.append((it[0][1], int(it[1][1])))

                                mm = float(phase.find("molecular_weight").text) / 1000
                                hfr = float(coefficients.find("hf298_div_r").text)

                                return Element(formula, Tmin_, _Tmax, mm, hfr, comp)
                    except:
                        pass
            except:
                pass

    def getmixturedata(self, components):
        """
        Creates a mixture of components given a list of tuples
        containing the formula and the volume percent
        """
        mixture = Mixture()
        for comp in components:
            mixture.add(self.getelementdata(comp[0]), comp[1])

        return mixture
<commit_msg>Use package import to avoid polluting namespace<commit_after>"""
This module extracts the information provided in "Third millenium
Ideal Gas and Condensed Phase Thermochemical Database for Combustion
with Updates from Active Thermochemical Tables. A. Burcat and B
Ruscic. It needs the actual database BURCAT_THR.xml (xml format) to
run.
"""

# TODO: Introduce the exception in all try-except clauses

from __future__ import division
from __future__ import print_function
import os
try:
    from xml.etree.ElementTree import parse
except ImportError:
    from elementtree import parse
import numpy as np

# Universal gas constant R
R = 8.314472

class Element(object):

    """
    This is a helper class.  It is intended to be created via an
    Elementdb object but you can use it by your own. Take a look at
    Elementdb class.

    Units are K, J, kg... conversion functions are provided in the
    external units module.

    One extra feature not explained in Elementdb documentation is that
    it contains the number of each atom, useful for computing chemical
    reactions.

    >>> db = Elementdb()
    >>> weird = db.getelementdata("C8H6O2")
    >>> print(weird.elements)
    [('C', 8), ('H', 6), ('O', 2)]
    """

    def __init__(self, formula, Tmin_, _Tmax, mm, hfr, elements):
        self.formula = formula
        self.Tmin_ = Tmin_
        self._Tmax = _Tmax
        self.mm = mm
        self.hfr = hfr
        self.elements = elements

    def density(self, p, T):
        """
        Density in kg/m3.
        """
        return p * self.mm / R / T

    def cpo(self, T):
        """
        Calculates the specific heat capacity in J/mol K
        """
        # I know perfectly that the most efficient way of evaluatin
        # polynomials is recursively but I want the implementation to
        # be as explicit as possible
        Ta = np.array([1, T, T ** 2, T ** 3, T ** 4], 'd')
        if T > 200 and T <= 1000:
            return np.dot(self.Tmin_[:5], Ta) * R
        elif T > 1000 and T < 6000:
            return np.dot(self._Tmax[:5], Ta) * R
        else:
            raise ValueError("Temperature out of range")

    def cp_(self, T):
        """
        Computes the specific heat capacity in J/kg K for a given temperature
        """
        return self.cpo(T) / self.mm

    @property
    def cp(self):
        """
        Computes the specific heat capacity in J/kg K at 298 K (Reference T)
        """
        return self.cp_(298)

    def ho(self, T):
        """
        Computes the sensible enthalpy in J/mol
        """
        Ta = np.array([1, T / 2, T ** 2 / 3, T ** 3 / 4, T ** 4 / 5, 1 / T], 'd')
        if T > 200 and T <= 1000:
            return np.dot(self.Tmin_[:6], Ta) * R * T
        elif T > 1000 and T < 6000:
            return np.dot(self._Tmax[:6], Ta) * R * T
        else:
            raise ValueError("Temperature out of range")

    def h(self, T):
        """
        Computes the total enthalpy in J/kg
        """
        return self.cp_(T) * T

    def so(self, T):
        """
        Computes enthropy in J/mol K
        """
        Ta = np.array([np.log(T), T, T ** 2 / 2, T ** 3 / 3, T ** 4 / 4, 0, 1], 'd')
        if T > 200 and T <= 1000:
            return np.dot(self.Tmin_, Ta) * R
        elif T > 1000 and T < 6000:
            return np.dot(self._Tmax, Ta) * R
        else:
            raise ValueError("Temperature out of range")

    def go(self, T):
        """
        Computes the Gibbs free energy from the sensible enthalpy in
        J/mol
        """
        if T > 200 and T < 6000:
            return self.ho(T) - self.so(T) * T
        else:
            raise ValueError("Temperature out of range")

    def __repr__(self):
        return """<element> %s""" % (self.formula)

    def __str__(self):
        return """<element> %s""" % (self.formula)

    def __unicode__(self):
        return u"""<element> %s""" % (self.formula)

class Mixture(object):

    """
    Class that models a gas mixture. By now only volume (molar)
    composition is supported.

    You can iterate through all its elements.  The item returned is a
    tuple containing the element and the amount.

    >>> db = Elementdb()
    >>> mix = db.getmixturedata([("O2 REF ELEMENT",20.9476),\
    ("N2  REF ELEMENT",78.084),\
    ("CO2",0.0319),\
    ("AR REF ELEMENT",0.9365),\
    ])
    >>> mix_list = [(e[0], round(e[1], 6)) for e in mix]
    >>> for e in mix_list: print(e)
    (<element> O2 REF ELEMENT, 20.9476)
    (<element> N2  REF ELEMENT, 78.084)
    (<element> CO2, 0.0319)
    (<element> AR REF ELEMENT, 0.9365)

    You can get elements either by index or by value.

    >>> print(mix['CO2'])
    (<element> CO2, 0.0319)

    You can also delete components of a mixture.  Needed by the
    MoistAir class

    >>> mix.delete('CO2')
    >>> print(mix)
    <Mixture>:
        O2 REF ELEMENT at 20.9476
        N2  REF ELEMENT at 78.084
        AR REF ELEMENT at 0.9365
    """

    def __init__(self, config='vol'):
        self.mix = list()
        self.config = config
        self.idx = 0

    # The following two functions are an iterator. Its purpose is to
    # be able to iterate through all the elements of a mix.
    def __iter__(self):
        return self

    def __next__(self):
        return self.next()

    def next(self):
        try:
            rv = self.mix[self.idx]
            self.idx += 1
            return rv

        except:
            self.idx = 0
            raise StopIteration

    def __getitem__(self, i):
        if isinstance(i, int):
            return self.mix[i]

        if isinstance(i, str):
            elem = (None, None)
            for e in self.mix:
                if i == e[0].formula:
                    elem = e

            return elem

    def add(self, component, prop):
        """Add a component to the mixture"""
        self.mix.append((component, prop))

    def delete(self, formula):
        """Delete a formula from the mixture"""
        erased = False
        for e in self.mix:
            if e[0].formula == formula:
                self.mix.remove(e)
                erased = True

        if not erased:
            raise ValueError("Not a component")

    @property
    def mm(self):
        """
        Computes the equivalent molar mass for a mix

        .. math::

          M_m = \\frac{1}{N_m} \\sum_i N_i M_i
        """
        if self.config == 'vol':
            Nm = 0
            Mm = 0
            for comp in self.mix:
                Nm += comp[1]

            for comp in self.mix:
                Mm += comp[1] * comp[0].mm

            return Mm / Nm

    def density(self, p, T):
        """
        Computes the density for a given mix of gases in kg/m3

        The equivalent R for a mix is :math:`R_m = \\frac{R_u}{M_n}`,
        where :math:`M_n` is the equivalent molar mass for the mix.
        """
        return p * self.mm / R / T

    def extensive(self, attr, T):
        """
        Computes the extensive value for a mix.  Remember that an
        extensive value depends on the amount of matter. Enthalpy and
        volume are extensive values.

        .. math::

          ext = \\frac{1}{N_m M_m} \\sum_i N_i M_i ext_i
        """
        if self.config == 'vol':
            Nm = 0
            Mm = 0
            ext = 0
            for comp in self.mix:
                Nm += comp[1]

            for comp in self.mix:
                Mm += comp[1] * comp[0].mm

            Mm = Mm / Nm

            for comp in self.mix:
                # Tricky use of getattr function to avoid cutting and
                # pasting several times the very same code
                iattr = getattr(comp[0], attr)
                ext += comp[1] * comp[0].mm * iattr(T)

            return ext / Nm / Mm

    def cp_(self, T):
        """
        Computes the heat capacity at a given temperature

        """
        return self.extensive('cp_', T)

    @property
    def cp(self):
        """
        Computes the heat capacity
        """
        return self.extensive('cp_', 298.15)

    def ho(self, T):
        return self.extensive('ho', T)

    def h(self, T):
        return self.cp_(T) * T

    def so(self, T):
        return self.extensive('so', T)

    def go(self, T):
        return self.extensive('go', T)

    def __repr__(self):
        repr_str = "<Mixture>:"
        for comp in self.mix:
            repr_str += "\n    %s at %s" % (comp[0].formula, comp[1])
        return repr_str

    def __str__(self):
        return self.__repr__()

    def __unicode__(self):
        repr_str = u"<Mixture>:"
        for comp in self.mix:
            repr_str += u"\n    %s at %s" % (comp[0].formula, comp[1])

        return repr_str

class Elementdb(object):
    """
    Class that reads the Alexander Burcat's thermochemical database
    for combustion.

    >>> db = Elementdb()
    >>> oxygen = db.getelementdata("O2 REF ELEMENT")
    >>> print(oxygen)
    <element> O2 REF ELEMENT
    >>> print('molar mass',oxygen.mm)
    molar mass 0.0319988
    >>> print('heat capacity',oxygen.cp)
    heat capacity 918.078952423

    The reference temperature for enthalpy is 298.15 K

    >>> print('enthropy',oxygen.so(298))
    enthropy 205.133745795
    >>> print('gibbs free energy',oxygen.go(298))
    gibbs free energy -61134.2629008

    There's a search function.  It is very useful because some names
    are a bit tricky.  Well, not this one.

    >>> db.search("AIR")
    ['AIR']
    >>> air = db.getelementdata("AIR")
    >>> print('air molar mass',air.mm)
    air molar mass 0.02896518
    >>> print('heat capacity',air.cp)
    heat capacity 1004.77625096
    >>> print(round(air.density(101325,298), 6))
    1.184519

    The element database can create also mixtures.  It returns an
    instance of Mixture object that can give you the same as the
    Element class for any mixture.

    >>> mix = db.getmixturedata([("O2 REF ELEMENT",20.9476),\
    ("N2  REF ELEMENT",78.084),\
    ("CO2",0.0319),\
    ("AR REF ELEMENT",0.9365),\
    ])
    >>> print(mix)
    <Mixture>:
        O2 REF ELEMENT at 20.9476
        N2  REF ELEMENT at 78.084
        CO2 at 0.0319
        AR REF ELEMENT at 0.9365
    >>> print(mix.cp)
    1004.72217065
    >>> print(round(mix.mm, 6))
    0.028965
    """

    def __init__(self):
        """
        The database file is read when the class is instantiated.
        This is terribly slow as the database is more than 2MB.
        Create the instance and the elements at boot, otherwise be
        prepared to face huge computation times.
        """
        dirname = os.path.dirname(__file__)
        burcat = os.path.join(dirname, 'BURCAT_THR.xml')
        with open(burcat, 'r') as database:
            tree = parse(database)
        self.db = tree.getroot()

    def search(self, formula):
        """
        List all the species containing a string. Helpful for
        interactive use of the database.
        """
        matches = []
        for specie in self.db:
            try:
                for element in specie:
                    try:
                        if element.tag == "phase":
                            if formula in element.find("formula").text:
                                matches.append(element.find("formula").text)
                    except:
                        pass
            except:
                pass

        return matches

    def getelementdata(self, formula):
        """
        Returns an element instance given the name of the element.
        """
        Tmin_ = np.empty((7), 'd')
        _Tmax = np.empty((7), 'd')
        comp = []
        for specie in self.db:
            try:
                for element in specie:
                    try:
                        if element.tag == "phase":
                            if formula == element.find("formula").text:
                                phase = element
                                coefficients = phase.find("coefficients")
                                low = coefficients.find("range_Tmin_to_1000")
                                for (i, c) in zip(range(7), low):
                                    Tmin_[i] = float(c.text)

                                high = coefficients.find("range_1000_to_Tmax")
                                for (i, c) in zip(range(7), high):
                                    _Tmax[i] = float(c.text)

                                elements = phase.find("elements")
                                elements = elements.getchildren()
                                for elem in elements:
                                    it = elem.items()
                                    # First is name of element, second is number
                                    # of atoms
                                    comp.append((it[0][1], int(it[1][1])))

                                mm = float(phase.find("molecular_weight").text) / 1000
                                hfr = float(coefficients.find("hf298_div_r").text)

                                return Element(formula, Tmin_, _Tmax, mm, hfr, comp)
                    except:
                        pass
            except:
                pass

    def getmixturedata(self, components):
        """
        Creates a mixture of components given a list of tuples
        containing the formula and the volume percent
        """
        mixture = Mixture()
        for comp in components:
            mixture.add(self.getelementdata(comp[0]), comp[1])

        return mixture
<|endoftext|>


<commit_before>from ..model import Model
from ..util import get_width
from .recurrent import recurrent
from .bidirectional import bidirectional
from .clone import clone
from .affine import Affine

def BiLSTM(nO=None, nI=None, *, depth=1, dropout=0.0):
    return clone(bidirectional(recurrent(LSTM_step(nO=nO, nI=nI))), depth)

def LSTM(nO=None, nI=None, *, depth=1, dropout=0.0):
    return clone(recurrent(LSTM_step(nO=nO, nI=nI)), depth)

def LSTM_step(nO=None, nI=None):
    """Create a step model for an LSTM."""
    model = Model(
        "lstm_step", forward, init=init, layers=[Affine()], dims={"nO": nO, "nI": nI}
    )
    if nO is not None and nI is not None:
        model.initialize()
    return model

def init(model, X=None, Y=None):
    if X is not None:
        model.set_dim("nI", get_width(X))
    if Y is not None:
        model.set_dim("nO", get_width(Y))
    nO = model.get_dim("nO")
    nI = model.get_dim("nI")
    model.layers[0].set_dim("nO", nO * 4)
    model.layers[0].set_dim("nI", nO + nI)
    model.layers[0].initialize()

def forward(model, prevstate_inputs, is_train):
    (cell_tm1, hidden_tm1), inputs = prevstate_inputs
    weights = model.layers[0]
    nI = inputs.shape[1]
    X = model.ops.xp.hstack((inputs, hidden_tm1))

    acts, bp_acts = weights(X, is_train)
    (cells, hiddens), bp_gates = _gates_forward(model.ops, acts, cell_tm1)

    def backprop(d_state_d_hiddens):
        (d_cells, d_hiddens), d_hiddens = d_state_d_hiddens
        d_acts, d_cell_tm1 = bp_gates(d_cells, d_hiddens)
        dX = bp_acts(d_acts)
        return (d_cell_tm1, dX[:, nI:]), dX[:, :nI]

    return ((cells, hiddens), hiddens), backprop

def _gates_forward(ops, acts, prev_cells):
    nB = acts.shape[0]
    nO = acts.shape[1] // 4
    acts = acts.reshape((nB, 4, nO)).transpose((1, 0, 2))
    new_cells = ops.allocate(prev_cells.shape)
    new_hiddens = ops.allocate(prev_cells.shape)
    ops.lstm(new_hiddens, new_cells, acts, prev_cells)
    size = new_cells.shape[0]

    def backprop_gates(d_cells, d_hiddens):
        d_cells = d_cells[:size]
        d_hiddens = d_hiddens[:size]
        d_acts = ops.allocate(acts.shape)
        d_prevcells = ops.allocate(prev_cells.shape)
        ops.backprop_lstm(
            d_cells, d_prevcells, d_acts, d_hiddens, acts, new_cells, prev_cells
        )
        d_acts = d_acts.transpose((1, 0, 2)).reshape((nB, 4 * nO))
        return d_acts, d_prevcells

    return (new_cells, new_hiddens), backprop_gates
<commit_msg>Update LSTM<commit_after>from ..model import Model
from ..util import get_width
from .recurrent import recurrent
from .bidirectional import bidirectional
from .clone import clone
from .affine import Affine
from .with_square_sequences import with_square_sequences

def BiLSTM(nO=None, nI=None, *, depth=1, dropout=0.0):
    return with_square_sequences(clone(bidirectional(recurrent(LSTM_step(nO=nO, nI=nI))), depth))

def LSTM(nO=None, nI=None, *, depth=1, dropout=0.0):
    return with_square_sequences(clone(recurrent(LSTM_step(nO=nO, nI=nI)), depth))

def LSTM_step(nO=None, nI=None):
    """Create a step model for an LSTM."""
    model = Model(
        "lstm_step", forward, init=init, layers=[Affine()], dims={"nO": nO, "nI": nI}
    )
    if nO is not None and nI is not None:
        model.initialize()
    return model

def init(model, X=None, Y=None):
    if X is not None:
        model.set_dim("nI", get_width(X))
    if Y is not None:
        model.set_dim("nO", get_width(Y))
    nO = model.get_dim("nO")
    nI = model.get_dim("nI")
    model.layers[0].set_dim("nO", nO * 4)
    model.layers[0].set_dim("nI", nO + nI)
    model.layers[0].initialize()

def forward(model, prevstate_inputs, is_train):
    (cell_tm1, hidden_tm1), inputs = prevstate_inputs
    weights = model.layers[0]
    nI = inputs.shape[1]
    X = model.ops.xp.hstack((inputs, hidden_tm1))

    acts, bp_acts = weights(X, is_train)
    (cells, hiddens), bp_gates = _gates_forward(model.ops, acts, cell_tm1)

    def backprop(d_state_d_hiddens):
        (d_cells, d_hiddens), d_hiddens = d_state_d_hiddens
        d_acts, d_cell_tm1 = bp_gates(d_cells, d_hiddens)
        dX = bp_acts(d_acts)
        return (d_cell_tm1, dX[:, nI:]), dX[:, :nI]

    return ((cells, hiddens), hiddens), backprop

def _gates_forward(ops, acts, prev_cells):
    nB = acts.shape[0]
    nO = acts.shape[1] // 4
    acts = acts.reshape((nB, 4, nO)).transpose((1, 0, 2))
    new_cells = ops.allocate(prev_cells.shape)
    new_hiddens = ops.allocate(prev_cells.shape)
    ops.lstm(new_hiddens, new_cells, acts, prev_cells)
    size = new_cells.shape[0]

    def backprop_gates(d_cells, d_hiddens):
        d_cells = d_cells[:size]
        d_hiddens = d_hiddens[:size]
        d_acts = ops.allocate(acts.shape)
        d_prevcells = ops.allocate(prev_cells.shape)
        ops.backprop_lstm(
            d_cells, d_prevcells, d_acts, d_hiddens, acts, new_cells, prev_cells
        )
        d_acts = d_acts.transpose((1, 0, 2)).reshape((nB, 4 * nO))
        return d_acts, d_prevcells

    return (new_cells, new_hiddens), backprop_gates
<|endoftext|>


<commit_before>import requests
from bs4 import BeautifulSoup

def getLinkInPara(para_list):
    for para in para_list:
        bracket = 0
        for tag in para.children:
            if tag.name is None and tag.string is not None:
                if '(' in tag.string.strip():
                    bracket = bracket + 1
                if ')' in tag.string.strip():
                    bracket = bracket - 1

            if tag.name == 'a' and bracket == 0:
                next_link = tag['href']
                if '#' in next_link:
                    continue
                return next_link
    return None

def getNextLink(link):
    wiki_url = "http://en.wikipedia.org/wiki/"

    r = requests.get(wiki_url+link)
    if r.status_code != 200:
        print(link + "Not a valid wiki link")
        return "--ERROR1--"

    data = r.text
    soup = BeautifulSoup(data)
    div = soup.find_all(id="mw-content-text")[0]

    para_list = []
    for child in div.children:
        if child.name == 'p':
            para_list.append(child)

    next_link = None
    if para_list is not None:
        next_link = getLinkInPara(para_list)

    if next_link is None:
        ul = None
        for child in div.children:
            if child.name == 'ul':
                ul = child
                break

        if ul is None:
            return "--ERROR2--"

        try:
            next_link = ul.li.a['href']
        except:
            return "--ERROR2--"

    if next_link is not None:
        args = next_link.split("/")[-1]
        print args
        return args
    else:
        return "--ERROR3--"
<commit_msg>Add Python 3 support<commit_after>from __future__ import print_function
import requests
from bs4 import BeautifulSoup

def getLinkInPara(para_list):
    for para in para_list:
        bracket = 0
        for tag in para.children:
            if tag.name is None and tag.string is not None:
                if '(' in tag.string.strip():
                    bracket = bracket + 1
                if ')' in tag.string.strip():
                    bracket = bracket - 1

            if tag.name == 'a' and bracket == 0:
                next_link = tag['href']
                if '#' in next_link:
                    continue
                return next_link
    return None

def getNextLink(link):
    wiki_url = "http://en.wikipedia.org/wiki/"

    r = requests.get(wiki_url+link)
    if r.status_code != 200:
        print(link + "Not a valid wiki link")
        return "--ERROR1--"

    data = r.text
    soup = BeautifulSoup(data)
    div = soup.find_all(id="mw-content-text")[0]

    para_list = []
    for child in div.children:
        if child.name == 'p':
            para_list.append(child)

    next_link = None
    if para_list is not None:
        next_link = getLinkInPara(para_list)

    if next_link is None:
        ul = None
        for child in div.children:
            if child.name == 'ul':
                ul = child
                break

        if ul is None:
            return "--ERROR2--"

        try:
            next_link = ul.li.a['href']
        except:
            return "--ERROR2--"

    if next_link is not None:
        args = next_link.split("/")[-1]
        print(args)
        return args
    else:
        return "--ERROR3--"
<|endoftext|>