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

from appium.webdriver.common.touch_action import TouchAction
from AppiumLibrary import utils
from AppiumLibrary.locators import ElementFinder
from keywordgroup import KeywordGroup

class _ElementKeywords(KeywordGroup):

    def __init__(self):
        self._element_finder = ElementFinder()

    # Public, element lookups
    def click_element(self, locator):
        """Click element identified by `locator`.

        Key attributes for arbitrary elements are `index` and `name`. See
        `introduction` for details about locating elements.
        """
        self._info("Clicking element '%s'." % locator)
        self._element_find(locator, True, True).click()

    def click_button(self, index_or_name):
        """ Click button """
        _platform_class_dict = {'ios':'UIAButton',
                                   'android': 'android.widget.Button'}
        if self._is_support_platform(_platform_class_dict):
            class_name = self._get_class(_platform_class_dict)
            self._click_element_by_class_name(class_name, index_or_name)

    def input_text(self, locator, text):
        """ Input text identified by `locator`.
        Key attributes for arbitrary elements are `index` and `name`. See
        `introduction` for details about locating elements.
        Examples:
        | Input text | index=0            | element_index |
        | Input text | login_textfiled | element_name |
        """
        self._element_input_text_by_locator(locator, text)

    def input_password(self, index_or_name, text):
        """ Input secure text """
        _platform_class_dict = {'ios':'UIASecureTextField',
                                   'android': 'android.widget.EditText'}
        if self._is_support_platform(_platform_class_dict):
            class_name = self._get_class(_platform_class_dict)
            self._element_input_text_by_class_name(class_name, index_or_name, text)

    def reset_application(self):
        """ Reset application """
        driver = self._current_application()
        driver.execute_script('mobile: reset')

    def hide_keyboard(self):
        """
        Hides the software keyboard on the device, using the specified key to
        press. If no key name is given, the keyboard is closed by moving focus
        from the text field. iOS only.
        """
        if not self._is_ios():
            raise EnvironmentError("Hide Keyword only support for iOS .")
        driver = self._current_application()
        driver.hide_keyboard()

    def page_should_contain_text(self, text, loglevel='INFO'):
        """Verifies that current page contains `text`.

        If this keyword fails, it automatically logs the page source
        using the log level specified with the optional `loglevel` argument.
        Giving `NONE` as level disables logging.
        """
        if not text in self.log_source(loglevel):
            self.log_source(loglevel)
            raise AssertionError("Page should have contained text '%s' "
                                 "but did not" % text)
        self._info("Current page contains text '%s'." % text)

    def page_should_not_contain_text(self, text, loglevel='INFO'):
        """Verifies that current page not contains `text`.

        If this keyword fails, it automatically logs the page source
        using the log level specified with the optional `loglevel` argument.
        Giving `NONE` as level disables logging.
        """
        if text in self.log_source(loglevel):
            self.log_source(loglevel)
            raise AssertionError("Page should not have contained text '%s' "
                                 "but did not" % text)
        self._info("Current page does not contains text '%s'." % text)

    def page_should_contain_element(self, locator, loglevel='INFO'):
        """Verifies that current page contains `locator` element.

        If this keyword fails, it automatically logs the page source
        using the log level specified with the optional `loglevel` argument.
        Givin
        """
        if not self._is_element_present(locator):
            self.log_source(loglevel)
            raise AssertionError("Page should have contained element '%s' "
                                 "but did not" % locator)
        self._info("Current page contains element '%s'." % locator)

    def page_should_not_contain_element(self, locator, loglevel='INFO'):
        """Verifies that current page not contains `locator` element.

        If this keyword fails, it automatically logs the page source
        using the log level specified with the optional `loglevel` argument.
        Givin
        """
        if self._is_element_present(locator):
            self.log_source(loglevel)
            raise AssertionError("Page should not have contained element '%s' "
                                 "but did not" % locator)
        self._info("Current page not contains element '%s'." % locator)

    def element_should_be_disabled(self, locator):
        """Verifies that element identified with locator is disabled.

        Key attributes for arbitrary elements are `id` and `name`. See
        `introduction` for details about locating elements.
        """
        if self._element_find(locator, True, True).is_enabled():
            self.log_source(loglevel)
            raise AssertionError("Element '%s' should be disabled "
                                 "but did not" % locator)
        self._info("Element '%s' is disabled ." % locator)

    def element_should_be_enabled(self, locator):
        """Verifies that element identified with locator is enabled.

        Key attributes for arbitrary elements are `id` and `name`. See
        `introduction` for details about locating elements.
        """
        if not self._element_find(locator, True, True).is_enabled():
            self.log_source(loglevel)
            raise AssertionError("Element '%s' should be enabled "
                                 "but did not" % locator)
        self._info("Element '%s' is enabled ." % locator)

    def element_name_should_be(self, locator, expected):
        element = self._element_find(locator, True, True)
        if expected != element.get_attribute('name'):
            raise AssertionError("Element '%s' name should be '%s' "
                                 "but it is '%s'." % (locator, expected, element.get_attribute('name')))
        self._info("Element '%s' name is '%s' " % (locator, expected))

    # Private

    def _is_index(self, index_or_name):
        if index_or_name.startswith('index='):
            return True
        else:
            return False

    def _click_element_by_name(self, name):
        driver = self._current_application()
        try:
            element = driver.find_element_by_name(name)
        except Exception, e:
            raise Exception, e

        try:
            element.click()
        except Exception, e:
            raise Exception, 'Cannot click the element with name "%s"' % name

    def _find_elements_by_class_name(self, class_name):
        driver = self._current_application()
        elements = driver.find_elements_by_class_name(class_name)
        return elements

    def _find_element_by_class_name(self, class_name, index_or_name):
        elements = self._find_elements_by_class_name(class_name)

        if self._is_index(index_or_name):
            try:
                index = int(index_or_name.split('=')[-1])
                element = elements[index]
            except IndexError, TypeError:
                raise Exception, 'Cannot find the element with index "%s"' % index_or_name
        else:
            found = False
            for element in elements:
                self._info("'%s'." % element.text)
                if element.text == index_or_name:
                    found = True
                    break
            if not found:
                raise Exception, 'Cannot find the element with name "%s"' % index_or_name

        return element

    def _get_class(self, platform_class_dict):
        return platform_class_dict.get(self._get_platform())

    def _is_support_platform(self, platform_class_dict):
        return platform_class_dict.has_key(self._get_platform())

    def _click_element_by_class_name(self, class_name, index_or_name):
        element = self._find_element_by_class_name(class_name, index_or_name)
        self._info("Clicking element '%s'." % element.text)
        try:
            element.click()
        except Exception, e:
            raise Exception, 'Cannot click the %s element "%s"' % (class_name, index_or_name)

    def _element_input_text_by_locator(self, locator, text):
        try:
            element = self._element_find(locator, True, True)
            element.send_keys(text)
        except Exception, e:
            raise e

    def _element_input_text_by_class_name(self, class_name, index_or_name, text):
        try:
            element = self._find_element_by_class_name(class_name, index_or_name)
        except Exception, e:
            raise Exception, e

        self._info("input text in element as '%s'." % element.text)
        try:
            element.send_keys(text)
        except Exception, e:
            raise Exception, 'Cannot input text "%s" for the %s element "%s"' % (text, class_name, index_or_name)

    def _element_find(self, locator, first_only, required, tag=None):
        application = self._current_application()
        elements = self._element_finder.find(application, locator, tag)
        if required and len(elements) == 0:
            raise ValueError("Element locator '" + locator + "' did not match any elements.")
        if first_only:
            if len(elements) == 0: return None
            return elements[0]
        return elements

    def _is_text_present(self, text):
        return text in self.get_source()

    def _is_element_present(self, locator):
        application = self._current_application()
        elements = self._element_finder.find(application, locator, None)
        return len(elements) > 0<commit_msg>fix input password<commit_after># -*- coding: utf-8 -*-

from appium.webdriver.common.touch_action import TouchAction
from AppiumLibrary import utils
from AppiumLibrary.locators import ElementFinder
from keywordgroup import KeywordGroup

class _ElementKeywords(KeywordGroup):

    def __init__(self):
        self._element_finder = ElementFinder()

    # Public, element lookups
    def click_element(self, locator):
        """Click element identified by `locator`.

        Key attributes for arbitrary elements are `index` and `name`. See
        `introduction` for details about locating elements.
        """
        self._info("Clicking element '%s'." % locator)
        self._element_find(locator, True, True).click()

    def click_button(self, index_or_name):
        """ Click button """
        _platform_class_dict = {'ios':'UIAButton',
                                   'android': 'android.widget.Button'}
        if self._is_support_platform(_platform_class_dict):
            class_name = self._get_class(_platform_class_dict)
            self._click_element_by_class_name(class_name, index_or_name)

    def input_text(self, locator, text):
        """Types the given `text` into text field identified by `locator`.

        See `introduction` for details about locating elements.
        """
        self._info("Typing text '%s' into text field '%s'" % (text, locator))
        self._element_input_text_by_locator(locator, text)

    def input_password(self, locator, text):
        """Types the given password into text field identified by `locator`.

        Difference between this keyword and `Input Text` is that this keyword
        does not log the given password. See `introduction` for details about
        locating elements.
        """
        self._info("Typing password into text field '%s'" % locator)
        self._element_input_text_by_locator(locator, text)

    def reset_application(self):
        """ Reset application """
        driver = self._current_application()
        driver.execute_script('mobile: reset')

    def hide_keyboard(self):
        """
        Hides the software keyboard on the device, using the specified key to
        press. If no key name is given, the keyboard is closed by moving focus
        from the text field. iOS only.
        """
        if not self._is_ios():
            raise EnvironmentError("Hide Keyword only support for iOS .")
        driver = self._current_application()
        driver.hide_keyboard()

    def page_should_contain_text(self, text, loglevel='INFO'):
        """Verifies that current page contains `text`.

        If this keyword fails, it automatically logs the page source
        using the log level specified with the optional `loglevel` argument.
        Giving `NONE` as level disables logging.
        """
        if not text in self.log_source(loglevel):
            self.log_source(loglevel)
            raise AssertionError("Page should have contained text '%s' "
                                 "but did not" % text)
        self._info("Current page contains text '%s'." % text)

    def page_should_not_contain_text(self, text, loglevel='INFO'):
        """Verifies that current page not contains `text`.

        If this keyword fails, it automatically logs the page source
        using the log level specified with the optional `loglevel` argument.
        Giving `NONE` as level disables logging.
        """
        if text in self.log_source(loglevel):
            self.log_source(loglevel)
            raise AssertionError("Page should not have contained text '%s' "
                                 "but did not" % text)
        self._info("Current page does not contains text '%s'." % text)

    def page_should_contain_element(self, locator, loglevel='INFO'):
        """Verifies that current page contains `locator` element.

        If this keyword fails, it automatically logs the page source
        using the log level specified with the optional `loglevel` argument.
        Givin
        """
        if not self._is_element_present(locator):
            self.log_source(loglevel)
            raise AssertionError("Page should have contained element '%s' "
                                 "but did not" % locator)
        self._info("Current page contains element '%s'." % locator)

    def page_should_not_contain_element(self, locator, loglevel='INFO'):
        """Verifies that current page not contains `locator` element.

        If this keyword fails, it automatically logs the page source
        using the log level specified with the optional `loglevel` argument.
        Givin
        """
        if self._is_element_present(locator):
            self.log_source(loglevel)
            raise AssertionError("Page should not have contained element '%s' "
                                 "but did not" % locator)
        self._info("Current page not contains element '%s'." % locator)

    def element_should_be_disabled(self, locator):
        """Verifies that element identified with locator is disabled.

        Key attributes for arbitrary elements are `id` and `name`. See
        `introduction` for details about locating elements.
        """
        if self._element_find(locator, True, True).is_enabled():
            self.log_source(loglevel)
            raise AssertionError("Element '%s' should be disabled "
                                 "but did not" % locator)
        self._info("Element '%s' is disabled ." % locator)

    def element_should_be_enabled(self, locator):
        """Verifies that element identified with locator is enabled.

        Key attributes for arbitrary elements are `id` and `name`. See
        `introduction` for details about locating elements.
        """
        if not self._element_find(locator, True, True).is_enabled():
            self.log_source(loglevel)
            raise AssertionError("Element '%s' should be enabled "
                                 "but did not" % locator)
        self._info("Element '%s' is enabled ." % locator)

    def element_name_should_be(self, locator, expected):
        element = self._element_find(locator, True, True)
        if expected != element.get_attribute('name'):
            raise AssertionError("Element '%s' name should be '%s' "
                                 "but it is '%s'." % (locator, expected, element.get_attribute('name')))
        self._info("Element '%s' name is '%s' " % (locator, expected))

    # Private

    def _is_index(self, index_or_name):
        if index_or_name.startswith('index='):
            return True
        else:
            return False

    def _click_element_by_name(self, name):
        driver = self._current_application()
        try:
            element = driver.find_element_by_name(name)
        except Exception, e:
            raise Exception, e

        try:
            element.click()
        except Exception, e:
            raise Exception, 'Cannot click the element with name "%s"' % name

    def _find_elements_by_class_name(self, class_name):
        driver = self._current_application()
        elements = driver.find_elements_by_class_name(class_name)
        return elements

    def _find_element_by_class_name(self, class_name, index_or_name):
        elements = self._find_elements_by_class_name(class_name)

        if self._is_index(index_or_name):
            try:
                index = int(index_or_name.split('=')[-1])
                element = elements[index]
            except IndexError, TypeError:
                raise Exception, 'Cannot find the element with index "%s"' % index_or_name
        else:
            found = False
            for element in elements:
                self._info("'%s'." % element.text)
                if element.text == index_or_name:
                    found = True
                    break
            if not found:
                raise Exception, 'Cannot find the element with name "%s"' % index_or_name

        return element

    def _get_class(self, platform_class_dict):
        return platform_class_dict.get(self._get_platform())

    def _is_support_platform(self, platform_class_dict):
        return platform_class_dict.has_key(self._get_platform())

    def _click_element_by_class_name(self, class_name, index_or_name):
        element = self._find_element_by_class_name(class_name, index_or_name)
        self._info("Clicking element '%s'." % element.text)
        try:
            element.click()
        except Exception, e:
            raise Exception, 'Cannot click the %s element "%s"' % (class_name, index_or_name)

    def _element_input_text_by_locator(self, locator, text):
        try:
            element = self._element_find(locator, True, True)
            element.send_keys(text)
        except Exception, e:
            raise e

    def _element_input_text_by_class_name(self, class_name, index_or_name, text):
        try:
            element = self._find_element_by_class_name(class_name, index_or_name)
        except Exception, e:
            raise Exception, e

        self._info("input text in element as '%s'." % element.text)
        try:
            element.send_keys(text)
        except Exception, e:
            raise Exception, 'Cannot input text "%s" for the %s element "%s"' % (text, class_name, index_or_name)

    def _element_find(self, locator, first_only, required, tag=None):
        application = self._current_application()
        elements = self._element_finder.find(application, locator, tag)
        if required and len(elements) == 0:
            raise ValueError("Element locator '" + locator + "' did not match any elements.")
        if first_only:
            if len(elements) == 0: return None
            return elements[0]
        return elements

    def _is_text_present(self, text):
        return text in self.get_source()

    def _is_element_present(self, locator):
        application = self._current_application()
        elements = self._element_finder.find(application, locator, None)
        return len(elements) > 0<|endoftext|>


<commit_before>#!/usr/bin/env python
# Stdlib
import sys
# 3rd party
from PySide import QtGui
# launchit package
from . import core

class MarkedCompletionDelegate(QtGui.QItemDelegate):
    def __init__(self, start_mark='', end_mark='', parent=None):
        QtGui.QItemDelegate.__init__(self, parent)
        self.start_mark = start_mark
        self.end_mark = end_mark
        self.fragment = ''
        self.renderer = QtGui.QTextDocument()

    def paint(self, painter, option, index):
        self.drawBackground(painter, option, index)
        self.draw_contents(painter, option, index)

    def draw_contents(self, painter, option, index):
        painter.save()
        painter.translate(option.rect.topLeft())
        self._draw_marked_text(painter, index.data(), option.rect.width())
        painter.restore()

    def _draw_marked_text(self, painter, text, width):
        # Note that truncation can't be made with QFontMetrics.elidedText()
        # here, since that doesn't handle rich text. The trial and error
        # approach has been chosen in order to avoid messing with the
        # rendering engine. There probably should be no situation where
        # memory consumption of this method is really getting noticeable.
        ellipsis = '...'
        rendered_width = self.renderer.idealWidth
        markup = self._markup_for_completion(text)
        self.renderer.setHtml(markup)
        while text and (rendered_width() > width):
            text = text[:-1]
            markup = self._markup_for_completion(text)
            self.renderer.setHtml(markup + ellipsis)
        self.renderer.drawContents(painter)

    def _markup_for_completion(self, completion):
        return core.get_marked_completion(completion, self.fragment,
                                          self.start_mark, self.end_mark)

    def sizeHint(self, option, index):
        return self.renderer.size().toSize()

class CommandlineCompleter(QtGui.QCompleter):
    def __init__(self, parent=None):
        QtGui.QCompleter.__init__(self, parent)
        mode = self.UnfilteredPopupCompletion
        self.setCompletionMode(mode)
        model = QtGui.QStringListModel()
        self.setModel(model)
        delegate = MarkedCompletionDelegate()
        self.popup().setItemDelegate(delegate)

    def update(self, fragment):
        completions = core.get_name_completions(fragment)
        self.model().setStringList(completions)
        self.popup().itemDelegate().fragment = fragment

class LaunchEdit(QtGui.QLineEdit):
    def __init__(self, parent=None):
        QtGui.QLineEdit.__init__(self, parent)
        completer = CommandlineCompleter()
        self.textEdited.connect(completer.update)
        self.setCompleter(completer)
        self.returnPressed.connect(self.launch)

    def launch(self):
        core.launch(self.text())

def run_app(args=[]):
    app = QtGui.QApplication(args)
    edit = LaunchEdit()
    edit.show()
    return app.exec_()

if __name__ == '__main__':
    sys.exit(run_app(sys.argv))
<commit_msg>The GUI is now using `icongetter` to display suitable command icons.<commit_after>#!/usr/bin/env python
# Stdlib
import sys

# 3rd party
from PySide import QtGui

# launchit package
from . import core, icongetter

class MarkedCompletionDelegate(QtGui.QItemDelegate):
    def __init__(self, start_mark='', end_mark='', parent=None):
        QtGui.QItemDelegate.__init__(self, parent)
        self.start_mark = start_mark
        self.end_mark = end_mark
        self.fragment = ''
        self.renderer = QtGui.QTextDocument()

    def paint(self, painter, option, index):
        self.drawBackground(painter, option, index)
        self.draw_contents(painter, option, index)

    def draw_contents(self, painter, option, index):
        painter.save()
        painter.translate(option.rect.topLeft())
        self._draw_marked_text(painter, index.data(), option.rect.width())
        painter.restore()

    def _draw_marked_text(self, painter, text, width):
        # Note that truncation can't be made with QFontMetrics.elidedText()
        # here, since that doesn't handle rich text. The trial and error
        # approach has been chosen in order to avoid messing with the
        # rendering engine. There probably should be no situation where
        # memory consumption of this method is really getting noticeable.
        ellipsis = '...'
        rendered_width = self.renderer.idealWidth
        markup = self._markup_for_completion(text)
        self.renderer.setHtml(markup)
        while text and (rendered_width() > width):
            text = text[:-1]
            markup = self._markup_for_completion(text)
            self.renderer.setHtml(markup + ellipsis)
        self.renderer.drawContents(painter)

    def _markup_for_completion(self, completion):
        return core.get_marked_completion(completion, self.fragment,
                                          self.start_mark, self.end_mark)

    def sizeHint(self, option, index):
        return self.renderer.size().toSize()

class CommandlineCompleter(QtGui.QCompleter):
    def __init__(self, parent=None):
        QtGui.QCompleter.__init__(self, parent)
        mode = self.UnfilteredPopupCompletion
        self.setCompletionMode(mode)
        model = QtGui.QStringListModel()
        self.setModel(model)
        delegate = MarkedCompletionDelegate()
        self.popup().setItemDelegate(delegate)

    def update(self, fragment):
        completions = core.get_name_completions(fragment)
        self.model().setStringList(completions)
        self.popup().itemDelegate().fragment = fragment

class LaunchEdit(QtGui.QLineEdit):
    def __init__(self, parent=None):
        QtGui.QLineEdit.__init__(self, parent)
        completer = CommandlineCompleter()
        self.textEdited.connect(completer.update)
        self.setCompleter(completer)
        self.returnPressed.connect(self.launch)

    def launch(self):
        core.launch(self.text())

class CommandIconLabel(QtGui.QLabel):
    def __init__(self, icon_size=32, icon=QtGui.QIcon(), parent=None):
        QtGui.QLabel.__init__(self, parent)
        self.icon_size = icon_size
        self.icon = icon

    @property
    def icon(self):
        return self._icon

    @icon.setter
    def icon(self, icon):
        width = height = self.icon_size
        pixmap = icon.pixmap(width, height)
        self.setPixmap(pixmap)
        self._icon = icon

    def set_icon_by_command(self, cmdline):
        args = (cmdline, self.icon_size, QtGui.QIcon.themeName())
        icon_path = icongetter.get_iconpath_for_commandline(*args)
        if icon_path is None:
            # TODO: Use fallback instead of empty icon
            icon = QtGui.QIcon()
        else:
            icon = QtGui.QIcon(icon_path)
        self.icon = icon

class LaunchWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        layout = QtGui.QHBoxLayout()
        self.icon_label = CommandIconLabel()
        layout.addWidget(self.icon_label)
        self.edit = LaunchEdit()
        self.edit.textChanged.connect(self.update)
        layout.addWidget(self.edit)
        self.setLayout(layout)
        # Start with empty state
        self.update('')

    def update(self, fragment):
        self.icon_label.set_icon_by_command(fragment)

def run_app(args=[]):
    app = QtGui.QApplication(args)
    launcher = LaunchWidget()
    launcher.show()
    return app.exec_()

if __name__ == '__main__':
    sys.exit(run_app(sys.argv))
<|endoftext|>


<commit_before>"""
Configure glymur to use installed libraries if possible.
"""
# configparser is new in python3 (pylint/python-2.7)
# pylint: disable=F0401

import ctypes
from ctypes.util import find_library
import os
import platform
import warnings

import sys
if sys.hexversion <= 0x03000000:
    from ConfigParser import SafeConfigParser as ConfigParser
    from ConfigParser import NoOptionError
else:
    from configparser import ConfigParser
    from configparser import NoOptionError

def glymurrc_fname():
    """Return the path to the configuration file.

    Search order:
        1) current working directory
        2) environ var XDG_CONFIG_HOME
        3) $HOME/.config/glymur/glymurrc
    """

    # Current directory.
    fname = os.path.join(os.getcwd(), 'glymurrc')
    if os.path.exists(fname):
        return fname

    confdir = get_configdir()
    if confdir is not None:
        fname = os.path.join(confdir, 'glymurrc')
        if os.path.exists(fname):
            return fname

    # didn't find a configuration file.
    return None

def load_openjpeg(path):
    """Load the openjpeg library, falling back on defaults if necessary.

    Parameters
    ----------
    path : str
        Path to openjpeg 1.5 library as specified by configuration file.  Will
        be None if no configuration file specified.
    """
    if path is None:
        # Let ctypes try to find it.
        path = find_library('openjpeg')

    # If we could not find it, then look in some likely locations on mac
    # and win.
    if path is None:
        # Could not find a library via ctypes
        if platform.system() == 'Darwin':
            # MacPorts
            path = '/opt/local/lib/libopenjpeg.dylib'
        elif os.name == 'nt':
            path = os.path.join('C:\\', 'Program files', 'OpenJPEG 1.5',
                                'bin', 'openjpeg.dll')

        if path is not None and not os.path.exists(path):
            # the mac/win default location does not exist.
            return None

    return load_library_handle(path)

def load_openjp2(path):
    """Load the openjp2 library, falling back on defaults if necessary.
    """
    if path is None:
        # No help from the config file, try to find it via ctypes.
        path = find_library('openjp2')

    if path is None:
        # Could not find a library via ctypes
        if platform.system() == 'Darwin':
            # MacPorts
            path = '/opt/local/lib/libopenjp2.dylib'
        elif os.name == 'nt':
            path = os.path.join('C:\\', 'Program files', 'OpenJPEG 2.0',
                                'bin', 'openjp2.dll')

        if path is not None and not os.path.exists(path):
            # the mac/win default location does not exist.
            return None

    return load_library_handle(path)

def load_library_handle(path):
    """Load the library, return the ctypes handle."""

    if path is None or path in ['None', 'none']:
        # Either could not find a library via ctypes or user-configuration-file,
        # or we could not find it in any of the default locations.
        # This is probably a very old linux.
        return None

    try:
        if os.name == "nt":
            opj_lib = ctypes.windll.LoadLibrary(path)
        else:
            opj_lib = ctypes.CDLL(path)
    except (TypeError, OSError):
       msg = '"Library {0}" could not be loaded.  Operating in degraded mode.'
       msg = msg.format(path)
       warnings.warn(msg, UserWarning)
       opj_lib = None

    return opj_lib

def read_config_file():
    """
    We must use a configuration file that the user must write.
    """
    lib = {'openjp2':  None, 'openjpeg':  None}
    filename = glymurrc_fname()
    if filename is not None:
        # Read the configuration file for the library location.
        parser = ConfigParser()
        parser.read(filename)
        for name in ['openjp2', 'openjpeg']:
            try:
                lib[name] = parser.get('library', name)
            except NoOptionError:
                pass

    return lib

def glymur_config():
    """Try to ascertain locations of openjp2, openjpeg libraries.
    """
    libs = read_config_file()
    libopenjp2_handle = load_openjp2(libs['openjp2'])
    libopenjpeg_handle = load_openjpeg(libs['openjpeg'])
    if libopenjp2_handle is None and libopenjpeg_handle is None:
        msg = "Neither the openjp2 nor the openjpeg library could be loaded.  "
        raise IOError(msg)
    return libopenjp2_handle, libopenjpeg_handle

def get_configdir():
    """Return string representing the configuration directory.

    Default is $HOME/.config/glymur.  You can override this with the
    XDG_CONFIG_HOME environment variable.
    """
    if 'XDG_CONFIG_HOME' in os.environ:
        return os.path.join(os.environ['XDG_CONFIG_HOME'], 'glymur')

    if 'HOME' in os.environ and os.name != 'nt':
        # HOME is set by WinPython to something unusual, so we don't
        # necessarily want that.
        return os.path.join(os.environ['HOME'], '.config', 'glymur')

    # Last stand.  Should handle windows... others?
    return os.path.join(os.path.expanduser('~'), 'glymur')
<commit_msg>refactored configuration file handling, closes #265<commit_after>"""
Configure glymur to use installed libraries if possible.
"""
# configparser is new in python3 (pylint/python-2.7)
# pylint: disable=F0401

import ctypes
from ctypes.util import find_library
import os
import platform
import warnings

import sys
if sys.hexversion <= 0x03000000:
    from ConfigParser import SafeConfigParser as ConfigParser
    from ConfigParser import NoOptionError
else:
    from configparser import ConfigParser
    from configparser import NoOptionError

# default library locations for MacPorts
_macports_default_location = {
        'openjp2': '/opt/local/lib/libopenjp2.dylib',
        'openjpeg': '/opt/local/lib/libopenjpeg.dylib'
}

# default library locations on Windows
_windows_default_location = {
        'openjp2': os.path.join('C:\\', 'Program files', 'OpenJPEG 2.0',
                                'bin', 'openjp2.dll'),
        'openjpeg': os.path.join('C:\\', 'Program files', 'OpenJPEG 1.5',
                                 'bin', 'openjpeg.dll')
}

def glymurrc_fname():
    """Return the path to the configuration file.

    Search order:
        1) current working directory
        2) environ var XDG_CONFIG_HOME
        3) $HOME/.config/glymur/glymurrc
    """

    # Current directory.
    fname = os.path.join(os.getcwd(), 'glymurrc')
    if os.path.exists(fname):
        return fname

    confdir = get_configdir()
    if confdir is not None:
        fname = os.path.join(confdir, 'glymurrc')
        if os.path.exists(fname):
            return fname

    # didn't find a configuration file.
    return None

def load_openjpeg_library(libname):

    path = read_config_file(libname)
    if path is not None:
        return load_library_handle(path)

    # No location specified by the configuration file, must look for it
    # elsewhere.
    path = find_library(libname)

    if path is None:
        # Could not find a library via ctypes
        if platform.system() == 'Darwin':
            # MacPorts
            path = _macports_default_location[libname]
        elif os.name == 'nt':
            path = _windows_default_location[libname]

        if path is not None and not os.path.exists(path):
            # the mac/win default location does not exist.
            return None

    return load_library_handle(path)

def load_library_handle(path):
    """Load the library, return the ctypes handle."""

    if path is None or path in ['None', 'none']:
        # Either could not find a library via ctypes or user-configuration-file,
        # or we could not find it in any of the default locations.
        # This is probably a very old linux.
        return None

    try:
        if os.name == "nt":
            opj_lib = ctypes.windll.LoadLibrary(path)
        else:
            opj_lib = ctypes.CDLL(path)
    except (TypeError, OSError):
       msg = '"Library {0}" could not be loaded.  Operating in degraded mode.'
       msg = msg.format(path)
       warnings.warn(msg, UserWarning)
       opj_lib = None

    return opj_lib

def read_config_file(libname):
    """
    Extract library locations from a configuration file.

    Parameters
    ----------
    libname : str
        One of either 'openjp2' or 'openjpeg'

    Returns
    -------
    path : None or str
        None if no location is specified, otherwise a path to the library
    """
    filename = glymurrc_fname()
    if filename is not None:
        # Read the configuration file for the library location.
        parser = ConfigParser()
        parser.read(filename)
        try:
            path = parser.get('library', libname)
        except NoOptionError:
            path = None

    return path

def glymur_config():
    """
    Try to ascertain locations of openjp2, openjpeg libraries.

    Returns
    -------
    tpl : tuple
        tuple of library handles
    """
    lst = []
    for libname in ['openjp2', 'openjpeg']:
        lst.append(load_openjpeg_library(libname))
    if all(handle is None for handle in lst):
        msg = "Neither the openjp2 nor the openjpeg library could be loaded.  "
        raise IOError(msg)
    return tuple(lst)

def get_configdir():
    """Return string representing the configuration directory.

    Default is $HOME/.config/glymur.  You can override this with the
    XDG_CONFIG_HOME environment variable.
    """
    if 'XDG_CONFIG_HOME' in os.environ:
        return os.path.join(os.environ['XDG_CONFIG_HOME'], 'glymur')

    if 'HOME' in os.environ and os.name != 'nt':
        # HOME is set by WinPython to something unusual, so we don't
        # necessarily want that.
        return os.path.join(os.environ['HOME'], '.config', 'glymur')

    # Last stand.  Should handle windows... others?
    return os.path.join(os.path.expanduser('~'), 'glymur')
<|endoftext|>


<commit_before>import math
import operator

def euclideanDistance(firstPoint, secondPoint, length):
  distance = 0
  for i in xrange(length):
    paramDifference = firstPoint[i] - secondPoint[i]
    distance += pow(paramDifference, 2)
  return math.sqrt(distance)

class Sample(object):

  def __init__(self, input, output):
    self.input = input
    self.output = output

class Classifier(object):

  def __init__(self, samples):
    self.samples = samples

  def neighbors(self, point, k):
	  distances = []
	  numParams = len(point)
	  for i in xrange(len(self.samples)):
		  distance = euclideanDistance(point, self.samples[i].input, numParams)
		  distances.append((self.samples[i], distance))
	  distances.sort(key = operator.itemgetter(1))
	  neighbors = []
	  for i in xrange(k):
		  neighbors.append(distances[i][0])
	  return neighbors

  def voteResponse(self, neighbors):
	  votes = {}
	  for i in xrange(len(neighbors)):
		  response = neighbors[i].output
		  if response in votes:
			  votes[response] += 1
		  else:
			  votes[response] = 1
	  sortedVotes = sorted(votes.iteritems(), key=operator.itemgetter(1), reverse=True)
	  return sortedVotes[0][0]

  def classify(self, point, k):
    nearest = self.neighbors(point, k)
    result = self.voteResponse(nearest)
    return result

  def addSample(self, sample):
	  self.samples.append(sample)
<commit_msg>Add comments<commit_after>import math
import operator

def euclideanDistance(firstPoint, secondPoint, length):
  #Calculate the distance between firstPoint and secondPoint, which are arrays of size length.
  distance = 0
  for i in xrange(length):
    paramDifference = firstPoint[i] - secondPoint[i]
    distance += pow(paramDifference, 2)
  return math.sqrt(distance)

class Sample(object):
  #Represents a single data point in the "lazy" learning model.

  def __init__(self, input, output):
    self.input = input
    self.output = output

class Classifier(object):

  def __init__(self, samples):
    self.samples = samples #A list of Sample instances

  def neighbors(self, point, k):
  	  #Finds the k nearest neighbors in self.samples to the input point.
	  distances = []
	  numParams = len(point)
	  for i in xrange(len(self.samples)):
		  distance = euclideanDistance(point, self.samples[i].input, numParams)
		  distances.append((self.samples[i], distance))
	  distances.sort(key = operator.itemgetter(1))
	  neighbors = []
	  for i in xrange(k):
		  neighbors.append(distances[i][0])
	  return neighbors

  def voteResponse(self, neighbors):
  	  #Given a set of possible Sample instances (neighbors), have them vote for an output.
	  votes = {}
	  for i in xrange(len(neighbors)):
		  response = neighbors[i].output
		  if response in votes:
			  votes[response] += 1
		  else:
			  votes[response] = 1
	  sortedVotes = sorted(votes.iteritems(), key=operator.itemgetter(1), reverse=True)
	  return sortedVotes[0][0]

  def classify(self, point, k):
    #Find the output of the classifier for an input point.
    nearest = self.neighbors(point, k)
    result = self.voteResponse(nearest)
    return result

  def addSample(self, sample):
    #Add a Sample instance to the current classifier dataset.
    self.samples.append(sample)
<|endoftext|>


<commit_before>from random import randint
from operator import itemgetter
# import matplotlib.pyplot as plt

from collections import OrderedDict
# from levenshteinDistance import levenshtein as ld

#------------------------
# shared variables:
#------------------------

words = OrderedDict()
words['Eng'] = ''
words['pie'] = ''
words['pa'] = ''
words['pii'] = ''
words['pbs'] = ''
words['ps'] = ''

outputFilename = 'output.txt'

allophones = {
    'aeiou' : 'a',
    'bp' : 'b',
    'cjsz' : 'z',
    'dt' : 'd',
    'fv' : 'v',
    'gkq' : 'g',
    'hx' : 'h',
    'lr' : 'l',
    'mn' : 'm',
    'w' : 'w',
    'y' : 'y'
}

#------------------------
# functions:
#------------------------

def respellWithInitialVowelAndConsonants(word):
    for char in word[1:]:
        if char in 'aeiou':
            word = word[0] + word[1:].replace(char,'')
    return word

def respellWithAllophones(word):
    for char in word:
        for allo in allophones:
            if char in allo:
                word = word.replace(char,allophones[allo])
    return word

def combineOverlappingWords(shortList):
    for language in shortList:
        for otherlanguage in shortList:
            if language != otherlanguage and language != 'Eng' and otherlanguage != 'Eng':
                a = shortList[language]
                b = shortList[otherlanguage]
                for i in range(1, len(b)):
                    if a.endswith(b[:i]):
                        shortList[otherlanguage] = ''
                        shortList[language] = a+b[i:]
    return shortList

# def evaluateScore_Levenshtein(word,originalWords):
#     score = 0
#
#     for lang in originalWords:
#         score += ld(word,lang)
#
#     return score

def evaluateScore_AlloWithVowels(word,originalWords):
    score = 0
    scoreLangs = [0] * len(originalWords)

    leastEfficientWord = ''.join(originalWords)

    # ABZDAVG allo w/ vowels

    alloWithVowels = respellWithAllophones(word)
    #print 'Allophone Form of Word, with Vowels: ', alloWithVowels

    alloOriginalWords = list(originalWords) # careful with creating references that overwrite!

    for index, srcWord in enumerate(alloOriginalWords):
        alloOriginalWords[index] = respellWithAllophones(srcWord)

    #print alloOriginalWords

    # get preliminary scores for each language:
    for lang, srcWordAllo in enumerate(alloOriginalWords):
        for i in range(len(srcWordAllo)):
            head = srcWordAllo[:i]
            if head in respellWithAllophones(word):
                # add to score per matching letter of word:
                scoreLangs[lang] += 1

    # adjust language scores by number of characters in original words:
    for lang, srcWordAllo in enumerate(alloOriginalWords):
        scoreLangs[lang] -= len(srcWordAllo)

    # language scores are weighted in reverse order
    scoreLangs.reverse()

    for wt, lang in enumerate(scoreLangs):
        score += lang + lang * ((wt+1)/10.0) # make weightings like these to make gradient of influence:  0.1, 0.2, 0.3, 0.4, 0.5
    #print 'language score contribution: ', score

    # get preliminary score for word length:
    scoreLen = (len(leastEfficientWord) - len(word)) # score increases with shorter word
    scoreLen *= 1.1 # this is the weighting for length score
    #print 'word length contribution', scoreLen
    score += scoreLen

    return round(score,2)

def evaluateScore_ConsonantsInOrder(word,originalWords):
    score = 0
    scoreLangs = [0] * len(originalWords)

    leastEfficientWord = ''.join(originalWords)

    alloConsonants = list(originalWords) # careful with creating references that overwrite!
    alloOfNewWord = respellWithAllophones(word).replace('a','').replace('e','').replace('i','').replace('o','').replace('u','')

    #print alloOfNewWord

    for index, srcWord in enumerate(alloConsonants):
        alloConsonants[index] = respellWithAllophones(srcWord).replace('a','').replace('e','').replace('i','').replace('o','').replace('u','')

    #print alloConsonants

    # BZDVG

    # go through each language's test pattern:
    for lang, testPattern in enumerate(alloConsonants):
        currentLetterPos = 0
        # go through as many letters of that test pattern as possible:
        for i in range(1,len(testPattern)):
            # if that letter is found in new word then update current letter position (= index+1 since list indices start at 0):
            if testPattern[i] in alloOfNewWord:
                #print testPattern[i]
                currentLetterPos = i+1
        # use full word length - the current letter into the test pattern as the score for that language
        scoreLangs[lang] = currentLetterPos - len(originalWords[lang])
        currentLetterPos = 0
        #print scoreLangs

    # language scores are weighted in reverse order
    scoreLangs.reverse()

    for wt, lang in enumerate(scoreLangs):
        score += lang + lang * ((wt+1)/10.0) # make weightings like these to make gradient of influence:  0.1, 0.2, 0.3, 0.4, 0.5

    # get preliminary score for word length:
    scoreLen = (len(leastEfficientWord) - len(word)) # score increases with shorter word
    scoreLen *= 1.1 # this is the weighting for length score
    #print 'word length contribution', scoreLen
    score += scoreLen

    return round(score,2)

def evaluateScore_LettersFromEachSource(word,originalWords):
    score = 0
    for letter in word:
        for srcWord in originalWords:
            # encourage using words with letters found in all source words
            score += 1 if letter in srcWord else 0
    return score

def penalizeRepeatedLetterSequences(word):
    score = 0
    currentLetter = ''
    for letter in word:
        if letter == currentLetter:
            score -= 1
        else:
            currentLetter = letter
    return score

def penalizeLength(word):
    score = -len(word)
    return score

def evaluate(line):
    newWord = line.split(',')[0]
    originalWords = line.split(',')[2:]

    score = 0
    score += evaluateScore_AlloWithVowels(newWord, originalWords)
    score += evaluateScore_ConsonantsInOrder(newWord, originalWords)
    # score -= evaluateScore_Levenshtein(newWord, originalWords)
    score += evaluateScore_LettersFromEachSource(newWord, originalWords)
    score += penalizeRepeatedLetterSequences(newWord)
    score += penalizeLength(newWord)
    return round(score, 2)

def getSourceWords(data):
    return data.split(',')[2:][:-1]

def generateNewIndividual():
    outputInstructions = []
    # possibleInstructions = [0,1,2,3,4,'+','+','x'] # make '+' more likely (heuristically seems good)
    for i in range(25):
        index = randint(0,len(possibleInstructions)-1)
        instruction = possibleInstructions[index]
        if instruction == 'x':
            if outputInstructions != '':
                break
        else:
            outputInstructions.append(instruction)
    return outputInstructions

def generateNewWord(srcWords, instructions):
    newWord = []
    sourceWords = srcWords
    i = 0
    for instruction in instructions:
        if instruction == 'x':
            break
        elif instruction == '+':
            i += 1
        else:
            sourceWord = sourceWords[instruction]
            if i < len(sourceWord):
                newWord.append(sourceWord[i])
    newWord = ''.join(newWord)
    return newWord

def sortByScore(population):
    population.sort(key=itemgetter(0), reverse=True)

def getBestAlgo():
    # assumes first one is best
    bestSoFar = population[0]
    return bestSoFar

def printOnSepLines(arr):
    for line in arr:
        print(line)

def updateScoreHistory():
    # assumes first one is best
    currentBestScore = population[0][0]
    scoreHistory.append(currentBestScore)

def updateWordHistory():
    wordHistory.append(population[0][1].split(',',1)[0])

#------------------------
# main part of the program:
#------------------------

possibleInstructions = [0,1,2,3,4,'+','+','x'] # make '+' more likely (heuristically seems good)

# data = '+,long,tcan,largo,lamba,towil,dlini,' # tcanlartowdlam
data = '0,use,yun,usa,istemal,istemal,potrebi,' # yunsastempot
srcWords = getSourceWords(data)
engWord = data.split(',')[1]

popSize = 10
numGenerations = 1000
epochMilestone = numGenerations//10
population = []
scoreHistory = []
wordHistory = []

# initialize population
for i in range(popSize):
    instructions = generateNewIndividual()
    newWord = generateNewWord(srcWords, instructions)
    entry = newWord + ',' + ','.join(srcWords) + ','
    score = evaluate(entry)
    individual = [score, entry, instructions]
    population.append(individual)

# train
for i in range(numGenerations):
    # sort by score
    sortByScore(population)
    # printOnSepLines(population)

    # update score history after sorting by score
    updateScoreHistory()

    # update word history after sorting by score
    if i%epochMilestone == 0:
        updateWordHistory()

    # remove lower scorers
    halfOfPop = popSize//2
    for i in range(halfOfPop):
        population.pop()

    # add new random individuals to population
    halfOfHalf = halfOfPop//2
    for i in range(halfOfHalf):
        instructions = generateNewIndividual()
        newWord = generateNewWord(srcWords, instructions)
        entry = newWord + ',' + engWord + ',' + ','.join(srcWords) + ',' # should have 7 commas
        score = evaluate(entry)
        individual = [score, entry, instructions]
        population.append(individual)

    # remove duplicate individuals
    mySet = []
    for indiv in population:
        if indiv not in mySet:
            mySet.append(indiv)
    duplicatesToReplace = len(population) - len(mySet)
    population = list(mySet)

    # add variations of existing individuals in population
    restOfPop = halfOfPop - halfOfHalf + duplicatesToReplace
    for i in range(restOfPop):
        index = randint(0,len(population)-1)
        instructions_toMutate = list(population[index][2]) # hacky: use list() to make an actual copy, not a reference
        if len(instructions_toMutate) > 0:
            for i in range(3):
                # mutate instructions
                index_toMutate = randint(0,len(instructions_toMutate)-1)
                instruction_toReplace = possibleInstructions[ randint(0,len(possibleInstructions)-1) ]
                if instruction_toReplace != 'x':
                    instructions_toMutate[index_toMutate] = instruction_toReplace
                else:
                    instructions_toMutate = instructions_toMutate[index_toMutate-1:]
        else:
            instructions_toMutate = ''
        instructions = instructions_toMutate
        newWord = generateNewWord(srcWords, instructions)
        entry = newWord + ',' + engWord + ',' + ','.join(srcWords) + ',' # should have 7 commas
        score = evaluate(entry)
        individual = [score, entry, instructions]
        population.append(individual)

# sort by score
sortByScore(population)
print('\nFINAL CANDIDATES:')
printOnSepLines(population)

# save the best so far
bestSoFar = getBestAlgo()
scoreBestSoFar, entryBestSoFar, instructionsBestSoFar = bestSoFar
print('\nBEST SO FAR:')
print(bestSoFar)

print('\nORIGINALLY:')
original = 'yunsastempot,use,yun,usa,istemal,istemal,potrebi,'
# original = 'tcanlartowdlam,long,tcan,largo,lamba,towil,dlini,'
print(evaluate(original), original)

print('\nIF USE BEST SO FAR ON DIFFERENT INPUT:')
data = '+,long,tcan,largo,lamba,towil,dlini,' # can use this to check still outputs same newWord
# data = '0,use,yun,usa,istemal,istemal,potrebi,'
srcWords = getSourceWords(data)
engWord = data.split(',')[1]
newWord = generateNewWord(srcWords, instructionsBestSoFar)
entry = newWord + ',' + engWord + ',' + ','.join(srcWords) + ',' # should have 7 commas
score = evaluate(entry)
individual = [score, entry, instructionsBestSoFar]
print(individual)

original = 'tcanlartowdlam,long,tcan,largo,lamba,towil,dlini,'
print('vs')
print(evaluate(original), original)

# show word history
print('\nBEST SCORERS AT EVERY '+str(epochMilestone)+' GENERATIONS:')
print(wordHistory)

# # plot score over generations
# plt.plot(scoreHistory)
# plt.title('Score History')
# plt.show()

# TODO save best scorer externally

# TODO use best scorer saved externally

# TODO train over multiple examples
<commit_msg>add notice that its running<commit_after>from random import randint
from operator import itemgetter
# import matplotlib.pyplot as plt

from collections import OrderedDict
# from levenshteinDistance import levenshtein as ld

#------------------------
# shared variables:
#------------------------

words = OrderedDict()
words['Eng'] = ''
words['pie'] = ''
words['pa'] = ''
words['pii'] = ''
words['pbs'] = ''
words['ps'] = ''

outputFilename = 'output.txt'

allophones = {
    'aeiou' : 'a',
    'bp' : 'b',
    'cjsz' : 'z',
    'dt' : 'd',
    'fv' : 'v',
    'gkq' : 'g',
    'hx' : 'h',
    'lr' : 'l',
    'mn' : 'm',
    'w' : 'w',
    'y' : 'y'
}

#------------------------
# functions:
#------------------------

def respellWithInitialVowelAndConsonants(word):
    for char in word[1:]:
        if char in 'aeiou':
            word = word[0] + word[1:].replace(char,'')
    return word

def respellWithAllophones(word):
    for char in word:
        for allo in allophones:
            if char in allo:
                word = word.replace(char,allophones[allo])
    return word

def combineOverlappingWords(shortList):
    for language in shortList:
        for otherlanguage in shortList:
            if language != otherlanguage and language != 'Eng' and otherlanguage != 'Eng':
                a = shortList[language]
                b = shortList[otherlanguage]
                for i in range(1, len(b)):
                    if a.endswith(b[:i]):
                        shortList[otherlanguage] = ''
                        shortList[language] = a+b[i:]
    return shortList

# def evaluateScore_Levenshtein(word,originalWords):
#     score = 0
#
#     for lang in originalWords:
#         score += ld(word,lang)
#
#     return score

def evaluateScore_AlloWithVowels(word,originalWords):
    score = 0
    scoreLangs = [0] * len(originalWords)

    leastEfficientWord = ''.join(originalWords)

    # ABZDAVG allo w/ vowels

    alloWithVowels = respellWithAllophones(word)
    #print 'Allophone Form of Word, with Vowels: ', alloWithVowels

    alloOriginalWords = list(originalWords) # careful with creating references that overwrite!

    for index, srcWord in enumerate(alloOriginalWords):
        alloOriginalWords[index] = respellWithAllophones(srcWord)

    #print alloOriginalWords

    # get preliminary scores for each language:
    for lang, srcWordAllo in enumerate(alloOriginalWords):
        for i in range(len(srcWordAllo)):
            head = srcWordAllo[:i]
            if head in respellWithAllophones(word):
                # add to score per matching letter of word:
                scoreLangs[lang] += 1

    # adjust language scores by number of characters in original words:
    for lang, srcWordAllo in enumerate(alloOriginalWords):
        scoreLangs[lang] -= len(srcWordAllo)

    # language scores are weighted in reverse order
    scoreLangs.reverse()

    for wt, lang in enumerate(scoreLangs):
        score += lang + lang * ((wt+1)/10.0) # make weightings like these to make gradient of influence:  0.1, 0.2, 0.3, 0.4, 0.5
    #print 'language score contribution: ', score

    # get preliminary score for word length:
    scoreLen = (len(leastEfficientWord) - len(word)) # score increases with shorter word
    scoreLen *= 1.1 # this is the weighting for length score
    #print 'word length contribution', scoreLen
    score += scoreLen

    return round(score,2)

def evaluateScore_ConsonantsInOrder(word,originalWords):
    score = 0
    scoreLangs = [0] * len(originalWords)

    leastEfficientWord = ''.join(originalWords)

    alloConsonants = list(originalWords) # careful with creating references that overwrite!
    alloOfNewWord = respellWithAllophones(word).replace('a','').replace('e','').replace('i','').replace('o','').replace('u','')

    #print alloOfNewWord

    for index, srcWord in enumerate(alloConsonants):
        alloConsonants[index] = respellWithAllophones(srcWord).replace('a','').replace('e','').replace('i','').replace('o','').replace('u','')

    #print alloConsonants

    # BZDVG

    # go through each language's test pattern:
    for lang, testPattern in enumerate(alloConsonants):
        currentLetterPos = 0
        # go through as many letters of that test pattern as possible:
        for i in range(1,len(testPattern)):
            # if that letter is found in new word then update current letter position (= index+1 since list indices start at 0):
            if testPattern[i] in alloOfNewWord:
                #print testPattern[i]
                currentLetterPos = i+1
        # use full word length - the current letter into the test pattern as the score for that language
        scoreLangs[lang] = currentLetterPos - len(originalWords[lang])
        currentLetterPos = 0
        #print scoreLangs

    # language scores are weighted in reverse order
    scoreLangs.reverse()

    for wt, lang in enumerate(scoreLangs):
        score += lang + lang * ((wt+1)/10.0) # make weightings like these to make gradient of influence:  0.1, 0.2, 0.3, 0.4, 0.5

    # get preliminary score for word length:
    scoreLen = (len(leastEfficientWord) - len(word)) # score increases with shorter word
    scoreLen *= 1.1 # this is the weighting for length score
    #print 'word length contribution', scoreLen
    score += scoreLen

    return round(score,2)

def evaluateScore_LettersFromEachSource(word,originalWords):
    score = 0
    for letter in word:
        for srcWord in originalWords:
            # encourage using words with letters found in all source words
            score += 1 if letter in srcWord else 0
    return score

def penalizeRepeatedLetterSequences(word):
    score = 0
    currentLetter = ''
    for letter in word:
        if letter == currentLetter:
            score -= 1
        else:
            currentLetter = letter
    return score

def penalizeLength(word):
    score = -len(word)
    return score

def evaluate(line):
    newWord = line.split(',')[0]
    originalWords = line.split(',')[2:]

    score = 0
    score += evaluateScore_AlloWithVowels(newWord, originalWords)
    score += evaluateScore_ConsonantsInOrder(newWord, originalWords)
    # score -= evaluateScore_Levenshtein(newWord, originalWords)
    score += evaluateScore_LettersFromEachSource(newWord, originalWords)
    score += penalizeRepeatedLetterSequences(newWord)
    score += penalizeLength(newWord)
    return round(score, 2)

def getSourceWords(data):
    return data.split(',')[2:][:-1]

def generateNewIndividual():
    outputInstructions = []
    # possibleInstructions = [0,1,2,3,4,'+','+','x'] # make '+' more likely (heuristically seems good)
    for i in range(25):
        index = randint(0,len(possibleInstructions)-1)
        instruction = possibleInstructions[index]
        if instruction == 'x':
            if outputInstructions != '':
                break
        else:
            outputInstructions.append(instruction)
    return outputInstructions

def generateNewWord(srcWords, instructions):
    newWord = []
    sourceWords = srcWords
    i = 0
    for instruction in instructions:
        if instruction == 'x':
            break
        elif instruction == '+':
            i += 1
        else:
            sourceWord = sourceWords[instruction]
            if i < len(sourceWord):
                newWord.append(sourceWord[i])
    newWord = ''.join(newWord)
    return newWord

def sortByScore(population):
    population.sort(key=itemgetter(0), reverse=True)

def getBestAlgo():
    # assumes first one is best
    bestSoFar = population[0]
    return bestSoFar

def printOnSepLines(arr):
    for line in arr:
        print(line)

def updateScoreHistory():
    # assumes first one is best
    currentBestScore = population[0][0]
    scoreHistory.append(currentBestScore)

def updateWordHistory():
    wordHistory.append(population[0][1].split(',',1)[0])

#------------------------
# main part of the program:
#------------------------

print('\n...Running...')

possibleInstructions = [0,1,2,3,4,'+','+','x'] # make '+' more likely (heuristically seems good)

# data = '+,long,tcan,largo,lamba,towil,dlini,' # tcanlartowdlam
data = '0,use,yun,usa,istemal,istemal,potrebi,' # yunsastempot
srcWords = getSourceWords(data)
engWord = data.split(',')[1]

popSize = 10
numGenerations = 1000
epochMilestone = numGenerations//10
population = []
scoreHistory = []
wordHistory = []

# initialize population
for i in range(popSize):
    instructions = generateNewIndividual()
    newWord = generateNewWord(srcWords, instructions)
    entry = newWord + ',' + ','.join(srcWords) + ','
    score = evaluate(entry)
    individual = [score, entry, instructions]
    population.append(individual)

# train
for i in range(numGenerations):
    # sort by score
    sortByScore(population)
    # printOnSepLines(population)

    # update score history after sorting by score
    updateScoreHistory()

    # update word history after sorting by score
    if i%epochMilestone == 0:
        updateWordHistory()

    # remove lower scorers
    halfOfPop = popSize//2
    for i in range(halfOfPop):
        population.pop()

    # add new random individuals to population
    halfOfHalf = halfOfPop//2
    for i in range(halfOfHalf):
        instructions = generateNewIndividual()
        newWord = generateNewWord(srcWords, instructions)
        entry = newWord + ',' + engWord + ',' + ','.join(srcWords) + ',' # should have 7 commas
        score = evaluate(entry)
        individual = [score, entry, instructions]
        population.append(individual)

    # remove duplicate individuals
    mySet = []
    for indiv in population:
        if indiv not in mySet:
            mySet.append(indiv)
    duplicatesToReplace = len(population) - len(mySet)
    population = list(mySet)

    # add variations of existing individuals in population
    restOfPop = halfOfPop - halfOfHalf + duplicatesToReplace
    for i in range(restOfPop):
        index = randint(0,len(population)-1)
        instructions_toMutate = list(population[index][2]) # hacky: use list() to make an actual copy, not a reference
        if len(instructions_toMutate) > 0:
            for i in range(3):
                # mutate instructions
                index_toMutate = randint(0,len(instructions_toMutate)-1)
                instruction_toReplace = possibleInstructions[ randint(0,len(possibleInstructions)-1) ]
                if instruction_toReplace != 'x':
                    instructions_toMutate[index_toMutate] = instruction_toReplace
                else:
                    instructions_toMutate = instructions_toMutate[index_toMutate-1:]
        else:
            instructions_toMutate = ''
        instructions = instructions_toMutate
        newWord = generateNewWord(srcWords, instructions)
        entry = newWord + ',' + engWord + ',' + ','.join(srcWords) + ',' # should have 7 commas
        score = evaluate(entry)
        individual = [score, entry, instructions]
        population.append(individual)

# sort by score
sortByScore(population)
print('\nFINAL CANDIDATES:')
printOnSepLines(population)

# save the best so far
bestSoFar = getBestAlgo()
scoreBestSoFar, entryBestSoFar, instructionsBestSoFar = bestSoFar
print('\nBEST SO FAR:')
print(bestSoFar)

print('\nORIGINALLY:')
original = 'yunsastempot,use,yun,usa,istemal,istemal,potrebi,'
# original = 'tcanlartowdlam,long,tcan,largo,lamba,towil,dlini,'
print(evaluate(original), original)

print('\nIF USE BEST SO FAR ON DIFFERENT INPUT:')
data = '+,long,tcan,largo,lamba,towil,dlini,' # can use this to check still outputs same newWord
# data = '0,use,yun,usa,istemal,istemal,potrebi,'
srcWords = getSourceWords(data)
engWord = data.split(',')[1]
newWord = generateNewWord(srcWords, instructionsBestSoFar)
entry = newWord + ',' + engWord + ',' + ','.join(srcWords) + ',' # should have 7 commas
score = evaluate(entry)
individual = [score, entry, instructionsBestSoFar]
print(individual)

original = 'tcanlartowdlam,long,tcan,largo,lamba,towil,dlini,'
print('vs')
print(evaluate(original), original)

# show word history
print('\nBEST SCORERS AT EVERY '+str(epochMilestone)+' GENERATIONS:')
print(wordHistory)

# # plot score over generations
# plt.plot(scoreHistory)
# plt.title('Score History')
# plt.show()

# TODO save best scorer externally

# TODO use best scorer saved externally

# TODO train over multiple examples
<|endoftext|>


<commit_before># Copyright (c) 2012 Santosh Philip
# =======================================================================
#  Distributed under the MIT License.
#  (See accompanying file LICENSE or copy at
#  http://opensource.org/licenses/MIT)
# =======================================================================

"""sub class bunch in steps going from data, aliases, functions"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import copy
from bunch import Bunch

class BadEPFieldError(Exception):
    """an exception"""
    pass

class RangeError(Exception):
    """an Exception"""
    pass

def somevalues(ddtt):
    """returns some values"""
    return ddtt.Name, ddtt.Construction_Name, ddtt.obj

def extendlist(lst, i, value=''):
    """extend the list so that you have i-th value"""
    if i < len(lst):
        pass
    else:
        lst.extend([value, ] * (i - len(lst) + 1))

class EpBunch_1(Bunch):
    """Has data in bunch"""
    def __init__(self, obj, objls, objidd, *args, **kwargs):
        super(EpBunch_1, self).__init__(*args, **kwargs)
        self.obj = obj
        self.objls = objls
        self.objidd = objidd

    @property
    def fieldnames(self):
        return self.objls

    @property
    def fieldvalues(self):
        return self.obj

    def __setattr__(self, name, value):
        if name in ('obj', 'objls', 'objidd'):
            super(EpBunch_1, self).__setattr__(name, value)
            return None
        elif name in self['objls']:
            i = self['objls'].index(name)
            try:
                self['obj'][i] = value
            except IndexError:
                extendlist(self['obj'], i)
                self['obj'][i] = value
        else:
            astr = "unable to find field %s" % (name, )
            raise BadEPFieldError(astr)
    def __getattr__(self, name):
        if name in ('obj', 'objls', 'objidd'):
            return super(EpBunch_1, self).__getattr__(name)
        elif name in self['objls']:
            i = self['objls'].index(name)
            try:
                return self['obj'][i]
            except IndexError:
                return ''
        else:
            astr = "unable to find field %s" % (name, )
            raise BadEPFieldError(astr)
    def __repr__(self):
        """print this as an idf snippet"""
        lines = [str(val) for val in self.obj]
        comments = [comm.replace('_', ' ') for comm in self.objls]
        lines[0] = "%s," % (lines[0], ) # comma after first line
        for i, line in enumerate(lines[1:-1]):
            lines[i + 1] = '    %s,' % (line, ) # indent and comma
        lines[-1] = '    %s;' % (lines[-1], )# ';' after last line
        lines = [line.ljust(26) for line in lines] # ljsut the lines
        filler = '%s    !- %s'
        nlines = [filler % (line, comm) for line,
                  comm in zip(lines[1:], comments[1:])]# adds comments to line
        nlines.insert(0, lines[0])# first line without comment
        astr = '\n'.join(nlines)
        return '\n%s\n' % (astr, )
    def __str__(self):
        """same as __repr__"""
        # needed if YAML is installed. See issue 67
        return self.__repr__()

class EpBunch_2(EpBunch_1):
    """Has data, aliases in bunch"""
    def __init__(self, obj, objls, objidd, *args, **kwargs):
        super(EpBunch_2, self).__init__(obj, objls, objidd, *args, **kwargs)
    def __setattr__(self, name, value):
        if name == '__aliases':
            self[name] = value
            return None
        try:
            origname = self['__aliases'][name]
            super(EpBunch_2, self).__setattr__(origname, value)
        except KeyError:
            super(EpBunch_2, self).__setattr__(name, value)
    def __getattr__(self, name):
        if name == '__aliases':
            return super(EpBunch_2, self).__getattr__(name)
        try:
            origname = self['__aliases'][name]
            return super(EpBunch_2, self).__getattr__(origname)
        except KeyError:
            return super(EpBunch_2, self).__getattr__(name)

class EpBunch_3(EpBunch_2):
    """Has data, aliases, functions in bunch"""
    def __init__(self, obj, objls, objidd, *args, **kwargs):
        super(EpBunch_3, self).__init__(obj, objls, objidd, *args, **kwargs)
        self['__functions'] = {}
    def __setattr__(self, name, value):
        if name == '__functions':
            self[name] = value
            return None
        try:
            origname = self['__functions'][name]
            self[origname] = value
        except KeyError:
            super(EpBunch_3, self).__setattr__(name, value)
    def __getattr__(self, name):
        if name == '__functions':
            return self['__functions']
        try:
            func = self['__functions'][name]
            if isinstance(func, EpBunchFunctionClass):
                return func.func
            else:
                return func(self)
        except KeyError:
            return super(EpBunch_3, self).__getattr__(name)

class EpBunch_4(EpBunch_3):
    """implements __getitem__ and __setitem__"""
    def __init__(self, obj, objls, objidd, *args, **kwargs):
        super(EpBunch_4, self).__init__(obj, objls, objidd, *args, **kwargs)
    def __getitem__(self, key):
        if key in ('obj', 'objls', 'objidd', '__functions', '__aliases'):
            return super(EpBunch_4, self).__getitem__(key)
        elif key in self['objls']:
            i = self['objls'].index(key)
            try:
                return self['obj'][i]
            except IndexError:
                return ''
        else:
            astr = "unknown field %s" % (key, )
            raise BadEPFieldError(astr)
    def __setitem__(self, key, value):
        if key in ('obj', 'objls', 'objidd', '__functions', '__aliases'):
            super(EpBunch_4, self).__setitem__(key, value)
            return None
        elif key in self['objls']:
            i = self['objls'].index(key)
            try:
                self['obj'][i] = value
            except IndexError:
                extendlist(self['obj'], i)
                self['obj'][i] = value

        else:
            astr = "unknown field %s" % (key, )
            raise BadEPFieldError(astr)

class EpBunchFunctionClass(object):
    """Exception Object"""
    pass

class GetRange(EpBunchFunctionClass):

    def __init__(self, arg):
        self.bch = arg

    def func(self, fieldname):
        """get the ranges for this field"""
        bch = self.bch
        keys = ['maximum', 'minimum', 'maximum<', 'minimum>', 'type']
        index = bch.objls.index(fieldname)
        fielddct_orig = bch.objidd[index]
        fielddct = copy.deepcopy(fielddct_orig)
        therange = {}
        for key in keys:
            therange[key] = fielddct.setdefault(key, None)
        if therange['type']:
            therange['type'] = therange['type'][0]
        if therange['type'] == 'real':
            for key in keys[:-1]:
                if therange[key]:
                    therange[key] = float(therange[key][0])
        if therange['type'] == 'integer':
            for key in keys[:-1]:
                if therange[key]:
                    therange[key] = int(therange[key][0])
        return therange

class CheckRange(EpBunchFunctionClass):

    def __init__(self, arg):
        self.bch = arg

    def func(self, fieldname):
        """throw exception if the out of range"""
        bch = self.bch
        fieldvalue = bch[fieldname]
        therange = bch.getrange(fieldname)
        if therange['maximum'] != None:
            if fieldvalue > therange['maximum']:
                astr = "Value %s is not less or equal to the 'maximum' of %s"
                astr = astr % (fieldvalue, therange['maximum'])
                raise RangeError(astr)
        if therange['minimum'] != None:
            if fieldvalue < therange['minimum']:
                astr = "Value %s is not greater or equal to the 'minimum' of %s"
                astr = astr % (fieldvalue, therange['minimum'])
                raise RangeError(astr)
        if therange['maximum<'] != None:
            if fieldvalue >= therange['maximum<']:
                astr = "Value %s is not less than the 'maximum<' of %s"
                astr = astr % (fieldvalue, therange['maximum<'])
                raise RangeError(astr)
        if  therange['minimum>'] != None:
            if fieldvalue <= therange['minimum>']:
                astr = "Value %s is not greater than the 'minimum>' of %s"
                astr = astr % (fieldvalue, therange['minimum>'])
                raise RangeError(astr)
        return fieldvalue

class EpBunch_5(EpBunch_4):
    """implements getrange, checkrange, fieldnames"""
    def __init__(self, obj, objls, objidd, *args, **kwargs):
        super(EpBunch_5, self).__init__(obj, objls, objidd, *args, **kwargs)
        self['__functions']['getrange'] = GetRange(self)
        self['__functions']['checkrange'] = CheckRange(self)

EpBunch = EpBunch_5
<commit_msg>Move registering of GetRange and SetRange into EpBunch_4<commit_after># Copyright (c) 2012 Santosh Philip
# =======================================================================
#  Distributed under the MIT License.
#  (See accompanying file LICENSE or copy at
#  http://opensource.org/licenses/MIT)
# =======================================================================

"""sub class bunch in steps going from data, aliases, functions"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import copy
from bunch import Bunch

class BadEPFieldError(Exception):
    """an exception"""
    pass

class RangeError(Exception):
    """an Exception"""
    pass

def somevalues(ddtt):
    """returns some values"""
    return ddtt.Name, ddtt.Construction_Name, ddtt.obj

def extendlist(lst, i, value=''):
    """extend the list so that you have i-th value"""
    if i < len(lst):
        pass
    else:
        lst.extend([value, ] * (i - len(lst) + 1))

class EpBunch_1(Bunch):
    """Has data in bunch"""
    def __init__(self, obj, objls, objidd, *args, **kwargs):
        super(EpBunch_1, self).__init__(*args, **kwargs)
        self.obj = obj
        self.objls = objls
        self.objidd = objidd

    @property
    def fieldnames(self):
        return self.objls

    @property
    def fieldvalues(self):
        return self.obj

    def __setattr__(self, name, value):
        if name in ('obj', 'objls', 'objidd'):
            super(EpBunch_1, self).__setattr__(name, value)
            return None
        elif name in self['objls']:
            i = self['objls'].index(name)
            try:
                self['obj'][i] = value
            except IndexError:
                extendlist(self['obj'], i)
                self['obj'][i] = value
        else:
            astr = "unable to find field %s" % (name, )
            raise BadEPFieldError(astr)
    def __getattr__(self, name):
        if name in ('obj', 'objls', 'objidd'):
            return super(EpBunch_1, self).__getattr__(name)
        elif name in self['objls']:
            i = self['objls'].index(name)
            try:
                return self['obj'][i]
            except IndexError:
                return ''
        else:
            astr = "unable to find field %s" % (name, )
            raise BadEPFieldError(astr)
    def __repr__(self):
        """print this as an idf snippet"""
        lines = [str(val) for val in self.obj]
        comments = [comm.replace('_', ' ') for comm in self.objls]
        lines[0] = "%s," % (lines[0], ) # comma after first line
        for i, line in enumerate(lines[1:-1]):
            lines[i + 1] = '    %s,' % (line, ) # indent and comma
        lines[-1] = '    %s;' % (lines[-1], )# ';' after last line
        lines = [line.ljust(26) for line in lines] # ljsut the lines
        filler = '%s    !- %s'
        nlines = [filler % (line, comm) for line,
                  comm in zip(lines[1:], comments[1:])]# adds comments to line
        nlines.insert(0, lines[0])# first line without comment
        astr = '\n'.join(nlines)
        return '\n%s\n' % (astr, )
    def __str__(self):
        """same as __repr__"""
        # needed if YAML is installed. See issue 67
        # unit test
        return self.__repr__()

class EpBunch_2(EpBunch_1):
    """Has data, aliases in bunch"""
    def __init__(self, obj, objls, objidd, *args, **kwargs):
        super(EpBunch_2, self).__init__(obj, objls, objidd, *args, **kwargs)
    def __setattr__(self, name, value):
        if name == '__aliases':
            self[name] = value
            return None
        try:
            origname = self['__aliases'][name]
            super(EpBunch_2, self).__setattr__(origname, value)
        except KeyError:
            super(EpBunch_2, self).__setattr__(name, value)
    def __getattr__(self, name):
        if name == '__aliases':
            # unit test
            return super(EpBunch_2, self).__getattr__(name)
        try:
            origname = self['__aliases'][name]
            return super(EpBunch_2, self).__getattr__(origname)
        except KeyError:
            return super(EpBunch_2, self).__getattr__(name)

class EpBunch_3(EpBunch_2):
    """Has data, aliases, functions in bunch"""
    def __init__(self, obj, objls, objidd, *args, **kwargs):
        super(EpBunch_3, self).__init__(obj, objls, objidd, *args, **kwargs)
        self['__functions'] = {}
    def __setattr__(self, name, value):
        if name == '__functions':
            self[name] = value
            return None
        try:
            origname = self['__functions'][name]
            # unit test
            self[origname] = value
        except KeyError:
            super(EpBunch_3, self).__setattr__(name, value)
    def __getattr__(self, name):
        if name == '__functions':
            # unit test
            return self['__functions']
        try:
            func = self['__functions'][name]
            if isinstance(func, EpBunchFunctionClass):
                return func.func
            else:
                return func(self)
        except KeyError:
            return super(EpBunch_3, self).__getattr__(name)

class EpBunch_4(EpBunch_3):
    """implements __getitem__ and __setitem__"""
    def __init__(self, obj, objls, objidd, *args, **kwargs):
        super(EpBunch_4, self).__init__(obj, objls, objidd, *args, **kwargs)
        self['__functions']['getrange'] = GetRange(self)
        self['__functions']['checkrange'] = CheckRange(self)

    def __getitem__(self, key):
        if key in ('obj', 'objls', 'objidd', '__functions', '__aliases'):
            return super(EpBunch_4, self).__getitem__(key)
        elif key in self['objls']:
            i = self['objls'].index(key)
            try:
                return self['obj'][i]
            except IndexError:
                return ''
        else:
            astr = "unknown field %s" % (key, )
            raise BadEPFieldError(astr)

    def __setitem__(self, key, value):
        if key in ('obj', 'objls', 'objidd', '__functions', '__aliases'):
            super(EpBunch_4, self).__setitem__(key, value)
            return None
        elif key in self['objls']:
            i = self['objls'].index(key)
            try:
                self['obj'][i] = value
            except IndexError:
                extendlist(self['obj'], i)
                self['obj'][i] = value
        else:
            astr = "unknown field %s" % (key, )
            raise BadEPFieldError(astr)

class EpBunchFunctionClass(object):
    """Exception Object"""
    pass

class GetRange(EpBunchFunctionClass):

    def __init__(self, arg):
        self.bch = arg

    def func(self, fieldname):
        """get the ranges for this field"""
        bch = self.bch
        keys = ['maximum', 'minimum', 'maximum<', 'minimum>', 'type']
        index = bch.objls.index(fieldname)
        fielddct_orig = bch.objidd[index]
        fielddct = copy.deepcopy(fielddct_orig)
        therange = {}
        for key in keys:
            therange[key] = fielddct.setdefault(key, None)
        if therange['type']:
            therange['type'] = therange['type'][0]
        if therange['type'] == 'real':
            for key in keys[:-1]:
                if therange[key]:
                    therange[key] = float(therange[key][0])
        if therange['type'] == 'integer':
            for key in keys[:-1]:
                if therange[key]:
                    therange[key] = int(therange[key][0])
        return therange

class CheckRange(EpBunchFunctionClass):

    def __init__(self, arg):
        self.bch = arg

    def func(self, fieldname):
        """throw exception if the out of range"""
        bch = self.bch
        fieldvalue = bch[fieldname]
        therange = bch.getrange(fieldname)
        if therange['maximum'] != None:
            if fieldvalue > therange['maximum']:
                astr = "Value %s is not less or equal to the 'maximum' of %s"
                astr = astr % (fieldvalue, therange['maximum'])
                raise RangeError(astr)
        if therange['minimum'] != None:
            if fieldvalue < therange['minimum']:
                astr = "Value %s is not greater or equal to the 'minimum' of %s"
                astr = astr % (fieldvalue, therange['minimum'])
                raise RangeError(astr)
        if therange['maximum<'] != None:
            if fieldvalue >= therange['maximum<']:
                astr = "Value %s is not less than the 'maximum<' of %s"
                astr = astr % (fieldvalue, therange['maximum<'])
                raise RangeError(astr)
        if  therange['minimum>'] != None:
            if fieldvalue <= therange['minimum>']:
                astr = "Value %s is not greater than the 'minimum>' of %s"
                astr = astr % (fieldvalue, therange['minimum>'])
                raise RangeError(astr)
        return fieldvalue

EpBunch = EpBunch_4
<|endoftext|>


<commit_before>#!/usr/bin/env python
import argparse
import string

def dec_to_bin(dec):
    rest = dec % 2
    if dec != 0:
        print "%s \t:\t 2 = %s \t-- Rest: %s" % (dec,int(dec/2),rest)
    if int(dec) != 0:
        binary = str(dec_to_bin(int(dec/2))) + str(rest)
        return binary
    else:
        return ""

def dec_to_hex(dec):
    substitution = {
        "10" : "A",
        "11" : "B",
        "12" : "C",
        "13" : "D",
        "14" : "E",
        "15" : "F"
    }
    rest = str(dec % 16)
    if dec != 0:
        print "%s \t:\t 16 = %s \t-- Rest: %s" % (dec,int(dec/16),rest)
    if rest in substitution:
        rest = rest.replace(rest,substitution[rest])

    if int(dec) != 0:
        hexa = str(dec_to_hex(int(dec/16))) + str(rest)
        return hexa
    else:
        return ""

def bin_to_dec(binary):
    decimal = 0
    reversed_binary = str(binary)[::-1]
    for digit in range(len(reversed_binary)):
        decimal = decimal + int(str(reversed_binary)[digit]) * (2 ** digit)

    return decimal

def hex_to_dec(hexa):
    substitution = {
        "a" : "10",
        "b" : "11",
        "c" : "12",
        "d" : "13",
        "e" : "14",
        "f" : "15"
    }
    """
    For further version, following code would inverse a decitionary, even when the values
    are not unique:
    inv_substitution = {}
    for k, v in substitution.iteritems():
        inv_substitution[v] = inv_substitution.get(v, [])
        inv_substitution[v].append(k)

    (found here: http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping)
    """

    decimal = 0
    rev_hex = str(hexa)[::-1].lower()
    for digit in range(len(rev_hex)):
        if rev_hex[digit] in substitution:
            new_hex = rev_hex[digit].replace(rev_hex[digit],substitution[rev_hex[digit]])
        else:
            new_hex = rev_hex[digit]

        decimal = decimal + int(new_hex) * (16 ** digit)

    return decimal

def hex_to_bin(hexa):
    return dec_to_bin(hex_to_dec(hexa))

def bin_to_hex(bin):
    return dec_to_hex(bin_to_dec(bin))

def is_binary(s):
    for digit in str(s):
        if digit != "0" and digit != "1":
            result = False
            break
        else:
            result = True
    return result

def main():
    parser = argparse.ArgumentParser(description='Covert hexadecimal, decimal and binary numbers.')
    parser.add_argument('-H', '--hex', type=str, help='hexadecimal number to convert', required=False, default=None)
    parser.add_argument('-b', '--binary', type=str, help='binary number to convert', required=False, default=None)
    parser.add_argument('-d', '--decimal', type=int, help='decimal number to convert', required=False, default=None)

    args = parser.parse_args()

    if args.hex:
        if all(c in string.hexdigits for c in args.hex) == True:
            print "%s(hex) = %s(dec)\n" % (args.hex, hex_to_dec(args.hex))
            binary = hex_to_bin(args.hex)
            print "%s(hex) = %s(bin)\n" % (args.hex,binary)
        else:
            print "%s is not a hexadecimal." % args.hex

    if args.binary:
        if is_binary(args.binary) == True:
            print "%s(bin) = %s(dec)\n" % (args.binary, bin_to_dec(args.binary))
            hexa = bin_to_hex(args.binary)
            print "%s(bin) = %s(hex)\n" % (args.binary,hexa)
        else:
            print "%s is not a binary number." % args.binary
    if args.decimal:
        print "%s(dec) = %s(hex)\n" % (args.decimal,dec_to_hex(args.decimal))
        print "%s(dec) = %s(bin)\n" % (args.decimal,dec_to_bin(args.decimal))
    if not args.decimal and not args.hex and not args.binary:
        parser.print_help()

if __name__ == "__main__":
    main()

<commit_msg>added check for postive number on input<commit_after>#!/usr/bin/env python
import argparse
import string

def dec_to_bin(dec):
    rest = dec % 2
    if dec != 0:
        print "%s \t:\t 2 = %s \t-- Rest: %s" % (dec,int(dec/2),rest)
    if int(dec) != 0:
        binary = str(dec_to_bin(int(dec/2))) + str(rest)
        return binary
    else:
        return ""

def dec_to_hex(dec):
    substitution = {
        "10" : "A",
        "11" : "B",
        "12" : "C",
        "13" : "D",
        "14" : "E",
        "15" : "F"
    }
    rest = str(dec % 16)
    if dec != 0:
        print "%s \t:\t 16 = %s \t-- Rest: %s" % (dec,int(dec/16),rest)
    if rest in substitution:
        rest = rest.replace(rest,substitution[rest])

    if int(dec) != 0:
        hexa = str(dec_to_hex(int(dec/16))) + str(rest)
        return hexa
    else:
        return ""

def bin_to_dec(binary):
    decimal = 0
    reversed_binary = str(binary)[::-1]
    for digit in range(len(reversed_binary)):
        decimal = decimal + int(str(reversed_binary)[digit]) * (2 ** digit)

    return decimal

def hex_to_dec(hexa):
    substitution = {
        "a" : "10",
        "b" : "11",
        "c" : "12",
        "d" : "13",
        "e" : "14",
        "f" : "15"
    }
    """
    For further version, following code would inverse a decitionary, even when the values
    are not unique:
    inv_substitution = {}
    for k, v in substitution.iteritems():
        inv_substitution[v] = inv_substitution.get(v, [])
        inv_substitution[v].append(k)

    (found here: http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping)
    """

    decimal = 0
    rev_hex = str(hexa)[::-1].lower()
    for digit in range(len(rev_hex)):
        if rev_hex[digit] in substitution:
            new_hex = rev_hex[digit].replace(rev_hex[digit],substitution[rev_hex[digit]])
        else:
            new_hex = rev_hex[digit]

        decimal = decimal + int(new_hex) * (16 ** digit)

    return decimal

def hex_to_bin(hexa):
    return dec_to_bin(hex_to_dec(hexa))

def bin_to_hex(bin):
    return dec_to_hex(bin_to_dec(bin))

def is_binary(s):
    for digit in str(s):
        if digit != "0" and digit != "1":
            result = False
            break
        else:
            result = True
    return result

def main():
    parser = argparse.ArgumentParser(description='Covert hexadecimal, decimal and binary numbers.')
    parser.add_argument('-H', '--hex', type=str, help='hexadecimal number to convert', required=False, default=None)
    parser.add_argument('-b', '--binary', type=str, help='binary number to convert', required=False, default=None)
    parser.add_argument('-d', '--decimal', type=int, help='positive decimal number to convert', required=False, default=None)

    args = parser.parse_args()

    if args.hex:
        if all(c in string.hexdigits for c in args.hex) == True:
            print "%s(hex) = %s(dec)\n" % (args.hex, hex_to_dec(args.hex))
            binary = hex_to_bin(args.hex)
            print "%s(hex) = %s(bin)\n" % (args.hex,binary)
        else:
            print "%s is not a hexadecimal." % args.hex

    if args.binary:
        if is_binary(args.binary) == True:
            print "%s(bin) = %s(dec)\n" % (args.binary, bin_to_dec(args.binary))
            hexa = bin_to_hex(args.binary)
            print "%s(bin) = %s(hex)\n" % (args.binary,hexa)
        else:
            print "%s is not a binary number." % args.binary

    if args.decimal and args.decimal > 0:
        print "%s(dec) = %s(hex)\n" % (args.decimal,dec_to_hex(args.decimal))
        print "%s(dec) = %s(bin)\n" % (args.decimal,dec_to_bin(args.decimal))
    else:
        print "%s is not a postive decimal number" % args.decimal

    if not args.decimal and not args.hex and not args.binary:
        parser.print_help()

if __name__ == "__main__":
    main()

<|endoftext|>