<commit_before>"""Model tests."""

from __future__ import unicode_literals
from contextlib import contextmanager

from django.template import Context
from django.test import TestCase
from django.test.client import RequestFactory
from django.utils.encoding import force_text

from el_pagination import (
    models as el_models,
    settings,
    utils,
)
from el_pagination.paginators import DefaultPaginator

@contextmanager
def local_settings(**kwargs):
    """Override local Django Endless Pagination settings.

    This context manager can be used in a way similar to Django own
    ``TestCase.settings()``.
    """
    original_values = []
    for key, value in kwargs.items():
        original_values.append([key, getattr(settings, key)])
        setattr(settings, key, value)
    try:
        yield
    finally:
        for key, value in original_values:
            setattr(settings, key, value)

class LocalSettingsTest(TestCase):

    def setUp(self):
        settings._LOCAL_SETTINGS_TEST = 'original'

    def tearDown(self):
        del settings._LOCAL_SETTINGS_TEST

    def test_settings_changed(self):
        # Check that local settings are changed.
        with local_settings(_LOCAL_SETTINGS_TEST='changed'):
            self.assertEqual('changed', settings._LOCAL_SETTINGS_TEST)

    def test_settings_restored(self):
        # Check that local settings are restored.
        with local_settings(_LOCAL_SETTINGS_TEST='changed'):
            pass
        self.assertEqual('original', settings._LOCAL_SETTINGS_TEST)

    def test_restored_after_exception(self):
        # Check that local settings are restored after an exception.
        with self.assertRaises(RuntimeError):
            with local_settings(_LOCAL_SETTINGS_TEST='changed'):
                raise RuntimeError()
            self.assertEqual('original', settings._LOCAL_SETTINGS_TEST)

def page_list_callable_arrows(number, num_pages):
    """Wrap ``el_pagination.utils.get_page_numbers``.

    Set first / last page arrows to True.
    """
    return utils.get_page_numbers(number, num_pages, arrows=True)

page_list_callable_dummy = lambda number, num_pages: [None]

class PageListTest(TestCase):

    def setUp(self):
        self.paginator = DefaultPaginator(range(30), 7, orphans=2)
        self.current_number = 2
        self.page_label = 'page'
        self.factory = RequestFactory()
        self.request = self.factory.get(
            self.get_path_for_page(self.current_number))
        self.pages = el_models.PageList(
            self.request, self.paginator.page(self.current_number),
            self.page_label, context=Context())

    def get_url_for_page(self, number):
        """Return a url for the given page ``number``."""
        return '?{0}={1}'.format(self.page_label, number)

    def get_path_for_page(self, number):
        """Return a path for the given page ``number``."""
        return '/' + self.get_url_for_page(number)

    def check_page(
            self, page, number, is_first, is_last, is_current, label=None):
        """Perform several assertions on the given page attrs."""
        if label is None:
            label = force_text(page.number)
        self.assertEqual(label, page.label)
        self.assertEqual(number, page.number)
        self.assertEqual(is_first, page.is_first)
        self.assertEqual(is_last, page.is_last)
        self.assertEqual(is_current, page.is_current)

    def check_page_list_callable(self, callable_or_path):
        """Check the provided *page_list_callable* is actually used."""
        with local_settings(PAGE_LIST_CALLABLE=callable_or_path):
            rendered = force_text(self.pages.get_rendered()).strip()
        expected = '...'
        self.assertEqual(expected, rendered)

    def test_length(self):
        # Ensure the length of the page list equals the number of pages.
        self.assertEqual(self.paginator.num_pages, len(self.pages))

    def test_paginated(self):
        # Ensure the *paginated* method returns True if the page list contains
        # more than one page, False otherwise.
        page = DefaultPaginator(range(10), 10).page(1)
        pages = el_models.PageList(self.request, page, self.page_label,
                                   context=Context())
        self.assertFalse(pages.paginated())
        self.assertTrue(self.pages.paginated())

    def test_first_page(self):
        # Ensure the attrs of the first page are correctly defined.
        page = self.pages.first()
        self.assertEqual('/', page.path)
        self.assertEqual('', page.url)
        self.check_page(page, 1, True, False, False)

    def test_last_page(self):
        # Ensure the attrs of the last page are correctly defined.
        page = self.pages.last()
        self.check_page(page, len(self.pages), False, True, False)

    def test_first_page_as_arrow(self):
        # Ensure the attrs of the first page are correctly defined when the
        # page is represented as an arrow.
        page = self.pages.first_as_arrow()
        self.assertEqual('/', page.path)
        self.assertEqual('', page.url)
        self.check_page(
            page, 1, True, False, False, label=settings.FIRST_LABEL)

    def test_last_page_as_arrow(self):
        # Ensure the attrs of the last page are correctly defined when the
        # page is represented as an arrow.
        page = self.pages.last_as_arrow()
        self.check_page(
            page, len(self.pages), False, True, False,
            label=settings.LAST_LABEL)

    def test_current_page(self):
        # Ensure the attrs of the current page are correctly defined.
        page = self.pages.current()
        self.check_page(page, self.current_number, False, False, True)

    def test_path(self):
        # Ensure the path of each page is correctly generated.
        for num, page in enumerate(list(self.pages)[1:]):
            expected = self.get_path_for_page(num + 2)
            self.assertEqual(expected, page.path)

    def test_url(self):
        # Ensure the path of each page is correctly generated.
        for num, page in enumerate(list(self.pages)[1:]):
            expected = self.get_url_for_page(num + 2)
            self.assertEqual(expected, page.url)

    def test_current_indexes(self):
        # Ensure the 1-based indexes of the first and last items on the current
        # page are correctly returned.
        self.assertEqual(8, self.pages.current_start_index())
        self.assertEqual(14, self.pages.current_end_index())

    def test_total_count(self):
        # Ensure the total number of objects is correctly returned.
        self.assertEqual(30, self.pages.total_count())

    def test_page_render(self):
        # Ensure the page is correctly rendered.
        page = self.pages.first()
        rendered_page = force_text(page.render_link())
        self.assertIn('href="/"', rendered_page)
        self.assertIn(page.label, rendered_page)

    def test_current_page_render(self):
        # Ensure the page is correctly rendered.
        page = self.pages.current()
        rendered_page = force_text(page.render_link())
        self.assertNotIn('href', rendered_page)
        self.assertIn(page.label, rendered_page)

    def test_page_list_render(self):
        # Ensure the page list is correctly rendered.
        rendered = force_text(self.pages.get_rendered())
        self.assertEqual(5, rendered.count('<a href'))
        self.assertIn(settings.PREVIOUS_LABEL, rendered)
        self.assertIn(settings.NEXT_LABEL, rendered)

    def test_page_list_render_using_arrows(self):
        # Ensure the page list is correctly rendered when using first / last
        # page arrows.
        page_list_callable = (
            'el_pagination.tests.test_models.page_list_callable_arrows')
        with local_settings(PAGE_LIST_CALLABLE=page_list_callable):
            rendered = force_text(self.pages.get_rendered())
        self.assertEqual(7, rendered.count('<a href'))
        self.assertIn(settings.FIRST_LABEL, rendered)
        self.assertIn(settings.LAST_LABEL, rendered)

    def test_page_list_render_just_one_page(self):
        # Ensure nothing is rendered if the page list contains only one page.
        page = DefaultPaginator(range(10), 10).page(1)
        pages = el_models.PageList(self.request, page, self.page_label,
                                   context=Context())
        self.assertEqual('', force_text(pages))

    def test_different_default_number(self):
        # Ensure the page path is generated based on the default number.
        pages = el_models.PageList(
            self.request, self.paginator.page(2), self.page_label,
            default_number=2, context=Context())
        self.assertEqual('/', pages.current().path)
        self.assertEqual(self.get_path_for_page(1), pages.first().path)

    def test_index_error(self):
        # Ensure an error if raised if a non existent page is requested.
        with self.assertRaises(IndexError):
            self.pages[len(self.pages) + 1]

    def test_previous(self):
        # Ensure the correct previous page is returned.
        previous_page = self.pages.previous()
        self.assertEqual(self.current_number - 1, previous_page.number)

    def test_next(self):
        # Ensure the correct next page is returned.
        next_page = self.pages.next()
        self.assertEqual(self.current_number + 1, next_page.number)

    def test_no_previous(self):
        # An empty string is returned if the previous page cannot be found.
        pages = el_models.PageList(
            self.request, self.paginator.page(1), self.page_label,
            context=Context())
        self.assertEqual('', pages.previous())

    def test_no_next(self):
        # An empty string is returned if the next page cannot be found.
        num_pages = self.paginator.num_pages
        pages = el_models.PageList(
            self.request, self.paginator.page(num_pages), self.page_label,
            context=Context())
        self.assertEqual('', pages.next())

    def test_customized_page_list_callable(self):
        # The page list is rendered based on ``settings.PAGE_LIST_CALLABLE``.
        self.check_page_list_callable(page_list_callable_dummy)

    def test_customized_page_list_dotted_path(self):
        # The option ``settings.PAGE_LIST_CALLABLE`` can be provided as a
        # dotted path, e.g.: 'path.to.my.callable'.
        self.check_page_list_callable(
            'el_pagination.tests.test_models.page_list_callable_dummy')

    def test_whitespace_in_path(self):
        # Ensure white spaces in paths are correctly handled.
        path = '/a path/containing spaces/'
        request = self.factory.get(path)
        next = el_models.PageList(
            request, self.paginator.page(self.current_number),
            self.page_label, context=Context()).next()
        self.assertEqual(path.replace(' ', '%20') + next.url, next.path)

    def test_lookup(self):
        # Ensure the page list correctly handles lookups.
        pages = self.pages
        self.assertEqual(pages.first().number, pages[1].number)

    def test_invalid_lookup(self):
        # A TypeError is raised if the lookup is not valid.
        with self.assertRaises(TypeError):
            self.pages['invalid']
<commit_msg>Add previous/next attrs tests for Issue #96<commit_after>"""Model tests."""

from __future__ import unicode_literals
from contextlib import contextmanager

from django.template import Context
from django.test import TestCase
from django.test.client import RequestFactory
from django.utils.encoding import force_text

from el_pagination import (
    models as el_models,
    settings,
    utils,
)
from el_pagination.paginators import DefaultPaginator

@contextmanager
def local_settings(**kwargs):
    """Override local Django Endless Pagination settings.

    This context manager can be used in a way similar to Django own
    ``TestCase.settings()``.
    """
    original_values = []
    for key, value in kwargs.items():
        original_values.append([key, getattr(settings, key)])
        setattr(settings, key, value)
    try:
        yield
    finally:
        for key, value in original_values:
            setattr(settings, key, value)

class LocalSettingsTest(TestCase):

    def setUp(self):
        settings._LOCAL_SETTINGS_TEST = 'original'

    def tearDown(self):
        del settings._LOCAL_SETTINGS_TEST

    def test_settings_changed(self):
        # Check that local settings are changed.
        with local_settings(_LOCAL_SETTINGS_TEST='changed'):
            self.assertEqual('changed', settings._LOCAL_SETTINGS_TEST)

    def test_settings_restored(self):
        # Check that local settings are restored.
        with local_settings(_LOCAL_SETTINGS_TEST='changed'):
            pass
        self.assertEqual('original', settings._LOCAL_SETTINGS_TEST)

    def test_restored_after_exception(self):
        # Check that local settings are restored after an exception.
        with self.assertRaises(RuntimeError):
            with local_settings(_LOCAL_SETTINGS_TEST='changed'):
                raise RuntimeError()
            self.assertEqual('original', settings._LOCAL_SETTINGS_TEST)

def page_list_callable_arrows(number, num_pages):
    """Wrap ``el_pagination.utils.get_page_numbers``.

    Set first / last page arrows to True.
    """
    return utils.get_page_numbers(number, num_pages, arrows=True)

page_list_callable_dummy = lambda number, num_pages: [None]

class PageListTest(TestCase):

    def setUp(self):
        self.paginator = DefaultPaginator(range(30), 7, orphans=2)
        self.current_number = 2
        self.page_label = 'page'
        self.factory = RequestFactory()
        self.request = self.factory.get(
            self.get_path_for_page(self.current_number))
        self.pages = el_models.PageList(
            self.request, self.paginator.page(self.current_number),
            self.page_label, context=Context())

    def get_url_for_page(self, number):
        """Return a url for the given page ``number``."""
        return '?{0}={1}'.format(self.page_label, number)

    def get_path_for_page(self, number):
        """Return a path for the given page ``number``."""
        return '/' + self.get_url_for_page(number)

    def check_page(
            self, page, number, is_first, is_last, is_current, label=None):
        """Perform several assertions on the given page attrs."""
        if label is None:
            label = force_text(page.number)
        self.assertEqual(label, page.label)
        self.assertEqual(number, page.number)
        self.assertEqual(is_first, page.is_first)
        self.assertEqual(is_last, page.is_last)
        self.assertEqual(is_current, page.is_current)

    def check_page_list_callable(self, callable_or_path):
        """Check the provided *page_list_callable* is actually used."""
        with local_settings(PAGE_LIST_CALLABLE=callable_or_path):
            rendered = force_text(self.pages.get_rendered()).strip()
        expected = '...'
        self.assertEqual(expected, rendered)

    def test_length(self):
        # Ensure the length of the page list equals the number of pages.
        self.assertEqual(self.paginator.num_pages, len(self.pages))

    def test_paginated(self):
        # Ensure the *paginated* method returns True if the page list contains
        # more than one page, False otherwise.
        page = DefaultPaginator(range(10), 10).page(1)
        pages = el_models.PageList(self.request, page, self.page_label,
                                   context=Context())
        self.assertFalse(pages.paginated())
        self.assertTrue(self.pages.paginated())

    def test_first_page(self):
        # Ensure the attrs of the first page are correctly defined.
        page = self.pages.first()
        self.assertEqual('/', page.path)
        self.assertEqual('', page.url)
        self.check_page(page, 1, True, False, False)

    def test_last_page(self):
        # Ensure the attrs of the last page are correctly defined.
        page = self.pages.last()
        self.check_page(page, len(self.pages), False, True, False)

    def test_first_page_as_arrow(self):
        # Ensure the attrs of the first page are correctly defined when the
        # page is represented as an arrow.
        page = self.pages.first_as_arrow()
        self.assertEqual('/', page.path)
        self.assertEqual('', page.url)
        self.check_page(
            page, 1, True, False, False, label=settings.FIRST_LABEL)

    def test_last_page_as_arrow(self):
        # Ensure the attrs of the last page are correctly defined when the
        # page is represented as an arrow.
        page = self.pages.last_as_arrow()
        self.check_page(
            page, len(self.pages), False, True, False,
            label=settings.LAST_LABEL)

    def test_current_page(self):
        # Ensure the attrs of the current page are correctly defined.
        page = self.pages.current()
        self.check_page(page, self.current_number, False, False, True)

    def test_path(self):
        # Ensure the path of each page is correctly generated.
        for num, page in enumerate(list(self.pages)[1:]):
            expected = self.get_path_for_page(num + 2)
            self.assertEqual(expected, page.path)

    def test_url(self):
        # Ensure the path of each page is correctly generated.
        for num, page in enumerate(list(self.pages)[1:]):
            expected = self.get_url_for_page(num + 2)
            self.assertEqual(expected, page.url)

    def test_current_indexes(self):
        # Ensure the 1-based indexes of the first and last items on the current
        # page are correctly returned.
        self.assertEqual(8, self.pages.current_start_index())
        self.assertEqual(14, self.pages.current_end_index())

    def test_total_count(self):
        # Ensure the total number of objects is correctly returned.
        self.assertEqual(30, self.pages.total_count())

    def test_page_render(self):
        # Ensure the page is correctly rendered.
        page = self.pages.first()
        rendered_page = force_text(page.render_link())
        self.assertIn('href="/"', rendered_page)
        self.assertIn(page.label, rendered_page)

    def test_current_page_render(self):
        # Ensure the page is correctly rendered.
        page = self.pages.current()
        rendered_page = force_text(page.render_link())
        self.assertNotIn('href', rendered_page)
        self.assertIn(page.label, rendered_page)

    def test_page_list_render(self):
        # Ensure the page list is correctly rendered.
        rendered = force_text(self.pages.get_rendered())
        self.assertEqual(5, rendered.count('<a href'))
        self.assertIn(settings.PREVIOUS_LABEL, rendered)
        self.assertIn(settings.NEXT_LABEL, rendered)

    def test_page_list_render_using_arrows(self):
        # Ensure the page list is correctly rendered when using first / last
        # page arrows.
        page_list_callable = (
            'el_pagination.tests.test_models.page_list_callable_arrows')
        with local_settings(PAGE_LIST_CALLABLE=page_list_callable):
            rendered = force_text(self.pages.get_rendered())
        self.assertEqual(7, rendered.count('<a href'))
        self.assertIn(settings.FIRST_LABEL, rendered)
        self.assertIn(settings.LAST_LABEL, rendered)

    def test_page_list_render_just_one_page(self):
        # Ensure nothing is rendered if the page list contains only one page.
        page = DefaultPaginator(range(10), 10).page(1)
        pages = el_models.PageList(self.request, page, self.page_label,
                                   context=Context())
        self.assertEqual('', force_text(pages))

    def test_different_default_number(self):
        # Ensure the page path is generated based on the default number.
        pages = el_models.PageList(
            self.request, self.paginator.page(2), self.page_label,
            default_number=2, context=Context())
        self.assertEqual('/', pages.current().path)
        self.assertEqual(self.get_path_for_page(1), pages.first().path)

    def test_index_error(self):
        # Ensure an error if raised if a non existent page is requested.
        with self.assertRaises(IndexError):
            self.pages[len(self.pages) + 1]

    def test_previous(self):
        # Ensure the correct previous page is returned.
        previous_page = self.pages.previous()
        self.assertEqual(self.current_number - 1, previous_page.number)

    def test_previous_attrs(self):
        # Ensure the attrs of the next page are correctly defined.
        with local_settings(USE_NEXT_PREVIOUS_LINKS=True):
            previous_page = self.pages.previous()
        self.assertEqual(True, previous_page.is_previous)
        self.check_page(
            previous_page, self.current_number - 1, True, False, False, label=settings.PREVIOUS_LABEL)

    def test_next(self):
        # Ensure the correct next page is returned.
        next_page = self.pages.next()
        self.assertEqual(self.current_number + 1, next_page.number)

    def test_next_attrs(self):
        # Ensure the attrs of the next page are correctly defined.
        with local_settings(USE_NEXT_PREVIOUS_LINKS=True):
            next_page = self.pages.next()
        self.assertEqual(True, next_page.is_next)
        self.check_page(
            next_page, self.current_number + 1, False, False, False, label=settings.NEXT_LABEL)

    def test_no_previous(self):
        # An empty string is returned if the previous page cannot be found.
        pages = el_models.PageList(
            self.request, self.paginator.page(1), self.page_label,
            context=Context())
        self.assertEqual('', pages.previous())

    def test_no_next(self):
        # An empty string is returned if the next page cannot be found.
        num_pages = self.paginator.num_pages
        pages = el_models.PageList(
            self.request, self.paginator.page(num_pages), self.page_label,
            context=Context())
        self.assertEqual('', pages.next())

    def test_customized_page_list_callable(self):
        # The page list is rendered based on ``settings.PAGE_LIST_CALLABLE``.
        self.check_page_list_callable(page_list_callable_dummy)

    def test_customized_page_list_dotted_path(self):
        # The option ``settings.PAGE_LIST_CALLABLE`` can be provided as a
        # dotted path, e.g.: 'path.to.my.callable'.
        self.check_page_list_callable(
            'el_pagination.tests.test_models.page_list_callable_dummy')

    def test_whitespace_in_path(self):
        # Ensure white spaces in paths are correctly handled.
        path = '/a path/containing spaces/'
        request = self.factory.get(path)
        next = el_models.PageList(
            request, self.paginator.page(self.current_number),
            self.page_label, context=Context()).next()
        self.assertEqual(path.replace(' ', '%20') + next.url, next.path)

    def test_lookup(self):
        # Ensure the page list correctly handles lookups.
        pages = self.pages
        self.assertEqual(pages.first().number, pages[1].number)

    def test_invalid_lookup(self):
        # A TypeError is raised if the lookup is not valid.
        with self.assertRaises(TypeError):
            self.pages['invalid']
<|endoftext|>


<commit_before><commit_msg>adding another  block to the cluster_spec<commit_after><|endoftext|>


<commit_before>import logging

from .device import AbstractDevice
from ..io.testio import TestIO

log = logging.getLogger("MPP-Solar")

class mppsolar(AbstractDevice):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__()
        self._name = kwargs["name"]
        self.set_port(**kwargs)
        self.set_protocol(**kwargs)
        log.debug(
            f"mppsolar __init__ name {self._name}, port {self._port}, protocol {self._protocol}"
        )
        log.debug(f"mppsolar __init__ args {args}")
        log.debug(f"mppsolar __init__ kwargs {kwargs}")

    def __str__(self):
        """
        Build a printable representation of this class
        """
        return (
            f"mppsolar device - name: {self._name}, port: {self._port}, protocol: {self._protocol}"
        )

    def run_command(self, command, show_raw=False) -> dict:
        """
        generic method for running a 'raw' command
        """
        log.info(f"Running command {command}")

        if self._protocol is None:
            log.error("Attempted to run command with no protocol defined")
            return {"ERROR": ["Attempted to run command with no protocol defined", ""]}
        if self._port is None:
            log.error(f"No communications port defined - unable to run command {command}")
            return {
                "ERROR": [
                    f"No communications port defined - unable to run command {command}",
                    "",
                ]
            }

        # Send command and receive data
        full_command = self._protocol.get_full_command(command)
        log.info(f"full command {full_command} for command {command}")

        # JkBleIO is very different from the others, only has protocol jk02 and jk04, maybe change full_command?
        if isinstance(self._port, JkBleIO):
            # need record type, SOR
            raw_response = self._port.send_and_receive(full_command, self._protocol)

        # Band-aid solution, can't really segregate TestIO from protocols w/o major rework of TestIO
        elif isinstance(self._port, TestIO):
            raw_response = self._port.send_and_receive(
                full_command, self._protocol.get_command_defn(command)
            )
        else:
            raw_response = self._port.send_and_receive(full_command)
        log.debug(f"Send and Receive Response {raw_response}")

        # Handle errors; dict is returned on exception
        # Maybe there should a decode for ERRORs and WARNINGS...
        if isinstance(raw_response, dict):
            return raw_response

        # Decode response
        decoded_response = self._protocol.decode(raw_response, show_raw, command)
        log.debug(f"Decoded response {decoded_response}")
        log.info(f"Decoded response {decoded_response}")

        return decoded_response

    def get_status(self, show_raw) -> dict:
        # Run all the commands that are defined as status from the protocol definition
        data = {}
        for command in self._protocol.STATUS_COMMANDS:
            data.update(self.run_command(command))
        return data

    def get_settings(self, show_raw) -> dict:
        # Run all the commands that are defined as settings from the protocol definition
        data = {}
        for command in self._protocol.SETTINGS_COMMANDS:
            data.update(self.run_command(command))
        return data
<commit_msg>change debug order for kwargs<commit_after>import logging

from .device import AbstractDevice
from ..io.testio import TestIO

log = logging.getLogger("MPP-Solar")

class mppsolar(AbstractDevice):
    def __init__(self, *args, **kwargs) -> None:
        log.debug(f"mppsolar __init__ args {args}")
        log.debug(f"mppsolar __init__ kwargs {kwargs}")
        super().__init__()
        self._name = kwargs["name"]
        self.set_port(**kwargs)
        self.set_protocol(**kwargs)
        log.debug(
            f"mppsolar __init__ name {self._name}, port {self._port}, protocol {self._protocol}"
        )

    def __str__(self):
        """
        Build a printable representation of this class
        """
        return (
            f"mppsolar device - name: {self._name}, port: {self._port}, protocol: {self._protocol}"
        )

    def run_command(self, command, show_raw=False) -> dict:
        """
        generic method for running a 'raw' command
        """
        log.info(f"Running command {command}")

        if self._protocol is None:
            log.error("Attempted to run command with no protocol defined")
            return {"ERROR": ["Attempted to run command with no protocol defined", ""]}
        if self._port is None:
            log.error(f"No communications port defined - unable to run command {command}")
            return {
                "ERROR": [
                    f"No communications port defined - unable to run command {command}",
                    "",
                ]
            }

        # Send command and receive data
        full_command = self._protocol.get_full_command(command)
        log.info(f"full command {full_command} for command {command}")

        # JkBleIO is very different from the others, only has protocol jk02 and jk04, maybe change full_command?
        if isinstance(self._port, JkBleIO):
            # need record type, SOR
            raw_response = self._port.send_and_receive(full_command, self._protocol)

        # Band-aid solution, can't really segregate TestIO from protocols w/o major rework of TestIO
        elif isinstance(self._port, TestIO):
            raw_response = self._port.send_and_receive(
                full_command, self._protocol.get_command_defn(command)
            )
        else:
            raw_response = self._port.send_and_receive(full_command)
        log.debug(f"Send and Receive Response {raw_response}")

        # Handle errors; dict is returned on exception
        # Maybe there should a decode for ERRORs and WARNINGS...
        if isinstance(raw_response, dict):
            return raw_response

        # Decode response
        decoded_response = self._protocol.decode(raw_response, show_raw, command)
        log.debug(f"Decoded response {decoded_response}")
        log.info(f"Decoded response {decoded_response}")

        return decoded_response

    def get_status(self, show_raw) -> dict:
        # Run all the commands that are defined as status from the protocol definition
        data = {}
        for command in self._protocol.STATUS_COMMANDS:
            data.update(self.run_command(command))
        return data

    def get_settings(self, show_raw) -> dict:
        # Run all the commands that are defined as settings from the protocol definition
        data = {}
        for command in self._protocol.SETTINGS_COMMANDS:
            data.update(self.run_command(command))
        return data
<|endoftext|>


<commit_before>{
  'targets': [
    {
      'target_name': 'sqlclient',
      'sources': [
        'src/client.cc',
      ],
      'include_dirs': [
        'deps/libmysql-maria/include',
      ],
      'cflags': [ '-O3' ],
      'conditions': [
        [ 'OS=="win"', {
          'msvs_settings': {
            'VCLinkerTool': {
              'IgnoreDefaultLibraryNames': ['libcmt.lib'],
            }
          },
          #'link_settings': {
            'conditions': [
              [ 'target_arch=="ia32"', {
                'libraries': [
                  '<(PRODUCT_DIR)/../../deps/libmysql-maria/win-x86/mysqlclient.lib',
                ],
              }, {
                'libraries': [
                  '<(PRODUCT_DIR)/../../deps/libmysql-maria/win-x86_64/clientlib.lib',
                ],
              }]
            ]
          #}
        }, {
          'libraries': [
            'libmysqlclient.a',
          ],
        }],
      ]
    },
  ],
}
<commit_msg>Fix linking on *nix<commit_after>{
  'targets': [
    {
      'target_name': 'sqlclient',
      'sources': [
        'src/client.cc',
      ],
      'include_dirs': [
        'deps/libmysql-maria/include',
      ],
      'cflags': [ '-O3' ],
      'conditions': [
        [ 'OS=="win"', {
          'msvs_settings': {
            'VCLinkerTool': {
              'IgnoreDefaultLibraryNames': ['libcmt.lib'],
            }
          },
          #'link_settings': {
            'conditions': [
              [ 'target_arch=="ia32"', {
                'libraries': [
                  '<(PRODUCT_DIR)/../../deps/libmysql-maria/win-x86/mysqlclient.lib',
                ],
              }, {
                'libraries': [
                  '<(PRODUCT_DIR)/../../deps/libmysql-maria/win-x86_64/clientlib.lib',
                ],
              }]
            ]
          #}
        }, {
          'libraries': [
            '-l:libmysqlclient.a',
          ],
        }],
      ]
    },
  ],
}
<|endoftext|>


<commit_before><commit_msg>fix: missing line due to conflict resolution<commit_after><|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$

import os
import sys
import re
from reportlab.platypus import *
import reportlab.lib.colors as colors
import reportlab.lib.units as units
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.fonts import addMapping
from reportlab.lib.styles import *
from reportlab.lib.enums import *
from reportlab.pdfbase import pdfmetrics
import reportlab.lib.pagesizes as pagesizes
from utils import log
from simplejson import loads

try:
    from wordaxe.rl.paragraph import Paragraph
    from wordaxe.rl.styles import ParagraphStyle,getSampleStyleSheet
except:
    log.warning("No hyphenation support, install wordaxe")

class StyleSheet(object):
    '''Class to handle a collection of stylesheets'''
    def __init__(self,flist):
        log.info('Using stylesheets: %s'%','.join(flist))
        '''flist is a list of stylesheet filenames.They will
        be loaded and merged in order'''
        self.TTFSearchPath=[os.path.join(os.path.abspath(os.path.dirname(__file__)), 'fonts'),'.']

        # Page width, height
        self.pw=0
        self.ph=0

        # Page size [w,h]
        self.ps=None

        # Margins (top,bottom,left,right,gutter)
        self.tm=0
        self.bm=0
        self.lm=0
        self.rm=0
        self.gm=0

        #text width
        self.tw=0

        self.languages=[]
        ssdata=[]
        # First parse all files and store the results
        for fname in flist:
            try:
                ssdata.append(loads(open(fname).read()))
            except ValueError,e: # Error parsing the JSON data
                log.error('Error parsing stylesheet "%s": %s'%(fname,str(e)))
                sys.exit(1)
            except IOError,e: #Error opening the ssheet
                log.error('Error opening stylesheet "%s": %s'%(fname,str(e)))
                sys.exit(1)

        # Get pageSetup data from all stylessheets in order:
        for data,ssname in zip(ssdata,flist):
            page=data.get('pageSetup',{})
            if page:
                if page.get('size',None): # A standard size
                    if page['size'] in pagesizes.__dict__:
                        self.ps=pagesizes.__dict__[page['size']]
                    else:
                        log.critical('Unknown page size %s in stylesheet %s' % (page['size'],ssname))
                        sys.exit(1)
                else: #A custom size
                    # The sizes are expressed in some unit.
                    # For example, 2cm is 2 centimeters, and we need
                    # to do 2*cm (cm comes from reportlab.lib.units)
                    self.ps=[self.adjustUnits(page['width']),self.adjustUnits(page['height'])]
                self.pw,self.ph=self.ps
                if 'margin-left' in page:
                    self.lm=self.adjustUnits(page['margin-left'])
                if 'margin-right' in page:
                    self.rm=self.adjustUnits(page['margin-right'])
                if 'margin-top' in page:
                    self.tm=self.adjustUnits(page['margin-top'])
                if 'margin-bottom' in page:
                    self.bm=self.adjustUnits(page['margin-bottom'])
                if 'margin-gutter' in page:
                    self.gm=self.adjustUnits(page['margin-gutter'])

                # tw is the text width.
                # We need it to calculate header-footer height
                # and compress literal blocks.
                self.tw=self.pw-self.lm-self.rm-self.gm
                self.firstTemplate=data.get('firstTemplate','firstPage')

        # Get page templates from all stylesheets
        self.pageTemplates={}
        for data,ssname in zip(ssdata,flist):
            templates=data.get('pageTemplates',{})
            # templates is a dictionary of pageTemplates
            for key in templates:
                template=templates[key]
                # template is a dict.
                # template[´frames'] is a list of frames
                if key in self.pageTemplates:
                    self.pageTemplates[key].update(template)
                else:
                    self.pageTemplates[key]=template

        # Get font aliases from all stylesheets in order
        self.fonts={}
        for data,ssname in zip(ssdata,flist):
            self.fonts.update(data.get('fontsAlias',{}))
            embedded=data.get('embeddedFonts',[])

            for font in embedded:
                try:
                    # Each "font" is a list of four files, which will be used for
                    # regular / bold / italic / bold+italic versions of the font.
                    # If your font doesn't have one of them, just repeat the regular
                    # font.

                    # Example, using the Tuffy font from http://tulrich.com/fonts/
                    # "embeddedFonts" : [
                    #                    ["Tuffy.ttf","Tuffy_Bold.ttf","Tuffy_Italic.ttf","Tuffy_Bold_Italic.ttf"]
                    #                   ],

                    # The fonts will be registered with the file name, minus the extension.

                    for variant in font:
                        pdfmetrics.registerFont(TTFont(str(variant.split('.')[0]), findFont(variant)))

                        # And map them all together
                        regular,bold,italic,bolditalic = [ variant.split('.')[0] for variant in font ]
                        addMapping(regular,0,0,regular)
                        addMapping(regular,0,1,italic)
                        addMapping(regular,1,0,bold)
                        addMapping(regular,1,1,bolditalic)
                except:
                    try:
                        fname=font[0].split('.')[0]
                        log.error("Error processing font %s, registering as Helvetica alias",fname)
                        fonts[fname]='Helvetica'
                    except:
                        log.error("Error processing font %s",fname)
                        sys.exit(1)

        # Get styles from all stylesheets in order
        self.stylesheet = {}
        self.styles=[]
        self.linkColor = 'navy'
        for data,ssname in zip(ssdata,flist):
            self.linkColor=data.get('linkColor') or self.linkColor
            styles=data.get('styles',{})
            for [skey,style] in styles:
                sdict={}
                # FIXME: this is done completely backwards
                for key in style:

                    # Handle font aliases
                    if (key == 'fontName' or key.endswith('FontName')) and style[key] in self.fonts:
                        style[key]=self.fonts[style[key]]

                    # Handle color references by name
                    elif key == 'color' or key.endswith('Color') and style[key]:
                        if style[key] in colors.__dict__:
                            style[key]=colors.__dict__[style[key]]
                        else: # Hopefully, a hex color:
                            c=style[key]
                            r=int(c[1:3],16)
                            g=int(c[3:5],16)
                            b=int(c[5:7],16)
                            style[key]=colors.Color(r,g,b)

                    # Handle alignment constants
                    elif key == 'alignment':
                        style[key]={'TA_LEFT':0, 'TA_CENTER':1, 'TA_CENTRE':1, 'TA_RIGHT':2, 'TA_JUSTIFY':4}[style[key]]

                    elif key == 'language':
                        if not style[key] in self.languages:
                            self.languages.append(style[key])
                    # Make keys str instead of unicode (required by reportlab)
                    sdict[str(key)]=style[key]
                    sdict['name']=skey
                # If the style already exists, update it
                if skey in self.stylesheet:
                    self.stylesheet[skey].update(sdict)
                else: # New style
                    self.stylesheet[skey]=sdict
                    self.styles.append(sdict)
        # And create  reportlabs stylesheet
        self.StyleSheet=StyleSheet1()
        for s in self.styles:
            if 'parent' in s:
                if s['parent'] is None:
                    if s['name'] <> 'base':
                        s['parent']=self.StyleSheet['base']
                    else:
                        del(s['parent'])
                else:
                    s['parent']=self.StyleSheet[s['parent']]
            else:
                if s['name'] <> 'base':
                    s['parent']=self.StyleSheet['base']
            self.StyleSheet.add(ParagraphStyle(**s))
    def __getitem__(self,key):
        return self.StyleSheet[key]

    def findFont(fn):
        '''Given a font file name, searches for it in TTFSearchPath
        and returns the real file name'''
        if not os.path.isabs(fn):
            for D in self.TTFSearchPath:
                tfn = os.path.join(D,fn)
                if os.path.isfile(tfn):
                    return str(tfn)
        return str(fn)

    def adjustUnits(self,v,total=None):
        '''Takes something like 2cm and returns 2*cm.
        If you use % as a unit, it returns the percentage
        of "total".

        If total is not given, returns a percentage of the page
        width. However, if you get to that stage, you are
        doing it wrong.

        Example::

                >>> adjustUnits('50%',200)
                100
        '''

        if total is None:
            total=self.pw

        _,n,u=re.split('(-?[0-9\.]*)',v)
        if not u:
            return float(n) # assume points
        if u in units.__dict__:
            return float(n)*units.__dict__[u]
        else:
            if u=='%':
                return float(n)*total/100
            log.error('Unknown unit "%s"' % u)
        return float(n)

# Some table styles used for pieces of the document

tstyles={}

# Used for regular tables

tstyleNorm = [ ('VALIGN',(0,0),(-1,-1),'TOP'),
               ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
               ('BOX', (0,0), (-1,-1), 0.25, colors.black),
             ]

# Header row in tables

def tstyleHead(rows=1):
    return ('BACKGROUND',(0,0),(-1,rows-1),colors.yellow)

tstyles['normal']=TableStyle(tstyleNorm)

# Used for field lists

tstyles['field']=TableStyle([ ('VALIGN',(0,0),(-1,-1),'TOP'),
                              ('ALIGNMENT',(0,0),(1,-1),'RIGHT'),
                            ])
fieldlist_lwidth=3*units.cm

# Used for endnotes

tstyles['endnote']=TableStyle([ ('VALIGN',(0,0),(-1,-1),'TOP'),
                                ('ALIGNMENT',(0,0),(1,-1),'RIGHT'),
                              ])
# Left column of the endnote. The content of the note takes the rest of
# the available space
endnote_lwidth=2*units.cm

# Used for sidebars

tstyles['sidebar']=TableStyle([ ('VALIGN',(0,0),(-1,-1),'TOP'),
                             ('BACKGROUND',(0,0),(-1,-1),colors.lightyellow),
                           ])

tstyles['bullet']=TableStyle([ ('VALIGN',(0,0),(-1,-1),'TOP'),
                             ])
<commit_msg>Fixed refactoring bug in font embedding.<commit_after># -*- coding: utf-8 -*-
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$

import os
import sys
import re
from reportlab.platypus import *
import reportlab.lib.colors as colors
import reportlab.lib.units as units
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.fonts import addMapping
from reportlab.lib.styles import *
from reportlab.lib.enums import *
from reportlab.pdfbase import pdfmetrics
import reportlab.lib.pagesizes as pagesizes
from utils import log
from simplejson import loads

try:
    from wordaxe.rl.paragraph import Paragraph
    from wordaxe.rl.styles import ParagraphStyle,getSampleStyleSheet
except:
    log.warning("No hyphenation support, install wordaxe")

class StyleSheet(object):
    '''Class to handle a collection of stylesheets'''
    def __init__(self,flist):
        log.info('Using stylesheets: %s'%','.join(flist))
        '''flist is a list of stylesheet filenames.They will
        be loaded and merged in order'''
        self.TTFSearchPath=[os.path.join(os.path.abspath(os.path.dirname(__file__)), 'fonts'),'.']

        # Page width, height
        self.pw=0
        self.ph=0

        # Page size [w,h]
        self.ps=None

        # Margins (top,bottom,left,right,gutter)
        self.tm=0
        self.bm=0
        self.lm=0
        self.rm=0
        self.gm=0

        #text width
        self.tw=0

        self.languages=[]
        ssdata=[]
        # First parse all files and store the results
        for fname in flist:
            try:
                ssdata.append(loads(open(fname).read()))
            except ValueError,e: # Error parsing the JSON data
                log.error('Error parsing stylesheet "%s": %s'%(fname,str(e)))
                sys.exit(1)
            except IOError,e: #Error opening the ssheet
                log.error('Error opening stylesheet "%s": %s'%(fname,str(e)))
                sys.exit(1)

        # Get pageSetup data from all stylessheets in order:
        for data,ssname in zip(ssdata,flist):
            page=data.get('pageSetup',{})
            if page:
                if page.get('size',None): # A standard size
                    if page['size'] in pagesizes.__dict__:
                        self.ps=pagesizes.__dict__[page['size']]
                    else:
                        log.critical('Unknown page size %s in stylesheet %s' % (page['size'],ssname))
                        sys.exit(1)
                else: #A custom size
                    # The sizes are expressed in some unit.
                    # For example, 2cm is 2 centimeters, and we need
                    # to do 2*cm (cm comes from reportlab.lib.units)
                    self.ps=[self.adjustUnits(page['width']),self.adjustUnits(page['height'])]
                self.pw,self.ph=self.ps
                if 'margin-left' in page:
                    self.lm=self.adjustUnits(page['margin-left'])
                if 'margin-right' in page:
                    self.rm=self.adjustUnits(page['margin-right'])
                if 'margin-top' in page:
                    self.tm=self.adjustUnits(page['margin-top'])
                if 'margin-bottom' in page:
                    self.bm=self.adjustUnits(page['margin-bottom'])
                if 'margin-gutter' in page:
                    self.gm=self.adjustUnits(page['margin-gutter'])

                # tw is the text width.
                # We need it to calculate header-footer height
                # and compress literal blocks.
                self.tw=self.pw-self.lm-self.rm-self.gm
                self.firstTemplate=data.get('firstTemplate','firstPage')

        # Get page templates from all stylesheets
        self.pageTemplates={}
        for data,ssname in zip(ssdata,flist):
            templates=data.get('pageTemplates',{})
            # templates is a dictionary of pageTemplates
            for key in templates:
                template=templates[key]
                # template is a dict.
                # template[´frames'] is a list of frames
                if key in self.pageTemplates:
                    self.pageTemplates[key].update(template)
                else:
                    self.pageTemplates[key]=template

        # Get font aliases from all stylesheets in order
        self.fonts={}
        for data,ssname in zip(ssdata,flist):
            self.fonts.update(data.get('fontsAlias',{}))
            embedded=data.get('embeddedFonts',[])

            for font in embedded:
                try:
                    # Each "font" is a list of four files, which will be used for
                    # regular / bold / italic / bold+italic versions of the font.
                    # If your font doesn't have one of them, just repeat the regular
                    # font.

                    # Example, using the Tuffy font from http://tulrich.com/fonts/
                    # "embeddedFonts" : [
                    #                    ["Tuffy.ttf","Tuffy_Bold.ttf","Tuffy_Italic.ttf","Tuffy_Bold_Italic.ttf"]
                    #                   ],

                    # The fonts will be registered with the file name, minus the extension.

                    for variant in font:
                        pdfmetrics.registerFont(TTFont(str(variant.split('.')[0]), self.findFont(variant)))

                        # And map them all together
                        regular,bold,italic,bolditalic = [ variant.split('.')[0] for variant in font ]
                        addMapping(regular,0,0,regular)
                        addMapping(regular,0,1,italic)
                        addMapping(regular,1,0,bold)
                        addMapping(regular,1,1,bolditalic)
                except Exception, e:
                    try:
                        fname=font[0].split('.')[0]
                        log.error("Error processing font %s: %s",fname,str(e))
                        log.error("Registering %s as Helvetica alias",fname)
                        self.fonts[fname]='Helvetica'
                    except Exception,e:
                        log.error("Error processing font %s: %s",fname,str(e))
                        sys.exit(1)

        # Get styles from all stylesheets in order
        self.stylesheet = {}
        self.styles=[]
        self.linkColor = 'navy'
        for data,ssname in zip(ssdata,flist):
            self.linkColor=data.get('linkColor') or self.linkColor
            styles=data.get('styles',{})
            for [skey,style] in styles:
                sdict={}
                # FIXME: this is done completely backwards
                for key in style:

                    # Handle font aliases
                    if (key == 'fontName' or key.endswith('FontName')) and style[key] in self.fonts:
                        style[key]=self.fonts[style[key]]

                    # Handle color references by name
                    elif key == 'color' or key.endswith('Color') and style[key]:
                        if style[key] in colors.__dict__:
                            style[key]=colors.__dict__[style[key]]
                        else: # Hopefully, a hex color:
                            c=style[key]
                            r=int(c[1:3],16)
                            g=int(c[3:5],16)
                            b=int(c[5:7],16)
                            style[key]=colors.Color(r,g,b)

                    # Handle alignment constants
                    elif key == 'alignment':
                        style[key]={'TA_LEFT':0, 'TA_CENTER':1, 'TA_CENTRE':1, 'TA_RIGHT':2, 'TA_JUSTIFY':4}[style[key]]

                    elif key == 'language':
                        if not style[key] in self.languages:
                            self.languages.append(style[key])
                    # Make keys str instead of unicode (required by reportlab)
                    sdict[str(key)]=style[key]
                    sdict['name']=skey
                # If the style already exists, update it
                if skey in self.stylesheet:
                    self.stylesheet[skey].update(sdict)
                else: # New style
                    self.stylesheet[skey]=sdict
                    self.styles.append(sdict)
        # And create  reportlabs stylesheet
        self.StyleSheet=StyleSheet1()
        for s in self.styles:
            if 'parent' in s:
                if s['parent'] is None:
                    if s['name'] <> 'base':
                        s['parent']=self.StyleSheet['base']
                    else:
                        del(s['parent'])
                else:
                    s['parent']=self.StyleSheet[s['parent']]
            else:
                if s['name'] <> 'base':
                    s['parent']=self.StyleSheet['base']
            self.StyleSheet.add(ParagraphStyle(**s))
    def __getitem__(self,key):
        return self.StyleSheet[key]

    def findFont(self,fn):
        '''Given a font file name, searches for it in TTFSearchPath
        and returns the real file name'''
        if not os.path.isabs(fn):
            for D in self.TTFSearchPath:
                tfn = os.path.join(D,fn)
                if os.path.isfile(tfn):
                    return str(tfn)
        return str(fn)

    def adjustUnits(self,v,total=None):
        '''Takes something like 2cm and returns 2*cm.
        If you use % as a unit, it returns the percentage
        of "total".

        If total is not given, returns a percentage of the page
        width. However, if you get to that stage, you are
        doing it wrong.

        Example::

                >>> adjustUnits('50%',200)
                100
        '''

        if total is None:
            total=self.pw

        _,n,u=re.split('(-?[0-9\.]*)',v)
        if not u:
            return float(n) # assume points
        if u in units.__dict__:
            return float(n)*units.__dict__[u]
        else:
            if u=='%':
                return float(n)*total/100
            log.error('Unknown unit "%s"' % u)
        return float(n)

# Some table styles used for pieces of the document

tstyles={}

# Used for regular tables

tstyleNorm = [ ('VALIGN',(0,0),(-1,-1),'TOP'),
               ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
               ('BOX', (0,0), (-1,-1), 0.25, colors.black),
             ]

# Header row in tables

def tstyleHead(rows=1):
    return ('BACKGROUND',(0,0),(-1,rows-1),colors.yellow)

tstyles['normal']=TableStyle(tstyleNorm)

# Used for field lists

tstyles['field']=TableStyle([ ('VALIGN',(0,0),(-1,-1),'TOP'),
                              ('ALIGNMENT',(0,0),(1,-1),'RIGHT'),
                            ])
fieldlist_lwidth=3*units.cm

# Used for endnotes

tstyles['endnote']=TableStyle([ ('VALIGN',(0,0),(-1,-1),'TOP'),
                                ('ALIGNMENT',(0,0),(1,-1),'RIGHT'),
                              ])
# Left column of the endnote. The content of the note takes the rest of
# the available space
endnote_lwidth=2*units.cm

# Used for sidebars

tstyles['sidebar']=TableStyle([ ('VALIGN',(0,0),(-1,-1),'TOP'),
                             ('BACKGROUND',(0,0),(-1,-1),colors.lightyellow),
                           ])

tstyles['bullet']=TableStyle([ ('VALIGN',(0,0),(-1,-1),'TOP'),
                             ])
<|endoftext|>


<commit_before>from __future__ import unicode_literals
import re

from django.apps import apps
from django.db import models
from django.urls import reverse

TRIGGER_TYPES = (
    ('manual', 'Manual'),
    ('commit', 'Commit'),
    ('tag', 'Tag'),
)

DASHBOARD_CHOICES = (
    ('last', 'Most Recent Build'),
    ('recent', '5 Most Recent Build'),
    ('branches', 'Latest Builds by Branch'),
)

class Plan(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    repo = models.ForeignKey('repository.Repository', related_name="plans")
    type = models.CharField(max_length=8, choices=TRIGGER_TYPES)
    regex = models.CharField(max_length=255, null=True, blank=True)
    flows = models.CharField(max_length=255)
    org = models.CharField(max_length=255)
    context = models.CharField(max_length=255, null=True, blank=True)
    public = models.BooleanField(default=True)
    active = models.BooleanField(default=True)
    dashboard = models.CharField(max_length=8, choices=DASHBOARD_CHOICES, default=None, null=True, blank=True)
    junit_path = models.CharField(max_length=255, null=True, blank=True)
    sfdx_config = models.TextField(null=True, blank=True)

    class Meta:
        ordering = ['name','repo__owner','repo__name', 'active', 'context']

    def get_absolute_url(self):
        return reverse('plan_detail', kwargs={'plan_id': self.id})

    def __unicode__(self):
        return u'[{}] {}'.format(self.repo.name, self.name)

    def check_push(self, push):
        run_build = False
        commit = None
        commit_message = None

        # Handle commit events
        if self.type == 'commit':
            # Check if the event was triggered by a commit
            if not push['ref'].startswith('refs/heads/'):
                return run_build, commit, commit_message
            branch = push['ref'][11:]

            # Check the branch against regex
            if not re.match(self.regex, branch):
                return run_build, commit, commit_message

            run_build = True
            commit = push['after']
            if commit == '0000000000000000000000000000000000000000':
                run_build = False
                commit = None
            return run_build, commit, commit_message

            for commit_info in push.get('commits',[]):
                if commit_info['id'] == commit:
                    commit_message = commit_info['message']
                    break

            # Skip build if commit message contains [ci skip]
            if commit_message and '[ci skip]' in commit_message:
                run_build = False
                commit = None
            return run_build, commit, commit_message

        # Handle tag events
        elif self.type == 'tag':
            # Check if the event was triggered by a tag
            if not push['ref'].startswith('refs/tags/'):
                return run_build, commit, commit_message
            tag = push['ref'][10:]

            # Check the tag against regex
            if not re.match(self.regex, tag):
                return run_build, commit, commit_message

            if push['head_commit']:
                # Skip... for some reason a second push event is sent that has no 'before' but does have a head_commit
                return run_build, commit, commit_message

            run_build = True
            commit = push['before']
            return run_build, commit, commit_message

        return run_build, commit, commit_message

SCHEDULE_CHOICES=(
    ('daily', 'Daily'),
    ('hourly', 'Hourly'),
)

class PlanSchedule(models.Model):
    plan = models.ForeignKey(Plan)
    branch = models.ForeignKey('repository.branch')
    schedule = models.CharField(max_length=16, choices=SCHEDULE_CHOICES)

    def run(self):
        Build = apps.get_model('build', 'Build')
        build = Build(
            repo = self.plan.repo,
            plan = self.plan,
            branch = self.branch,
            commit = self.branch.github_api.commit.sha,
            schedule = self,
            build_type = 'scheduled',
        )
        build.save()
        return build
<commit_msg>add field<commit_after>from __future__ import unicode_literals
import re

from django.apps import apps
from django.db import models
from django.urls import reverse

TRIGGER_TYPES = (
    ('manual', 'Manual'),
    ('commit', 'Commit'),
    ('tag', 'Tag'),
)

DASHBOARD_CHOICES = (
    ('last', 'Most Recent Build'),
    ('recent', '5 Most Recent Build'),
    ('branches', 'Latest Builds by Branch'),
)

class Plan(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    repo = models.ForeignKey('repository.Repository', related_name="plans")
    type = models.CharField(max_length=8, choices=TRIGGER_TYPES)
    regex = models.CharField(max_length=255, null=True, blank=True)
    flows = models.CharField(max_length=255)
    org = models.CharField(max_length=255)
    context = models.CharField(max_length=255, null=True, blank=True)
    public = models.BooleanField(default=True)
    active = models.BooleanField(default=True)
    dashboard = models.CharField(max_length=8, choices=DASHBOARD_CHOICES, default=None, null=True, blank=True)
    junit_path = models.CharField(max_length=255, null=True, blank=True)
    sfdx_config = models.TextField(null=True, blank=True)
    yaml_config = models.TextField(null=True, blank=True)

    class Meta:
        ordering = ['name','repo__owner','repo__name', 'active', 'context']

    def get_absolute_url(self):
        return reverse('plan_detail', kwargs={'plan_id': self.id})

    def __unicode__(self):
        return u'[{}] {}'.format(self.repo.name, self.name)

    def check_push(self, push):
        run_build = False
        commit = None
        commit_message = None

        # Handle commit events
        if self.type == 'commit':
            # Check if the event was triggered by a commit
            if not push['ref'].startswith('refs/heads/'):
                return run_build, commit, commit_message
            branch = push['ref'][11:]

            # Check the branch against regex
            if not re.match(self.regex, branch):
                return run_build, commit, commit_message

            run_build = True
            commit = push['after']
            if commit == '0000000000000000000000000000000000000000':
                run_build = False
                commit = None
            return run_build, commit, commit_message

            for commit_info in push.get('commits',[]):
                if commit_info['id'] == commit:
                    commit_message = commit_info['message']
                    break

            # Skip build if commit message contains [ci skip]
            if commit_message and '[ci skip]' in commit_message:
                run_build = False
                commit = None
            return run_build, commit, commit_message

        # Handle tag events
        elif self.type == 'tag':
            # Check if the event was triggered by a tag
            if not push['ref'].startswith('refs/tags/'):
                return run_build, commit, commit_message
            tag = push['ref'][10:]

            # Check the tag against regex
            if not re.match(self.regex, tag):
                return run_build, commit, commit_message

            if push['head_commit']:
                # Skip... for some reason a second push event is sent that has no 'before' but does have a head_commit
                return run_build, commit, commit_message

            run_build = True
            commit = push['before']
            return run_build, commit, commit_message

        return run_build, commit, commit_message

SCHEDULE_CHOICES=(
    ('daily', 'Daily'),
    ('hourly', 'Hourly'),
)

class PlanSchedule(models.Model):
    plan = models.ForeignKey(Plan)
    branch = models.ForeignKey('repository.branch')
    schedule = models.CharField(max_length=16, choices=SCHEDULE_CHOICES)

    def run(self):
        Build = apps.get_model('build', 'Build')
        build = Build(
            repo = self.plan.repo,
            plan = self.plan,
            branch = self.branch,
            commit = self.branch.github_api.commit.sha,
            schedule = self,
            build_type = 'scheduled',
        )
        build.save()
        return build
<|endoftext|>


<commit_before>"""
TODO: Implement other error handlers - http://flask.pocoo.org/docs/0.12/patterns/errorpages/
TODO: Shit-loads of refactoring
TODO: Proper Error Handling of Entries in report_filter()
"""

from flask import Flask, render_template, request, redirect, url_for, session, flash
import psycopg2
import datetime

from config import *

# Instantiate App
app = Flask(__name__)
app.secret_key = APP_SECRET_KEY

# MARK: DATABASE FUNCTIONS
# Database Query Function
def db_query(sql_string, data_array):
	conn = psycopg2.connect(DB_LOCATION)
	cur = conn.cursor()
	print("\nThe query is:\n", sql_string, "\nThe data array is:\n", data_array)
	cur.execute(sql_string, data_array)

	# Return data as an array of dictionaries
	result = cur.fetchall()
	print('\nQuery result:', result)
	records = []

	# If the query returns something...
	if len(result) != 0:
		entries = result
		print("\nLine 33 - entries:", entries)
		for row in entries:
			records.append(row)
	else:
		# No results in query
		print('\nNO RESULTS IN QUERY\n')
		redirect(url_for('failed_query', query_string=sql_string))

	conn.commit()
	cur.close()
	conn.close()
	return records

# Date Validation Function
def validate_date(date_string):
	try:
		date = datetime.datetime.strptime(date_string, '%m/%d/%Y').date()
		return str(date)
	except ValueError:
		raise ValueError('Incorrect data format, should be MM/DD/YYYY')

# MARK: TEMPLATES
@app.route('/')
@app.route('/index')
@app.route('/index.html')
def index():
	return redirect(url_for('login'))

@app.route('/login', methods=['GET', 'POST'])
def login():
	error = None
	if request.method == 'POST':
		if False or request.form['username'] != USERNAME:
			error = 'Invalid username'
		elif False or request.form['password'] != PASSWORD:
			error = 'Invalid password'
		else:
			session['logged_in'] = True
			session['username'] = request.form['username']
			session['password'] = request.form['password']
			return redirect(url_for('report_filter'))

	return render_template('login.html')

@app.route('/logout', methods=['GET', 'POST'])
def logout():
	session['logged_in'] = False
	return render_template('logout.html')

@app.route('/report_filter', methods=['GET', 'POST'])
def report_filter():
	# Populate Facilities Drop-down menu
	fac_query = 'SELECT common_name FROM facilities;'
	conn = psycopg2.connect(DB_LOCATION)
	cur = conn.cursor()
	cur.execute(fac_query)
	list_of_single_tuples = cur.fetchall()

	facilities_list = []
	for name, in list_of_single_tuples:
		facilities_list.append(name)

	conn.commit()
	cur.close()
	conn.close()

	# If a form has been submitted
	if request.method == 'POST':
		# Validate and pass date
		try:
			validated_date = validate_date(request.form['filter_date'])
		except ValueError:
			print('VALUE ERROR:', ValueError.args)
			pass
		except TypeError or UnboundLocalError:
			print('TYPE ERROR:', 'You need to enter a date.')
			pass

		# FILTER: Inventory by 'In Transit' status
		if request.form['filter_facility'] == 'none':
			return moving_inventory(validated_date)

		# FILTER: Inventory by Facility
		else:
			return facility_inventory(validated_date)

	return render_template('report_filter.html', facilities_list=facilities_list)

@app.route('/moving_inventory', methods=['GET', 'POST'])
def moving_inventory(validated_date):
	moving_query = "SELECT assets.asset_tag, assets.description, f1.location as location1, f2.location as location2, convoys.depart_dt, convoys.arrive_dt" \
				   " FROM assets" \
				   " JOIN asset_on ON assets.asset_pk = asset_on.asset_fk" \
				   " JOIN convoys ON asset_on.convoy_fk = convoys.convoy_pk" \
				   " JOIN facilities f1 ON convoys.src_fk = f1.facility_pk" \
				   " JOIN facilities f2 ON convoys.dst_fk = f2.facility_pk" \
				   " WHERE convoys.arrive_dt >= %s AND convoys.depart_dt <= %s"

	moving_inventory_data = db_query(moving_query, [validated_date, validated_date])

	column_names = ['asset_tag', 'description', 'location1', 'location2', 'depart_dt', 'arrive_dt']
	moving_inventory_processed = []

	# TODO: Refactor by creating array of tuples to dictionary conversion function
	# If list is not empty and it's size matches the array of column headers
	if moving_inventory_data and (len(moving_inventory_data[0]) == len(column_names)):
		for record in moving_inventory_data:
			moving_inventory_processed.append(dict(zip(column_names, record)))
	else:
		print('\n\nERROR LIST OF COLUMN SIZE IS NOT THE SAME SIZE AS RECORD SIZE\n\n')

	return render_template('moving_inventory.html', date=validated_date, data=moving_inventory_processed)

@app.route('/facility_inventory', methods=['GET', 'POST'])
def facility_inventory(validated_date):
	selected_facility = request.form['filter_facility']
	facility_query = "SELECT facilities.fcode, facilities.location, assets.asset_tag, assets.description, asset_at.arrive_dt, asset_at.depart_dt" \
					 " FROM (SELECT * FROM facilities WHERE common_name = '%s') as facilities" \
					 " JOIN asset_at ON facilities.facility_pk = asset_at.facility_fk" \
					 " JOIN assets ON asset_at.asset_fk = assets.asset_pk" \
					 " WHERE (asset_at.depart_dt <= %s OR asset_at.depart_dt IS NULL)" \
					 " AND asset_at.arrive_dt >= %s"

	facility_inventory_data = db_query(facility_query, [selected_facility, validated_date, validated_date])
	print("\n\nLine 166 - facility_inventory_data:", facility_inventory_data)

	column_names = ['fcode', 'location', 'asset_tag', 'description', 'arrive_dt', ' depart_dt']
	facility_inventory_processed = []

	# TODO: Refactor by creating array of tuples to dictionary conversion function
	# If list is not empty and it's size matches the array of column headers
	if facility_inventory_data and (len(facility_inventory_data[0]) == len(column_names)):
		for record in facility_inventory_data:
			facility_inventory_processed.append(dict(zip(column_names, record)))
	else:
		print('\n\nERROR LIST OF COLUMN SIZE IS NOT THE SAME SIZE AS RECORD SIZE\n\n')

	print('\nThis is the data being passed:', facility_inventory_processed)
	return render_template('facility_inventory.html', facility=str(selected_facility), data=facility_inventory_processed, date=validated_date)

@app.route('/facility_inventory', methods=['GET'])
def failed_query(query_string):
	return render_template('failed_query.html', query=query_string)

# MARK: ERROR PAGES
@app.errorhandler(404)
def page_not_found(e):
	return render_template('404.html'), 404

# Application Deployment
if __name__ == '__main__':
	app.run(host='0.0.0.0', port=8080, debug=True)

"""
SELECT facilities.fcode, facilities.location, assets.asset_tag, assets.description, asset_at.arrive_dt, asset_at.depart_dt
FROM (SELECT * FROM facilities WHERE common_name = %s) as facilities
JOIN asset_at ON facilities.facility_pk = asset_at.facility_fk
JOIN assets ON asset_at.asset_fk = assets.asset_pk
WHERE (asset_at.depart_dt <= %s OR asset_at.depart_dt IS NULL) AND asset_at.arrive_dt >= %s
"""

"""
SELECT assets.asset_tag, assets.description, f1.location as location1, f2.location as location2, convoys.depart_dt, convoys.arrive_dt
FROM assets
JOIN asset_on ON assets.asset_pk = asset_on.asset_fk
JOIN convoys ON asset_on.convoy_fk = convoys.convoy_pk
JOIN facilities f1 ON convoys.src_fk = f1.facility_pk
JOIN facilities f2 ON convoys.dst_fk = f2.facility_pk
WHERE convoys.arrive_dt >= %s AND convoys.depart_dt <= %s
"""<commit_msg>Fix facility query - Attempt #4<commit_after>"""
TODO: Implement other error handlers - http://flask.pocoo.org/docs/0.12/patterns/errorpages/
TODO: Shit-loads of refactoring
TODO: Proper Error Handling of Entries in report_filter()
"""

from flask import Flask, render_template, request, redirect, url_for, session, flash
import psycopg2
import datetime

from config import *

# Instantiate App
app = Flask(__name__)
app.secret_key = APP_SECRET_KEY

# MARK: DATABASE FUNCTIONS
# Database Query Function
def db_query(sql_string, data_array):
	conn = psycopg2.connect(DB_LOCATION)
	cur = conn.cursor()
	print("\nThe query is:\n", sql_string, "\nThe data array is:\n", data_array)
	cur.execute(sql_string, data_array)

	# Return data as an array of dictionaries
	result = cur.fetchall()
	print('\nQuery result:', result)
	records = []

	# If the query returns something...
	if len(result) != 0:
		entries = result
		print("\nLine 33 - entries:", entries)
		for row in entries:
			records.append(row)
	else:
		# No results in query
		print('\nNO RESULTS IN QUERY\n')
		redirect(url_for('failed_query', query_string=sql_string))

	conn.commit()
	cur.close()
	conn.close()
	return records

# Date Validation Function
def validate_date(date_string):
	try:
		date = datetime.datetime.strptime(date_string, '%m/%d/%Y').date()
		return str(date)
	except ValueError:
		raise ValueError('Incorrect data format, should be MM/DD/YYYY')

# MARK: TEMPLATES
@app.route('/')
@app.route('/index')
@app.route('/index.html')
def index():
	return redirect(url_for('login'))

@app.route('/login', methods=['GET', 'POST'])
def login():
	error = None
	if request.method == 'POST':
		if False or request.form['username'] != USERNAME:
			error = 'Invalid username'
		elif False or request.form['password'] != PASSWORD:
			error = 'Invalid password'
		else:
			session['logged_in'] = True
			session['username'] = request.form['username']
			session['password'] = request.form['password']
			return redirect(url_for('report_filter'))

	return render_template('login.html')

@app.route('/logout', methods=['GET', 'POST'])
def logout():
	session['logged_in'] = False
	return render_template('logout.html')

@app.route('/report_filter', methods=['GET', 'POST'])
def report_filter():
	# Populate Facilities Drop-down menu
	fac_query = 'SELECT common_name FROM facilities;'
	conn = psycopg2.connect(DB_LOCATION)
	cur = conn.cursor()
	cur.execute(fac_query)
	list_of_single_tuples = cur.fetchall()

	facilities_list = []
	for name, in list_of_single_tuples:
		facilities_list.append(name)

	conn.commit()
	cur.close()
	conn.close()

	# If a form has been submitted
	if request.method == 'POST':
		# Validate and pass date
		try:
			validated_date = validate_date(request.form['filter_date'])
		except ValueError:
			print('VALUE ERROR:', ValueError.args)
			pass
		except TypeError or UnboundLocalError:
			print('TYPE ERROR:', 'You need to enter a date.')
			pass

		# FILTER: Inventory by 'In Transit' status
		if request.form['filter_facility'] == 'none':
			return moving_inventory(validated_date)

		# FILTER: Inventory by Facility
		else:
			return facility_inventory(validated_date)

	return render_template('report_filter.html', facilities_list=facilities_list)

@app.route('/moving_inventory', methods=['GET', 'POST'])
def moving_inventory(validated_date):
	moving_query = "SELECT assets.asset_tag, assets.description, f1.location as location1, f2.location as location2, convoys.depart_dt, convoys.arrive_dt" \
				   " FROM assets" \
				   " JOIN asset_on ON assets.asset_pk = asset_on.asset_fk" \
				   " JOIN convoys ON asset_on.convoy_fk = convoys.convoy_pk" \
				   " JOIN facilities f1 ON convoys.src_fk = f1.facility_pk" \
				   " JOIN facilities f2 ON convoys.dst_fk = f2.facility_pk" \
				   " WHERE convoys.arrive_dt >= %s AND convoys.depart_dt <= %s"

	moving_inventory_data = db_query(moving_query, [validated_date, validated_date])

	column_names = ['asset_tag', 'description', 'location1', 'location2', 'depart_dt', 'arrive_dt']
	moving_inventory_processed = []

	# TODO: Refactor by creating array of tuples to dictionary conversion function
	# If list is not empty and it's size matches the array of column headers
	if moving_inventory_data and (len(moving_inventory_data[0]) == len(column_names)):
		for record in moving_inventory_data:
			moving_inventory_processed.append(dict(zip(column_names, record)))
	else:
		print('\n\nERROR LIST OF COLUMN SIZE IS NOT THE SAME SIZE AS RECORD SIZE\n\n')

	return render_template('moving_inventory.html', date=validated_date, data=moving_inventory_processed)

@app.route('/facility_inventory', methods=['GET', 'POST'])
def facility_inventory(validated_date):
	selected_facility = request.form['filter_facility']
	facility_query = "SELECT facilities.fcode, facilities.location, assets.asset_tag, assets.description, asset_at.arrive_dt, asset_at.depart_dt" \
					 " FROM (SELECT * FROM facilities WHERE common_name = %s) as facilities" \
					 " JOIN asset_at ON facilities.facility_pk = asset_at.facility_fk" \
					 " JOIN assets ON asset_at.asset_fk = assets.asset_pk" \
					 " WHERE (asset_at.depart_dt <= '%s' OR asset_at.depart_dt IS NULL)" \
					 " AND asset_at.arrive_dt >= '%s'"

	facility_inventory_data = db_query(facility_query, [selected_facility, validated_date, validated_date])
	print("\n\nLine 166 - facility_inventory_data:", facility_inventory_data)

	column_names = ['fcode', 'location', 'asset_tag', 'description', 'arrive_dt', ' depart_dt']
	facility_inventory_processed = []

	# TODO: Refactor by creating array of tuples to dictionary conversion function
	# If list is not empty and it's size matches the array of column headers
	if facility_inventory_data and (len(facility_inventory_data[0]) == len(column_names)):
		for record in facility_inventory_data:
			facility_inventory_processed.append(dict(zip(column_names, record)))
	else:
		print('\n\nERROR LIST OF COLUMN SIZE IS NOT THE SAME SIZE AS RECORD SIZE\n\n')

	print('\nThis is the data being passed:', facility_inventory_processed)
	return render_template('facility_inventory.html', facility=str(selected_facility), data=facility_inventory_processed, date=validated_date)

@app.route('/facility_inventory', methods=['GET'])
def failed_query(query_string):
	return render_template('failed_query.html', query=query_string)

# MARK: ERROR PAGES
@app.errorhandler(404)
def page_not_found(e):
	return render_template('404.html'), 404

# Application Deployment
if __name__ == '__main__':
	app.run(host='0.0.0.0', port=8080, debug=True)

"""
SELECT facilities.fcode, facilities.location, assets.asset_tag, assets.description, asset_at.arrive_dt, asset_at.depart_dt
FROM (SELECT * FROM facilities WHERE common_name = %s) as facilities
JOIN asset_at ON facilities.facility_pk = asset_at.facility_fk
JOIN assets ON asset_at.asset_fk = assets.asset_pk
WHERE (asset_at.depart_dt <= %s OR asset_at.depart_dt IS NULL) AND asset_at.arrive_dt >= %s
"""

"""
SELECT assets.asset_tag, assets.description, f1.location as location1, f2.location as location2, convoys.depart_dt, convoys.arrive_dt
FROM assets
JOIN asset_on ON assets.asset_pk = asset_on.asset_fk
JOIN convoys ON asset_on.convoy_fk = convoys.convoy_pk
JOIN facilities f1 ON convoys.src_fk = f1.facility_pk
JOIN facilities f2 ON convoys.dst_fk = f2.facility_pk
WHERE convoys.arrive_dt >= %s AND convoys.depart_dt <= %s
"""<|endoftext|>


<commit_before>"""
Example of how to train a keras model from simulated images or a
previously recorded session.

Usage:
    train.py (--sessions=<sessions>) [--epochs=<epochs>]

Options:
  --sessions=<name>   session to train on
  --epochs=<epochs>   number of epochs [default: 3].
"""

from docopt import docopt

import donkey as dk
from keras.callbacks import ModelCheckpoint
import keras

# Get args.
args = docopt(__doc__)

if __name__ == "__main__":
    print(args)
    sessions = args['--sessions'].split(',')
    epochs = int(args['--epochs'])
    #Train on session pictures
    sh = dk.sessions.SessionHandler(sessions_path='~/donkey_data/sessions/')
    s = sh.load(sessions[0])
    X, Y = s.load_dataset()

    #Train on simulated pictures
    #X, Y = dk.datasets.moving_square(n_frames=2000, return_x=True, return_y=False)

    #print('Downloading file, this could take some time.')
    #url = 'https://s3.amazonaws.com/donkey_resources/port.pkl'
    #X, Y = dk.datasets.load_url(url)

    print('Loading Model.')
    #m = dk.models.cnn3_full1_relu()
    m = keras.models.load_model('/home/wroscoe/donkey_data/models/best-diff_lines2.hdf5')

    filepath="best-"+sessions[0]+".hdf5"
    checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1,
                                 save_best_only=True, mode='min')
    callbacks_list = [checkpoint]

    hist = m.fit(X, Y, batch_size=64, nb_epoch=epochs,
                     validation_split=.2, callbacks=callbacks_list)
<commit_msg>training fix<commit_after>"""
Example of how to train a keras model from simulated images or a
previously recorded session.

Usage:
    train.py (--sessions=<sessions>) [--epochs=<epochs>]

Options:
  --sessions=<name>   session to train on
  --epochs=<epochs>   number of epochs [default: 3].
"""

from docopt import docopt

import donkey as dk
from keras.callbacks import ModelCheckpoint
import keras

# Get args.
args = docopt(__doc__)

if __name__ == "__main__":
    print(args)
    sessions = args['--sessions'].split(',')
    epochs = int(args['--epochs'])
    #Train on session pictures
    sh = dk.sessions.SessionHandler(sessions_path='~/donkey_data/sessions/')
    s = sh.load(sessions[0])
    X, Y = s.load_dataset()

    #Train on simulated pictures
    #X, Y = dk.datasets.moving_square(n_frames=2000, return_x=True, return_y=False)

    #print('Downloading file, this could take some time.')
    #url = 'https://s3.amazonaws.com/donkey_resources/port.pkl'
    #X, Y = dk.datasets.load_url(url)

    print('Loading Model.')
    m = dk.models.cnn3_full1()
    #m = keras.models.load_model('/home/wroscoe/donkey_data/models/best-diff_lines2.hdf5')

    filepath="best-"+sessions[0]+".hdf5"
    checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1,
                                 save_best_only=True, mode='min')
    callbacks_list = [checkpoint]

    hist = m.fit(X, Y, batch_size=64, nb_epoch=epochs,
                     validation_split=.2, callbacks=callbacks_list)
<|endoftext|>


<commit_before>{
  'variables':{
    # Definiton of variables that can be interpolated and used in various
    # other parts of the file.
    'conditions': [
      ['OS == "mac"', {
        'mac_sdk_min%':'10.8',
        'mac_deployment_target':'10.8',
      }],
      ['OS =="linux"',{
      },
      {}]
    ],
  },
  'includes':[
    # include other gyp settings suffix .gypi
  ],
  'target_defaults':{
    # settings that will apply to all of the targets defined
    # in this .gyp.
    'default_configuration':'Debug',
    'configurations' : {
      'Debug' : {
        'defines': [ 'DEBUG', '_DEBUG', 'VERIFY_HEAP' ],
        'cflags': [ '-g', '-O0' ],
        #'xcode_settings': {
        #  'MACOSX_DEPLOYMENT_TARGET':'<(mac_deployment_target)',
        #  'GCC_OPTIMIZATION_LEVEL': '0', # stop gyp from defaulting to -Os
        #},
      },
      'Release' : {
        'xcode_settings' : {
          # It will not work if set this in the following 'conditions'
          'MACOSX_DEPLOYMENT_TARGET':'<(mac_deployment_target)',
          }
       }
    }, # configurations
    'include_dirs' : [
      'include',
      '<(node_root_dir)/deps/v8/include'
    ],
   'conditions' : [
      # A list of condition specifications that can modify the contents of the items
      # in the global dictionary defined by this .gyp file based on the values of
      # different variables. The common use of a condition section in the top-level
      # dictionary is to add platform-specific targets to the targets list.
      ['OS=="mac"', {
        'variables':{
          'mac_sdk_min%':'10.8',
          'mac_deployment_target':'10.8',
        },
        'xcode_settings': {
          'ALWAYS_SEARCH_USER_PATHS':'YES',
          'GCC_C_LANGUAGE_STANDARD': 'c99',         # -std=c99
          'GCC_CW_ASM_SYNTAX': 'NO',                # No -fasm-blocks
          'GCC_DYNAMIC_NO_PIC': 'NO',               # No -mdynamic-no-pic
                                                    # (Equivalent to -fPIC)
          'GCC_CW_ASM_SYNTAX': 'NO',                # No -fasm-blocks
          'GCC_ENABLE_CPP_EXCEPTIONS': 'NO',        # -fno-exceptions
          'GCC_ENABLE_CPP_RTTI': 'NO',              # -fno-rtti
          'GCC_ENABLE_PASCAL_STRINGS': 'NO',        # No -mpascal-strings
          'GCC_THREADSAFE_STATICS': 'NO',           # -fno-threadsafe-statics
          'GCC_TREAT_WARNINGS_AS_ERRORS': 'NO',     # -Werror
          'PREBINDING': 'NO',                       # No -Wl,-prebind

          # -mmacosx-version-min=10.5
          'MACOSX_DEPLOYMENT_TARGET':'<(mac_deployment_target)',
          #'MACOSX_DEPLOYMENT_TARGET':'10.8',
          'USE_HEADERMAP': 'NO',

          'GCC_OPTIMIZATION_LEVEL': '3',  # -O3     # optimize -O3

          # c++ 11 Options
          'CLANG_CXX_LANGUAGE_STANDARD': 'c++11',   # c++
          'OTHER_CPLUSPLUSFLAGS':['-stdlib=libc++'], # when using c++11
          #'OTHER_LDFLAGS':['-stdlib=libc++'],

          # Warn if automatic synthesis is triggered with
          # the -Wobjc-missing-property-synthesis flag.
          'CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS': 'YES',

          'OTHER_CFLAGS': [
            '-fno-strict-aliasing',
            '-fstack-protector-all',  # Implies -fstack-protector
          ],

          'WARNING_CFLAGS': [
            '-Wall',
            '-Wendif-labels',
            '-Wextra',
            # Don't warn about unused function parameters.
            '-Wno-unused-parameter',
            # Don't warn about the "struct foo f = {0};" initialization
            # pattern.
            '-Wno-missing-field-initializers',
            '-W',
            # Match OS X clang C++11 warning settings.
            '-Wno-c++11-narrowing',
          ],
        },
      }],

      ['OS=="linux"', {
        'cflags': [
            #'<!@(pkg-config --cflags QtCore QtGui QtTest)'
          ],
        'cflags!':['-fno-exceptions'],
        'cflags_cc+': [
          '-fno-exceptions',
          '-fpermissive',
          '-std=c++11'
        ],
        'ldflags': [
            #'<!@(pkg-config --libs-only-L --libs-only-other QtCore QtGui QtTest)'
          ],
        'include_dirs':[
            'include'
          ],
        'libraries': [
            #'<!@(pkg-config --libs-only-l QtCore QtGui QtTest)'
          ],
        'linkflags':[
            '-v'
          ],
        'link_settings':{
             'libraries': [
                '-lm',
                '-lstdc++'
               ],
             'library_dirs': []
          },
        'conditions':[
            ['clang == 0 and gcc_version >=44',{
              'cflags!':['-fno-tree-sink','-fno-tree-vrp'] # disable default compiler option
              }
            ]
          ]
      }],

      ['OS!="mac" and OS!="win"', {
        'cflags': [ '-fno-omit-frame-pointer' ],
      }],
    ]
  },

  'targets': [
    # The list of targets for which this .gyp file can generate builds.
    # Each target is a dictionary that contains settings describing all
    # information necessary to build the target.
    {
      'target_name': 'svmpredict',
      #'type':'',
      #'variables': '',
      'sources': [
        #'src/svmpredict-node.cpp',
        'src/svm-predict.cpp',
        'src/svm.cpp'
       ],
      'include_dirs': [
        #'include',
      ]
    },
    {
      'target_name':'aaproperties',
      #'type':'executable',
      #'variables': '',
      'sources': [
          'src/feature.cpp'
       ],
      'include_dirs': [
          #'include',
       ],
    },
  ],
}
<commit_msg>add xcode_settings in the section of Release<commit_after>{
  'variables':{
    # Definiton of variables that can be interpolated and used in various
    # other parts of the file.
#    'conditions': [
#      ['OS == "mac"', {
#        'mac_sdk_min%':'10.8',
#        'mac_deployment_target':'10.8',
#      }],
#      ['OS =="linux"',{
#      },
#      {}]
#    ],
    'mac_sdk_min%':'10.8',
    'mac_deployment_target':'10.8',
  },
  'includes':[
    # include other gyp settings suffix .gypi
  ],
  'target_defaults':{
    # settings that will apply to all of the targets defined
    # in this .gyp.
    'default_configuration':'Debug',
    'configurations' : {
      'Debug' : {
        'defines': [ 'DEBUG', '_DEBUG', 'VERIFY_HEAP' ],
        'cflags': [ '-g', '-O0' ],
        #'xcode_settings': {
        #  'MACOSX_DEPLOYMENT_TARGET':'<(mac_deployment_target)',
        #  'GCC_OPTIMIZATION_LEVEL': '0', # stop gyp from defaulting to -Os
        #},
      },
      'Release' : {
        'xcode_settings' : {
          # It will not work if set this in the following 'conditions'
          'MACOSX_DEPLOYMENT_TARGET':'<(mac_deployment_target)',
          }
       }
    }, # configurations
    'include_dirs' : [
      'include',
      '<(node_root_dir)/deps/v8/include'
    ],
   'conditions' : [
      # A list of condition specifications that can modify the contents of the items
      # in the global dictionary defined by this .gyp file based on the values of
      # different variables. The common use of a condition section in the top-level
      # dictionary is to add platform-specific targets to the targets list.
      ['OS=="mac"', {
        'xcode_settings': {
          'ALWAYS_SEARCH_USER_PATHS':'YES',
          'GCC_C_LANGUAGE_STANDARD': 'c99',         # -std=c99
          'GCC_CW_ASM_SYNTAX': 'NO',                # No -fasm-blocks
          'GCC_DYNAMIC_NO_PIC': 'NO',               # No -mdynamic-no-pic
                                                    # (Equivalent to -fPIC)
          'GCC_CW_ASM_SYNTAX': 'NO',                # No -fasm-blocks
          'GCC_ENABLE_CPP_EXCEPTIONS': 'NO',        # -fno-exceptions
          'GCC_ENABLE_CPP_RTTI': 'NO',              # -fno-rtti
          'GCC_ENABLE_PASCAL_STRINGS': 'NO',        # No -mpascal-strings
          'GCC_THREADSAFE_STATICS': 'NO',           # -fno-threadsafe-statics
          'GCC_TREAT_WARNINGS_AS_ERRORS': 'NO',     # -Werror
          'PREBINDING': 'NO',                       # No -Wl,-prebind

          # -mmacosx-version-min=10.5
          'MACOSX_DEPLOYMENT_TARGET':'<(mac_deployment_target)',
          #'MACOSX_DEPLOYMENT_TARGET':'10.8',
          'USE_HEADERMAP': 'NO',

          'GCC_OPTIMIZATION_LEVEL': '3',  # -O3     # optimize -O3

          # c++ 11 Options
          'CLANG_CXX_LANGUAGE_STANDARD': 'c++11',   # c++
          'OTHER_CPLUSPLUSFLAGS':['-stdlib=libc++'], # when using c++11
          #'OTHER_LDFLAGS':['-stdlib=libc++'],

          # Warn if automatic synthesis is triggered with
          # the -Wobjc-missing-property-synthesis flag.
          'CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS': 'YES',

          'OTHER_CFLAGS': [
            '-fno-strict-aliasing',
            '-fstack-protector-all',  # Implies -fstack-protector
          ],

          'WARNING_CFLAGS': [
            '-Wall',
            '-Wendif-labels',
            '-Wextra',
            # Don't warn about unused function parameters.
            '-Wno-unused-parameter',
            # Don't warn about the "struct foo f = {0};" initialization
            # pattern.
            '-Wno-missing-field-initializers',
            '-W',
            # Match OS X clang C++11 warning settings.
            '-Wno-c++11-narrowing',
          ],
        },
      }],

      ['OS=="linux"', {
        'cflags': [
            #'<!@(pkg-config --cflags QtCore QtGui QtTest)'
          ],
        'cflags!':['-fno-exceptions'],
        'cflags_cc+': [
          '-fno-exceptions',
          '-fpermissive',
          '-std=c++11'
        ],
        'ldflags': [
            #'<!@(pkg-config --libs-only-L --libs-only-other QtCore QtGui QtTest)'
          ],
        'include_dirs':[
            'include'
          ],
        'libraries': [
            #'<!@(pkg-config --libs-only-l QtCore QtGui QtTest)'
          ],
        'linkflags':[
            '-v'
          ],
        'link_settings':{
             'libraries': [
                '-lm',
                '-lstdc++'
               ],
             'library_dirs': []
          },
        'conditions':[
            ['clang == 0 and gcc_version >=44',{
              'cflags!':['-fno-tree-sink','-fno-tree-vrp'] # disable default compiler option
              }
            ]
          ]
      }],

      ['OS!="mac" and OS!="win"', {
        'cflags': [ '-fno-omit-frame-pointer' ],
      }],
    ]
  },

  'targets': [
    # The list of targets for which this .gyp file can generate builds.
    # Each target is a dictionary that contains settings describing all
    # information necessary to build the target.
    {
      'target_name': 'svmpredict',
      #'type':'',
      #'variables': '',
      'sources': [
        #'src/svmpredict-node.cpp',
        'src/svm-predict.cpp',
        'src/svm.cpp'
       ],
      'include_dirs': [
        #'include',
      ]
    },
    {
      'target_name':'aaproperties',
      #'type':'executable',
      #'variables': '',
      'sources': [
          'src/feature.cpp'
       ],
      'include_dirs': [
          #'include',
       ],
    },
  ],
}
<|endoftext|>


<commit_before># ===
# This is the main GYP file, which builds better-sqlite3 with SQLite3 itself.
# ===

{
  'includes': ['deps/common.gypi'],
  'targets': [
    {
      'target_name': 'better_sqlite3',
      'dependencies': ['deps/sqlite3.gyp:sqlite3'],
      'sources': ['src/better_sqlite3.cpp'],
      'cflags': ['-std=c++11'],
      'xcode_settings': {
        'OTHER_CPLUSPLUSFLAGS': ['-std=c++11', '-stdlib=libc++'],
      },
    },
    {
      'target_name': 'test_extension',
      'dependencies': ['deps/sqlite3.gyp:sqlite3'],
      'conditions': [['sqlite3 == ""', { 'sources': ['deps/test_extension.c'] }]],
    },
  ],
}
<commit_msg>Adopt C++14 (#497)<commit_after># ===
# This is the main GYP file, which builds better-sqlite3 with SQLite3 itself.
# ===

{
  'includes': ['deps/common.gypi'],
  'targets': [
    {
      'target_name': 'better_sqlite3',
      'dependencies': ['deps/sqlite3.gyp:sqlite3'],
      'sources': ['src/better_sqlite3.cpp'],
      'cflags': ['-std=c++14'],
      'xcode_settings': {
        'OTHER_CPLUSPLUSFLAGS': ['-std=c++14', '-stdlib=libc++'],
      },
    },
    {
      'target_name': 'test_extension',
      'dependencies': ['deps/sqlite3.gyp:sqlite3'],
      'conditions': [['sqlite3 == ""', { 'sources': ['deps/test_extension.c'] }]],
    },
  ],
}
<|endoftext|>