<commit_before>"""
Drop-in replacement for ``django.conf.settings`` that provides a
consistent access method for settings defined in applications, the project
or Django itself. Settings can also be made editable via the admin.
"""

from __future__ import unicode_literals
from future.builtins import bytes, str

from functools import partial
from warnings import warn

from django.conf import settings as django_settings
from django.utils.functional import Promise
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule

from mezzanine import __version__

registry = {}

def register_setting(name=None, label=None, editable=False, description=None,
                     default=None, choices=None, append=False):
    """
    Registers a setting that can be edited via the admin. This mostly
    equates to storing the given args as a dict in the ``registry``
    dict by name.
    """
    if name is None:
        raise TypeError("mezzanine.conf.register_setting requires the "
                        "'name' keyword argument.")
    if editable and default is None:
        raise TypeError("mezzanine.conf.register_setting requires the "
                        "'default' keyword argument when 'editable' is True.")

    # append is True when called from an app (typically external)
    # after the setting has already been registered, with the
    # intention of appending to its default value.
    if append and name in registry:
        registry[name]["default"] += default
        return

    # If an editable setting has a value defined in the
    # project's settings.py module, it can't be editable, since
    # these lead to a lot of confusion once its value gets
    # defined in the db.
    if hasattr(django_settings, name):
        editable = False
    if label is None:
        label = name.replace("_", " ").title()

    # Python 2/3 compatibility. isinstance() is overridden by future
    # on Python 2 to behave as Python 3 in conjunction with either
    # Python 2's native types or the future.builtins types.
    if isinstance(default, bool):
        # Prevent bools treated as ints
        setting_type = bool
    elif isinstance(default, int):
        # An int or long or subclass on Py2
        setting_type = int
    elif isinstance(default, (str, Promise)):
        # A unicode or subclass on Py2
        setting_type = str
    elif isinstance(default, bytes):
        # A byte-string or subclass on Py2
        setting_type = bytes
    else:
        setting_type = type(default)
    registry[name] = {"name": name, "label": label, "editable": editable,
                      "description": description, "default": default,
                      "choices": choices, "type": setting_type}

class Settings(object):
    """
    An object that provides settings via dynamic attribute access.

    Settings that are registered as editable will be stored in the
    database once the site settings form in the admin is first saved.
    When these values are accessed via this settings object, *all*
    database stored settings get retrieved from the database.

    When accessing uneditable settings their default values are used,
    unless they've been given a value in the project's settings.py
    module.

    The settings object also provides access to Django settings via
    ``django.conf.settings``, in order to provide a consistent method
    of access for all settings.
    """

    # These functions map setting types to the functions that should be
    # used to convert them from the Unicode string stored in the database.
    # If a type doesn't appear in this map, the type itself will be used.
    TYPE_FUNCTIONS = {
        bool: lambda val: val != "False",
        bytes: partial(bytes, encoding='utf8')
    }

    def __init__(self):
        """
        The ``_loaded`` attribute is a flag for defining whether
        editable settings have been loaded from the database. It
        defaults to ``True`` here to avoid errors when the DB table
        is first created. It's then set to ``False`` whenever the
        ``use_editable`` method is called, which should be called
        before using editable settings in the database.
        ``_editable_cache`` is the dict that stores the editable
        settings once they're loaded from the database, the first
        time an editable setting is accessed.
        """
        self._loaded = True
        self._editable_cache = {}

    def use_editable(self):
        """
        Empty the editable settings cache and set the loaded flag to
        ``False`` so that settings will be loaded from the DB on next
        access. If the conf app is not installed then set the loaded
        flag to ``True`` in order to bypass DB lookup entirely.
        """
        self._loaded = __name__ not in getattr(self, "INSTALLED_APPS")

    def _load(self):
        """
        Load settings from the database into cache. Delete any settings from
        the database that are no longer registered, and emit a warning if
        there are settings that are defined in settings.py and the database.
        """
        from mezzanine.conf.models import Setting

        removed_settings = []
        conflicting_settings = []

        valid_settings = []
        for setting_obj in Setting.objects.all():
            try:
                registry[setting_obj.name]
            except KeyError:
                # Setting in DB isn't registered (removed from code),
                # so add to removal list and skip remaining handling.
                removed_settings.append(setting_obj.name)
                continue

            # Convert DB value to correct type.
            setting_type = registry[setting_obj.name]["type"]
            type_fn = self.TYPE_FUNCTIONS.get(setting_type, setting_type)
            try:
                setting_value = type_fn(setting_obj.value)
            except ValueError:
                # Shouldn't occur, but just a safeguard
                # for if the db value somehow ended up as
                # an invalid type.
                setting_value = registry[setting_obj.name]["default"]

            # Only use DB setting if it's not defined in settings.py
            # module, in which case add it to conflicting list for
            # warning.
            try:
                getattr(django_settings, setting_obj.name)
            except AttributeError:
                valid_settings.append((setting_obj.name, setting_value))
            else:
                if setting_value != registry[setting_obj.name]["default"]:
                    conflicting_settings.append(setting_obj.name)

        if removed_settings:
            Setting.objects.filter(name__in=removed_settings).delete()
        if conflicting_settings:
            warn("These settings are defined in both settings.py and "
                 "the database: %s. The settings.py values will be used."
                 % ", ".join(conflicting_settings))
        self._editable_cache = dict(valid_settings)
        self._loaded = True

    def __getattr__(self, name):

        # Lookup name as a registered setting or a Django setting.
        try:
            setting = registry[name]
        except KeyError:
            return getattr(django_settings, name)

        # First access for an editable setting - load from DB into cache.
        if setting["editable"] and not self._loaded:
            self._load()

        # Use cached editable setting if found, otherwise use the
        # value defined in the project's settings.py module if it
        # exists, finally falling back to the default defined when
        # registered.
        try:
            return self._editable_cache[name]
        except KeyError:
            return getattr(django_settings, name, setting["default"])

mezz_first = lambda app: not app.startswith("mezzanine.")
for app in sorted(django_settings.INSTALLED_APPS, key=mezz_first):
    module = import_module(app)
    try:
        import_module("%s.defaults" % app)
    except:
        if module_has_submodule(module, "defaults"):
            raise

settings = Settings()
<commit_msg>Slightly faster settings loader.<commit_after>"""
Drop-in replacement for ``django.conf.settings`` that provides a
consistent access method for settings defined in applications, the project
or Django itself. Settings can also be made editable via the admin.
"""

from __future__ import unicode_literals
from future.builtins import bytes, str

from functools import partial
from warnings import warn

from django.conf import settings as django_settings
from django.utils.functional import Promise
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule

from mezzanine import __version__

registry = {}

def register_setting(name=None, label=None, editable=False, description=None,
                     default=None, choices=None, append=False):
    """
    Registers a setting that can be edited via the admin. This mostly
    equates to storing the given args as a dict in the ``registry``
    dict by name.
    """
    if name is None:
        raise TypeError("mezzanine.conf.register_setting requires the "
                        "'name' keyword argument.")
    if editable and default is None:
        raise TypeError("mezzanine.conf.register_setting requires the "
                        "'default' keyword argument when 'editable' is True.")

    # append is True when called from an app (typically external)
    # after the setting has already been registered, with the
    # intention of appending to its default value.
    if append and name in registry:
        registry[name]["default"] += default
        return

    # If an editable setting has a value defined in the
    # project's settings.py module, it can't be editable, since
    # these lead to a lot of confusion once its value gets
    # defined in the db.
    if hasattr(django_settings, name):
        editable = False
    if label is None:
        label = name.replace("_", " ").title()

    # Python 2/3 compatibility. isinstance() is overridden by future
    # on Python 2 to behave as Python 3 in conjunction with either
    # Python 2's native types or the future.builtins types.
    if isinstance(default, bool):
        # Prevent bools treated as ints
        setting_type = bool
    elif isinstance(default, int):
        # An int or long or subclass on Py2
        setting_type = int
    elif isinstance(default, (str, Promise)):
        # A unicode or subclass on Py2
        setting_type = str
    elif isinstance(default, bytes):
        # A byte-string or subclass on Py2
        setting_type = bytes
    else:
        setting_type = type(default)
    registry[name] = {"name": name, "label": label, "editable": editable,
                      "description": description, "default": default,
                      "choices": choices, "type": setting_type}

class Settings(object):
    """
    An object that provides settings via dynamic attribute access.

    Settings that are registered as editable will be stored in the
    database once the site settings form in the admin is first saved.
    When these values are accessed via this settings object, *all*
    database stored settings get retrieved from the database.

    When accessing uneditable settings their default values are used,
    unless they've been given a value in the project's settings.py
    module.

    The settings object also provides access to Django settings via
    ``django.conf.settings``, in order to provide a consistent method
    of access for all settings.
    """

    # These functions map setting types to the functions that should be
    # used to convert them from the Unicode string stored in the database.
    # If a type doesn't appear in this map, the type itself will be used.
    TYPE_FUNCTIONS = {
        bool: lambda val: val != "False",
        bytes: partial(bytes, encoding='utf8')
    }

    def __init__(self):
        """
        The ``_loaded`` attribute is a flag for defining whether
        editable settings have been loaded from the database. It
        defaults to ``True`` here to avoid errors when the DB table
        is first created. It's then set to ``False`` whenever the
        ``use_editable`` method is called, which should be called
        before using editable settings in the database.
        ``_editable_cache`` is the dict that stores the editable
        settings once they're loaded from the database, the first
        time an editable setting is accessed.
        """
        self._loaded = True
        self._editable_cache = {}

    def use_editable(self):
        """
        Empty the editable settings cache and set the loaded flag to
        ``False`` so that settings will be loaded from the DB on next
        access. If the conf app is not installed then set the loaded
        flag to ``True`` in order to bypass DB lookup entirely.
        """
        self._loaded = __name__ not in getattr(self, "INSTALLED_APPS")

    def _load(self):
        """
        Load settings from the database into cache. Delete any settings from
        the database that are no longer registered, and emit a warning if
        there are settings that are defined in settings.py and the database.
        """
        from mezzanine.conf.models import Setting

        removed_settings = []
        conflicting_settings = []
        new_cache = {}

        for setting_obj in Setting.objects.all():
            try:
                registry[setting_obj.name]
            except KeyError:
                # Setting in DB isn't registered (removed from code),
                # so add to removal list and skip remaining handling.
                removed_settings.append(setting_obj.name)
                continue

            # Convert DB value to correct type.
            setting_type = registry[setting_obj.name]["type"]
            type_fn = self.TYPE_FUNCTIONS.get(setting_type, setting_type)
            try:
                setting_value = type_fn(setting_obj.value)
            except ValueError:
                # Shouldn't occur, but just a safeguard
                # for if the db value somehow ended up as
                # an invalid type.
                setting_value = registry[setting_obj.name]["default"]

            # Only use DB setting if it's not defined in settings.py
            # module, in which case add it to conflicting list for
            # warning.
            try:
                getattr(django_settings, setting_obj.name)
            except AttributeError:
                new_cache[setting_obj.name] = setting_value
            else:
                if setting_value != registry[setting_obj.name]["default"]:
                    conflicting_settings.append(setting_obj.name)

        if removed_settings:
            Setting.objects.filter(name__in=removed_settings).delete()
        if conflicting_settings:
            warn("These settings are defined in both settings.py and "
                 "the database: %s. The settings.py values will be used."
                 % ", ".join(conflicting_settings))
        self._editable_cache = new_cache
        self._loaded = True

    def __getattr__(self, name):

        # Lookup name as a registered setting or a Django setting.
        try:
            setting = registry[name]
        except KeyError:
            return getattr(django_settings, name)

        # First access for an editable setting - load from DB into cache.
        if setting["editable"] and not self._loaded:
            self._load()

        # Use cached editable setting if found, otherwise use the
        # value defined in the project's settings.py module if it
        # exists, finally falling back to the default defined when
        # registered.
        try:
            return self._editable_cache[name]
        except KeyError:
            return getattr(django_settings, name, setting["default"])

mezz_first = lambda app: not app.startswith("mezzanine.")
for app in sorted(django_settings.INSTALLED_APPS, key=mezz_first):
    module = import_module(app)
    try:
        import_module("%s.defaults" % app)
    except:
        if module_has_submodule(module, "defaults"):
            raise

settings = Settings()
<|endoftext|>


<commit_before>from __future__ import unicode_literals
from future.builtins import str

from json import dumps

from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.messages import error
from django.core.urlresolvers import reverse
from django.db.models import ObjectDoesNotExist
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _

from mezzanine.conf import settings
from mezzanine.generic.forms import ThreadedCommentForm, RatingForm
from mezzanine.generic.models import Keyword
from mezzanine.utils.cache import add_cache_bypass
from mezzanine.utils.models import get_model
from mezzanine.utils.views import render, set_cookie, is_spam

@staff_member_required
def admin_keywords_submit(request):
    """
    Adds any new given keywords from the custom keywords field in the
    admin, and returns their IDs for use when saving a model with a
    keywords field.
    """
    keyword_ids, titles = [], []
    for title in request.POST.get("text_keywords", "").split(","):
        title = "".join([c for c in title if c.isalnum() or c in "- "]).strip()
        if title:
            kw, created = Keyword.objects.get_or_create_iexact(title=title)
            keyword_id = str(kw.id)
            if keyword_id not in keyword_ids:
                keyword_ids.append(keyword_id)
                titles.append(title)
    return HttpResponse("%s|%s" % (",".join(keyword_ids), ", ".join(titles)))

def initial_validation(request, prefix):
    """
    Returns the related model instance and post data to use in the
    comment/rating views below.

    Both comments and ratings have a ``prefix_ACCOUNT_REQUIRED``
    setting. If this is ``True`` and the user is unauthenticated, we
    store their post data in their session, and redirect to login with
    the view's url (also defined by the prefix arg) as the ``next``
    param. We can then check the session data once they log in,
    and complete the action authenticated.

    On successful post, we pass the related object and post data back,
    which may have come from the session, for each of the comments and
    ratings view functions to deal with as needed.
    """
    post_data = request.POST
    settings.use_editable()
    login_required_setting_name = prefix.upper() + "S_ACCOUNT_REQUIRED"
    posted_session_key = "unauthenticated_" + prefix
    redirect_url = ""
    if getattr(settings, login_required_setting_name, False):
        if not request.user.is_authenticated():
            request.session[posted_session_key] = request.POST
            error(request, _("You must be logged in. Please log in or "
                             "sign up to complete this action."))
            redirect_url = "%s?next=%s" % (settings.LOGIN_URL, reverse(prefix))
        elif posted_session_key in request.session:
            post_data = request.session.pop(posted_session_key)
    if not redirect_url:
        try:
            model = get_model(*post_data.get("content_type", "").split(".", 1))
            obj = model.objects.get(id=post_data.get("object_pk", None))
        except (TypeError, ObjectDoesNotExist, LookupError):
            redirect_url = "/"
    if redirect_url:
        if request.is_ajax():
            return HttpResponse(dumps({"location": redirect_url}))
        else:
            return redirect(redirect_url)
    return obj, post_data

def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "comment")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    form = ThreadedCommentForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.save(request)
        response = redirect(add_cache_bypass(comment.get_absolute_url()))
        # Store commenter's details in a cookie for 90 days.
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value)
        return response
    elif request.is_ajax() and form.errors:
        return HttpResponse(dumps({"errors": form.errors}))
    # Show errors with stand-alone comment form.
    context = {"obj": obj, "posted_comment_form": form}
    response = render(request, template, context)
    return response

def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "rating")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    url = add_cache_bypass(obj.get_absolute_url().split("#")[0])
    response = redirect(url + "#rating-%s" % obj.id)
    rating_form = RatingForm(request, obj, post_data)
    if rating_form.is_valid():
        rating_form.save()
        if request.is_ajax():
            # Reload the object and return the rating fields as json.
            obj = obj.__class__.objects.get(id=obj.id)
            rating_name = obj.get_ratingfield_name()
            json = {}
            for f in ("average", "count", "sum"):
                json["rating_" + f] = getattr(obj, "%s_%s" % (rating_name, f))
            response = HttpResponse(dumps(json))
        ratings = ",".join(rating_form.previous + [rating_form.current])
        set_cookie(response, "mezzanine-rating", ratings)
    return response
<commit_msg>Strip punctuation from keywords instead of non-alphanumeric chars, since languages like Hindi use characters that Python doesn't consider to be alphanumeric.<commit_after>from __future__ import unicode_literals
from future.builtins import str

from json import dumps
from string import punctuation

from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.messages import error
from django.core.urlresolvers import reverse
from django.db.models import ObjectDoesNotExist
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.translation import ugettext_lazy as _

from mezzanine.conf import settings
from mezzanine.generic.forms import ThreadedCommentForm, RatingForm
from mezzanine.generic.models import Keyword
from mezzanine.utils.cache import add_cache_bypass
from mezzanine.utils.models import get_model
from mezzanine.utils.views import render, set_cookie, is_spam

@staff_member_required
def admin_keywords_submit(request):
    """
    Adds any new given keywords from the custom keywords field in the
    admin, and returns their IDs for use when saving a model with a
    keywords field.
    """
    keyword_ids, titles = [], []
    remove = punctuation.replace("-", "")  # Strip punctuation, allow dashes.
    for title in request.POST.get("text_keywords", "").split(","):
        title = "".join([c for c in title if c not in remove]).strip()
        if title:
            kw, created = Keyword.objects.get_or_create_iexact(title=title)
            keyword_id = str(kw.id)
            if keyword_id not in keyword_ids:
                keyword_ids.append(keyword_id)
                titles.append(title)
    return HttpResponse("%s|%s" % (",".join(keyword_ids), ", ".join(titles)))

def initial_validation(request, prefix):
    """
    Returns the related model instance and post data to use in the
    comment/rating views below.

    Both comments and ratings have a ``prefix_ACCOUNT_REQUIRED``
    setting. If this is ``True`` and the user is unauthenticated, we
    store their post data in their session, and redirect to login with
    the view's url (also defined by the prefix arg) as the ``next``
    param. We can then check the session data once they log in,
    and complete the action authenticated.

    On successful post, we pass the related object and post data back,
    which may have come from the session, for each of the comments and
    ratings view functions to deal with as needed.
    """
    post_data = request.POST
    settings.use_editable()
    login_required_setting_name = prefix.upper() + "S_ACCOUNT_REQUIRED"
    posted_session_key = "unauthenticated_" + prefix
    redirect_url = ""
    if getattr(settings, login_required_setting_name, False):
        if not request.user.is_authenticated():
            request.session[posted_session_key] = request.POST
            error(request, _("You must be logged in. Please log in or "
                             "sign up to complete this action."))
            redirect_url = "%s?next=%s" % (settings.LOGIN_URL, reverse(prefix))
        elif posted_session_key in request.session:
            post_data = request.session.pop(posted_session_key)
    if not redirect_url:
        try:
            model = get_model(*post_data.get("content_type", "").split(".", 1))
            obj = model.objects.get(id=post_data.get("object_pk", None))
        except (TypeError, ObjectDoesNotExist, LookupError):
            redirect_url = "/"
    if redirect_url:
        if request.is_ajax():
            return HttpResponse(dumps({"location": redirect_url}))
        else:
            return redirect(redirect_url)
    return obj, post_data

def comment(request, template="generic/comments.html"):
    """
    Handle a ``ThreadedCommentForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "comment")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    form = ThreadedCommentForm(request, obj, post_data)
    if form.is_valid():
        url = obj.get_absolute_url()
        if is_spam(request, form, url):
            return redirect(url)
        comment = form.save(request)
        response = redirect(add_cache_bypass(comment.get_absolute_url()))
        # Store commenter's details in a cookie for 90 days.
        for field in ThreadedCommentForm.cookie_fields:
            cookie_name = ThreadedCommentForm.cookie_prefix + field
            cookie_value = post_data.get(field, "")
            set_cookie(response, cookie_name, cookie_value)
        return response
    elif request.is_ajax() and form.errors:
        return HttpResponse(dumps({"errors": form.errors}))
    # Show errors with stand-alone comment form.
    context = {"obj": obj, "posted_comment_form": form}
    response = render(request, template, context)
    return response

def rating(request):
    """
    Handle a ``RatingForm`` submission and redirect back to its
    related object.
    """
    response = initial_validation(request, "rating")
    if isinstance(response, HttpResponse):
        return response
    obj, post_data = response
    url = add_cache_bypass(obj.get_absolute_url().split("#")[0])
    response = redirect(url + "#rating-%s" % obj.id)
    rating_form = RatingForm(request, obj, post_data)
    if rating_form.is_valid():
        rating_form.save()
        if request.is_ajax():
            # Reload the object and return the rating fields as json.
            obj = obj.__class__.objects.get(id=obj.id)
            rating_name = obj.get_ratingfield_name()
            json = {}
            for f in ("average", "count", "sum"):
                json["rating_" + f] = getattr(obj, "%s_%s" % (rating_name, f))
            response = HttpResponse(dumps(json))
        ratings = ",".join(rating_form.previous + [rating_form.current])
        set_cookie(response, "mezzanine-rating", ratings)
    return response
<|endoftext|>


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

import sys

from midas.tests import IntegrationTestCase

class FindStrangNamesTests(IntegrationTestCase):

    def _run_test(self, sites):
        from midas.assign import find_strange_names
        _in = '\t1900-01-01, 2\n'.join(sites)
        sys.stdin.write(_in)
        sys.stdin.seek(0)
        result = find_strange_names()
        sys.stdout.seek(0)
        return result, sys.stdout.getvalue()

    def test_normal_names(self):
        sites = ['foo.example',
                 'bar.sub.example',
                 'example.com', '']
        result, out = self._run_test(sites)
        self.assertEqual(result, 0)
        self.assertEqual(out, '')

    def test_names_with_slashes(self):
        sites = ['http://foo.example',
                 'bar.example/',
                 'example.com/query', '']
        result, out = self._run_test(sites)
        self.assertEqual(result, 0)
        self.assertEqual(out, '\n'.join(sites))
<commit_msg>test is not needed<commit_after># -*- coding: utf-8 -*-

import sys

from midas.tests import IntegrationTestCase

<|endoftext|>


<commit_before>'''
Created on 08.04.2016

@author: meinel
'''

class Node(dict):
    """ This is the base class for the simplified AST that can easily be used
        in templates. It is simply a dict which stores child nodes as values.
        This allows to simply use node.child to access the values from a
        template. E.g. to get the modules name, you can simply use

        {{ module.name }}
    """

    def __init__(self, ast):
        """ Node constructor stores local AST node in self._ast and calls
            self._init_children() which should be overwritten by child classes.
        """
        self._ast = ast
        self._init_children()

    def _init_children(self):
        """ Implement this to store useful values (i.e. lists or dicts) in the properties. """
        raise NotImplementedError()

class VarDecl(Node):
    """
    A variable declaration.

    The following properties are available:

    - name: The symbolic name of the variable.
    - type: The C type of this variable. This might be a basic type (REAL, INTEGER, LOGICAL) or TYPE(C) for any
            other type like arrays, derived types or strings.
    - pytype, cstype: The type to be used by Python or C# respectively.
    - intent: May be 'IN', 'OUT' or 'INOUT'.
    - getter: This indicates whether the generated getter should be a 'function' or 'subroutine'.
    - setter (opt): This indicates whether a 'subroutine' should be generated as setter.
    - ftype (opt): The name of the derived type.
    - strlen (opt): The length of the string.
    - kind (opt): The kind specifier if available.
    - dynamic (opt): Indicates whether the variable is 'ALLOCATABLE' or a 'POINTER'.
    - dims (opt): For an array contains a list with the sizes per dimension.
    """

    _PYTYPES = {
        "REAL": "ctypes.c_double",
        "INTEGER": "ctypes.c_int",
        "LOGICAL": "ctypes.c_bool",
        "TYPE(C_PTR)": "ctypes.c_void_p",
    }

    _CSTYPES = {
        "REAL": "Double",
        "INTEGER": "Int32",
        "LOGICAL": "Int32",
        "TYPE(C_PTR)": "IntPtr",
    }

    def __init__(self, ast, prefix=""):
        """ Slightly modified constructor to allow for re-use for type-specs and var-specs.

        For the grammar to work, component arrays have their own rule which divers from the
        variable array only in the prefix "component_" which can be passed in.
        """
        self._prefix = prefix
        super(VarDecl, self).__init__(ast)

    def _init_children(self):
        self["name"] = self._ast.select1("name").tail[0]

        # Identify FORTRAN type and store properties accordingly
        full_spec = self._ast.parent().parent()
        #print("full_spec: {}".format(full_spec))
        type_spec = full_spec.select1("declaration_type_spec")
        try:
            self["ftype"] = type_spec.select1("derived_type_spec name").tail[0]
            self["type"] = "TYPE(C_PTR)"
            self["getter"] = "function"
            self["dynamic"] = False
        except ValueError:
            try:
                self["strlen"] = int(type_spec.select1("char_selector int_literal_constant").tail[0])
                self["intent"] = "IN"
                self["type"] = "TYPE(C_PTR)"
                self["pytype"] = "ctypes.c_char_p"
                self["cstype"] = "String"
                self["getter"] = "subroutine"
                self["setter"] = "subroutine"
            except ValueError:
                try:
                    self["strlen"] = type_spec.select1("char_selector /\*/")
                    self["intent"] = "IN"
                    self["type"] = "TYPE(C_PTR)"
                    self["pytype"] = "ctypes.c_char_p"
                    self["cstype"] = "String"
                    self["getter"] = "subroutine"
                    self["setter"] = "subroutine"
                except ValueError:
                    self["type"] = type_spec.select1("intrinsic_type_kind").tail[0]
                    self["getter"] = "function"
                    self["setter"] = "subroutine"

        for attr in full_spec.select("component_attr_spec"):
            #print("attr: {}".format(attr))
            if 'ALLOCATABLE' in attr.tail:
                self["dynamic"] = 'ALLOCATABLE'
            elif 'POINTER' in attr.tail:
                self["dynamic"] = 'POINTER'

        # Identify array dimensions
        for ast in (self._ast, full_spec):
            dims = ast.select(self._prefix + "array_spec int_literal_constant")
            if dims:
                self["dims"] = [int(dim.tail[0]) for dim in dims]
                break

            dims = ast.select(self._prefix + "array_spec array_spec_element")
            if not dims:
                dims = ast.select(self._prefix + "array_spec deferred_shape_spec_list")
            if dims:
                self["dims"] = [0] * len(dims[0].tail)
                break

        if "dims" in self \
        and "strlen" not in self:
            if "setter" in self:
                del self["setter"]

        if "pytype" not in self \
        and self["type"] in self._PYTYPES:
            self["pytype"] = self._PYTYPES[self["type"]]

        if "cstype" not in self \
        and self["type"] in self._CSTYPES:
            self["cstype"] = self._CSTYPES[self["type"]]

        try:
            kind_selector = type_spec.select1("kind_selector int_literal_constant")
            self["kind"] = int(kind_selector.tail[0])
        except ValueError:
            try:
                kind_selector = type_spec.select1("kind_selector part_ref")
                self["kind"] = kind_selector.tail[0]
            except ValueError:
                pass

        try:
            intent_spec = type_spec.parent().select1("intent_spec")
            self["intent"] = intent_spec.tail[0]
        except ValueError:
            self["intent"] = 'IN'

        # No setter for PARAMETERs
        if "setter" in self \
        and len(full_spec.select("attr_spec /PARAMETER/")) > 0:
            del self["setter"]

    def with_intent(self, intent):
        self["intent"] = intent
        return self

class TypeDef(Node):
    def _init_children(self):
        self["name"] = self._ast.select1("derived_type_stmt name").tail[0]
        try:
            self["public"] = (self._ast.select1("access_spec").tail[0].upper() == 'PUBLIC')
        except ValueError:
            self["public"] = False

        self["fields"] = [
            VarDecl(decl, 'component_') # See documentation of VarDecl.__init__
            for decl in self._ast.select("component_decl")
        ]
        for field in self["fields"]:
            del field["intent"]

class SubDef(Node):
    _PREFIX = "subroutine"

    def _init_children(self):
        self["name"] = self._ast.select(self._PREFIX + "_stmt name")[0].tail[0]

        # Two-stage argument extraction:
        # First, identify all variables declared and the dummy argument list.
        dummy_args = [arg.tail[0] for arg in self._ast.select("dummy_arg name")]
        var_specs = dict(
            (argdecl.select1("name").tail[0], VarDecl(argdecl))
            for argdecl in self._ast.select("entity_decl")
        )

        # Fill up self["args"] based on dummy argument list order.
        self["args"] = [var_specs[argname] for argname in dummy_args]

        return var_specs # to be re-used in child classes.

class FuncDef(SubDef):
    _PREFIX = "function"
    def _init_children(self):
        var_specs = super(FuncDef, self)._init_children()

        # Capture return type of function for return value.
        res_name = self._ast.select("result_name name")
        if res_name:
            self["ret"] = var_specs[res_name[0].tail[0]]
        else:
            try:
                self["ret"] = var_specs[self["name"] + "_VALUE"]
            except KeyError:
                self["ret"] = var_specs[self["name"]]

class Module(Node):
    def _init_children(self):
        self["name"] = self._ast.select1("module_stmt name").tail[0]
        self["uses"] = [use.tail[0] for use in self._ast.select("use_stmt name")]
        self["types"] = [
            TypeDef(typedef)
            for typedef in self._ast.select("derived_type_def")
        ]
        self["globals"] = [
            VarDecl(var)
            for var in self._ast.select("module > specification_part type_declaration_stmt entity_decl")
            if len(var.parent().parent().select("access_spec /PUBLIC/")) > 0
        ]
#       self["subroutines"] = [
#           SubDef(subdef)
#           for subdef in self._ast.select("subroutine_subprogram")
#       ]
#       self["functions"] = [
#           FuncDef(funcdef)
#           for funcdef in self._ast.select("function_subprogram")
#       ]

#   def export_methods(self, config):
#       if not config.has_section("export"):
#           return
#
#       methods = []
#       for method in self["subroutines"] + self["functions"]:
#           if config.has_option("export", method["name"].lower()):
#               method["export_name"] = config.get("export", method["name"].lower())
#               if "ret" in method:
#                   if method["ret"]["getter"] == "subroutine":
#                       method["ret"]["name"] = method["export_name"].upper() + '_OUT'
#                       method["ret"]["intent"] = "OUT"
#                   else:
#                       method["ret"]["name"] = method["export_name"].upper()
#                       del method["ret"]["intent"]
#               methods.append(method)
#
#       self["methods"] = methods

#    def export_methods(self, config):
    def export_methods(self, src):
        config = src.config
        if not config.has_section("export"):
            return

        methods = []
        for export in config.items("export"):
            for funcdef in self._ast.select("function_subprogram") :
                if funcdef.select("function_stmt name")[0].tail[0].lower() == export[0] :
                   method = FuncDef(funcdef)
                   method["export_name"] = config.get("export", method["name"].lower())
                   if "ret" in method:
                       if "dims" in method["ret"]:
                            l_line = [line for line in src.source_lines if method["ret"]["name"] in line and "ALLOCATE" in line]
                            if len(l_line) == 1:
                                #ok, it is a dynamic array, find the size variable of the array
                                l_aux_line = l_line[0][l_line[0].find(method["ret"]["name"]):-2]
                                l_size_var = l_aux_line[len(method["ret"]["name"])+1:-1].split(',')
                                method["ret"]["dims"] = l_size_var
                       if method["ret"]["getter"] == "subroutine":
                            method["ret"]["name"] = method["export_name"].upper() + '_OUT'
                            method["ret"]["intent"] = "OUT"
                       else:
                           method["ret"]["name"] = method["export_name"].upper()
                           del method["ret"]["intent"]
                   methods.append(method)
                   break
            else :
                for subdef in self._ast.select("subroutine_subprogram") :
                    if subdef.select("subroutine_stmt name")[0].tail[0].lower() == export[0] :
                        method = SubDef(subdef)
                        method["export_name"] = config.get("export", method["name"].lower())
                        l_array_args = [ l_arg for l_arg in method["args"] if "dims" in l_arg ]
                        if len(l_array_args) > 0:
                            #okay, we have arguments of array type
                            sub_start, sub_end = self._get_subroutine(method["name"], src.source_lines)
                            for arg in l_array_args:
                                self._set_array_size(arg, src.source_lines[sub_start: sub_end])

                        if "ret" in method:
                            method["ret"]["name"] = method["export_name"].upper() + '_OUT'
                            method["ret"]["intent"] = "OUT"
                        methods.append(method)
                        break

        self["methods"] = methods

    def _set_array_size(self, a_argument, a_src):
        l_arg = a_argument["name"]
        l_arg_len = len(l_arg)
        l_key_len = 8  # keyword "ALLOCATE"

        for index, line in enumerate(a_src) :
            # to do: skip the comments
            l_line = line[line.find("::")+2 : ].strip()

            # this is the declaration line
            if l_line.startswith(l_arg+'(') :
                l_follow = l_line.find('!')
                if l_follow != -1 :
                    # removed the trailing comment
                    l_line = l_line[:l_follow].strip()
                l_size_var = l_line[l_arg_len+1:-1].split(',')
                if  l_size_var[0] == ':':
                   # check if the array is dynamically allocated within the function/subroutine body
                   for line in a_src[index:] :
                       line = line.strip()
                       if line.startswith("ALLOCATE") :
                           # skip comment
                           l_follow = line.find('!')
                           l_line = ''
                           if l_follow == -1 :
                               l_line = line[l_key_len:].strip()[1:-1]
                           else :
                               l_line = line[l_key_len:l_follow].strip()[1:-1]
                           l_alloc_list = l_line.split('),')
                           # check if more than one variables are allocated
                           if len(l_alloc_list) > 1 :
                               for l_alloc in l_alloc_list :
                                   l_alloc = l_alloc.strip()
                                   if l_alloc.startswith(l_arg + '(') :
                                       l_aux_line = ''
                                       if l_alloc.endswith(')') :
                                            l_aux_line = l_alloc[l_arg_len+1:-1].strip()
                                       else :
                                            l_aux_line = l_alloc[l_arg_len+1:].strip()
                                       l_size_var = l_aux_line.split(',')
                                       a_argument["dims"] = l_size_var
                                       break
                           else :
                               l_alloc = l_alloc_list[0].strip()
                               if l_alloc.startswith(l_arg + '(') :
                                    l_aux_line = l_alloc[l_arg_len+1:-1].strip()
                                    l_size_var = l_aux_line.split(',')
                                    a_argument["dims"] = l_size_var

                   else :
                        # okay, no size variable is found. It could be "IN" type, make sure the dimension is correctly set
                        n = len(l_size_var)
                        a_argument["dims"] = [ x.replace(':', str(n)) for x in l_size_var ]
                else :
                    a_argument["dims"] = l_size_var
                break

    def _get_subroutine(self,a_argument, a_src):
        startIndex = 0
        stopIndex =0
        for i in range(len(a_src)):
            l_str = a_src[i].strip()
            if l_str.startswith("SUBROUTINE") and a_argument in l_str :
                startIndex = i
                for j, line in enumerate(a_src[i:]):
                    line = line.strip()
                    if line.startswith("END SUBROUTINE") :
                        stopIndex = i + j
                        break
                break
        else:
            # should not happend
            pass

        return (startIndex, stopIndex)

<commit_msg>Added support to retrieve array shape information for IN parameter type<commit_after>'''
Created on 08.04.2016

@author: meinel
'''

class Node(dict):
    """ This is the base class for the simplified AST that can easily be used
        in templates. It is simply a dict which stores child nodes as values.
        This allows to simply use node.child to access the values from a
        template. E.g. to get the modules name, you can simply use

        {{ module.name }}
    """

    def __init__(self, ast):
        """ Node constructor stores local AST node in self._ast and calls
            self._init_children() which should be overwritten by child classes.
        """
        self._ast = ast
        self._init_children()

    def _init_children(self):
        """ Implement this to store useful values (i.e. lists or dicts) in the properties. """
        raise NotImplementedError()

class VarDecl(Node):
    """
    A variable declaration.

    The following properties are available:

    - name: The symbolic name of the variable.
    - type: The C type of this variable. This might be a basic type (REAL, INTEGER, LOGICAL) or TYPE(C) for any
            other type like arrays, derived types or strings.
    - pytype, cstype: The type to be used by Python or C# respectively.
    - intent: May be 'IN', 'OUT' or 'INOUT'.
    - getter: This indicates whether the generated getter should be a 'function' or 'subroutine'.
    - setter (opt): This indicates whether a 'subroutine' should be generated as setter.
    - ftype (opt): The name of the derived type.
    - strlen (opt): The length of the string.
    - kind (opt): The kind specifier if available.
    - dynamic (opt): Indicates whether the variable is 'ALLOCATABLE' or a 'POINTER'.
    - dims (opt): For an array contains a list with the sizes per dimension.
    """

    _PYTYPES = {
        "REAL": "ctypes.c_double",
        "INTEGER": "ctypes.c_int",
        "LOGICAL": "ctypes.c_bool",
        "TYPE(C_PTR)": "ctypes.c_void_p",
    }

    _CSTYPES = {
        "REAL": "Double",
        "INTEGER": "Int32",
        "LOGICAL": "Int32",
        "TYPE(C_PTR)": "IntPtr",
    }

    def __init__(self, ast, prefix=""):
        """ Slightly modified constructor to allow for re-use for type-specs and var-specs.

        For the grammar to work, component arrays have their own rule which divers from the
        variable array only in the prefix "component_" which can be passed in.
        """
        self._prefix = prefix
        super(VarDecl, self).__init__(ast)

    def _init_children(self):
        self["name"] = self._ast.select1("name").tail[0]

        # Identify FORTRAN type and store properties accordingly
        full_spec = self._ast.parent().parent()
        #print("full_spec: {}".format(full_spec))
        type_spec = full_spec.select1("declaration_type_spec")
        try:
            self["ftype"] = type_spec.select1("derived_type_spec name").tail[0]
            self["type"] = "TYPE(C_PTR)"
            self["getter"] = "function"
            self["dynamic"] = False
        except ValueError:
            try:
                self["strlen"] = int(type_spec.select1("char_selector int_literal_constant").tail[0])
                self["intent"] = "IN"
                self["type"] = "TYPE(C_PTR)"
                self["pytype"] = "ctypes.c_char_p"
                self["cstype"] = "String"
                self["getter"] = "subroutine"
                self["setter"] = "subroutine"
            except ValueError:
                try:
                    self["strlen"] = type_spec.select1("char_selector /\*/")
                    self["intent"] = "IN"
                    self["type"] = "TYPE(C_PTR)"
                    self["pytype"] = "ctypes.c_char_p"
                    self["cstype"] = "String"
                    self["getter"] = "subroutine"
                    self["setter"] = "subroutine"
                except ValueError:
                    self["type"] = type_spec.select1("intrinsic_type_kind").tail[0]
                    self["getter"] = "function"
                    self["setter"] = "subroutine"

        for attr in full_spec.select("component_attr_spec"):
            #print("attr: {}".format(attr))
            if 'ALLOCATABLE' in attr.tail:
                self["dynamic"] = 'ALLOCATABLE'
            elif 'POINTER' in attr.tail:
                self["dynamic"] = 'POINTER'

        # Identify array dimensions
        for ast in (self._ast, full_spec):
            dims = ast.select(self._prefix + "array_spec int_literal_constant")
            if dims:
                self["dims"] = [int(dim.tail[0]) for dim in dims]
                break

            dims = ast.select(self._prefix + "array_spec array_spec_element")
            if not dims:
                dims = ast.select(self._prefix + "array_spec deferred_shape_spec_list")
            if dims:
                self["dims"] = [0] * len(dims[0].tail)
                break

        if "dims" in self \
        and "strlen" not in self:
            if "setter" in self:
                del self["setter"]

        if "pytype" not in self \
        and self["type"] in self._PYTYPES:
            self["pytype"] = self._PYTYPES[self["type"]]

        if "cstype" not in self \
        and self["type"] in self._CSTYPES:
            self["cstype"] = self._CSTYPES[self["type"]]

        try:
            kind_selector = type_spec.select1("kind_selector int_literal_constant")
            self["kind"] = int(kind_selector.tail[0])
        except ValueError:
            try:
                kind_selector = type_spec.select1("kind_selector part_ref")
                self["kind"] = kind_selector.tail[0]
            except ValueError:
                pass

        try:
            intent_spec = type_spec.parent().select1("intent_spec")
            self["intent"] = intent_spec.tail[0]
        except ValueError:
            self["intent"] = 'IN'

        # No setter for PARAMETERs
        if "setter" in self \
        and len(full_spec.select("attr_spec /PARAMETER/")) > 0:
            del self["setter"]

    def with_intent(self, intent):
        self["intent"] = intent
        return self

class TypeDef(Node):
    def _init_children(self):
        self["name"] = self._ast.select1("derived_type_stmt name").tail[0]
        try:
            self["public"] = (self._ast.select1("access_spec").tail[0].upper() == 'PUBLIC')
        except ValueError:
            self["public"] = False

        self["fields"] = [
            VarDecl(decl, 'component_') # See documentation of VarDecl.__init__
            for decl in self._ast.select("component_decl")
        ]
        for field in self["fields"]:
            del field["intent"]

class SubDef(Node):
    _PREFIX = "subroutine"

    def _init_children(self):
        self["name"] = self._ast.select(self._PREFIX + "_stmt name")[0].tail[0]

        # Two-stage argument extraction:
        # First, identify all variables declared and the dummy argument list.
        dummy_args = [arg.tail[0] for arg in self._ast.select("dummy_arg name")]
        var_specs = dict(
            (argdecl.select1("name").tail[0], VarDecl(argdecl))
            for argdecl in self._ast.select("entity_decl")
        )

        # Fill up self["args"] based on dummy argument list order.
        self["args"] = [var_specs[argname] for argname in dummy_args]

        return var_specs # to be re-used in child classes.

class FuncDef(SubDef):
    _PREFIX = "function"
    def _init_children(self):
        var_specs = super(FuncDef, self)._init_children()

        # Capture return type of function for return value.
        res_name = self._ast.select("result_name name")
        if res_name:
            self["ret"] = var_specs[res_name[0].tail[0]]
        else:
            try:
                self["ret"] = var_specs[self["name"] + "_VALUE"]
            except KeyError:
                self["ret"] = var_specs[self["name"]]

class Module(Node):
    def _init_children(self):
        self["name"] = self._ast.select1("module_stmt name").tail[0]
        self["uses"] = [use.tail[0] for use in self._ast.select("use_stmt name")]
        self["types"] = [
            TypeDef(typedef)
            for typedef in self._ast.select("derived_type_def")
        ]
        self["globals"] = [
            VarDecl(var)
            for var in self._ast.select("module > specification_part type_declaration_stmt entity_decl")
            if len(var.parent().parent().select("access_spec /PUBLIC/")) > 0
        ]
#       self["subroutines"] = [
#           SubDef(subdef)
#           for subdef in self._ast.select("subroutine_subprogram")
#       ]
#       self["functions"] = [
#           FuncDef(funcdef)
#           for funcdef in self._ast.select("function_subprogram")
#       ]

#   def export_methods(self, config):
#       if not config.has_section("export"):
#           return
#
#       methods = []
#       for method in self["subroutines"] + self["functions"]:
#           if config.has_option("export", method["name"].lower()):
#               method["export_name"] = config.get("export", method["name"].lower())
#               if "ret" in method:
#                   if method["ret"]["getter"] == "subroutine":
#                       method["ret"]["name"] = method["export_name"].upper() + '_OUT'
#                       method["ret"]["intent"] = "OUT"
#                   else:
#                       method["ret"]["name"] = method["export_name"].upper()
#                       del method["ret"]["intent"]
#               methods.append(method)
#
#       self["methods"] = methods

#    def export_methods(self, config):
    def export_methods(self, src):
        config = src.config
        if not config.has_section("export"):
            return

        methods = []
        for export in config.items("export"):
            for funcdef in self._ast.select("function_subprogram") :
                if funcdef.select("function_stmt name")[0].tail[0].lower() == export[0] :
                   method = FuncDef(funcdef)
                   method["export_name"] = config.get("export", method["name"].lower())
                   if "ret" in method:
                       if "dims" in method["ret"]:
                            l_line = [line for line in src.source_lines if method["ret"]["name"] in line and "ALLOCATE" in line]
                            if len(l_line) == 1:
                                #ok, it is a dynamic array, find the size variable of the array
                                l_aux_line = l_line[0][l_line[0].find(method["ret"]["name"]):-2]
                                l_size_var = l_aux_line[len(method["ret"]["name"])+1:-1].split(',')
                                method["ret"]["dims"] = l_size_var
                       if method["ret"]["getter"] == "subroutine":
                            method["ret"]["name"] = method["export_name"].upper() + '_OUT'
                            method["ret"]["intent"] = "OUT"
                       else:
                           method["ret"]["name"] = method["export_name"].upper()
                           del method["ret"]["intent"]
                   methods.append(method)
                   break
            else :
                for subdef in self._ast.select("subroutine_subprogram") :
                    if subdef.select("subroutine_stmt name")[0].tail[0].lower() == export[0] :
                        method = SubDef(subdef)
                        method["export_name"] = config.get("export", method["name"].lower())
                        l_array_args = [ l_arg for l_arg in method["args"] if "dims" in l_arg ]
                        if len(l_array_args) > 0:
                            #okay, we have arguments of array type
                            sub_start, sub_end = self._get_subroutine(method["name"], src.source_lines)
                            for arg in l_array_args:
                                self._set_array_size(arg, src.source_lines[sub_start: sub_end])

                        if "ret" in method:
                            method["ret"]["name"] = method["export_name"].upper() + '_OUT'
                            method["ret"]["intent"] = "OUT"
                        methods.append(method)
                        break

        self["methods"] = methods

    def _set_array_size(self, a_argument, a_src):
        l_arg = a_argument["name"]
        l_arg_len = len(l_arg)
        l_key_len = 8  # keyword "ALLOCATE"

        for index, line in enumerate(a_src) :
            # to do: skip the comments
            l_line = line[line.find("::")+2 : ].strip()

            # this is the declaration line
            if l_line.startswith(l_arg+'(') :
                l_declare = l_line.split('!')
                l_array_var = l_declare[0].strip()
                l_size_var = l_array_var[l_arg_len+1:-1].split(',')
                if  l_size_var[0] == ':':
                   # check if the array is dynamically allocated within the function/subroutine body
                   for line in a_src[index:] :
                       line = line.strip()
                       if line.startswith("ALLOCATE") :
                           # skip comment
                           l_alloc = line.split('!')[0].strip()
                           l_line = l_alloc[l_key_len:][1:-1]
                           l_alloc_list = l_line.split('),')
                           # check if more than one variables are allocated
                           if len(l_alloc_list) > 1 :
                               for l_alloc in l_alloc_list :
                                   l_alloc = l_alloc.strip()
                                   if l_alloc.startswith(l_arg + '(') :
                                       l_aux_line = ''
                                       if l_alloc.endswith(')') :
                                            l_aux_line = l_alloc[l_arg_len+1:-1].strip()
                                       else :
                                            l_aux_line = l_alloc[l_arg_len+1:].strip()
                                       l_size_var = l_aux_line.split(',')
                                       a_argument["dims"] = l_size_var
                                       break
                           else :
                               l_alloc = l_alloc_list[0].strip()
                               if l_alloc.startswith(l_arg + '(') :
                                    l_aux_line = l_alloc[l_arg_len+1:-1].strip()
                                    l_size_var = l_aux_line.split(',')
                                    a_argument["dims"] = l_size_var
                   else :
                        # okay, no size variable is found. It could be "IN" or "INOUT" type,
                        if len(l_declare) == 2 :
                            l_comment = l_declare[1].strip()
                            if l_comment.startswith('@F2x') :
                                l_vars = l_comment.split(l_arg)[1]
                                l_size_var = l_vars[1:-1].split(',')
                                a_argument["dims"] = l_size_var
                            else :
                                # Attention: no information is provided, code is not reliable !!
                                # But at leaset make sure the dimension is correctly set
                                n = len(l_size_var)
                                a_argument["dims"] = [ x.replace(':', '0') for x in l_size_var ]
                        else :
                            # Same problem as above !!
                            n = len(l_size_var)
                            a_argument["dims"] = [ x.replace(':', '0') for x in l_size_var ]
                else :
                    # size variables are set explicitly
                    a_argument["dims"] = l_size_var
                break

    def _get_subroutine(self,a_argument, a_src):
        startIndex = 0
        stopIndex =0
        for i in range(len(a_src)):
            l_str = a_src[i].strip()
            if l_str.startswith("SUBROUTINE") and a_argument in l_str :
                startIndex = i
                for j, line in enumerate(a_src[i:]):
                    line = line.strip()
                    if line.startswith("END SUBROUTINE") :
                        stopIndex = i + j
                        break
                break
        else:
            # should not happend
            pass

        return (startIndex, stopIndex)

<|endoftext|>


<commit_before>"""Just to ease the access to the files.
"""
import os
import sys

from . import checks

_CWD = os.path.dirname(os.path.abspath(__file__))

default_catalog = {
        'NAME': 'SciELO Style Catalog for Packtools',

        # Validation schemas: XSD or DTD files.
        'SCH_SCHEMAS': {
            'sps-1.1': os.path.join(_CWD, 'scielo-style-1.1.sch'),
            'sps-1.2': os.path.join(_CWD, 'scielo-style-1.2.sch'),
            'sps-1.3': os.path.join(_CWD, 'scielo-style-1.3.sch'),
            'sps-1.4': os.path.join(_CWD, 'scielo-style-1.4.sch'),
            'sps-1.5': os.path.join(_CWD, 'scielo-style-1.5.sch'),
            'sps-1.6': os.path.join(_CWD, 'scielo-style-1.6.sch'),
            'sps-1.7': os.path.join(_CWD, 'scielo-style-1.7.sch'),
            'sps-1.8': os.path.join(_CWD, 'scielo-style-1.8.sch'),
            'sps-1.9': os.path.join(_CWD, 'scielo-style-1.9.sch'),

            # Collection-specific schema
            'scielo-br': os.path.join(_CWD, 'scielo-br.sch'),
        },
        'DTDS': {
            'JATS-journalpublishing1.dtd': os.path.join(
                _CWD, 'jats-publishing-dtd-1.0/JATS-journalpublishing1.dtd'),
            'journalpublishing3.dtd': os.path.join(
                _CWD, 'pmc-publishing-dtd-3.0/journalpublishing3.dtd'),
        },

        # XML Catalog - OASIS Standard.
        'XML_CATALOG': os.path.join(_CWD, 'scielo-publishing-schema.xml'),

        # HTML GENERATOR default constants
        'HTML_GEN_XSLTS': {
            'root-html-1.2.xslt': os.path.join(_CWD, 'htmlgenerator/root-html-1.2.xslt'),
            'root-html-2.0.xslt': os.path.join(_CWD, 'htmlgenerator/root-html-2.0.xslt'),
        },
        'HTML_GEN_DEFAULT_PRINT_CSS_PATH': os.path.join(_CWD,
            'htmlgenerator/static/scielo-bundle-print.css'),
        'HTML_GEN_DEFAULT_CSS_PATH': os.path.join(_CWD,
            'htmlgenerator/static/scielo-article-standalone.css'),
        'HTML_GEN_DEFAULT_JS_PATH': os.path.join(_CWD,
            'htmlgenerator/static/scielo-article-standalone-min.js'),

        # As a general rule, only the latest 2 versions are supported simultaneously.
        'CURRENTLY_SUPPORTED_VERSIONS': os.environ.get(
            'PACKTOOLS_SUPPORTED_SPS_VERSIONS', 'sps-1.7:sps-1.8').split(':'),

        'ALLOWED_PUBLIC_IDS': (
            '-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.0 20120330//EN',
            '-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.1 20151215//EN',
        ),
        # doctype public ids for sps <= 1.1
        'ALLOWED_PUBLIC_IDS_LEGACY': (
            '-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.0 20120330//EN',
            '-//NLM//DTD Journal Publishing DTD v3.0 20080202//EN',
        ),
}

# Python>=3.5 is possible to use the syntax: SCHEMAS = {**SCH_SCHEMAS, **DTDS}
# https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations
default_catalog['SCHEMAS'] = dict(default_catalog['SCH_SCHEMAS'])
default_catalog['SCHEMAS'].update(default_catalog['DTDS'])

class Catalog(object):
    """A catalog is a namespace that groups constants together and makes them
    accessible through *dot* accessors.
    """
    ISO3166_CODES = os.path.join(_CWD, 'iso3166-codes.json')

    def __init__(self, **kwargs):
        for name, value in kwargs.items():
            setattr(self, name, value)

    @classmethod
    def fromdict(cls, d):
        return cls(**d)

class CatalogLoader(object):
    group_name = 'packtools.catalog'

    def _load_plugin_if_exists(self, name):
        """Returns the plugged-in Catalog if it exists or None.
        """
        from pkg_resources import iter_entry_points
        for entry_point in iter_entry_points(group=self.group_name, name=None):
            if entry_point.name == name:
                return entry_point.load()

        return None

    def load(self, name, default, plugin_wrapper=None):
        """Returns the plugged-in Catalog if it exists or otherwise the default
        catalog.

        :param default: object that will be returned if ``name`` is not set.
        :param plugin_wrapper: a callable that will be called with the loaded
        object as argument.
        """
        plugin_wrapper = plugin_wrapper if plugin_wrapper else lambda p: p

        plugin = self._load_plugin_if_exists(name) or default
        return plugin_wrapper(plugin)

class PluggableModule(object):
    def __init__(self):
        self.catalog = CatalogLoader().load('packtools_catalog',
                default=default_catalog,
                plugin_wrapper=lambda p: Catalog.fromdict(p))
        self.StyleCheckingPipeline = CatalogLoader().load('packtools_checks',
                default=checks.StyleCheckingPipeline)
        self.checks = checks

    def __getattr__(self, name):
        try:
            return getattr(self.catalog, name)
        except AttributeError:
            return getattr(self.StyleCheckingPipeline, name)

# This is a documented and recommended hack. See:
# https://mail.python.org/pipermail/python-ideas/2012-May/014969.html
sys.modules[__name__] = PluggableModule()
<commit_msg>Altera as versões ativas de sps<commit_after>"""Just to ease the access to the files.
"""
import os
import sys

from . import checks

_CWD = os.path.dirname(os.path.abspath(__file__))

default_catalog = {
        'NAME': 'SciELO Style Catalog for Packtools',

        # Validation schemas: XSD or DTD files.
        'SCH_SCHEMAS': {
            'sps-1.1': os.path.join(_CWD, 'scielo-style-1.1.sch'),
            'sps-1.2': os.path.join(_CWD, 'scielo-style-1.2.sch'),
            'sps-1.3': os.path.join(_CWD, 'scielo-style-1.3.sch'),
            'sps-1.4': os.path.join(_CWD, 'scielo-style-1.4.sch'),
            'sps-1.5': os.path.join(_CWD, 'scielo-style-1.5.sch'),
            'sps-1.6': os.path.join(_CWD, 'scielo-style-1.6.sch'),
            'sps-1.7': os.path.join(_CWD, 'scielo-style-1.7.sch'),
            'sps-1.8': os.path.join(_CWD, 'scielo-style-1.8.sch'),
            'sps-1.9': os.path.join(_CWD, 'scielo-style-1.9.sch'),

            # Collection-specific schema
            'scielo-br': os.path.join(_CWD, 'scielo-br.sch'),
        },
        'DTDS': {
            'JATS-journalpublishing1.dtd': os.path.join(
                _CWD, 'jats-publishing-dtd-1.0/JATS-journalpublishing1.dtd'),
            'journalpublishing3.dtd': os.path.join(
                _CWD, 'pmc-publishing-dtd-3.0/journalpublishing3.dtd'),
        },

        # XML Catalog - OASIS Standard.
        'XML_CATALOG': os.path.join(_CWD, 'scielo-publishing-schema.xml'),

        # HTML GENERATOR default constants
        'HTML_GEN_XSLTS': {
            'root-html-1.2.xslt': os.path.join(_CWD, 'htmlgenerator/root-html-1.2.xslt'),
            'root-html-2.0.xslt': os.path.join(_CWD, 'htmlgenerator/root-html-2.0.xslt'),
        },
        'HTML_GEN_DEFAULT_PRINT_CSS_PATH': os.path.join(_CWD,
            'htmlgenerator/static/scielo-bundle-print.css'),
        'HTML_GEN_DEFAULT_CSS_PATH': os.path.join(_CWD,
            'htmlgenerator/static/scielo-article-standalone.css'),
        'HTML_GEN_DEFAULT_JS_PATH': os.path.join(_CWD,
            'htmlgenerator/static/scielo-article-standalone-min.js'),

        # As a general rule, only the latest 2 versions are supported simultaneously.
        'CURRENTLY_SUPPORTED_VERSIONS': os.environ.get(
            'PACKTOOLS_SUPPORTED_SPS_VERSIONS', 'sps-1.8:sps-1.9').split(':'),

        'ALLOWED_PUBLIC_IDS': (
            '-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.0 20120330//EN',
            '-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.1 20151215//EN',
        ),
        # doctype public ids for sps <= 1.1
        'ALLOWED_PUBLIC_IDS_LEGACY': (
            '-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.0 20120330//EN',
            '-//NLM//DTD Journal Publishing DTD v3.0 20080202//EN',
        ),
}

# Python>=3.5 is possible to use the syntax: SCHEMAS = {**SCH_SCHEMAS, **DTDS}
# https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations
default_catalog['SCHEMAS'] = dict(default_catalog['SCH_SCHEMAS'])
default_catalog['SCHEMAS'].update(default_catalog['DTDS'])

class Catalog(object):
    """A catalog is a namespace that groups constants together and makes them
    accessible through *dot* accessors.
    """
    ISO3166_CODES = os.path.join(_CWD, 'iso3166-codes.json')

    def __init__(self, **kwargs):
        for name, value in kwargs.items():
            setattr(self, name, value)

    @classmethod
    def fromdict(cls, d):
        return cls(**d)

class CatalogLoader(object):
    group_name = 'packtools.catalog'

    def _load_plugin_if_exists(self, name):
        """Returns the plugged-in Catalog if it exists or None.
        """
        from pkg_resources import iter_entry_points
        for entry_point in iter_entry_points(group=self.group_name, name=None):
            if entry_point.name == name:
                return entry_point.load()

        return None

    def load(self, name, default, plugin_wrapper=None):
        """Returns the plugged-in Catalog if it exists or otherwise the default
        catalog.

        :param default: object that will be returned if ``name`` is not set.
        :param plugin_wrapper: a callable that will be called with the loaded
        object as argument.
        """
        plugin_wrapper = plugin_wrapper if plugin_wrapper else lambda p: p

        plugin = self._load_plugin_if_exists(name) or default
        return plugin_wrapper(plugin)

class PluggableModule(object):
    def __init__(self):
        self.catalog = CatalogLoader().load('packtools_catalog',
                default=default_catalog,
                plugin_wrapper=lambda p: Catalog.fromdict(p))
        self.StyleCheckingPipeline = CatalogLoader().load('packtools_checks',
                default=checks.StyleCheckingPipeline)
        self.checks = checks

    def __getattr__(self, name):
        try:
            return getattr(self.catalog, name)
        except AttributeError:
            return getattr(self.StyleCheckingPipeline, name)

# This is a documented and recommended hack. See:
# https://mail.python.org/pipermail/python-ideas/2012-May/014969.html
sys.modules[__name__] = PluggableModule()
<|endoftext|>


<commit_before>#!/usr/bin/python
#
# Copyright (c) 2016 Mikkel Schubert <MSchubert@snm.ku.dk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import os
import shutil
import sys

from pkg_resources import Requirement, resource_filename

_REQUIREMENT = Requirement.parse("PALEOMIX")

def rscript(tool, script):
    """Returns the path to an Rscript for a given tool."""

    path = os.path.join("resources", "rscript", tool, script)

    return resource_filename(_REQUIREMENT, path)

def copy_example(tool, argv):
    """Command-line interface to copy a folder containing example data to a
    folder specified by the user. Arguments are a tool name (e.g.
    'bam_pipeline'), and any command-line options specified by the user;
    returns 0 on success, or 1 on errors.
    """
    if len(argv) != 1:
        sys.stderr.write("Copy example project folder to folder <destination>:\n\n")
        sys.stderr.write("Usage: %s example <destination>\n" % (tool,))
        sys.stderr.write("Example: %s example .\n" % (tool,))

        return 1

    destination = os.path.join(argv[0], tool)
    if os.path.exists(destination):
        sys.stderr.write("Example folder already exists at destination, "
                         "cannot proceed:\n")
        sys.stderr.write("  - %r\n" % (destination,))
        return 1

    path = os.path.join("paleomix", "resources", "examples", tool)
    source = resource_filename(_REQUIREMENT, path)

    shutil.copytree(source, destination)

    sys.stderr.write("Sucessfully saved example in %r\n" % (destination,))

    return 0
<commit_msg>Better argument parsing for 'example' commands.<commit_after>#!/usr/bin/python
#
# Copyright (c) 2016 Mikkel Schubert <MSchubert@snm.ku.dk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import argparse
import os
import shutil
import sys

from pkg_resources import Requirement, resource_filename

_REQUIREMENT = Requirement.parse("PALEOMIX")

def rscript(tool, script):
    """Returns the path to an Rscript for a given tool."""

    path = os.path.join("resources", "rscript", tool, script)

    return resource_filename(_REQUIREMENT, path)

def copy_example(tool, argv):
    """Command-line interface to copy a folder containing example data to a
    folder specified by the user. Arguments are a tool name (e.g.
    'bam_pipeline'), and any command-line options specified by the user;
    returns 0 on success, or 1 on errors.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('root', help="Destination folder for example data.")

    args = parser.parse_args(argv)

    destination = os.path.join(args.root, tool)
    if os.path.exists(destination):
        sys.stderr.write("Example folder already exists at destination, "
                         "cannot proceed:\n")
        sys.stderr.write("  - %r\n" % (destination,))
        return 1

    path = os.path.join("paleomix", "resources", "examples", tool)
    source = resource_filename(_REQUIREMENT, path)

    shutil.copytree(source, destination)

    sys.stderr.write("Sucessfully saved example in %r\n" % (destination,))

    return 0
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import sys
from uuid import uuid4

import pytest

from pandas.compat import PY3, intern
from pandas.util._move import BadMove, move_into_mutable_buffer, stolenbuf

def test_cannot_create_instance_of_stolen_buffer():
    # Stolen buffers need to be created through the smart constructor
    # "move_into_mutable_buffer," which has a bunch of checks in it.

    msg = "cannot create 'pandas.util._move.stolenbuf' instances"
    with pytest.raises(TypeError, match=msg):
        stolenbuf()

def test_more_than_one_ref():
    # Test case for when we try to use "move_into_mutable_buffer"
    # when the object being moved has other references.

    b = b"testing"

    with pytest.raises(BadMove) as e:
        def handle_success(type_, value, tb):
            assert value.args[0] is b
            return type(e).handle_success(e, type_, value, tb)  # super

        e.handle_success = handle_success
        move_into_mutable_buffer(b)

def test_exactly_one_ref():
    # Test case for when the object being moved has exactly one reference.

    b = b"testing"

    # We need to pass an expression on the stack to ensure that there are
    # not extra references hanging around. We cannot rewrite this test as
    #   buf = b[:-3]
    #   as_stolen_buf = move_into_mutable_buffer(buf)
    # because then we would have more than one reference to buf.
    as_stolen_buf = move_into_mutable_buffer(b[:-3])

    # Materialize as byte-array to show that it is mutable.
    assert bytearray(as_stolen_buf) == b"test"

@pytest.mark.skipif(PY3, reason="bytes objects cannot be interned in PY3")
def test_interned():
    salt = uuid4().hex

    def make_string():
        # We need to actually create a new string so that it has refcount
        # one. We use a uuid so that we know the string could not already
        # be in the intern table.
        return "".join(("testing: ", salt))

    # This should work, the string has one reference on the stack.
    move_into_mutable_buffer(make_string())
    refcount = [None]  # nonlocal

    def ref_capture(ob):
        # Subtract two because those are the references owned by this frame:
        #   1. The local variables of this stack frame.
        #   2. The python data stack of this stack frame.
        refcount[0] = sys.getrefcount(ob) - 2
        return ob

    with pytest.raises(BadMove, match="testing"):
        # If we intern the string, it will still have one reference. Now,
        # it is in the intern table, so if other people intern the same
        # string while the mutable buffer holds the first string they will
        # be the same instance.
        move_into_mutable_buffer(ref_capture(intern(make_string())))  # noqa

    assert refcount[0] == 1
<commit_msg>TST: Add missing match parameter in test_move (#24393)<commit_after># -*- coding: utf-8 -*-
import sys
from uuid import uuid4

import pytest

from pandas.compat import PY3, intern
from pandas.util._move import BadMove, move_into_mutable_buffer, stolenbuf

def test_cannot_create_instance_of_stolen_buffer():
    # Stolen buffers need to be created through the smart constructor
    # "move_into_mutable_buffer," which has a bunch of checks in it.

    msg = "cannot create 'pandas.util._move.stolenbuf' instances"
    with pytest.raises(TypeError, match=msg):
        stolenbuf()

def test_more_than_one_ref():
    # Test case for when we try to use "move_into_mutable_buffer"
    # when the object being moved has other references.

    b = b"testing"

    with pytest.raises(BadMove, match="testing") as e:
        def handle_success(type_, value, tb):
            assert value.args[0] is b
            return type(e).handle_success(e, type_, value, tb)  # super

        e.handle_success = handle_success
        move_into_mutable_buffer(b)

def test_exactly_one_ref():
    # Test case for when the object being moved has exactly one reference.

    b = b"testing"

    # We need to pass an expression on the stack to ensure that there are
    # not extra references hanging around. We cannot rewrite this test as
    #   buf = b[:-3]
    #   as_stolen_buf = move_into_mutable_buffer(buf)
    # because then we would have more than one reference to buf.
    as_stolen_buf = move_into_mutable_buffer(b[:-3])

    # Materialize as byte-array to show that it is mutable.
    assert bytearray(as_stolen_buf) == b"test"

@pytest.mark.skipif(PY3, reason="bytes objects cannot be interned in PY3")
def test_interned():
    salt = uuid4().hex

    def make_string():
        # We need to actually create a new string so that it has refcount
        # one. We use a uuid so that we know the string could not already
        # be in the intern table.
        return "".join(("testing: ", salt))

    # This should work, the string has one reference on the stack.
    move_into_mutable_buffer(make_string())
    refcount = [None]  # nonlocal

    def ref_capture(ob):
        # Subtract two because those are the references owned by this frame:
        #   1. The local variables of this stack frame.
        #   2. The python data stack of this stack frame.
        refcount[0] = sys.getrefcount(ob) - 2
        return ob

    with pytest.raises(BadMove, match="testing"):
        # If we intern the string, it will still have one reference. Now,
        # it is in the intern table, so if other people intern the same
        # string while the mutable buffer holds the first string they will
        # be the same instance.
        move_into_mutable_buffer(ref_capture(intern(make_string())))  # noqa

    assert refcount[0] == 1
<|endoftext|>


<commit_before>#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      programar
#
# Created:     16/11/2015
# Copyright:   (c) programar 2015
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import msvcrt
titulo="Empresa Rubben Rc Corporation\n".capitalize()
print titulo.center(50," ")
print("Telefono: 6948209")

class modelo_presupuesto:
    titulo="presupuesto"
    inicio_nombre="Empresa Rubben Rc Corporation"
    inicio_web= "www.rubbenrc.com"
    inicio_email= "rubbenrc@hotmail.com"

    cuota_iva= 7
    div= "="*80

    def set_cliente(self):
        self.empresa= raw_input("Empresa: ")
        self.cliente= raw_input("Nombre del cliente: ")

    def set_datos_basicos(self):
        self.fecha= raw_input(" Fecha: ")
        self.servicio= raw_input("Descripcion del servicio: ")
        importe= raw_input("importe bruto:  $")
        self.importe= float(importe)
        self.vencimiento= raw_input("fecha de expiracion: ")

    def iva(self):
         self.monto_iva= self.importe*self.cuota_iva/100
    def monto_neto(self):
        self.neto= self.importe+self.monto_iva

    def armar_presupuesto(self):
        """
            Esta funcion se encarga de armar todo el presupuesto
        """
        txt = '\n'+self.div+'\n'
        txt += '\t'+self.inicio_nombre+'\n'
        txt += '\tWeb Site: '+self.inicio_web+' | '
        txt += 'E-mail: '+self.inicio_email+'\n'
        txt += self.div+'\n'
        txt += '\t'+self.titulo+'\n'
        txt += self.div+'\n\n'
        txt += '\tFecha: '+self.fecha+'\n'
        txt += '\tEmpresa: '+self.empresa+'\n'
        txt += '\tCliente: '+self.cliente+'\n'
        txt += self.div+'\n\n'
        txt += '\tDetalle del servicio:'
        txt += '\t'+self.servicio+'\n\n'
        txt += '\tImporte: $%0.2f | IVA: $%0.2f\n' % (
                                  self.importe, self.monto_iva)
        txt += '-'*80
        txt += '\n\tMONTO TOTAL: $%0.2f\n' % (self.neto)
        txt += self.div+'\n'
        print txt

# Metodo constructor
    def __init__(self):
        print self.div
        print "\tPRESUPUESTO A OFRECER"
        print self.div
        self.set_cliente()
        self.set_datos_basicos()
        self.iva()
        self.monto_neto()
        self.armar_presupuesto()

# Instanciar clase
presupuesto =  modelo_presupuesto()

msvcrt.getch()
<commit_msg>Update presupuesto_parcial.py<commit_after>#-------------------------------------------------------------------------------
# Name:       presupuesto parcial#1
# Author:      programar
#
# Creado:     12/11/2015
# Copyright:   (c) programar 2015
# Licence:     <your licence 1.1>
#-------------------------------------------------------------------------------
import msvcrt
titulo="Empresa Rubben Rc Corporation\n".capitalize()
print titulo.center(50," ")
print("Telefono: 6948209")

class modelo_presupuesto:
    titulo="presupuesto"
    inicio_nombre="Empresa Rubben Rc Corporation"
    inicio_web= "www.rubbenrc.com"
    inicio_email= "rubbenrc@hotmail.com"

    cuota_iva= 7
    div= "="*80

    def set_cliente(self):
        self.empresa= raw_input("Empresa: ")
        self.cliente= raw_input("Nombre del cliente: ")

    def set_datos_basicos(self):
        self.fecha= raw_input(" Fecha: ")
        self.servicio= raw_input("Descripcion del servicio: ")
        importe= raw_input("importe bruto:  $")
        self.importe= float(importe)
        self.vencimiento= raw_input("fecha de expiracion: ")

    def iva(self):
         self.monto_iva= self.importe*self.cuota_iva/100
    def monto_neto(self):
        self.neto= self.importe+self.monto_iva

    def armar_presupuesto(self):
        """
            Esta funcion se encarga de armar todo el presupuesto
        """
        txt = '\n'+self.div+'\n'
        txt += '\t'+self.inicio_nombre+'\n'
        txt += '\tWeb Site: '+self.inicio_web+' | '
        txt += 'E-mail: '+self.inicio_email+'\n'
        txt += self.div+'\n'
        txt += '\t'+self.titulo+'\n'
        txt += self.div+'\n\n'
        txt += '\tFecha: '+self.fecha+'\n'
        txt += '\tEmpresa: '+self.empresa+'\n'
        txt += '\tCliente: '+self.cliente+'\n'
        txt += self.div+'\n\n'
        txt += '\tDetalle del servicio:'
        txt += '\t'+self.servicio+'\n\n'
        txt += '\tImporte: $%0.2f | IVA: $%0.2f\n' % (
                                  self.importe, self.monto_iva)
        txt += '-'*80
        txt += '\n\tMONTO TOTAL: $%0.2f\n' % (self.neto)
        txt += self.div+'\n'
        print txt

# Metodo constructor
    def __init__(self):
        print self.div
        print "\tPRESUPUESTO A OFRECER"
        print self.div
        self.set_cliente()
        self.set_datos_basicos()
        self.iva()
        self.monto_neto()
        self.armar_presupuesto()

# Instanciar clase
presupuesto =  modelo_presupuesto()

msvcrt.getch()
<|endoftext|>


<commit_before>import email
import datetime
import re

from django.conf import settings
import twitter

from parliament.core.models import Politician, PoliticianInfo
from parliament.activity import utils as activity

import logging
logger = logging.getLogger(__name__)

def save_tweets():
    twitter_to_pol = dict([(int(i.value), i.politician) for i in PoliticianInfo.objects.filter(schema='twitter_id').select_related('politician')])
    screen_names = set(PoliticianInfo.objects.filter(schema='twitter').values_list('value', flat=True))
    twit = twitter.Twitter(domain='api.twitter.com/1')
    statuses = twit.openparlca.lists.mps.statuses(per_page=200)
    statuses.reverse()
    for status in statuses:
        try:
            pol = twitter_to_pol[status['user']['id']]
        except KeyError:
            logger.error("Can't find twitter ID %s (name %s)"
                % (status['user']['id'], status['user']['screen_name']))
            continue
        if status['user']['screen_name'] not in screen_names:
            # Changed screen name
            pol.set_info('twitter', status['user']['screen_name'])
        date = datetime.date.fromtimestamp(
            email.utils.mktime_tz(
                email.utils.parsedate_tz(status['created_at'])
            )
        ) # fuck you, time formats
        guid = 'twit_%s' % status['id']
        # Twitter apparently escapes < > but not & "
        # so I'm clunkily unescaping lt and gt then reescaping in the template
        text = status['text'].replace('<', '<').replace('>', '>')
        activity.save_activity({'text': status['text']}, politician=pol,
            date=date, guid=guid, variety='twitter')

<commit_msg>Twitter API v1.1 migration<commit_after>import email
import datetime
import re

from django.conf import settings
import twitter

from parliament.core.models import Politician, PoliticianInfo
from parliament.activity import utils as activity

import logging
logger = logging.getLogger(__name__)

def save_tweets():
    twitter_to_pol = dict([(int(i.value), i.politician) for i in PoliticianInfo.objects.filter(schema='twitter_id').select_related('politician')])
    screen_names = set(PoliticianInfo.objects.filter(schema='twitter').values_list('value', flat=True))
    twit = twitter.Twitter(
        auth=twitter.OAuth(**settings.TWITTER_OAUTH), domain='api.twitter.com/1.1')

    statuses = twit.lists.statuses(slug='mps', owner_screen_name='openparlca', include_rts=False, count=200)
    statuses.reverse()
    for status in statuses:
        try:
            pol = twitter_to_pol[status['user']['id']]
        except KeyError:
            logger.error("Can't find twitter ID %s (name %s)"
                % (status['user']['id'], status['user']['screen_name']))
            continue
        if status['user']['screen_name'] not in screen_names:
            # Changed screen name
            pol.set_info('twitter', status['user']['screen_name'])
        date = datetime.date.fromtimestamp(
            email.utils.mktime_tz(
                email.utils.parsedate_tz(status['created_at'])
            )
        ) # fuck you, time formats
        guid = 'twit_%s' % status['id']
        # Twitter apparently escapes < > but not & "
        # so I'm clunkily unescaping lt and gt then reescaping in the template
        text = status['text'].replace('<', '<').replace('>', '>')
        activity.save_activity({'text': status['text']}, politician=pol,
            date=date, guid=guid, variety='twitter')

<|endoftext|>


<commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

def parent(i):
    return i // 2

def left(i):
    return 2 * i

def right(i):
    return 2 * i + 1

class MinBinaryHeapVertices(object):
    """Min Binary Heap of vertices implmentation of Priority Queue.

    Applications:
      - Dijkstra's Algorithm.
      - Prim's Minimum Spanning Tree Algorithm.

    Min-heap property: A[parent(i)][0] <= A[i][0].
    """
    def __init__(self):
        self.A = [[0, 0]]
        self.heap_size = 0

    def show(self):
        print(self.A)

    def find_min(self):
        return self.A[1]

    def min_heapify(self, i):
        """Min heapify.

        Complexity: O(log(n)).
        """
        l = left(i)
        r = right(i)
        if l <= self.heap_size and self.A[l][0] < self.A[i][0]:
            min_i = l
        else:
            min_i = i
        if r <= self.heap_size and self.A[r][0] < self.A[min_i][0]:
            min_i = r
        if min_i != i:
            self.A[i], self.A[min_i] = self.A[min_i], self.A[i]
            self.min_heapify(min_i)

    def build_min_heap():
        """Build min heap from unordered array."""
        pass

    def extract_min(self):
        if self.heap_size < 1:
            raise ValueError('Heap underflow.')
        minimum = self.A[1]
        last = self.A.pop()
        self.heap_size -= 1
        if self.heap_size < 1:
            # The last element is minimum.
            pass
        else:
            self.A[1] = last
            self.min_heapify(1)
        return minimum

    def decrease_key(self, i, key):
        if key > self.A[i][0]:
            raise ValueError('New key is larger than current key.')
        self.A[i][0] = key
        while i > 1 and self.A[parent(i)][0] > self.A[i][0]:
            # Swap node i and node parent(i).
            self.A[i], self.A[parent(i)] = self.A[parent(i)], self.A[i]
            i = parent(i)

    def insert(self, new_node):
        key, item = new_node
        self.A.append([np.inf, item])
        self.heap_size += 1
        self.decrease_key(self.heap_size, key)

def main():
    print('Binary heap of vertices with [5, a], [7, c], [3, b], [1, e]:')
    min_pq = MinBinaryHeapVertices()
    min_pq.insert([3, 'a'])
    min_pq.insert([7, 'c'])
    min_pq.insert([5, 'b'])
    min_pq.insert([1, 'd'])
    min_pq.show()

    print('Decrease key 7 at position 4 to 2.')
    min_pq.decrease_key(4, 2)
    min_pq.show()

    print('Find min key:')
    print(min_pq.find_min())

    print('Extract min key:')
    _min = min_pq.extract_min()
    print('- Min: {}'.format(_min))
    print('- The remaining:')
    min_pq.show()

if __name__ == '__main__':
    main()
<commit_msg>Complete build_min_heap() and its testing in main()<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

def parent(i):
    return i // 2

def left(i):
    return 2 * i

def right(i):
    return 2 * i + 1

class MinBinaryHeapVertices(object):
    """Min Binary Heap of vertices implmentation of Priority Queue.

    Applications:
      - Dijkstra's Algorithm.
      - Prim's Minimum Spanning Tree Algorithm.

    Min-heap property: A[parent(i)][0] <= A[i][0].
    """
    def __init__(self):
        self.A = [[0, 0]]
        self.heap_size = 0

    def show(self):
        print(self.A)

    def find_min(self):
        return self.A[1]

    def min_heapify(self, i):
        """Min heapify.

        Complexity: O(log(n)).
        """
        l = left(i)
        r = right(i)
        if l <= self.heap_size and self.A[l][0] < self.A[i][0]:
            min_i = l
        else:
            min_i = i
        if r <= self.heap_size and self.A[r][0] < self.A[min_i][0]:
            min_i = r
        if min_i != i:
            self.A[i], self.A[min_i] = self.A[min_i], self.A[i]
            self.min_heapify(min_i)

    def build_min_heap(self, A):
        """Build min heap from unordered array.

        Start from level-1 nodes from leaves back to level-long(n) nodes.
        Specifically, node (n/2), node (n/2 - 1), ..., node 1, where
        n is the number of nodes including the root node.

        Complexity: O(n*log(n)) via simple analysis. Actually O(n).
        """
        self.A.extend(A)
        self.heap_size = len(A)
        for i in reversed(range(1, (self.heap_size + 1) // 2 + 1)):
            self.min_heapify(i)

    def extract_min(self):
        if self.heap_size < 1:
            raise ValueError('Heap underflow.')
        minimum = self.A[1]
        last = self.A.pop()
        self.heap_size -= 1
        if self.heap_size < 1:
            # The last element is minimum.
            pass
        else:
            self.A[1] = last
            self.min_heapify(1)
        return minimum

    def decrease_key(self, i, key):
        if key > self.A[i][0]:
            raise ValueError('New key is larger than current key.')
        self.A[i][0] = key
        while i > 1 and self.A[parent(i)][0] > self.A[i][0]:
            # Swap node i and node parent(i).
            self.A[i], self.A[parent(i)] = self.A[parent(i)], self.A[i]
            i = parent(i)

    def insert(self, new_node):
        key, item = new_node
        self.A.append([np.inf, item])
        self.heap_size += 1
        self.decrease_key(self.heap_size, key)

def main():
    print('Binary heap of vertices by inserting [3, a], [7, c], [5, b], [1, e]:')
    min_pq = MinBinaryHeapVertices()
    min_pq.insert([3, 'a'])
    min_pq.insert([7, 'c'])
    min_pq.insert([5, 'b'])
    min_pq.insert([1, 'e'])
    min_pq.show()

    print('Build min heap of vertices from unordered list')
    print('by inserting [[3, a], [7, c], [5, b], [1, e]]:')
    min_pq = MinBinaryHeapVertices()
    min_pq.build_min_heap([[3, 'a'], [7, 'c'], [5, 'b'], [1, 'e']])
    min_pq.show()

    print('Decrease key 7 at position 4 to 2.')
    min_pq.decrease_key(4, 2)
    min_pq.show()

    print('Find min key:')
    print(min_pq.find_min())

    print('Extract min key:')
    _min = min_pq.extract_min()
    print('- Min: {}'.format(_min))
    print('- The remaining:')
    min_pq.show()

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


<commit_before>from astropy.modeling import Fittable1DModel, Parameter

__all__ = ["AxAvToExv"]

class AxAvToExv(Fittable1DModel):
    """
    Model to convert from A(x)/A(V) to E(x-V)

    Parameters
    ----------
    Av : float
      dust column in A(V) [mag]
    """

    inputs = ("axav",)
    outputs = ("exv",)

    Av = Parameter(description="A(V)", default=1.0, min=0.0)

    @staticmethod
    def evaluate(axav, Av):
        """
        AlAvToElv function

        Parameters
        ----------
        axav : np array (float)
           E(x-V)/E(B-V) values

        Returns
        -------
        exv : np array (float)
           E(x - V)
        """
        return (axav - 1.0) * Av

    @staticmethod
    def fit_deriv(axav, Av):
        """
        Derivatives of the AxAvtoElv function with respect to the parameters
        """
        # derivatives
        d_Av = axav - 1.0

        return [d_Av]
<commit_msg>removing analytic derivative from AxAvtoExv (never used)<commit_after>from astropy.modeling import Fittable1DModel, Parameter

__all__ = ["AxAvToExv"]

class AxAvToExv(Fittable1DModel):
    """
    Model to convert from A(x)/A(V) to E(x-V)

    Parameters
    ----------
    Av : float
      dust column in A(V) [mag]
    """

    inputs = ("axav",)
    outputs = ("exv",)

    Av = Parameter(description="A(V)", default=1.0, min=0.0)

    @staticmethod
    def evaluate(axav, Av):
        """
        AlAvToElv function

        Parameters
        ----------
        axav : np array (float)
           E(x-V)/E(B-V) values

        Returns
        -------
        exv : np array (float)
           E(x - V)
        """
        return (axav - 1.0) * Av

# Removed 4 Sep 2019 as this code is never used due to this model
# only is ever used in a compound model, hence the analytic derivatives
# are never used.  Code never used or tested, better to not have it.
# The code is kept as a comment if in the future there is a need for it.
#
#    @staticmethod
#    def fit_deriv(axav, Av):
#        """
#        Derivatives of the AxAvtoElv function with respect to the parameters
#        """
#        # derivatives
#        d_Av = axav - 1.0
#
#        return [d_Av]
<|endoftext|>