<commit_before>"""Tests for authentication tools"""
import unittest
from unittest import mock

from utility.authentication_tools import check_resource_availability
from utility.authentication_tools import add_new_resource

class TestResponse:
    """Mock Test Response after a request"""
    @property
    def content(self):
        """Mock the content from Requests.get(params).content"""
        return '["foo"]'

class TestUser:
    """Mock user"""
    @property
    def user_id(self):
        """Mockes user id. Used in Flask.g.user_session.user_id"""
        return "Jane"

class TestUserSession:
    """Mock user session"""
    @property
    def user_session(self):
        """Mock user session. Mocks Flask.g.user_session object"""
        return TestUser()

def mock_add_resource(resource_ob, update=False):
    return resource_ob

class TestCheckResourceAvailability(unittest.TestCase):
    """Test methods related to checking the resource availability"""
    @mock.patch('utility.authentication_tools.add_new_resource')
    @mock.patch('utility.authentication_tools.Redis')
    @mock.patch('utility.authentication_tools.g', mock.Mock())
    @mock.patch('utility.authentication_tools.get_resource_id')
    def test_check_resource_availability_default_mask(
            self,
            resource_id_mock,
            redis_mock,
            add_new_resource_mock):
        """Test the resource availability with default mask"""
        resource_id_mock.return_value = 1
        redis_mock.smembers.return_value = []
        test_dataset = mock.MagicMock()
        type(test_dataset).type = mock.PropertyMock(return_value="Test")
        add_new_resource_mock.return_value = {"default_mask": 2}
        self.assertEqual(check_resource_availability(test_dataset), 2)

    @mock.patch('utility.authentication_tools.requests.get')
    @mock.patch('utility.authentication_tools.add_new_resource')
    @mock.patch('utility.authentication_tools.Redis')
    @mock.patch('utility.authentication_tools.g', TestUserSession())
    @mock.patch('utility.authentication_tools.get_resource_id')
    def test_check_resource_availability_non_default_mask(
            self,
            resource_id_mock,
            redis_mock,
            add_new_resource_mock,
            requests_mock):
        """Test the resource availability with default mask"""
        resource_id_mock.return_value = 1
        redis_mock.smembers.return_value = []
        add_new_resource_mock.return_value = {"default_mask": 2}
        requests_mock.return_value = TestResponse()
        test_dataset = mock.MagicMock()
        type(test_dataset).type = mock.PropertyMock(return_value="Test")
        self.assertEqual(check_resource_availability(test_dataset),
                         ['foo'])

    @mock.patch('utility.authentication_tools.webqtlConfig.SUPER_PRIVILEGES',
                "SUPERUSER")
    @mock.patch('utility.authentication_tools.requests.get')
    @mock.patch('utility.authentication_tools.add_new_resource')
    @mock.patch('utility.authentication_tools.Redis')
    @mock.patch('utility.authentication_tools.g', TestUserSession())
    @mock.patch('utility.authentication_tools.get_resource_id')
    def test_check_resource_availability_of_super_user(
            self,
            resource_id_mock,
            redis_mock,
            add_new_resource_mock,
            requests_mock):
        """Test the resource availability if the user is the super user"""
        resource_id_mock.return_value = 1
        redis_mock.smembers.return_value = ["Jane"]
        add_new_resource_mock.return_value = {"default_mask": 2}
        requests_mock.return_value = TestResponse()
        test_dataset = mock.MagicMock()
        type(test_dataset).type = mock.PropertyMock(return_value="Test")
        self.assertEqual(check_resource_availability(test_dataset),
                         "SUPERUSER")

    @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES',
                "John Doe")
    def test_check_resource_availability_string_dataset(self):
        """Test the resource availability if the dataset is a string"""
        self.assertEqual(check_resource_availability("Test"),
                         "John Doe")

    @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES',
                "John Doe")
    def test_check_resource_availability_temp(self):
        """Test the resource availability if the dataset is a string"""
        test_dataset = mock.MagicMock()
        type(test_dataset).type = mock.PropertyMock(return_value="Temp")
        self.assertEqual(check_resource_availability(test_dataset),
                         "John Doe")

class TestAddNewResource(unittest.TestCase):
    """Test cases for add_new_resource method"""
    @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES',
                "John Doe")
    @mock.patch('utility.authentication_tools.add_resource', mock_add_resource)
    @mock.patch('utility.authentication_tools.get_group_code')
    def test_add_new_resource_if_publish_datatype(self, group_code_mock):
        """Test add_new_resource if dataset type is 'publish'"""
        group_code_mock.return_value = "Test"
        test_dataset = mock.MagicMock()
        type(test_dataset).type = mock.PropertyMock(return_value="Publish")
        type(test_dataset).id = mock.PropertyMock(return_value=10)
        expected_value = {
            "owner_id": "none",
            "default_mask": "John Doe",
            "group_masks": {},
            "name": "Test_None",
            "data": {
                "dataset": 10,
                "trait": None
            },
            "type": "dataset-publish"
        }
        self.assertEqual(add_new_resource(test_dataset),
                         expected_value)

    @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES',
                "John Doe")
    @mock.patch('utility.authentication_tools.add_resource', mock_add_resource)
    @mock.patch('utility.authentication_tools.get_group_code')
    def test_add_new_resource_if_geno_datatype(self, group_code_mock):
        """Test add_new_resource if dataset type is 'geno'"""
        group_code_mock.return_value = "Test"
        test_dataset = mock.MagicMock()
        type(test_dataset).name = mock.PropertyMock(return_value="Geno")
        type(test_dataset).type = mock.PropertyMock(return_value="Geno")
        type(test_dataset).id = mock.PropertyMock(return_value=20)
        expected_value = {
            "owner_id": "none",
            "default_mask": "John Doe",
            "group_masks": {},
            "name": "Geno",
            "data": {
                "dataset": 20,
            },
            "type": "dataset-geno"
        }
        self.assertEqual(add_new_resource(test_dataset),
                         expected_value)

    @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES',
                "John Doe")
    @mock.patch('utility.authentication_tools.add_resource', mock_add_resource)
    @mock.patch('utility.authentication_tools.get_group_code')
    def test_add_new_resource_if_other_datatype(self, group_code_mock):
        """Test add_new_resource if dataset type is not 'geno' or 'publish'"""
        group_code_mock.return_value = "Test"
        test_dataset = mock.MagicMock()
        type(test_dataset).name = mock.PropertyMock(return_value="Geno")
        type(test_dataset).type = mock.PropertyMock(return_value="other")
        type(test_dataset).id = mock.PropertyMock(return_value=20)
        expected_value = {
            "owner_id": "none",
            "default_mask": "John Doe",
            "group_masks": {},
            "name": "Geno",
            "data": {
                "dataset": 20,
            },
            "type": "dataset-probeset"
        }
        self.assertEqual(add_new_resource(test_dataset),
                         expected_value)
<commit_msg>Patched utility.authentication_tools.g as TestUserSession because otherwise the str.encode failed on the mock.Mock() object, and this also seems consistent with the way it's done in a later method<commit_after>"""Tests for authentication tools"""
import unittest
from unittest import mock

from utility.authentication_tools import check_resource_availability
from utility.authentication_tools import add_new_resource

class TestResponse:
    """Mock Test Response after a request"""
    @property
    def content(self):
        """Mock the content from Requests.get(params).content"""
        return '["foo"]'

class TestUser:
    """Mock user"""
    @property
    def user_id(self):
        """Mockes user id. Used in Flask.g.user_session.user_id"""
        return "Jane"

class TestUserSession:
    """Mock user session"""
    @property
    def user_session(self):
        """Mock user session. Mocks Flask.g.user_session object"""
        return TestUser()

def mock_add_resource(resource_ob, update=False):
    return resource_ob

class TestCheckResourceAvailability(unittest.TestCase):
    """Test methods related to checking the resource availability"""
    @mock.patch('utility.authentication_tools.add_new_resource')
    @mock.patch('utility.authentication_tools.Redis')
    @mock.patch('utility.authentication_tools.g', TestUserSession())
    @mock.patch('utility.authentication_tools.get_resource_id')
    def test_check_resource_availability_default_mask(
            self,
            resource_id_mock,
            redis_mock,
            add_new_resource_mock):
        """Test the resource availability with default mask"""

        resource_id_mock.return_value = 1
        redis_mock.smembers.return_value = []
        test_dataset = mock.MagicMock()
        type(test_dataset).type = mock.PropertyMock(return_value="Test")
        add_new_resource_mock.return_value = {"default_mask": 2}
        self.assertEqual(check_resource_availability(test_dataset), 2)

    @mock.patch('utility.authentication_tools.requests.get')
    @mock.patch('utility.authentication_tools.add_new_resource')
    @mock.patch('utility.authentication_tools.Redis')
    @mock.patch('utility.authentication_tools.g', TestUserSession())
    @mock.patch('utility.authentication_tools.get_resource_id')
    def test_check_resource_availability_non_default_mask(
            self,
            resource_id_mock,
            redis_mock,
            add_new_resource_mock,
            requests_mock):
        """Test the resource availability with non-default mask"""
        resource_id_mock.return_value = 1
        redis_mock.smembers.return_value = []
        add_new_resource_mock.return_value = {"default_mask": 2}
        requests_mock.return_value = TestResponse()
        test_dataset = mock.MagicMock()
        type(test_dataset).type = mock.PropertyMock(return_value="Test")
        self.assertEqual(check_resource_availability(test_dataset),
                         ['foo'])

    @mock.patch('utility.authentication_tools.webqtlConfig.SUPER_PRIVILEGES',
                "SUPERUSER")
    @mock.patch('utility.authentication_tools.requests.get')
    @mock.patch('utility.authentication_tools.add_new_resource')
    @mock.patch('utility.authentication_tools.Redis')
    @mock.patch('utility.authentication_tools.g', TestUserSession())
    @mock.patch('utility.authentication_tools.get_resource_id')
    def test_check_resource_availability_of_super_user(
            self,
            resource_id_mock,
            redis_mock,
            add_new_resource_mock,
            requests_mock):
        """Test the resource availability if the user is the super user"""
        resource_id_mock.return_value = 1
        redis_mock.smembers.return_value = ["Jane"]
        add_new_resource_mock.return_value = {"default_mask": 2}
        requests_mock.return_value = TestResponse()
        test_dataset = mock.MagicMock()
        type(test_dataset).type = mock.PropertyMock(return_value="Test")
        self.assertEqual(check_resource_availability(test_dataset),
                         "SUPERUSER")

    @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES',
                "John Doe")
    def test_check_resource_availability_string_dataset(self):
        """Test the resource availability if the dataset is a string"""
        self.assertEqual(check_resource_availability("Test"),
                         "John Doe")

    @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES',
                "John Doe")
    def test_check_resource_availability_temp(self):
        """Test the resource availability if the dataset is a string"""
        test_dataset = mock.MagicMock()
        type(test_dataset).type = mock.PropertyMock(return_value="Temp")
        self.assertEqual(check_resource_availability(test_dataset),
                         "John Doe")

class TestAddNewResource(unittest.TestCase):
    """Test cases for add_new_resource method"""
    @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES',
                "John Doe")
    @mock.patch('utility.authentication_tools.add_resource', mock_add_resource)
    @mock.patch('utility.authentication_tools.get_group_code')
    def test_add_new_resource_if_publish_datatype(self, group_code_mock):
        """Test add_new_resource if dataset type is 'publish'"""
        group_code_mock.return_value = "Test"
        test_dataset = mock.MagicMock()
        type(test_dataset).type = mock.PropertyMock(return_value="Publish")
        type(test_dataset).id = mock.PropertyMock(return_value=10)
        expected_value = {
            "owner_id": "none",
            "default_mask": "John Doe",
            "group_masks": {},
            "name": "Test_None",
            "data": {
                "dataset": 10,
                "trait": None
            },
            "type": "dataset-publish"
        }
        self.assertEqual(add_new_resource(test_dataset),
                         expected_value)

    @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES',
                "John Doe")
    @mock.patch('utility.authentication_tools.add_resource', mock_add_resource)
    @mock.patch('utility.authentication_tools.get_group_code')
    def test_add_new_resource_if_geno_datatype(self, group_code_mock):
        """Test add_new_resource if dataset type is 'geno'"""
        group_code_mock.return_value = "Test"
        test_dataset = mock.MagicMock()
        type(test_dataset).name = mock.PropertyMock(return_value="Geno")
        type(test_dataset).type = mock.PropertyMock(return_value="Geno")
        type(test_dataset).id = mock.PropertyMock(return_value=20)
        expected_value = {
            "owner_id": "none",
            "default_mask": "John Doe",
            "group_masks": {},
            "name": "Geno",
            "data": {
                "dataset": 20,
            },
            "type": "dataset-geno"
        }
        self.assertEqual(add_new_resource(test_dataset),
                         expected_value)

    @mock.patch('utility.authentication_tools.webqtlConfig.DEFAULT_PRIVILEGES',
                "John Doe")
    @mock.patch('utility.authentication_tools.add_resource', mock_add_resource)
    @mock.patch('utility.authentication_tools.get_group_code')
    def test_add_new_resource_if_other_datatype(self, group_code_mock):
        """Test add_new_resource if dataset type is not 'geno' or 'publish'"""
        group_code_mock.return_value = "Test"
        test_dataset = mock.MagicMock()
        type(test_dataset).name = mock.PropertyMock(return_value="Geno")
        type(test_dataset).type = mock.PropertyMock(return_value="other")
        type(test_dataset).id = mock.PropertyMock(return_value=20)
        expected_value = {
            "owner_id": "none",
            "default_mask": "John Doe",
            "group_masks": {},
            "name": "Geno",
            "data": {
                "dataset": 20,
            },
            "type": "dataset-probeset"
        }
        self.assertEqual(add_new_resource(test_dataset),
                         expected_value)
<|endoftext|>


<commit_before># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class PyTabulate(PythonPackage):
    """Pretty-print tabular data"""

    homepage = "https://bitbucket.org/astanin/python-tabulate"
    pypi = "tabulate/tabulate-0.8.6.tar.gz"

    version('0.8.7', sha256='db2723a20d04bcda8522165c73eea7c300eda74e0ce852d9022e0159d7895007')
    version('0.8.6', sha256='5470cc6687a091c7042cee89b2946d9235fe9f6d49c193a4ae2ac7bf386737c8')
    version('0.8.3', sha256='8af07a39377cee1103a5c8b3330a421c2d99b9141e9cc5ddd2e3263fea416943')
    version('0.7.7', sha256='83a0b8e17c09f012090a50e1e97ae897300a72b35e0c86c0b53d3bd2ae86d8c6')

    depends_on('py-setuptools', type='build')
<commit_msg>[py-tabulate] added version 0.8.9 (#25974)<commit_after># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class PyTabulate(PythonPackage):
    """Pretty-print tabular data"""

    homepage = "https://bitbucket.org/astanin/python-tabulate"
    pypi = "tabulate/tabulate-0.8.6.tar.gz"

    version('0.8.9', sha256='eb1d13f25760052e8931f2ef80aaf6045a6cceb47514db8beab24cded16f13a7')
    version('0.8.7', sha256='db2723a20d04bcda8522165c73eea7c300eda74e0ce852d9022e0159d7895007')
    version('0.8.6', sha256='5470cc6687a091c7042cee89b2946d9235fe9f6d49c193a4ae2ac7bf386737c8')
    version('0.8.3', sha256='8af07a39377cee1103a5c8b3330a421c2d99b9141e9cc5ddd2e3263fea416943')
    version('0.7.7', sha256='83a0b8e17c09f012090a50e1e97ae897300a72b35e0c86c0b53d3bd2ae86d8c6')

    depends_on('py-setuptools', type='build')
<|endoftext|>


<commit_before>#!/usr/bin/env python
# encoding: utf-8

def validate(f):
    '''
    Check if resource parameters is valid
    '''
    def wrapper(self, params):
        if not params.is_valid():
            return params.errors()
        return f(self, params)
    return wrapper
<commit_msg>add useful decorators<commit_after>#!/usr/bin/env python
# encoding: utf-8

def validate(f):
    '''
    Check if resource parameters is valid
    '''
    def wrapper(self, params):
        if not params.is_valid():
            return params.errors()
        return f(self, params)
    return wrapper

def login_required(f):
    def wrapper(self, *args, **kwargs):
        if self.request.user.is_authenticated():
            return f(self, *args, **kwargs)
        else:
            return 401
    return wrapper

class validateForm(object):
    def __init__(self, form):
        self.form   = form

    def __call__(self, f):
        def wrapper(klass, *args, **kwargs):

            def validate(*form_args):
                form = self.form(*form_args)
                if form.is_valid():
                    klass.form = form
                    return f(klass, *args, **kwargs)
                return 400

            request = klass.request
            if not hasattr(request, "FILES"):
                return validate( request.REQUEST )
            return validate( request.REQUEST, request.FILES )
        return wrapper

class exceptionHandling(object):
    def __init__(self, exception, return_value=400):
        self.exception    = exception
        self.return_value = return_value

    def __call__(self, f):
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except self.exception:
                return self.return_value
        return wrapper
        <|endoftext|>


<commit_before>#!/usr/bin/env python
#
# Save/restore dashboards
#

import os
import sys
import zipfile
import json
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdcClient

#
# Parse arguments
#
if len(sys.argv) != 3:
    print 'usage: %s <sysdig-token> <file-name>' % sys.argv[0]
    print 'You can find your token at https://app.sysdigcloud.com/#/settings/user'
    sys.exit(1)

sdc_token = sys.argv[1]
dashboard_state_file = sys.argv[2]

#
# Instantiate the SDC client
#
sdclient = SdcClient(sdc_token)

zipf = zipfile.ZipFile(dashboard_state_file, 'r')

for info in zipf.infolist():
    data = zipf.read(info.filename)
    dboard = json.loads(data)

    dboard['timeMode'] = {'mode' : 1}
    dboard['time'] = {'last' : 2 * 60 * 60 * 1000000, 'sampling' : 2 * 60 * 60 * 1000000}

    # Single filter support for all restored dashboards
    # TODO: add support to get filter from saved dashboard
    dashboardFilter = "proc.name = cassandra"
    res = sdclient.create_dashboard_from_template(dboard['name'] + '-restored', dboard, dashboardFilter)
    if res[0] == False:
        print "Dashboard creation failed for dashboard name %s with error %s" % (j['name'], res[1])
<commit_msg>At Kini's request, revert "Enhanced restore capability". Too much original dashboard config was stripped.<commit_after>#!/usr/bin/env python
#
# Save/restore dashboards
#

import os
import sys
import zipfile
import json
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdcClient

#
# Parse arguments
#
if len(sys.argv) != 3:
    print 'usage: %s <sysdig-token> <file-name>' % sys.argv[0]
    print 'You can find your token at https://app.sysdigcloud.com/#/settings/user'
    sys.exit(1)

sdc_token = sys.argv[1]
dashboard_state_file = sys.argv[2]

#
# Instantiate the SDC client
#
sdclient = SdcClient(sdc_token)

zipf = zipfile.ZipFile(dashboard_state_file, 'r')

dashboard_conf_items = ['showAsType', 'filterRoot', 'linkMetrics',
                        'singleTimeNavigation', 'gridConfiguration', 'responsive',
                        'nodesNoiseFilter', 'compareWith', 'format', 'linksNoiseFilter',
                        'filterProcesses', 'isLegendExpanded', 'inhertitTimeNavigation',
                        'schema', 'sortAscending', 'mapDataLimit', 'metrics', 'filterExtNodes',
                        'sorting', 'name', 'sourceExploreView', 'items', 'showAs', 'eventsFilter',
                        'timeMode', 'isShared', 'sourceDrilldownView']

for info in zipf.infolist():
    data = zipf.read(info.filename)
    j = json.loads(data)
    k = {}
    for item in j.keys():
        if item in dashboard_conf_items:
            k[item] = j[item]

    res = sdclient.create_dashboard_with_configuration(k)
    if res[0] == False:
        print "Dashboard creation failed for dashboard name %s with error %s" % (j['name'], res[1])
<|endoftext|>


<commit_before># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

class PyTraitsui(PythonPackage):
    """The TraitsUI project contains a toolkit-independent GUI abstraction
    layer, which is used to support the "visualization" features of the Traits
    package. Thus, you can write model in terms of the Traits API and specify a
    GUI in terms of the primitives supplied by TraitsUI (views, items, editors,
    etc.), and let TraitsUI and your selected toolkit and back-end take care of
    the details of displaying them."""

    homepage = "https://docs.enthought.com/traitsui"
    pypi = "traitsui/traitsui-6.1.3.tar.gz"

    version('6.1.3', sha256='48381763b181efc58eaf288431d1d92d028d0d97dfdd33eba7809aae8aef814f')

    variant('backend', default='pyqt5', description='Default backend',
            values=('wx', 'pyqt', 'pyqt5', 'pyside'), multi=False)

    depends_on('py-setuptools', type='build')
    depends_on('py-traits', type=('build', 'run'))
    depends_on('py-pyface@6.0.0:', type=('build', 'run'))
    depends_on('py-six', type=('build', 'run'))

    # Backends
    depends_on('py-wxpython@2.8.10:', when='backend=wx', type=('build', 'run'))
    depends_on('py-numpy', when='backend=wx', type=('build', 'run'))
    depends_on('py-pyqt4@4.10:', when='backend=pyqt', type=('build', 'run'))
    depends_on('py-pygments', when='backend=pyqt', type=('build', 'run'))
    depends_on('py-pyqt5@5:', when='backend=pyqt5', type=('build', 'run'))
    depends_on('py-pygments', when='backend=pyqt5', type=('build', 'run'))
    depends_on('py-pyside@1.2:', when='backend=pyside', type=('build', 'run'))
    depends_on('py-pygments', when='backend=pyside', type=('build', 'run'))
<commit_msg>py-traitsui: add v7.2.1 (#26392)<commit_after># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

class PyTraitsui(PythonPackage):
    """The TraitsUI project contains a toolkit-independent GUI abstraction
    layer, which is used to support the "visualization" features of the Traits
    package. Thus, you can write model in terms of the Traits API and specify a
    GUI in terms of the primitives supplied by TraitsUI (views, items, editors,
    etc.), and let TraitsUI and your selected toolkit and back-end take care of
    the details of displaying them."""

    homepage = "https://docs.enthought.com/traitsui"
    pypi = "traitsui/traitsui-6.1.3.tar.gz"

    version('7.2.1', sha256='dfc39015faf0591f9927e3d4d22bd95a16d49c85db30e60acd4ba7b85c7c5d5b')
    version('6.1.3', sha256='48381763b181efc58eaf288431d1d92d028d0d97dfdd33eba7809aae8aef814f')

    variant('backend', default='pyqt5', description='Default backend',
            values=('wx', 'pyqt', 'pyqt5', 'pyside', 'pyside2'), multi=False)

    depends_on('python@3.6:', when='@7.2:', type='build')
    depends_on('py-setuptools', type='build')
    depends_on('py-traits@6.2:', when='@7.3:', type=('build', 'run'))
    depends_on('py-traits@6.1:', when='@7.2:', type=('build', 'run'))
    depends_on('py-traits@6:', when='@7.1:', type=('build', 'run'))
    depends_on('py-traits', type=('build', 'run'))
    depends_on('py-pyface@7.3:', when='@7.3:', type=('build', 'run'))
    depends_on('py-pyface@7.1:', when='@7.1:', type=('build', 'run'))
    depends_on('py-pyface@6:', type=('build', 'run'))
    depends_on('py-six', when='@:6', type=('build', 'run'))

    conflicts('backend=pyside', when='@7.1:')
    conflicts('backend=pyside2', when='@:7.0')

    # Backends
    with when('backend=wx'):
        depends_on('py-wxpython@4:', when='@7:', type=('build', 'run'))
        depends_on('py-wxpython@2.8.10:', type=('build', 'run'))
        depends_on('py-numpy', type=('build', 'run'))
    with when('backend=pyqt'):
        depends_on('py-pyqt4@4.10:', type=('build', 'run'))
        depends_on('py-pygments', type=('build', 'run'))
    with when('backend=pyqt5'):
        depends_on('py-pyqt5@5:', type=('build', 'run'))
        depends_on('py-pygments', type=('build', 'run'))
    with when('backend=pyside'):
        depends_on('py-pyside@1.2:', type=('build', 'run'))
        depends_on('py-pygments', type=('build', 'run'))
    with when('backend=pyside2'):
        depends_on('py-pyside2', type=('build', 'run'))
        depends_on('py-shiboken2', type=('build', 'run'))
        depends_on('py-pygments', type=('build', 'run'))
<|endoftext|>


<commit_before># Copyright (c) 2010-2011 gocept gmbh & co. kg
# See also LICENSE.txt

from zope.cachedescriptors.property import Lazy as cachedproperty
import calendar
import datetime
import grokcore.component as grok
import pytz
import transaction
import zeit.addcentral.add
import zeit.addcentral.interfaces
import zeit.brightcove.interfaces
import zeit.cms.checkout.interfaces
import zeit.cms.content.interfaces
import zeit.cms.interfaces
import zeit.cms.tagging.interfaces
import zeit.cms.workflow.interfaces
import zeit.connector.interfaces
import zeit.connector.search
import zeit.content.video.interfaces
import zeit.content.video.playlist
import zeit.content.video.video
import zope.component
import zope.interface

def to_epoch(value):
    return calendar.timegm(value.utctimetuple())

class mapped(object):

    field = None

    def __init__(self, *path):
        assert path
        self.path = path

    def __get__(self, instance, class_):
        if instance is None:
            return self
        try:
            return self._get_from_dict(instance.data)
        except KeyError:
            if self.field is None:
                self._guess_field(class_)
            if self.field is not None:
                return self.field.default

    def _guess_field(self, class_):
        for key, value in class_.__dict__.items():
            if value is self:
                break
        else:
            return
        for interface in zope.interface.implementedBy(class_):
            try:
                field = interface[key]
            except KeyError:
                pass
            else:
                self.field = field
                break

    def _get_from_dict(self, value):
        for key in self.path:
            value = value[key]
        return value

    def __set__(self, instance, value):
        data = instance.data
        for key in self.path[:-1]:
            data = data.setdefault(key, {})
        data[self.path[-1]] = value

class mapped_bool(mapped):

    def _get_from_dict(self, value):
        value = super(mapped_bool, self)._get_from_dict(value)
        return value == '1'

    def __set__(self, instance, value):
        value = '1' if value else '0'
        super(mapped_bool, self).__set__(instance, value)

class mapped_keywords(mapped):
    """Maps the labels stored in brightcove to a list of tags.
    """

    def __get__(self, instance, class_):
        whitelist = zope.component.getUtility(
            zeit.cms.tagging.interfaces.IWhitelist)
        value = super(mapped_keywords, self).__get__(instance, class_)
        result = []
        if value:
            for code in value.split(';'):
                tag = whitelist.get(code)
                if tag is not None:
                    result.append(tag)
        return tuple(result)

    def __set__(self, instance, value):
        value = ';'.join(tag.code for tag in value)
        super(mapped_keywords, self).__set__(instance, value)

class mapped_datetime(mapped):

    def __get__(self, instance, class_):
        value = super(mapped_datetime, self).__get__(instance, class_)
        if not value:
            return None
        date = datetime.datetime.utcfromtimestamp(int(value)/1000)
        return pytz.utc.localize(date)

    def __set__(self, instance, value):
        value = str(to_epoch(value) * 1000)
        super(mapped_datetime, self).__set__(instance, value)

class mapped_product(mapped):

    def _get_from_dict(self, value):
        if (value['customFields']['produkt-id'] is None and
            value['referenceId'] is not None):
            return 'Reuters'
        for key in self.path:
            value = value[key]
        return value

class BCContent(object):
    # XXX remove at some point

    pass

class Converter(object):

    zope.interface.implements(zeit.brightcove.interfaces.IBrightcoveContent)

    data = None
    id = mapped('id')
    title = mapped('name')
    teaserText = mapped('shortDescription')
    brightcove_thumbnail = mapped('thumbnailURL')

    def __init__(self, data, connection=None):
        if data is not None:
            self.data = data
            if 'customFields' in self.data:
                self.data['customFields'] = self.data['customFields']

    @cachedproperty
    def uniqueId(self):
        return '%s/%s' % (
            zeit.addcentral.interfaces.IAddLocation(self).uniqueId, self.id)

    @property
    def thumbnail(self):
        return self.data['thumbnailURL']

    @classmethod
    def find_by_id(cls, id):
        try:
            return iter(cls.find_by_ids([id])).next()
        except StopIteration:
            raise KeyError(id)

    @staticmethod
    def get_connection():
        return zope.component.getUtility(
            zeit.brightcove.interfaces.IAPIConnection)

    def save(self):
        registered = getattr(self, '_v_save_hook_registered', False)
        if not registered:
            transaction.get().addBeforeCommitHook(self._save)
            self._v_save_hook_registered = True

    def _save(self):
        try:
            del self._v_save_hook_registered
        except AttributeError:
            pass
        __traceback_info__ = (self.data,)

        data = dict(self.data)
        if 'customFields' in data:
            data['customFields'] = dict(data['customFields'])
        READ_ONLY = ['lastModifiedDate', 'creationDate', 'publishedDate']
        for field in READ_ONLY:
            data.pop(field, None)
        self.get_connection().post('update_video', video=data)

    def __str__(self):
        return '<%s id=%s>' % (self.__class__.__name__, self.id)

class Video(Converter):

    zope.interface.implements(zeit.brightcove.interfaces.IVideo)

    type = 'video'
    id_prefix = 'vid' # for old-style asset IDs
    commentsAllowed = mapped_bool('customFields', 'allow_comments')
    banner = mapped_bool('customFields', 'banner')
    banner_id = mapped('customFields', 'banner-id')
    breaking_news = mapped_bool('customFields', 'breaking-news')
    dailyNewsletter = mapped_bool('customFields', 'newsletter')
    has_recensions = mapped_bool('customFields', 'recensions')
    item_state = mapped('itemState')
    keywords = mapped_keywords('customFields', 'cmskeywords')
    product_id = mapped('customFields', 'produkt-id')
    ressort = mapped('customFields', 'ressort')
    serie = mapped('customFields', 'serie')
    subtitle = mapped('longDescription')
    supertitle = mapped('customFields', 'supertitle')
    video_still = mapped('videoStillURL')
    flv_url = mapped('FLVURL')

    expires = mapped_datetime('endDate')
    date_last_modified = mapped_datetime('lastModifiedDate')
    date_created = mapped_datetime('creationDate')
    date_first_released = mapped_datetime('publishedDate')

    fields = ",".join((
        'creationDate',
        'customFields',
        'economics',
        'endDate',
        'id',
        'itemState',
        'lastModifiedDate',
        'length',
        'linkText',
        'linkURL',
        'longDescription',
        'name',
        'playsTotal',
        'playsTrailingWeek',
        'publisheddate',
        'referenceId',
        'shortDescription',
        'tags',
        'thumbnailURL',
        'videoStillURL',
        'FLVURL',
    ))

    @classmethod
    def find_by_ids(class_, ids):
        ids = ','.join(str(i) for i in ids)
        return class_.get_connection().get_list(
            'find_videos_by_ids', class_, video_ids=ids,
            video_fields=class_.fields)

    @classmethod
    def find_modified(class_, from_date):
        from_date = to_epoch(from_date) / 60
        return class_.get_connection().get_list(
            'find_modified_videos', class_,
            from_date=from_date,
            video_fields=class_.fields,
            filter='PLAYABLE,DELETED,INACTIVE,UNSCHEDULED',
            sort_by='MODIFIED_DATE', sort_order='DESC')

    @property
    def related(self):
        result = []
        custom = self.data.get('customFields')
        if custom is None:
            return ()
        for i in range(1, 6):
            unique_id = custom.get('ref_link%s' % i)
            if unique_id is not None:
                content = zeit.cms.interfaces.ICMSContent(unique_id, None)
                if content is not None:
                    result.append(content)
        return tuple(result)

    @related.setter
    def related(self, value):
        if not value:
            value = ()
        custom = self.data.setdefault('customFields', {})

        for i in range(1, 6):
            custom['ref_link%i' % i] = ''
            custom['ref_title%i' % i] = ''
        for i, obj in enumerate(value, 1):
            metadata = zeit.cms.content.interfaces.ICommonMetadata(obj, None)
            if metadata is None:
                continue
            custom['ref_link%s' % i] = obj.uniqueId
            custom['ref_title%s' % i] = metadata.teaserTitle

    @property
    def year(self):
        try:
            modified = int(self.data.get('lastModifiedDate'))
        except (TypeError, ValueError):
            return None
        return datetime.datetime.fromtimestamp(modified/1000).year

    # XXX year.setter is missing

    def to_cms(self, video=None):
        if video is None:
            video = zeit.content.video.video.Video()
        for key in zeit.content.video.interfaces.IVideo:
            try:
                setattr(video, key, getattr(self, key))
            except AttributeError:
                pass
        video.brightcove_id = str(self.id)
        sc = zeit.cms.content.interfaces.ISemanticChange(video)
        sc.last_semantic_change = self.date_last_modified
        info = zeit.cms.workflow.interfaces.IPublishInfo(video)
        info.date_last_published = self.date_first_released
        return video

    @classmethod
    def from_cms(cls, video):
        instance = cls(data=dict(id='foo'))
        instance.id = video.brightcove_id
        for key in zeit.content.video.interfaces.IVideo:
            try:
                setattr(instance, key, getattr(video, key))
            except AttributeError:
                pass
        date_last_modified = \
            zeit.cms.content.interfaces.ISemanticChange(
            video).last_semantic_change
        if date_last_modified is not None:
            instance.date_last_modified = date_last_modified
        try:
            bc_state = cls.find_by_id(instance.id)
            instance.date_first_released = bc_state.date_first_released
        except KeyError:
            pass # avoid failures in test setup
        return instance

@grok.implementer(zeit.addcentral.interfaces.IAddLocation)
@grok.adapter(Video)
def video_location(bc_object):
    config = zope.app.appsetup.product.getProductConfiguration(
        'zeit.brightcove')
    path = config['video-folder']
    return zeit.addcentral.add.find_or_create_folder(
        *(path.split('/') + [bc_object.date_created.strftime('%Y-%m')]))

class Playlist(Converter):

    zope.interface.implements(zeit.brightcove.interfaces.IPlaylist)
    type = 'playlist'
    id_prefix = 'pls' # for old-style asset IDs
    item_state = 'ACTIVE'
    fields = ",".join((
        'id',
        'name',
        'shortDescription',
        'thumbnailURL',
        'videoIds',
    ))

    @property
    def video_ids(self):
        return tuple(
            resolve_video_id(str(id)) for id in self.data['videoIds'])

    @classmethod
    def find_by_ids(class_, ids):
        ids = ','.join(str(i) for i in ids)
        return class_.get_connection().get_list(
            'find_playlists_by_ids', class_,
            playlist_fields=class_.fields,
            playlist_ids=ids)

    @classmethod
    def find_all(class_):
        return class_.get_connection().get_list(
            'find_all_playlists', class_,
            playlist_fields=class_.fields)

    def to_cms(self, playlist=None):
        if playlist is None:
            playlist = zeit.content.video.playlist.Playlist()
        for key in zeit.content.video.interfaces.IPlaylist:
            try:
                setattr(playlist, key, getattr(self, key))
            except AttributeError:
                pass
        return playlist

    @classmethod
    def from_cms(cls, playlist):
        instance = cls(data=dict(id='foo'))
        for key in zeit.content.video.interfaces.IPlaylist:
            try:
                setattr(instance, key, getattr(playlist, key))
            except AttributeError:
                pass
        return instance

@grok.implementer(zeit.addcentral.interfaces.IAddLocation)
@grok.adapter(Playlist)
def playlist_location(bc_object):
    config = zope.app.appsetup.product.getProductConfiguration(
        'zeit.brightcove')
    path = config['playlist-folder']
    return zeit.addcentral.add.find_or_create_folder(*path.split('/'))

BRIGHTCOVE_ID = zeit.connector.search.SearchVar(
    'id', 'http://namespaces.zeit.de/CMS/brightcove')

def resolve_video_id(video_id):
    connector = zope.component.getUtility(
            zeit.connector.interfaces.IConnector)
    result = list(
        connector.search([BRIGHTCOVE_ID], BRIGHTCOVE_ID == video_id))
    if not result:
        raise LookupError(video_id)
    if len(result) > 1:
        raise LookupError(
            'Found multiple CMS objects with video id %r.' % video_id)
    result = result[0]
    unique_id = result[0]
    return unique_id

def update_brightcove(context, event):
    zeit.brightcove.interfaces.IBrightcoveObject(context).save()

@grok.adapter(zeit.content.video.interfaces.IVideo)
@grok.implementer(zeit.brightcove.interfaces.IBrightcoveObject)
def video_from_cms(context):
    return Video.from_cms(context)

@grok.adapter(zeit.content.video.interfaces.IPlaylist)
@grok.implementer(zeit.brightcove.interfaces.IBrightcoveObject)
def playlist_from_cms(context):
    return Playlist.from_cms(context)

def publish_on_checkin(context, event):
    # prevent infinite loop, since there is a checkout/checkin cycle during
    # publishing (to update XML references etc.)
    if not event.publishing:
        zeit.cms.workflow.interfaces.IPublish(context).publish()
<commit_msg>Fix inconsistency between mock and real connector regarding trailing slashes in folder uniqueIds<commit_after># Copyright (c) 2010-2011 gocept gmbh & co. kg
# See also LICENSE.txt

from zope.cachedescriptors.property import Lazy as cachedproperty
import calendar
import datetime
import grokcore.component as grok
import pytz
import transaction
import zeit.addcentral.add
import zeit.addcentral.interfaces
import zeit.brightcove.interfaces
import zeit.cms.checkout.interfaces
import zeit.cms.content.interfaces
import zeit.cms.interfaces
import zeit.cms.tagging.interfaces
import zeit.cms.workflow.interfaces
import zeit.connector.interfaces
import zeit.connector.search
import zeit.content.video.interfaces
import zeit.content.video.playlist
import zeit.content.video.video
import zope.component
import zope.interface

def to_epoch(value):
    return calendar.timegm(value.utctimetuple())

class mapped(object):

    field = None

    def __init__(self, *path):
        assert path
        self.path = path

    def __get__(self, instance, class_):
        if instance is None:
            return self
        try:
            return self._get_from_dict(instance.data)
        except KeyError:
            if self.field is None:
                self._guess_field(class_)
            if self.field is not None:
                return self.field.default

    def _guess_field(self, class_):
        for key, value in class_.__dict__.items():
            if value is self:
                break
        else:
            return
        for interface in zope.interface.implementedBy(class_):
            try:
                field = interface[key]
            except KeyError:
                pass
            else:
                self.field = field
                break

    def _get_from_dict(self, value):
        for key in self.path:
            value = value[key]
        return value

    def __set__(self, instance, value):
        data = instance.data
        for key in self.path[:-1]:
            data = data.setdefault(key, {})
        data[self.path[-1]] = value

class mapped_bool(mapped):

    def _get_from_dict(self, value):
        value = super(mapped_bool, self)._get_from_dict(value)
        return value == '1'

    def __set__(self, instance, value):
        value = '1' if value else '0'
        super(mapped_bool, self).__set__(instance, value)

class mapped_keywords(mapped):
    """Maps the labels stored in brightcove to a list of tags.
    """

    def __get__(self, instance, class_):
        whitelist = zope.component.getUtility(
            zeit.cms.tagging.interfaces.IWhitelist)
        value = super(mapped_keywords, self).__get__(instance, class_)
        result = []
        if value:
            for code in value.split(';'):
                tag = whitelist.get(code)
                if tag is not None:
                    result.append(tag)
        return tuple(result)

    def __set__(self, instance, value):
        value = ';'.join(tag.code for tag in value)
        super(mapped_keywords, self).__set__(instance, value)

class mapped_datetime(mapped):

    def __get__(self, instance, class_):
        value = super(mapped_datetime, self).__get__(instance, class_)
        if not value:
            return None
        date = datetime.datetime.utcfromtimestamp(int(value)/1000)
        return pytz.utc.localize(date)

    def __set__(self, instance, value):
        value = str(to_epoch(value) * 1000)
        super(mapped_datetime, self).__set__(instance, value)

class mapped_product(mapped):

    def _get_from_dict(self, value):
        if (value['customFields']['produkt-id'] is None and
            value['referenceId'] is not None):
            return 'Reuters'
        for key in self.path:
            value = value[key]
        return value

class BCContent(object):
    # XXX remove at some point

    pass

class Converter(object):

    zope.interface.implements(zeit.brightcove.interfaces.IBrightcoveContent)

    data = None
    id = mapped('id')
    title = mapped('name')
    teaserText = mapped('shortDescription')
    brightcove_thumbnail = mapped('thumbnailURL')

    def __init__(self, data, connection=None):
        if data is not None:
            self.data = data
            if 'customFields' in self.data:
                self.data['customFields'] = self.data['customFields']

    @cachedproperty
    def uniqueId(self):
        path = zeit.addcentral.interfaces.IAddLocation(self).uniqueId
        # XXX folders in the mock connector don't have a trailing slash, while
        # in the real connector they do
        if not path.endswith('/'):
            path += '/'
        return path + str(self.id)

    @property
    def thumbnail(self):
        return self.data['thumbnailURL']

    @classmethod
    def find_by_id(cls, id):
        try:
            return iter(cls.find_by_ids([id])).next()
        except StopIteration:
            raise KeyError(id)

    @staticmethod
    def get_connection():
        return zope.component.getUtility(
            zeit.brightcove.interfaces.IAPIConnection)

    def save(self):
        registered = getattr(self, '_v_save_hook_registered', False)
        if not registered:
            transaction.get().addBeforeCommitHook(self._save)
            self._v_save_hook_registered = True

    def _save(self):
        try:
            del self._v_save_hook_registered
        except AttributeError:
            pass
        __traceback_info__ = (self.data,)

        data = dict(self.data)
        if 'customFields' in data:
            data['customFields'] = dict(data['customFields'])
        READ_ONLY = ['lastModifiedDate', 'creationDate', 'publishedDate']
        for field in READ_ONLY:
            data.pop(field, None)
        self.get_connection().post('update_video', video=data)

    def __str__(self):
        return '<%s id=%s>' % (self.__class__.__name__, self.id)

class Video(Converter):

    zope.interface.implements(zeit.brightcove.interfaces.IVideo)

    type = 'video'
    id_prefix = 'vid' # for old-style asset IDs
    commentsAllowed = mapped_bool('customFields', 'allow_comments')
    banner = mapped_bool('customFields', 'banner')
    banner_id = mapped('customFields', 'banner-id')
    breaking_news = mapped_bool('customFields', 'breaking-news')
    dailyNewsletter = mapped_bool('customFields', 'newsletter')
    has_recensions = mapped_bool('customFields', 'recensions')
    item_state = mapped('itemState')
    keywords = mapped_keywords('customFields', 'cmskeywords')
    product_id = mapped('customFields', 'produkt-id')
    ressort = mapped('customFields', 'ressort')
    serie = mapped('customFields', 'serie')
    subtitle = mapped('longDescription')
    supertitle = mapped('customFields', 'supertitle')
    video_still = mapped('videoStillURL')
    flv_url = mapped('FLVURL')

    expires = mapped_datetime('endDate')
    date_last_modified = mapped_datetime('lastModifiedDate')
    date_created = mapped_datetime('creationDate')
    date_first_released = mapped_datetime('publishedDate')

    fields = ",".join((
        'creationDate',
        'customFields',
        'economics',
        'endDate',
        'id',
        'itemState',
        'lastModifiedDate',
        'length',
        'linkText',
        'linkURL',
        'longDescription',
        'name',
        'playsTotal',
        'playsTrailingWeek',
        'publisheddate',
        'referenceId',
        'shortDescription',
        'tags',
        'thumbnailURL',
        'videoStillURL',
        'FLVURL',
    ))

    @classmethod
    def find_by_ids(class_, ids):
        ids = ','.join(str(i) for i in ids)
        return class_.get_connection().get_list(
            'find_videos_by_ids', class_, video_ids=ids,
            video_fields=class_.fields)

    @classmethod
    def find_modified(class_, from_date):
        from_date = to_epoch(from_date) / 60
        return class_.get_connection().get_list(
            'find_modified_videos', class_,
            from_date=from_date,
            video_fields=class_.fields,
            filter='PLAYABLE,DELETED,INACTIVE,UNSCHEDULED',
            sort_by='MODIFIED_DATE', sort_order='DESC')

    @property
    def related(self):
        result = []
        custom = self.data.get('customFields')
        if custom is None:
            return ()
        for i in range(1, 6):
            unique_id = custom.get('ref_link%s' % i)
            if unique_id is not None:
                content = zeit.cms.interfaces.ICMSContent(unique_id, None)
                if content is not None:
                    result.append(content)
        return tuple(result)

    @related.setter
    def related(self, value):
        if not value:
            value = ()
        custom = self.data.setdefault('customFields', {})

        for i in range(1, 6):
            custom['ref_link%i' % i] = ''
            custom['ref_title%i' % i] = ''
        for i, obj in enumerate(value, 1):
            metadata = zeit.cms.content.interfaces.ICommonMetadata(obj, None)
            if metadata is None:
                continue
            custom['ref_link%s' % i] = obj.uniqueId
            custom['ref_title%s' % i] = metadata.teaserTitle

    @property
    def year(self):
        try:
            modified = int(self.data.get('lastModifiedDate'))
        except (TypeError, ValueError):
            return None
        return datetime.datetime.fromtimestamp(modified/1000).year

    # XXX year.setter is missing

    def to_cms(self, video=None):
        if video is None:
            video = zeit.content.video.video.Video()
        for key in zeit.content.video.interfaces.IVideo:
            try:
                setattr(video, key, getattr(self, key))
            except AttributeError:
                pass
        video.brightcove_id = str(self.id)
        sc = zeit.cms.content.interfaces.ISemanticChange(video)
        sc.last_semantic_change = self.date_last_modified
        info = zeit.cms.workflow.interfaces.IPublishInfo(video)
        info.date_last_published = self.date_first_released
        return video

    @classmethod
    def from_cms(cls, video):
        instance = cls(data=dict(id='foo'))
        instance.id = video.brightcove_id
        for key in zeit.content.video.interfaces.IVideo:
            try:
                setattr(instance, key, getattr(video, key))
            except AttributeError:
                pass
        date_last_modified = \
            zeit.cms.content.interfaces.ISemanticChange(
            video).last_semantic_change
        if date_last_modified is not None:
            instance.date_last_modified = date_last_modified
        try:
            bc_state = cls.find_by_id(instance.id)
            instance.date_first_released = bc_state.date_first_released
        except KeyError:
            pass # avoid failures in test setup
        return instance

@grok.implementer(zeit.addcentral.interfaces.IAddLocation)
@grok.adapter(Video)
def video_location(bc_object):
    config = zope.app.appsetup.product.getProductConfiguration(
        'zeit.brightcove')
    path = config['video-folder']
    return zeit.addcentral.add.find_or_create_folder(
        *(path.split('/') + [bc_object.date_created.strftime('%Y-%m')]))

class Playlist(Converter):

    zope.interface.implements(zeit.brightcove.interfaces.IPlaylist)
    type = 'playlist'
    id_prefix = 'pls' # for old-style asset IDs
    item_state = 'ACTIVE'
    fields = ",".join((
        'id',
        'name',
        'shortDescription',
        'thumbnailURL',
        'videoIds',
    ))

    @property
    def video_ids(self):
        return tuple(
            resolve_video_id(str(id)) for id in self.data['videoIds'])

    @classmethod
    def find_by_ids(class_, ids):
        ids = ','.join(str(i) for i in ids)
        return class_.get_connection().get_list(
            'find_playlists_by_ids', class_,
            playlist_fields=class_.fields,
            playlist_ids=ids)

    @classmethod
    def find_all(class_):
        return class_.get_connection().get_list(
            'find_all_playlists', class_,
            playlist_fields=class_.fields)

    def to_cms(self, playlist=None):
        if playlist is None:
            playlist = zeit.content.video.playlist.Playlist()
        for key in zeit.content.video.interfaces.IPlaylist:
            try:
                setattr(playlist, key, getattr(self, key))
            except AttributeError:
                pass
        return playlist

    @classmethod
    def from_cms(cls, playlist):
        instance = cls(data=dict(id='foo'))
        for key in zeit.content.video.interfaces.IPlaylist:
            try:
                setattr(instance, key, getattr(playlist, key))
            except AttributeError:
                pass
        return instance

@grok.implementer(zeit.addcentral.interfaces.IAddLocation)
@grok.adapter(Playlist)
def playlist_location(bc_object):
    config = zope.app.appsetup.product.getProductConfiguration(
        'zeit.brightcove')
    path = config['playlist-folder']
    return zeit.addcentral.add.find_or_create_folder(*path.split('/'))

BRIGHTCOVE_ID = zeit.connector.search.SearchVar(
    'id', 'http://namespaces.zeit.de/CMS/brightcove')

def resolve_video_id(video_id):
    connector = zope.component.getUtility(
            zeit.connector.interfaces.IConnector)
    result = list(
        connector.search([BRIGHTCOVE_ID], BRIGHTCOVE_ID == video_id))
    if not result:
        raise LookupError(video_id)
    if len(result) > 1:
        raise LookupError(
            'Found multiple CMS objects with video id %r.' % video_id)
    result = result[0]
    unique_id = result[0]
    return unique_id

def update_brightcove(context, event):
    zeit.brightcove.interfaces.IBrightcoveObject(context).save()

@grok.adapter(zeit.content.video.interfaces.IVideo)
@grok.implementer(zeit.brightcove.interfaces.IBrightcoveObject)
def video_from_cms(context):
    return Video.from_cms(context)

@grok.adapter(zeit.content.video.interfaces.IPlaylist)
@grok.implementer(zeit.brightcove.interfaces.IBrightcoveObject)
def playlist_from_cms(context):
    return Playlist.from_cms(context)

def publish_on_checkin(context, event):
    # prevent infinite loop, since there is a checkout/checkin cycle during
    # publishing (to update XML references etc.)
    if not event.publishing:
        zeit.cms.workflow.interfaces.IPublish(context).publish()
<|endoftext|>


<commit_before>import ggame
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame, CircleAsset, PolygonAsset, TextAsset

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700

# THE WALLS
class wall(Sprite):
    Red = Color(0xF44366, 1.0)
    noline = LineStyle(0, Red)

    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.fxcenter = self.fycenter = 0

# LADDER
class ladder(Sprite):
    Blue = Color(0x558b24, 1.0)
    noline = LineStyle(0, Blue)

    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.fxcenter = self.fycenter = 0

# Barrel
class Barrel(Sprite):
    brown = Color(0x996633, 1.0)
    Black = Color(1,0)
    yellow = Color(0xfdd835, 1.0)
    noline = LineStyle(1, Black)
    asset= CircleAsset(15, noline, brown)

    def __init__(self, position):
        super().__init__(Barrel.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.hit = False
        self.falling = False
        self.mover = False
        self.movel = False
        self.p = self.collidingWithSprites(player)
        self.fxcenter = self.fycenter = 0.25

    def step(self):
        self.x += self.vx
        self.y += self.vy
        if self.mover == True:
            self.vy = 0
            self.vx = 2.5
        if self.movel == True:
            self.vy = 0
            self.vx = -2.5
        if self.falling == True:
            self.vy = 2.5
            self.vx = 0
        if self.y == 145:
            self.falling = False
            self.mover = True
        if self.x >= 620 and self.y == 145:
            self.mover = False
            self.falling = True
        if self.y >= 312 and self.x >= 620:
            self.falling = False
            self.movel = True
        if self.x <= 130 and self.y >= 312:
            self.movel = False
            self.falling = True
        if self.x <= 130 and self.y >= 482:
            self.falling = False
            self.mover = True
        if self.x >= 569 and self.y >= 482:
            self.mover = False
            self.falling = True
        if self.y >= 651:
            self.falling = False
            self.movel = True
        if len(self.p) != 0:
           self.hit = True
        if self.hit == True:

# PLAYER
class player(Sprite):
    purple = Color(0x9575cd, 1.0)
    white = Color(0xfafafa, 1.0)
    line= LineStyle(1, white)
    asset = RectangleAsset(25, 25, line, purple)

    def __init__(self, position):
        super().__init__(player.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.a = self.collidingWithSprites(wall)
        self.b = self.collidingWithSprites(ladder)
        self.c = self.collidingWithSprites(Barrel)
        self.d = self.collidingWithSprites(trophy)
        self.fxcenter = self.fycenter = 0.25
        self.YourDad = True
        self.YourUncle = False
        self.You = False
        self.YourAunt = False
        self.won = False
        self.lives = 3
        Kong.listenKeyEvent("keydown", "right arrow", self.MoveRIGHT)
        Kong.listenKeyEvent("keyup", "right arrow", self.MoveOff)
        Kong.listenKeyEvent("keydown", "left arrow", self.MoveLEFT)
        Kong.listenKeyEvent("keyup", "left arrow", self.MoveOff)
        Kong.listenKeyEvent("keydown", "up arrow", self.JumpOn)
        Kong.listenKeyEvent("keyup", "up arrow", self.JumpOff)
        Kong.listenKeyEvent("keydown", "right arrow", self.falling)
        Kong.listenKeyEvent("keydown", "left arrow", self.falling)
        Kong.listenKeyEvent("keydown", "down arrow", self.ClimbDOWN)
        Kong.listenKeyEvent("keyup", "down arrow", self.ClimbOFF)

    def step(self):
        self.b = self.collidingWithSprites(ladder)
        if len(self.b) != 0:
            #ON LADDAR
            self.You = True
            self.y += self.vy
            self.a = self.collidingWithSprites(wall)
            if len(self.a) != 0:
                self.y -= self.vy
                self.vy = 1
                self.YourDad = True
            else:
                self.YourDad = True
            if self.YourDad == True:
                self.YourUncle = True
            else:
                self.YourUncle = False
            self.x += self.vx
            self.a = self.collidingWithSprites(wall)
            if len(self.a) != 0:
                self.x -= self.vx
                self.vx = 0
                self.YourDad = False
            else:
                self.YourDad = True
            if len(self.b) != 0:
                self.lives = self.lives - 1
            if len(self.d) != 0:
                self.won = True
        else:
            # OFF LADDER
            self.vy = self.vy + 1.25
            self.y += self.vy
            self.a = self.collidingWithSprites(wall)
            self.You = False
            if len(self.a) != 0:
                self.y -= self.vy
                self.vy = 1
                self.YourDad = False
            else:
                self.YourDad = True
            if self.YourDad == True:
                self.YourUncle = True
            else:
                self.YourUncle = False
            self.x += self.vx
            self.a = self.collidingWithSprites(wall)
            if len(self.a) != 0:
                self.x -= self.vx
                self.vx = 0
                self.YourDad = False
            else:
                self.YourDad = True
            if len(self.d) != 0:
                self.won = True

    def ClimbDOWN(self, event):
        self.vy = 5

    def ClimbOFF(self, event):
        self.vy = 0

    def falling(self, event):
        if self.YourDad == True:
            self.vy = self.vy + 1

    def MoveRIGHT(self, event):
        if len(self.a) == 0:
            self.YourDad = True
        if self.YourDad == False:
            self.vx = 5
        else:
            self.vx = 5
            self.vy = 5

    def MoveLEFT(self, event):
        if len(self.a) == 0:
            self.YourDad = True
        if self.YourDad == False:
            self.vx = -5
        else:
            self.vx = -5
            self.vy = 5

    def MoveOff(self, event):
        self.vx = 0
        self.vy = 5

    def JumpOn(self, event):
        if len(self.a) == 0:
            self.YourDad = True
        if self.YourUncle == False:
            if self.YourDad == True and self.You == False: #NOT TOUCHING A LADDER JUMP
                self.vy = -18
            if self.YourDad == True and self.You == True: #TOUCHING A LADDER JUMP
                self.vy = -5
        else:
            self.vy = -5

    def JumpOff(self, event):
        if self.You == False:
            self. vy = self.vy + 1
        if self.You == True:
            self.vy = 0

#TROPY
class trophy(Sprite):
    yellow = Color(0xffca28, 1.0)
    white = Color(0xfafafa, 1.0)
    liner = LineStyle(1, white)

    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.fxcenter = self.fycenter = 0

# THE WORLD
class Kong(App):

    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        yellow = Color(0xffeb3b, 1.0)
        white = Color(0xfafafa, 1.0)
        liner = LineStyle(1, white)
        line = LineStyle(1, black)
        self.play = False
        self.ComicSans = True
        bg_asset=RectangleAsset(width, height, line, black)
        bg=Sprite(bg_asset, (0, 0))
        text = TextAsset("Press ENTER To Start", style='40pt Comic Sans MS', fill= Color(0xffeb3b, 1), width=700)
        self.prompt = Sprite(text,(50, 250))
        TEXT = TextAsset("Press R to Resart", style='40pt Comic Sans Ms', fill= Color(0xffeb3b, 1), width= 700)
        self.Prompt = Sprite(TEXT,(50, 250))
        self.Prompt.visible = False
        Kong.listenKeyEvent("keydown", "enter", self.playing)
        Kong.listenKeyEvent("keydown", "r", self.playing)

    def playing(self, event):
        self.prompt.destroy()
        self.play = True
        if self.play == True:
            player((50, 640))
            Barrel((70, 145))
            black=Color(1, 0)
            Black=Color(0, 1)
            Red = Color(0xF44366, 1.0)
            noline=LineStyle(1000, Black)
            oline= LineStyle(0, Red)
            white = Color(0xfafafa, 1.0)
            yellow = Color(0xffca28, 1.0)
            liner = LineStyle(1, white)
            brown = Color(0x996633, 1.0)
            Blue = Color(0x558b24, 1.0)
            wall(RectangleAsset(700, 30, oline, Red), (0, 670))
            wall(RectangleAsset(550, 30, oline, Red), (0, 500))
            wall(RectangleAsset(550, 30, oline, Red), (150, 330))
            wall(RectangleAsset(600, 30, oline, Red), (0, 160))
            wall(RectangleAsset(100, 30, oline, Red), (100, 50))
            ladder(RectangleAsset(10, 170, oline, Blue), (550, 500))
            ladder(RectangleAsset(10, 170, oline, Blue), (140, 330))
            ladder(RectangleAsset(10, 170, oline, Blue), (600, 160))
            trophy(RectangleAsset(25, 25, liner, yellow), (100, 22))

    def step(self):
        for ship in self.getSpritesbyClass(player):
            ship.step()
        for hip in self.getSpritesbyClass(Barrel):
            hip.step()
            if hip.x <= 0:
                hip.destroy()

# I DON'T KNOW WHAT THIS IS BUT I NEED IT
myapp = Kong(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<commit_msg>Updated from Brython Server: 1/8/2017 12:29:41 PM<commit_after>import ggame
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame, CircleAsset, PolygonAsset, TextAsset

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 700

# THE WALLS
class wall(Sprite):
    Red = Color(0xF44366, 1.0)
    noline = LineStyle(0, Red)

    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.fxcenter = self.fycenter = 0

# LADDER
class ladder(Sprite):
    Blue = Color(0x558b24, 1.0)
    noline = LineStyle(0, Blue)

    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.fxcenter = self.fycenter = 0

# Barrel
class Barrel(Sprite):
    brown = Color(0x996633, 1.0)
    Black = Color(1,0)
    yellow = Color(0xfdd835, 1.0)
    noline = LineStyle(1, Black)
    asset= CircleAsset(15, noline, brown)

    def __init__(self, position):
        super().__init__(Barrel.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.hit = False
        self.falling = False
        self.mover = False
        self.movel = False
        self.p = self.collidingWithSprites(player)
        self.fxcenter = self.fycenter = 0.25

    def step(self):
        self.x += self.vx
        self.y += self.vy
        if self.mover == True:
            self.vy = 0
            self.vx = 2.5
        if self.movel == True:
            self.vy = 0
            self.vx = -2.5
        if self.falling == True:
            self.vy = 2.5
            self.vx = 0
        if self.y == 145:
            self.falling = False
            self.mover = True
        if self.x >= 620 and self.y == 145:
            self.mover = False
            self.falling = True
        if self.y >= 312 and self.x >= 620:
            self.falling = False
            self.movel = True
        if self.x <= 130 and self.y >= 312:
            self.movel = False
            self.falling = True
        if self.x <= 130 and self.y >= 482:
            self.falling = False
            self.mover = True
        if self.x >= 569 and self.y >= 482:
            self.mover = False
            self.falling = True
        if self.y >= 651:
            self.falling = False
            self.movel = True

# PLAYER
class player(Sprite):
    purple = Color(0x9575cd, 1.0)
    white = Color(0xfafafa, 1.0)
    line= LineStyle(1, white)
    asset = RectangleAsset(25, 25, line, purple)

    def __init__(self, position):
        super().__init__(player.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.a = self.collidingWithSprites(wall)
        self.b = self.collidingWithSprites(ladder)
        self.c = self.collidingWithSprites(Barrel)
        self.d = self.collidingWithSprites(trophy)
        self.fxcenter = self.fycenter = 0.25
        self.YourDad = True
        self.YourUncle = False
        self.You = False
        self.YourAunt = False
        self.won = False
        self.lives = 3
        self.hit = False
        Kong.listenKeyEvent("keydown", "right arrow", self.MoveRIGHT)
        Kong.listenKeyEvent("keyup", "right arrow", self.MoveOff)
        Kong.listenKeyEvent("keydown", "left arrow", self.MoveLEFT)
        Kong.listenKeyEvent("keyup", "left arrow", self.MoveOff)
        Kong.listenKeyEvent("keydown", "up arrow", self.JumpOn)
        Kong.listenKeyEvent("keyup", "up arrow", self.JumpOff)
        Kong.listenKeyEvent("keydown", "right arrow", self.falling)
        Kong.listenKeyEvent("keydown", "left arrow", self.falling)
        Kong.listenKeyEvent("keydown", "down arrow", self.ClimbDOWN)
        Kong.listenKeyEvent("keyup", "down arrow", self.ClimbOFF)

    def step(self):
        self.b = self.collidingWithSprites(ladder)
        if len(self.b) != 0:
            #ON LADDAR
            self.You = True
            self.y += self.vy
            self.a = self.collidingWithSprites(wall)
            if len(self.a) != 0:
                self.y -= self.vy
                self.vy = 1
                self.YourDad = True
            else:
                self.YourDad = True
            if self.YourDad == True:
                self.YourUncle = True
            else:
                self.YourUncle = False
            self.x += self.vx
            self.a = self.collidingWithSprites(wall)
            if len(self.a) != 0:
                self.x -= self.vx
                self.vx = 0
                self.YourDad = False
            else:
                self.YourDad = True
            if len(self.b) != 0:
                self.lives = self.lives - 1
            if len(self.d) != 0:
                self.won = True
        else:
            # OFF LADDER
            self.vy = self.vy + 1.25
            self.y += self.vy
            self.a = self.collidingWithSprites(wall)
            self.You = False
            if len(self.a) != 0:
                self.y -= self.vy
                self.vy = 1
                self.YourDad = False
            else:
                self.YourDad = True
            if self.YourDad == True:
                self.YourUncle = True
            else:
                self.YourUncle = False
            self.x += self.vx
            self.a = self.collidingWithSprites(wall)
            if len(self.a) != 0:
                self.x -= self.vx
                self.vx = 0
                self.YourDad = False
            else:
                self.YourDad = True
            if len(self.d) != 0:
                self.won = True
            if len(self.c) != 0:
                self.hit = True
            if self.hit == True:
                self.lives = self.lives - 1
                self.hit = False

    def ClimbDOWN(self, event):
        self.vy = 5

    def ClimbOFF(self, event):
        self.vy = 0

    def falling(self, event):
        if self.YourDad == True:
            self.vy = self.vy + 1

    def MoveRIGHT(self, event):
        if len(self.a) == 0:
            self.YourDad = True
        if self.YourDad == False:
            self.vx = 5
        else:
            self.vx = 5
            self.vy = 5

    def MoveLEFT(self, event):
        if len(self.a) == 0:
            self.YourDad = True
        if self.YourDad == False:
            self.vx = -5
        else:
            self.vx = -5
            self.vy = 5

    def MoveOff(self, event):
        self.vx = 0
        self.vy = 5

    def JumpOn(self, event):
        if len(self.a) == 0:
            self.YourDad = True
        if self.YourUncle == False:
            if self.YourDad == True and self.You == False: #NOT TOUCHING A LADDER JUMP
                self.vy = -18
            if self.YourDad == True and self.You == True: #TOUCHING A LADDER JUMP
                self.vy = -5
        else:
            self.vy = -5

    def JumpOff(self, event):
        if self.You == False:
            self. vy = self.vy + 1
        if self.You == True:
            self.vy = 0

#TROPY
class trophy(Sprite):
    yellow = Color(0xffca28, 1.0)
    white = Color(0xfafafa, 1.0)
    liner = LineStyle(1, white)

    def __init__(self, asset, position):
        super().__init__(asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.fxcenter = self.fycenter = 0

# THE WORLD
class Kong(App):

    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        yellow = Color(0xffeb3b, 1.0)
        white = Color(0xfafafa, 1.0)
        liner = LineStyle(1, white)
        line = LineStyle(1, black)
        self.play = False
        self.ComicSans = True
        bg_asset=RectangleAsset(width, height, line, black)
        bg=Sprite(bg_asset, (0, 0))
        text = TextAsset("Press ENTER To Start", style='40pt Comic Sans MS', fill= Color(0xffeb3b, 1), width=700)
        self.prompt = Sprite(text,(50, 250))
        TEXT = TextAsset("Press R to Resart", style='40pt Comic Sans Ms', fill= Color(0xffeb3b, 1), width= 700)
        self.Prompt = Sprite(TEXT,(50, 250))
        self.Prompt.visible = False
        Kong.listenKeyEvent("keydown", "enter", self.playing)
        Kong.listenKeyEvent("keydown", "r", self.playing)

    def playing(self, event):
        self.prompt.destroy()
        self.play = True
        if self.play == True:
            player((50, 640))
            Barrel((70, 145))
            black=Color(1, 0)
            Black=Color(0, 1)
            Red = Color(0xF44366, 1.0)
            noline=LineStyle(1000, Black)
            oline= LineStyle(0, Red)
            white = Color(0xfafafa, 1.0)
            yellow = Color(0xffca28, 1.0)
            liner = LineStyle(1, white)
            brown = Color(0x996633, 1.0)
            Blue = Color(0x558b24, 1.0)
            wall(RectangleAsset(700, 30, oline, Red), (0, 670))
            wall(RectangleAsset(550, 30, oline, Red), (0, 500))
            wall(RectangleAsset(550, 30, oline, Red), (150, 330))
            wall(RectangleAsset(600, 30, oline, Red), (0, 160))
            wall(RectangleAsset(100, 30, oline, Red), (100, 50))
            ladder(RectangleAsset(10, 170, oline, Blue), (550, 500))
            ladder(RectangleAsset(10, 170, oline, Blue), (140, 330))
            ladder(RectangleAsset(10, 170, oline, Blue), (600, 160))
            trophy(RectangleAsset(25, 25, liner, yellow), (100, 22))

    def step(self):
        for ship in self.getSpritesbyClass(player):
            ship.step()
        for hip in self.getSpritesbyClass(Barrel):
            hip.step()
            if hip.x <= 0:
                hip.destroy()

# I DON'T KNOW WHAT THIS IS BUT I NEED IT
myapp = Kong(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()
<|endoftext|>