<commit_before>import os
import unittest

from magetool.commands.layout import Layout
from magetool.commands.module import Module
from magetool.libraries.util import remove_module

TEST_DIR = os.path.abspath(os.path.join("..", "app", "code", "local", "Foo"))

LAYOUT_DIR = os.path.join("..", "..", "..", "..", "design",
                          "frontend","default", "default", "layout")

XML = """<?xml version="1.0"?>
<layout version="0.1.0">

</layout>
"""

CONFIG = """<?xml version="1.0"?>
<config>
  <modules>
    <Foo_Quux>
      <version>0.1.0</version>
    </Foo_Quux>
  </modules>
  <frontend>
    <layout>
      <updates>
        <quux>
          <file>quux.xml</file>
        </quux>
      </updates>
    </layout>
  </frontend>
</config>
"""

class LayoutTest(unittest.TestCase):

    def setUp(self):
        self.old_cwd = os.getcwd()
        os.chdir(TEST_DIR)
        Module().create("Quux")
        os.chdir("Quux")
        self.layout = Layout()

    def tearDown(self):
        os.chdir("..")
        remove_module("Foo", "Quux")
        os.chdir(self.old_cwd)
        del self.layout

    def test_create(self):
        file_name = "quux.xml"
        self.layout.create(file_name)
        try:
            with open(os.path.join(LAYOUT_DIR, file_name)) as layout_file:
                self.assertEqual(XML, layout_file.read())
        finally:
            os.remove(os.path.join(LAYOUT_DIR, file_name))
        with open(os.path.join("etc", "config.xml")) as config:
            self.assertEqual(CONFIG, config.read())

    def test_create_without_file_extension(self):
        file_name = "quux"
        self.layout.create(file_name)
        try:
            with open(os.path.join(LAYOUT_DIR, file_name + ".xml")) as layout_file:
                self.assertEqual(XML, layout_file.read())
        finally:
            os.remove(os.path.join(LAYOUT_DIR, file_name + ".xml"))
        with open(os.path.join("etc", "config.xml")) as config:
            self.assertEqual(CONFIG, config.read())

if __name__ == "__main__":
    unittest.main()
<commit_msg>Add more tests for Layout.<commit_after>import os
import unittest

from magetool.commands.layout import Layout
from magetool.commands.module import Module
from magetool.libraries.util import remove_module

TEST_DIR = os.path.abspath(os.path.join("..", "app", "code", "local", "Foo"))

LAYOUT_DIR = os.path.join("..", "..", "..", "..", "design",
                          "frontend","default", "default", "layout")

XML = """<?xml version="1.0"?>
<layout version="0.1.0">

</layout>
"""

CONFIG = """<?xml version="1.0"?>
<config>
  <modules>
    <Foo_Quux>
      <version>0.1.0</version>
    </Foo_Quux>
  </modules>
  <frontend>
    <layout>
      <updates>
        <quux>
          <file>quux.xml</file>
        </quux>
      </updates>
    </layout>
  </frontend>
</config>
"""

class LayoutTest(unittest.TestCase):

    def setUp(self):
        self.old_cwd = os.getcwd()
        os.chdir(TEST_DIR)
        Module().create("Quux")
        os.chdir("Quux")
        self.layout = Layout()

    def tearDown(self):
        os.chdir("..")
        remove_module("Foo", "Quux")
        os.chdir(self.old_cwd)
        del self.layout

    def test_create(self):
        file_name = "quux.xml"
        self.layout.create(file_name)
        try:
            with open(os.path.join(LAYOUT_DIR, file_name)) as layout_file:
                self.assertEqual(XML, layout_file.read())
        finally:
            os.remove(os.path.join(LAYOUT_DIR, file_name))
        with open(os.path.join("etc", "config.xml")) as config:
            self.assertEqual(CONFIG, config.read())

    def test_create_without_file_extension(self):
        file_name = "quux"
        self.layout.create(file_name)
        try:
            with open(os.path.join(LAYOUT_DIR, file_name + ".xml")) as layout_file:
                self.assertEqual(XML, layout_file.read())
        finally:
            os.remove(os.path.join(LAYOUT_DIR, file_name + ".xml"))
        with open(os.path.join("etc", "config.xml")) as config:
            self.assertEqual(CONFIG, config.read())

    def test_create_works_in_depth(self):
        file_name = "quux.xml"
        os.chdir("etc")
        self.layout.create(file_name)
        os.chdir("..")
        try:
            with open(os.path.join(LAYOUT_DIR, file_name)) as layout_file:
                self.assertEqual(XML, layout_file.read())
        finally:
            os.remove(os.path.join(LAYOUT_DIR, file_name))
        with open(os.path.join("etc", "config.xml")) as config:
            self.assertEqual(CONFIG, config.read())

    def test_register(self):
        self.layout.register("quux")
        with open(os.path.join("etc", "config.xml")) as config:
            self.assertEqual(CONFIG, config.read())

    def test_register_twice(self):
        self.layout.register("quux")
        self.layout.register("quux")
        with open(os.path.join("etc", "config.xml")) as config:
            self.assertEqual(CONFIG, config.read())

if __name__ == "__main__":
    unittest.main()
<|endoftext|>


<commit_before>from markupsafe import Markup

from odoo import api, models, tools

class MailMail(models.Model):
    _inherit = "mail.mail"

    @api.model
    def _build_cc_text(self, partners):
        if not partners:
            return ""

        def get_ctx_param(ctx_key, default_parm):
            if ctx_key in self.env.context:
                return self.env.context[ctx_key]
            return default_parm

        company = self.env.company
        partner_format = get_ctx_param(
            "partner_format", company.show_followers_partner_format
        )
        msg_sent_to = get_ctx_param(
            "msg_sent_to", company.show_followers_message_sent_to
        )
        msg_warn = get_ctx_param(
            "msg_warn", company.show_followers_message_response_warning
        )
        partner_message = ", ".join(
            [
                partner_format
                % {
                    # Supported parameters
                    "partner_name": p.name,
                    "partner_email": p.email,
                    "partner_email_domain": tools.email_domain_extract(p.email),
                }
                for p in partners
            ]
        )
        full_text = """

            {msg_sent_to} {partner_message}
            {rc}{msg_warn}

        """.format(
            msg_sent_to=msg_sent_to,
            partner_message=Markup.escape(partner_message),
            rc=msg_warn and "
" or "",
            msg_warn=msg_warn or "",
        )
        return full_text

    def _send(self, auto_commit=False, raise_exception=False, smtp_session=None):
        group_portal = self.env.ref("base.group_portal")
        for mail_id in self.ids:
            mail = self.browse(mail_id)
            # if the email has a model, id and it belongs to the portal group
            if mail.model and mail.res_id and group_portal:
                obj = self.env[mail.model].browse(mail.res_id)
                # those partners are obtained, who do not have a user and
                # if they do it must be a portal, we exclude internal
                # users of the system.
                if hasattr(obj, "message_follower_ids"):
                    partners_obj = obj.message_follower_ids.mapped("partner_id")
                    # internal partners
                    user_partner_ids = (
                        self.env["res.users"]
                        .search(
                            [
                                ("active", "in", (True, False)),
                                ("show_in_cc", "=", False),
                            ]
                        )
                        .filtered(lambda x: group_portal not in x.groups_id)
                        .mapped("partner_id")
                        .ids
                    )
                    partners_len = len(
                        partners_obj.filtered(
                            lambda x: x.id not in user_partner_ids
                            and (
                                not x.user_ids
                                or group_portal in x.user_ids.mapped("groups_id")
                            )
                        )
                    )
                    if partners_len > 1:
                        # get partners
                        cc_internal = True
                        # else get company in object
                        if hasattr(obj, "company_id") and obj.company_id:
                            cc_internal = obj.company_id.show_internal_users_cc
                        # get company in user
                        elif mail.env and mail.env.user and mail.env.user.company_id:
                            cc_internal = (
                                self.env.user.company_id.show_internal_users_cc
                            )
                        if cc_internal:
                            partners = partners_obj.filtered(
                                lambda x: x.id not in user_partner_ids
                                and (not x.user_ids or x.user_ids.show_in_cc)
                            )
                        else:
                            partners = partners_obj.filtered(
                                lambda x: x.id not in user_partner_ids
                                and (
                                    not x.user_ids
                                    or group_portal in x.user_ids.mapped("groups_id")
                                )
                            )
                        partners = partners.filtered(
                            lambda x: not x.user_ids
                            or x.user_ids  # otherwise, email is not sent
                            and "email" in x.user_ids.mapped("notification_type")
                        )
                        # set proper lang for recipients
                        langs = list(
                            filter(
                                bool,
                                mail.mapped("recipient_ids.lang")
                                + [
                                    mail.author_id.lang,
                                    self.env.company.partner_id.lang,
                                ],
                            )
                        )
                        # get show follower text
                        final_cc = mail.with_context(
                            lang=langs and langs[0]
                        )._build_cc_text(partners)
                        # it is saved in the body_html field so that it does
                        # not appear in the odoo log
                        mail.body_html = final_cc + mail.body_html
        return super()._send(
            auto_commit=auto_commit,
            raise_exception=raise_exception,
            smtp_session=smtp_session,
        )
<commit_msg>[FIX] Add recipients of the all related messages on the notification<commit_after>from markupsafe import Markup

from odoo import api, models, tools

class MailMail(models.Model):
    _inherit = "mail.mail"

    @api.model
    def _build_cc_text(self, partners):
        if not partners:
            return ""

        def get_ctx_param(ctx_key, default_parm):
            if ctx_key in self.env.context:
                return self.env.context[ctx_key]
            return default_parm

        company = self.env.company
        partner_format = get_ctx_param(
            "partner_format", company.show_followers_partner_format
        )
        msg_sent_to = get_ctx_param(
            "msg_sent_to", company.show_followers_message_sent_to
        )
        msg_warn = get_ctx_param(
            "msg_warn", company.show_followers_message_response_warning
        )
        partner_message = ", ".join(
            [
                partner_format
                % {
                    # Supported parameters
                    "partner_name": p.name,
                    "partner_email": p.email,
                    "partner_email_domain": tools.email_domain_extract(p.email),
                }
                for p in partners
            ]
        )
        full_text = """

            {msg_sent_to} {partner_message}
            {rc}{msg_warn}

        """.format(
            msg_sent_to=msg_sent_to,
            partner_message=Markup.escape(partner_message),
            rc=msg_warn and "
" or "",
            msg_warn=msg_warn or "",
        )
        return full_text

    def _send(self, auto_commit=False, raise_exception=False, smtp_session=None):
        group_portal = self.env.ref("base.group_portal")
        for mail_id in self.ids:
            mail = self.browse(mail_id)
            message_recipients = self.search(
                [
                    ("message_id", "=", mail.message_id),
                ]
            ).mapped("recipient_ids")
            # if the email has a model, id and it belongs to the portal group
            if mail.model and mail.res_id and group_portal:
                obj = self.env[mail.model].browse(mail.res_id)
                # those partners are obtained, who do not have a user and
                # if they do it must be a portal, we exclude internal
                # users of the system.
                if hasattr(obj, "message_follower_ids"):
                    partners_obj = (
                        obj.message_follower_ids.mapped("partner_id")
                        | message_recipients
                    )
                    # internal partners
                    user_partner_ids = (
                        self.env["res.users"]
                        .search(
                            [
                                ("active", "in", (True, False)),
                                ("show_in_cc", "=", False),
                            ]
                        )
                        .filtered(lambda x: group_portal not in x.groups_id)
                        .mapped("partner_id")
                        .ids
                    )
                    partners_len = len(
                        partners_obj.filtered(
                            lambda x: x.id not in user_partner_ids
                            and (
                                not x.user_ids
                                or group_portal in x.user_ids.mapped("groups_id")
                            )
                        )
                    )
                    if partners_len > 1:
                        # get partners
                        cc_internal = True
                        # else get company in object
                        if hasattr(obj, "company_id") and obj.company_id:
                            cc_internal = obj.company_id.show_internal_users_cc
                        # get company in user
                        elif mail.env and mail.env.user and mail.env.user.company_id:
                            cc_internal = (
                                self.env.user.company_id.show_internal_users_cc
                            )
                        if cc_internal:
                            partners = partners_obj.filtered(
                                lambda x: x.id not in user_partner_ids
                                and (not x.user_ids or x.user_ids.show_in_cc)
                            )
                        else:
                            partners = partners_obj.filtered(
                                lambda x: x.id not in user_partner_ids
                                and (
                                    not x.user_ids
                                    or group_portal in x.user_ids.mapped("groups_id")
                                )
                            )
                        partners = partners.filtered(
                            lambda x: not x.user_ids
                            or x.user_ids  # otherwise, email is not sent
                            and "email" in x.user_ids.mapped("notification_type")
                        )
                        # set proper lang for recipients
                        langs = list(
                            filter(
                                bool,
                                mail.mapped("recipient_ids.lang")
                                + [
                                    mail.author_id.lang,
                                    self.env.company.partner_id.lang,
                                ],
                            )
                        )
                        # get show follower text
                        final_cc = mail.with_context(
                            lang=langs and langs[0]
                        )._build_cc_text(partners)
                        # it is saved in the body_html field so that it does
                        # not appear in the odoo log
                        mail.body_html = final_cc + mail.body_html
        return super()._send(
            auto_commit=auto_commit,
            raise_exception=raise_exception,
            smtp_session=smtp_session,
        )
<|endoftext|>


<commit_before>import tempfile
import json

import fabric

import vcloud_plugin_common

def configure(vcloud_config):
    _copy_vsphere_configuration_to_manager(vcloud_config)
    _install_docker()

def _copy_vsphere_configuration_to_manager(vcloud_config):
    tmp = tempfile.mktemp()
    with open(tmp, 'w') as f:
        json.dump(vcloud_config, f)
    fabric.api.put(tmp,
                   vcloud_plugin_common.Config.VCLOUD_CONFIG_PATH_DEFAULT)

def _install_docker():
    distro = fabric.api.run(
        'python -c "import platform; print platform.dist()[0]"')
    kernel_version = fabric.api.run(
        'python -c "import platform; print platform.release()"')
    if kernel_version.startswith("3.13") and 'Ubuntu' in distro:
        fabric.api.run("wget -qO- https://get.docker.com/ | sudo sh")
<commit_msg>cfy-2153: save manager context<commit_after>import tempfile
import json

import fabric

import vcloud_plugin_common
from cloudify import ctx
from network_plugin import get_network_name

PROVIDER_CONTEXT_RUNTIME_PROPERTY = 'provider_context'

def configure(vcloud_config):
    _copy_vsphere_configuration_to_manager(vcloud_config)
    _install_docker()
    _save_context()

def _copy_vsphere_configuration_to_manager(vcloud_config):
    tmp = tempfile.mktemp()
    with open(tmp, 'w') as f:
        json.dump(vcloud_config, f)
    fabric.api.put(tmp,
                   vcloud_plugin_common.Config.VCLOUD_CONFIG_PATH_DEFAULT)

def _install_docker():
    distro = fabric.api.run(
        'python -c "import platform; print platform.dist()[0]"')
    kernel_version = fabric.api.run(
        'python -c "import platform; print platform.release()"')
    if kernel_version.startswith("3.13") and 'Ubuntu' in distro:
        fabric.api.run("wget -qO- https://get.docker.com/ | sudo sh")

def _save_context():

    resources = dict()

    node_instances = ctx._endpoint.storage.get_node_instances()
    nodes_by_id = \
        {node.id: node for node in ctx._endpoint.storage.get_nodes()}

    for node_instance in node_instances:
        run_props = node_instance.runtime_properties
        props = nodes_by_id[node_instance.node_id].properties

        if "management_network" == node_instance.node_id:
            resources['int_network'] = {
                "name": props.get('resource_id'),
                "use_external_resource": props.get('use_external_resource')
            }
        if "manager_floating_ip" == node_instance.node_id:
            resources['floating_ip'] = {
                "ip": run_props.get('public_ip')
            }

    return {
        'resources': resources
    }
<|endoftext|>


<commit_before>"""
conway.py
Author: Dimitri
Credit: Morgan
Assignment:
Write and submit a program that plays Conway's Game of Life, per
https://github.com/HHS-IntroProgramming/Conway-Life
"""
"""
from ggame import App, Color, Sprite, RectangleAsset, LineStyle, MouseEvent

purple = Color(0x512DA8, 1)
colortwo = Color(0xFF0000, 1)
nostroke = LineStyle(0, purple)
livecells = {}
makecells = []
surcells = []
killcells = {}
xdiff = 0
ydiff = 0

def create():
    for celle in makecells[:]:
        Cell((celle[0], celle[1]))
        makecells.remove(celle)

def getcoor(xx, yy):
    return([[xx - 10, yy - 10], [xx - 10, yy], [xx - 10, yy + 10], [xx, yy - 10], [xx, yy + 10], [xx + 10, yy - 10], [xx + 10, yy], [xx + 10, yy + 10]])

def check():
    for celle in surcells[:]:
        if find(celle[0], celle[1]) == 3:
            makecells.append(celle)
        surcells.remove(celle)

def checking(xx, yy):
    dei = getcoor(xx, yy)
    for deadcell in dei:
        if livecells.get((deadcell[0], deadcell[1]), False) == False:
            if deadcell in surcells:
                at = 1
            else:
                surcells.append(deadcell)

def find(xx, yy):
    neighbors = getcoor(xx, yy)
    neighborcount = 0
    for posi in neighbors:
        if livecells.get((posi[0], posi[1]), False) == True:
            neighborcount += 1
    return(neighborcount)

class Cell(Sprite):
    pix = RectangleAsset(10, 10, nostroke, purple)

    def __init__(self, position):
        super().__init__(Cell.pix, position)
        self.ogposx = self.x
        self.ogposy = self.y
        livecells[(self.ogposx, self.ogposy)] = True
        self.x += xdiff
        self.y += ydiff
        self.day = 0
        self.changed = False

    def step(self):
        if livecells.get((self.ogposx, self.ogposy)) == True:
            self.day += 1
            if self.day > 1 and self.changed == False:
                self.color = colortwo
                self.changed = True
            n = find(self.ogposx, self.ogposy)
            if n < 2 or n > 3:
                killcells[(self.ogposx, self.ogposy)] = True
            checking(self.ogposx, self.ogposy)
        else:
            self.visible = False

    def kill(self):
        if killcells.get((self.ogposx, self.ogposy), False) == True:
            livecells[(self.ogposx, self.ogposy)] = False
            killcells[(self.ogposx, self.ogposy)] = False

    def mover(self, direction):
        if direction == "r":
            self.x += 20
        elif direction == "l":
            self.x -= 20
        elif direction == "u":
            self.y -= 20
        elif direction == "d":
            self.y += 20

    def checktokill(self, px, py):
        if px == self.ogposx and py == self.ogposy:
            self.visible = False
            killcells[(self.ogposx, self.ogposy)] = True
            self.kill()

class Conway(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        self.stopped = True
        Cell((100, 50))
        Cell((110, 60))
        Cell((110, 70))
        Cell((100, 70))
        Cell((90, 70))
        self.listenKeyEvent("keydown", "right arrow", self.moveright)
        self.listenKeyEvent("keydown", "left arrow", self.moveleft)
        self.listenKeyEvent("keydown", "up arrow", self.moveup)
        self.listenKeyEvent("keydown", "down arrow", self.movedown)
        self.listenKeyEvent("keydown", "space", self.toggle)
        self.listenMouseEvent('click', self.create)

    def moveright(self, event):
        xdiff += 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("r")
    def moveleft(self, event):
        xdiff -= 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("l")
    def moveup(self, event):
        ydiff -= 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("u")
    def movedown(self, event):
        ydiff += 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("d")
    def toggle(self, event):
        if self.stopped == True:
            self.stopped = False
        else:
            self.stopped = True

    def create(self, event):
        diffx = event.x % 10
        diffy = event.y % 10
        finx = event.x - diffx - 10 - xdiff
        finy = event.y - diffy - 10 - ydiff
        if livecells.get((finx, finy), False) == True:
            for cell in self.getSpritesbyClass(Cell):
                cell.checktokill(finx, finy)
        else:
            Cell((finx, finy))

    def step(self):
        if self.stopped == False:
            create()
            for cell in self.getSpritesbyClass(Cell):
                cell.kill()
            for cell in self.getSpritesbyClass(Cell):
                cell.step()
            check()

myapp = Conway(640, 480)
myapp.run()
"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

black = Color(0, 1)
white = Color(0xffffff, 1)
noline = LineStyle(0, white)
livecells = {}
deadcells = {}
addcells = []
surcells = []

def neighborlist(x1, y1):
    return([[x1-10, y1-10], [x1-10, y1], [x1-10, y1+10], [x1, y1-10], [x1, y1+10], [x1+10, y1-10], [x1+10, y1], [x1+10, y1+10]])

def getneighbors(x1, y1):
    neighbors = neighborlist(x1, y1)
    counted = 0
    for outsidecells in neighbors:
        if livecells.get((outsidecells[0], outsidecells[1]), False) == True:
            counted += 1
        else:
            if outsidecells in surcells:
                at = 1
            else:
                surcells.append(outsidecells)
    return(counted)

def createcells(self):
    for cells in addcells[:]:
        Cell((cells[0], cells[1]))
        addcells.remove(cells)

def revive(self):
    for nextcells in surcells[:]:
        if getneighbors((nextcells[0], nextcells[1])) == 3:
            addcells.append(nextcells)
        surcells.remove(nextcells)

class Cell(Sprite):
    asset = RectangleAsset(10, 10, noline, black)

    def __init__(self, position):
        super().__init__(Cell.asset, position)
        livecells[(self.x, self.y)] = True
        generation = 0

    def step(self):
        neighbors = getneighbors(self.x, self.y)
        if neighbors < 2 or neighbors > 3:
            self.visible = False
            deadcells[(self.x, self.y)] = True
            livecells[(self.x, self.y)] = False
        if neighbors == 3 and deadcells[(self.x, self.y)] == True:
            self.visible = True
            deadcells[(self.x, self.y)] = False
            livecells[(self.x, self.y)] = True

class Conways(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        #self.stopped = True
        Cell((100, 100))
        Cell((90, 100))
        Cell((110, 100))

    def step(self):
      #  for cell in self.getSpritesbyClass(Cell):
      #      cell.kill()

        for cell in self.getSpritesbyClass(Cell):
            cell.step()
        revive()
        createcells()

myapp = Conways(640, 480)
myapp.run()
<commit_msg>Updated from Brython Server: 12/8/2015 2:30:32 PM<commit_after>"""
conway.py
Author: Dimitri
Credit: Morgan
Assignment:
Write and submit a program that plays Conway's Game of Life, per
https://github.com/HHS-IntroProgramming/Conway-Life
"""
"""
from ggame import App, Color, Sprite, RectangleAsset, LineStyle, MouseEvent

purple = Color(0x512DA8, 1)
colortwo = Color(0xFF0000, 1)
nostroke = LineStyle(0, purple)
livecells = {}
makecells = []
surcells = []
killcells = {}
xdiff = 0
ydiff = 0

def create():
    for celle in makecells[:]:
        Cell((celle[0], celle[1]))
        makecells.remove(celle)

def getcoor(xx, yy):
    return([[xx - 10, yy - 10], [xx - 10, yy], [xx - 10, yy + 10], [xx, yy - 10], [xx, yy + 10], [xx + 10, yy - 10], [xx + 10, yy], [xx + 10, yy + 10]])

def check():
    for celle in surcells[:]:
        if find(celle[0], celle[1]) == 3:
            makecells.append(celle)
        surcells.remove(celle)

def checking(xx, yy):
    dei = getcoor(xx, yy)
    for deadcell in dei:
        if livecells.get((deadcell[0], deadcell[1]), False) == False:
            if deadcell in surcells:
                at = 1
            else:
                surcells.append(deadcell)

def find(xx, yy):
    neighbors = getcoor(xx, yy)
    neighborcount = 0
    for posi in neighbors:
        if livecells.get((posi[0], posi[1]), False) == True:
            neighborcount += 1
    return(neighborcount)

class Cell(Sprite):
    pix = RectangleAsset(10, 10, nostroke, purple)

    def __init__(self, position):
        super().__init__(Cell.pix, position)
        self.ogposx = self.x
        self.ogposy = self.y
        livecells[(self.ogposx, self.ogposy)] = True
        self.x += xdiff
        self.y += ydiff
        self.day = 0
        self.changed = False

    def step(self):
        if livecells.get((self.ogposx, self.ogposy)) == True:
            self.day += 1
            if self.day > 1 and self.changed == False:
                self.color = colortwo
                self.changed = True
            n = find(self.ogposx, self.ogposy)
            if n < 2 or n > 3:
                killcells[(self.ogposx, self.ogposy)] = True
            checking(self.ogposx, self.ogposy)
        else:
            self.visible = False

    def kill(self):
        if killcells.get((self.ogposx, self.ogposy), False) == True:
            livecells[(self.ogposx, self.ogposy)] = False
            killcells[(self.ogposx, self.ogposy)] = False

    def mover(self, direction):
        if direction == "r":
            self.x += 20
        elif direction == "l":
            self.x -= 20
        elif direction == "u":
            self.y -= 20
        elif direction == "d":
            self.y += 20

    def checktokill(self, px, py):
        if px == self.ogposx and py == self.ogposy:
            self.visible = False
            killcells[(self.ogposx, self.ogposy)] = True
            self.kill()

class Conway(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        self.stopped = True
        Cell((100, 50))
        Cell((110, 60))
        Cell((110, 70))
        Cell((100, 70))
        Cell((90, 70))
        self.listenKeyEvent("keydown", "right arrow", self.moveright)
        self.listenKeyEvent("keydown", "left arrow", self.moveleft)
        self.listenKeyEvent("keydown", "up arrow", self.moveup)
        self.listenKeyEvent("keydown", "down arrow", self.movedown)
        self.listenKeyEvent("keydown", "space", self.toggle)
        self.listenMouseEvent('click', self.create)

    def moveright(self, event):
        xdiff += 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("r")
    def moveleft(self, event):
        xdiff -= 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("l")
    def moveup(self, event):
        ydiff -= 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("u")
    def movedown(self, event):
        ydiff += 20
        for cell in self.getSpritesbyClass(Cell):
            cell.mover("d")
    def toggle(self, event):
        if self.stopped == True:
            self.stopped = False
        else:
            self.stopped = True

    def create(self, event):
        diffx = event.x % 10
        diffy = event.y % 10
        finx = event.x - diffx - 10 - xdiff
        finy = event.y - diffy - 10 - ydiff
        if livecells.get((finx, finy), False) == True:
            for cell in self.getSpritesbyClass(Cell):
                cell.checktokill(finx, finy)
        else:
            Cell((finx, finy))

    def step(self):
        if self.stopped == False:
            create()
            for cell in self.getSpritesbyClass(Cell):
                cell.kill()
            for cell in self.getSpritesbyClass(Cell):
                cell.step()
            check()

myapp = Conway(640, 480)
myapp.run()
"""
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame

black = Color(0, 1)
white = Color(0xffffff, 1)
noline = LineStyle(0, white)
livecells = {}
deadcells = {}
addcells = []
surcells = []

def neighborlist(x1, y1):
    return([[x1-10, y1-10], [x1-10, y1], [x1-10, y1+10], [x1, y1-10], [x1, y1+10], [x1+10, y1-10], [x1+10, y1], [x1+10, y1+10]])

def getneighbors(x1, y1):
    neighbors = neighborlist(x1, y1)
    counted = 0
    for outsidecells in neighbors:
        if livecells.get((outsidecells[0], outsidecells[1]), False) == True:
            counted += 1
        else:
            if outsidecells in surcells:
                at = 1
            else:
                surcells.append(outsidecells)
    return(counted)

def createcells(self):
    for cells in addcells[:]:
        Cell((cells[0], cells[1]))
        addcells.remove(cells)

def revive(self):
    for nextcells in surcells[:]:
        if getneighbors((nextcells[0], nextcells[1])) == 3:
            addcells.append(nextcells)
        surcells.remove(nextcells)

class Cell(Sprite):
    asset = RectangleAsset(10, 10, noline, black)

    def __init__(self, position):
        super().__init__(Cell.asset, position)
        livecells[(self.x, self.y)] = True
        generation = 0

    def step(self):
        neighbors = getneighbors(self.x, self.y)
        if neighbors < 2 or neighbors > 3:
            self.visible = False
            deadcells[(self.x, self.y)] = True
            livecells[(self.x, self.y)] = False
        if neighbors == 3 and deadcells[(self.x, self.y)] == True:
            self.visible = True
            deadcells[(self.x, self.y)] = False
            livecells[(self.x, self.y)] = True

class Conways(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        #self.stopped = True
        Cell((100, 100))
        Cell((90, 100))
        Cell((110, 100))

    def step(self):
      #  for cell in self.getSpritesbyClass(Cell):
      #      cell.kill()
        revive()
        for cell in self.getSpritesbyClass(Cell):
            cell.step()

        createcells()

myapp = Conways(640, 480)
myapp.run()
<|endoftext|>


<commit_before>"""
conway.py
Author: Morgan Meliment
Credit: http://brythonserver.github.io/ggame/#ggame.EllipseAsset
Assignment:
Write and submit a program that plays Conway's Game of Life, per
https://github.com/HHS-IntroProgramming/Conway-Life

"""
from ggame import App, Color, Sprite, RectangleAsset, LineStyle, MouseEvent

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

grey = Color(0x808080, 1)
nostroke = LineStyle(0, grey)
livecells = []
makecells = []
surcells = []
killcells = []

def create():
    for celle in makecells:
        Cell((celle[0], celle[1]))
        makecells.remove(celle)

def getcoor(xx, yy):
    return([[xx - 10, yy - 10], [xx - 10, yy], [xx - 10, yy + 10], [xx, yy - 10], [xx, yy + 10], [xx + 10, yy - 10], [xx + 10, yy], [xx + 10, yy + 10]])

def check():
    for celle in surcells:
        if find(celle[0], celle[1]) == 3:
            makecells.append(celle)
        surcells.remove(celle)

def checking(xx, yy):
    dei = getcoor(xx, yy)
    for deadcell in dei:
        if str((deadcell[0], deadcell[1])) in livecells:
            i = 3
        else:
            if deadcell in surcells:
                at = 1
            else:
                surcells.append(deadcell)

def find(xx, yy):
    neighbors = getcoor(xx, yy)
    neighborcount = 0
    for posi in neighbors:
        if str((posi[0], posi[1])) in livecells:
            neighborcount += 1
    return(neighborcount)

class Cell(Sprite):
    pix = RectangleAsset(10, 10, nostroke, grey)

    def __init__(self, position):
        super().__init__(Cell.pix, position)
        livecells.append(str(self.position))

    def step(self):
        if str(self.position) in killcells:
            livecells.remove(str(self.position))
            killcells.remove(str(self.position))
            self.destroy()
        else:
            n = find(self.x, self.y)
            if n < 2 or n > 3:
                killcells.append(str(self.position))
            checking(self.x, self.y)

class Conway(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        Cell((10, 0))
        Cell((10, 10))
        Cell((10, 20))

    def step(self):
        create()
        for cell in self.getSpritesbyClass(Cell):
            cell.step()
        print(livecells)
        check()

myapp = Conway(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()

<commit_msg>Updated from Brython Server: October 12, 2015 5:02:23 PM EDT<commit_after>"""
conway.py
Author: Morgan Meliment
Credit: http://brythonserver.github.io/ggame/#ggame.EllipseAsset
Assignment:
Write and submit a program that plays Conway's Game of Life, per
https://github.com/HHS-IntroProgramming/Conway-Life

"""
from ggame import App, Color, Sprite, RectangleAsset, LineStyle, MouseEvent

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

grey = Color(0x808080, 1)
nostroke = LineStyle(0, grey)
livecells = []
makecells = []
surcells = []
killcells = []

def create():
    for celle in makecells:
        Cell((celle[0], celle[1]))
        makecells.remove(celle)

def getcoor(xx, yy):
    return([[xx - 10, yy - 10], [xx - 10, yy], [xx - 10, yy + 10], [xx, yy - 10], [xx, yy + 10], [xx + 10, yy - 10], [xx + 10, yy], [xx + 10, yy + 10]])

def check():
    for celle in surcells:
        if find(celle[0], celle[1]) == 3:
            makecells.append(celle)
        surcells.remove(celle)

def checking(xx, yy):
    dei = getcoor(xx, yy)
    for deadcell in dei:
        if (deadcell[0], deadcell[1]) in livecells:
            i = 3
        else:
            if deadcell in surcells:
                at = 1
            else:
                surcells.append(deadcell)

def find(xx, yy):
    neighbors = getcoor(xx, yy)
    neighborcount = 0
    for posi in neighbors:
        if (posi[0], posi[1]) in livecells:
            neighborcount += 1
    return(neighborcount)

class Cell(Sprite):
    pix = RectangleAsset(10, 10, nostroke, grey)

    def __init__(self, position):
        super().__init__(Cell.pix, position)
        livecells.append(self.position)

    def step(self):
        n = find(self.x, self.y)
        if n < 2 or n > 3:
            killcells.append(self.position)
        else:
            checking(self.x, self.y)

    def kill(self):
        if self.position in killcells:
            livecells.remove(self.position)
            killcells.remove(self.position)
            self.destroy()

class Conway(App):
    def __init__(self, width, height):
        super().__init__(width, height)
        Cell((10, 0))
        Cell((10, 10))
        Cell((10, 20))

    def step(self):
        create()
        for cell in self.getSpritesbyClass(Cell):
            cell.step()
        print(livecells)
        check()

myapp = Conway(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()

<|endoftext|>


<commit_before>"""
conway.py
Author: <your name here>
Credit: <list sources used, if any>
Assignment:
Write and submit a program that plays Conway's Game of Life, per
https://github.com/HHS-IntroProgramming/Conway-Life
"""
from ggame import App, Sprite, CircleAsset, RectangleAsset, Color, LineStyle

red = Color(0xff0000, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0, 1.0)
noline = LineStyle(0, black)
CELLDIAMETER = 10
CELLSWIDE = 100
CELLSHIGH = 50

class Cell(Sprite):
    """
    Cell that is either new or old.
    Pass True for new if it shall be a new color.
    """
    bluecircle = CircleAsset(4, noline, blue)
    redcircle = CircleAsset(4, noline, red)

    def __init__(self, new, pos):
        asset = Cell.bluecircle
        if new:
            asset = Cell.redcircle
        super().__init__(asset, pos)

class ConwayGame(App):
    """
    App for implementing Conway's Game of Life
    """
    def __init__(self):
        w = CELLDIAMETER*CELLSWIDE
        h = CELLDIAMETER*CELLSHIGH
        super().__init__(w, h)
        bgasset = RectangleAsset(w, h, noline, black)
        # Sprite(bgasset, (0,0))
        self.livingcells = {}
        self.newcells = []
        self.oldcells = []
        # set three living cells
        self.makeglider((10,10))
        self.makeglider((20,25))

    def makeglider(self, pos):
        self.livingcells[pos] = 0
        self.livingcells[(pos[0]+1, pos[1])] = 0
        self.livingcells[(pos[0]+2, pos[1])] = 0
        self.livingcells[(pos[0]+2, pos[1]-1)] = 0
        self.livingcells[(pos[0]+1, pos[1]-2)] = 0

    def population(self, addr):
        if addr in self.livingcells:
            return 1
        else:
            return 0

    def neighboraddresses(self, addr):
        return [(addr[0]+1, addr[1]+1),
                (addr[0], addr[1]+1),
                (addr[0]-1, addr[1]+1),
                (addr[0]-1, addr[1]),
                (addr[0]+1, addr[1]),
                (addr[0]+1, addr[1]-1),
                (addr[0], addr[1]-1),
                (addr[0]-1, addr[1]-1)]

    def countneighbors(self, addr):
        count = 0
        for naddr in self.neighboraddresses(addr):
            count += self.population(naddr)
        return count

    def birthnew(self, nextgen, addr):
        if addr not in self.livingcells:
            if self.countneighbors(addr) == 3:
                nextgen[addr] = 0

    def step(self):
        nextgen = {}
        for addr in self.livingcells:
            n = self.countneighbors(addr)
            if n in (2, 3):
                nextgen[addr] = self.livingcells[addr]+1
            for naddr in self.neighboraddresses(addr):
                self.birthnew(nextgen, naddr)
        for s in self.getSpritesbyClass(Cell):
            s.visible = False
            s.destroy()
        self.livingcells = nextgen
        for c in self.livingcells:
            isnew = self.livingcells[c] == 0
            Cell(isnew, (c[0]*CELLDIAMETER, c[1]*CELLDIAMETER))

App = ConwayGame()
App.run()<commit_msg>Updated from Brython Server: 10/8/2015 12:32:47 PM<commit_after>"""
conway.py
Author: <your name here>
Credit: <list sources used, if any>
Assignment:
Write and submit a program that plays Conway's Game of Life, per
https://github.com/HHS-IntroProgramming/Conway-Life
"""
from ggame import App, Sprite, CircleAsset, RectangleAsset, Color, LineStyle

red = Color(0xff0000, 1.0)
blue = Color(0x0000ff, 1.0)
black = Color(0, 1.0)
noline = LineStyle(0, black)
CELLDIAMETER = 10
CELLSWIDE = 100
CELLSHIGH = 50

class Cell(Sprite):
    """
    Cell that is either new or old.
    Pass True for new if it shall be a new color.
    """
    bluecircle = CircleAsset(4, noline, blue)
    redcircle = CircleAsset(4, noline, red)

    def __init__(self, new, pos):
        asset = Cell.bluecircle
        if new:
            asset = Cell.redcircle
        super().__init__(asset, pos)

class ConwayGame(App):
    """
    App for implementing Conway's Game of Life
    """
    def __init__(self):
        w = CELLDIAMETER*CELLSWIDE
        h = CELLDIAMETER*CELLSHIGH
        super().__init__(w, h)
        bgasset = RectangleAsset(w, h, noline, black)
        # Sprite(bgasset, (0,0))
        self.livingcells = {}
        self.newcells = []
        self.oldcells = []
        # set three living cells
        for i in range(10):
            self.makeglider((i*10,10))

    def makeglider(self, pos):
        self.livingcells[pos] = 0
        self.livingcells[(pos[0]+1, pos[1])] = 0
        self.livingcells[(pos[0]+2, pos[1])] = 0
        self.livingcells[(pos[0]+2, pos[1]-1)] = 0
        self.livingcells[(pos[0]+1, pos[1]-2)] = 0

    def population(self, addr):
        if addr in self.livingcells:
            return 1
        else:
            return 0

    def neighboraddresses(self, addr):
        return [(addr[0]+1, addr[1]+1),
                (addr[0], addr[1]+1),
                (addr[0]-1, addr[1]+1),
                (addr[0]-1, addr[1]),
                (addr[0]+1, addr[1]),
                (addr[0]+1, addr[1]-1),
                (addr[0], addr[1]-1),
                (addr[0]-1, addr[1]-1)]

    def countneighbors(self, addr):
        count = 0
        for naddr in self.neighboraddresses(addr):
            count += self.population(naddr)
        return count

    def birthnew(self, nextgen, addr):
        if addr not in self.livingcells:
            if self.countneighbors(addr) == 3:
                nextgen[addr] = 0

    def step(self):
        nextgen = {}
        for addr in self.livingcells:
            n = self.countneighbors(addr)
            if n in (2, 3):
                nextgen[addr] = self.livingcells[addr]+1
            for naddr in self.neighboraddresses(addr):
                self.birthnew(nextgen, naddr)
        for s in self.getSpritesbyClass(Cell):
            s.visible = False
            s.destroy()
        self.livingcells = nextgen
        for c in self.livingcells:
            isnew = self.livingcells[c] == 0
            Cell(isnew, (c[0]*CELLDIAMETER, c[1]*CELLDIAMETER))

App = ConwayGame()
App.run()<|endoftext|>


<commit_before>"""
Copyright (C) 2016  Genome Research Ltd.

Author: Irina Colgiu <ic4@sanger.ac.uk>

This program is part of meta-check

meta-check is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

This file has been created on Jun 10, 2016.
"""

from mcheck.results.checks_results import CheckResult, RESULT
from mcheck.check_names import CHECK_NAMES
from collections import  defaultdict

class FileMetadataComparison:

    @staticmethod
    def check_metadata_across_different_sources(irods_metadata_dict, header_metadata_dict, seqsc_metadata_dict, issues_dict):
        """
        This function checks the metadata from 3 different sources in terms of samples, libraries and studies.
        At the moment the checks across these sources consist of comparing: libraries, studies and samples
        As a result it updates the issues_dict by appending the CheckResults obtain after running the latest tests.
        :param irods_metadata_dict: key: fpath, value: irods_metadata for that file
        :param header_metadata_dict: key: fpath, value: header_metadata for that file
        :param seqsc_metadata_dict: key: fpath, value: seqscape_metadata for that file
        :param issues_dict: key: fpath, value: list of CheckResults
        :return:
        """
        for fpath, irods_metadata in irods_metadata_dict.items():
            header_metadata = header_metadata_dict[fpath]
            seqscape_metadata = seqsc_metadata_dict[fpath]

            ss_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_seqscape_ids_compared_to_header_ids, error_message=[])
            h_vs_ss_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_seqscape_ids, error_message=[])
            i_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_irods_ids_compared_to_header_ids, error_message=[])
            h_vs_i_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_irods_ids, error_message=[])
            if not header_metadata.has_metadata():
                error_msg = "No header metadata"
                ss_vs_h_check_result.executed = False
                h_vs_ss_check_result.executed = False
                i_vs_h_check_result.executed = False
                h_vs_i_check_result.executed = False

                ss_vs_h_check_result.error_message.append(error_msg)
                h_vs_ss_check_result.error_message.append(error_msg)
                i_vs_h_check_result.error_message.append(error_msg)
                h_vs_i_check_result.error_message.append(error_msg)
            else:
                if not seqscape_metadata.has_metadata():
                    error_msg = "No seqscape metadata"
                    ss_vs_h_check_result.executed = False
                    h_vs_ss_check_result.executed = False
                    ss_vs_h_check_result.error_message.append(error_msg)
                    h_vs_ss_check_result.error_message.append(error_msg)
                else:
                    seqscape_diff_header = seqscape_metadata.difference(header_metadata)
                    header_diff_seqscape = header_metadata.difference(seqscape_metadata)
                    if seqscape_diff_header:
                        error_msg = "Differences: %s" % seqscape_diff_header
                        ss_vs_h_check_result.error_message = error_msg
                        ss_vs_h_check_result.result = RESULT.FAILURE
                    if header_diff_seqscape:
                        error_msg = "Differences: %s" % header_diff_seqscape
                        h_vs_ss_check_result.result = RESULT.FAILURE
                        h_vs_ss_check_result.error_message = error_msg

                if not irods_metadata.has_metadata():
                    error_msg = "No irods metadata"
                    i_vs_h_check_result.error_message.append(error_msg)
                    h_vs_i_check_result.error_message.append(error_msg)
                else:
                    irods_diff_header = irods_metadata.difference(header_metadata)
                    header_diff_irods = header_metadata.difference(irods_metadata)
                    if irods_diff_header:
                        error_msg = "Differences: %s" % irods_diff_header
                        i_vs_h_check_result.error_message = error_msg
                        i_vs_h_check_result.result = RESULT.FAILURE

                    if header_diff_irods:
                        error_msg = "Differences between what is in the header and not in iRODS: %s" % header_diff_irods
                        h_vs_i_check_result.error_message = error_msg
                        h_vs_i_check_result.result = RESULT.FAILURE

            issues_dict[fpath].append(ss_vs_h_check_result)
            issues_dict[fpath].append(h_vs_ss_check_result)
            issues_dict[fpath].append(i_vs_h_check_result)
            issues_dict[fpath].append(h_vs_i_check_result)

            #
            # impossible_to_exe = False
            # if not seqscape_metadata and not header_metadata:
            #     error_msg = "No seqscape metadata and no header_metadata"
            #     impossible_to_exe = True
            # elif not seqscape_metadata:
            #     impossible_to_exe = True
            #     error_msg = "No seqscape metadata"
            # elif not header_metadata:
            #     impossible_to_exe = True
            #     error_msg = "No header metadata"
            #
            # if impossible_to_exe:
            #     ss_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_seqscape_ids_compared_to_header_ids, executed=False, error_message=error_msg)
            #     h_vs_ss_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_seqscape_ids, executed=False, error_message=error_msg)
            #
            # else:
            #     ss_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_seqscape_ids_compared_to_header_ids)
            #
            #
            #     issues_dict[fpath].append(ss_vs_h_check_result)
            #
            #     h_vs_ss_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_seqscape_ids)
            #     if header_metadata and seqscape_metadata:
            #
            #     issues_dict[fpath].append(h_vs_ss_check_result)
            #
            #
            # impossible_to_exe = False
            # error_msg = ""
            # if not irods_metadata and not header_metadata:
            #     error_msg = "No header_metadata and no irods_metadata"
            #     impossible_to_exe = True
            # elif not irods_metadata:
            #     error_msg = "No irods_metadata"
            #     impossible_to_exe = True
            # elif not header_metadata:
            #     error_msg = "No header metadata"
            #     impossible_to_exe = True
            #
            # if impossible_to_exe:
            #     i_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_irods_ids_compared_to_header_ids, executed=False, error_message=error_msg)
            #     h_vs_i_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_irods_ids, executed=False, error_message=error_msg)
            #
            # else:
            #     i_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_irods_ids_compared_to_header_ids)
            #
            #     issues_dict[fpath].append(i_vs_h_check_result)
            #
            #     h_vs_i_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_irods_ids)
            #
            #     issues_dict[fpath].append(h_vs_i_check_result)
            #
            #

<commit_msg>Fixed small bug - wrong check result<commit_after>"""
Copyright (C) 2016  Genome Research Ltd.

Author: Irina Colgiu <ic4@sanger.ac.uk>

This program is part of meta-check

meta-check is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.

This file has been created on Jun 10, 2016.
"""

from mcheck.results.checks_results import CheckResult, RESULT
from mcheck.check_names import CHECK_NAMES
from collections import  defaultdict

class FileMetadataComparison:

    @staticmethod
    def check_metadata_across_different_sources(irods_metadata_dict, header_metadata_dict, seqsc_metadata_dict, issues_dict):
        """
        This function checks the metadata from 3 different sources in terms of samples, libraries and studies.
        At the moment the checks across these sources consist of comparing: libraries, studies and samples
        As a result it updates the issues_dict by appending the CheckResults obtain after running the latest tests.
        :param irods_metadata_dict: key: fpath, value: irods_metadata for that file
        :param header_metadata_dict: key: fpath, value: header_metadata for that file
        :param seqsc_metadata_dict: key: fpath, value: seqscape_metadata for that file
        :param issues_dict: key: fpath, value: list of CheckResults
        :return:
        """
        for fpath, irods_metadata in irods_metadata_dict.items():
            header_metadata = header_metadata_dict[fpath]
            seqscape_metadata = seqsc_metadata_dict[fpath]

            ss_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_seqscape_ids_compared_to_header_ids, error_message=[])
            h_vs_ss_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_seqscape_ids, error_message=[])
            i_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_irods_ids_compared_to_header_ids, error_message=[])
            h_vs_i_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_irods_ids, error_message=[])
            if not header_metadata.has_metadata():
                error_msg = "No header metadata"
                ss_vs_h_check_result.executed = False
                h_vs_ss_check_result.executed = False
                i_vs_h_check_result.executed = False
                h_vs_i_check_result.executed = False

                i_vs_h_check_result.result = None
                h_vs_i_check_result.result = None
                h_vs_ss_check_result.result = None
                ss_vs_h_check_result.result = None

                ss_vs_h_check_result.error_message.append(error_msg)
                h_vs_ss_check_result.error_message.append(error_msg)
                i_vs_h_check_result.error_message.append(error_msg)
                h_vs_i_check_result.error_message.append(error_msg)
            else:
                if not seqscape_metadata.has_metadata():
                    error_msg = "No seqscape metadata"
                    ss_vs_h_check_result.executed = False
                    h_vs_ss_check_result.executed = False
                    ss_vs_h_check_result.result = None
                    h_vs_ss_check_result.result = None
                    ss_vs_h_check_result.error_message.append(error_msg)
                    h_vs_ss_check_result.error_message.append(error_msg)
                else:
                    seqscape_diff_header = seqscape_metadata.difference(header_metadata)
                    header_diff_seqscape = header_metadata.difference(seqscape_metadata)
                    if seqscape_diff_header:
                        error_msg = "Differences: %s" % seqscape_diff_header
                        ss_vs_h_check_result.error_message = error_msg
                        ss_vs_h_check_result.result = RESULT.FAILURE
                    if header_diff_seqscape:
                        error_msg = "Differences: %s" % header_diff_seqscape
                        h_vs_ss_check_result.result = RESULT.FAILURE
                        h_vs_ss_check_result.error_message = error_msg

                if not irods_metadata.has_metadata():
                    error_msg = "No irods metadata"
                    i_vs_h_check_result.executed = False
                    h_vs_i_check_result.executed = False
                    i_vs_h_check_result.result = None
                    h_vs_i_check_result.result = None
                    i_vs_h_check_result.error_message.append(error_msg)
                    h_vs_i_check_result.error_message.append(error_msg)
                else:
                    irods_diff_header = irods_metadata.difference(header_metadata)
                    header_diff_irods = header_metadata.difference(irods_metadata)
                    if irods_diff_header:
                        error_msg = "Differences: %s" % irods_diff_header
                        i_vs_h_check_result.error_message = error_msg
                        i_vs_h_check_result.result = RESULT.FAILURE

                    if header_diff_irods:
                        error_msg = "Differences between what is in the header and not in iRODS: %s" % header_diff_irods
                        h_vs_i_check_result.error_message = error_msg
                        h_vs_i_check_result.result = RESULT.FAILURE

            issues_dict[fpath].append(ss_vs_h_check_result)
            issues_dict[fpath].append(h_vs_ss_check_result)
            issues_dict[fpath].append(i_vs_h_check_result)
            issues_dict[fpath].append(h_vs_i_check_result)

            #
            # impossible_to_exe = False
            # if not seqscape_metadata and not header_metadata:
            #     error_msg = "No seqscape metadata and no header_metadata"
            #     impossible_to_exe = True
            # elif not seqscape_metadata:
            #     impossible_to_exe = True
            #     error_msg = "No seqscape metadata"
            # elif not header_metadata:
            #     impossible_to_exe = True
            #     error_msg = "No header metadata"
            #
            # if impossible_to_exe:
            #     ss_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_seqscape_ids_compared_to_header_ids, executed=False, error_message=error_msg)
            #     h_vs_ss_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_seqscape_ids, executed=False, error_message=error_msg)
            #
            # else:
            #     ss_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_seqscape_ids_compared_to_header_ids)
            #
            #
            #     issues_dict[fpath].append(ss_vs_h_check_result)
            #
            #     h_vs_ss_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_seqscape_ids)
            #     if header_metadata and seqscape_metadata:
            #
            #     issues_dict[fpath].append(h_vs_ss_check_result)
            #
            #
            # impossible_to_exe = False
            # error_msg = ""
            # if not irods_metadata and not header_metadata:
            #     error_msg = "No header_metadata and no irods_metadata"
            #     impossible_to_exe = True
            # elif not irods_metadata:
            #     error_msg = "No irods_metadata"
            #     impossible_to_exe = True
            # elif not header_metadata:
            #     error_msg = "No header metadata"
            #     impossible_to_exe = True
            #
            # if impossible_to_exe:
            #     i_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_irods_ids_compared_to_header_ids, executed=False, error_message=error_msg)
            #     h_vs_i_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_irods_ids, executed=False, error_message=error_msg)
            #
            # else:
            #     i_vs_h_check_result = CheckResult(check_name=CHECK_NAMES.check_irods_ids_compared_to_header_ids)
            #
            #     issues_dict[fpath].append(i_vs_h_check_result)
            #
            #     h_vs_i_check_result = CheckResult(check_name=CHECK_NAMES.check_header_ids_compared_to_irods_ids)
            #
            #     issues_dict[fpath].append(h_vs_i_check_result)
            #
            #

<|endoftext|>


<commit_before>"""
conway.py
Author: Morgan Meliment
Credit: http://brythonserver.github.io/ggame/#ggame.EllipseAsset, http://stackoverflow.com/questions/26454649/python-round-up-to-the-nearest-ten
Assignment:
Write and submit a program that plays Conway's Game of Life, per
https://github.com/HHS-IntroProgramming/Conway-Life
"""
from ggame import App, Color, Sprite, RectangleAsset, LineStyle
import math

grey = Color(0x808080, 1.0)
dark = Color(0x333333, 1.0)
nostroke = LineStyle(0, black)

pixel = RectangleAsset(10, 10, nostroke, grey)

field = []
[field.append(1) for x in range(0, 30)]

g = 0
for b in field:
    g += 1
    if b == 1:
        x = (g % 10) * 11
        y = int(math.floor(g / 10.0)) * 11
        Sprite(pixel, (x, y))
        print(x , y)

myapp = App()
myapp.run()
<commit_msg>Updated from Brython Server: October 6, 2015 2:51:58 PM EDT<commit_after>"""
conway.py
Author: Morgan Meliment
Credit: http://brythonserver.github.io/ggame/#ggame.EllipseAsset, http://stackoverflow.com/questions/26454649/python-round-up-to-the-nearest-ten
Assignment:
Write and submit a program that plays Conway's Game of Life, per
https://github.com/HHS-IntroProgramming/Conway-Life
"""
from ggame import App, Color, Sprite, RectangleAsset, LineStyle
import math

grey = Color(0x808080, 0.5)
dark = Color(0x333333, 1.0)
nostroke = LineStyle(0, grey)

pixel = RectangleAsset(10, 10, nostroke, grey)

field = []
[field.append(0) for x in range(0, 1000)]

g = 0
for b in field:
    if b == 1:
        x = (g % 50) * 11
        y = int(math.floor(g / 50.0)) * 11
        Sprite(pixel, (x, y))
        print(x , y)
    g += 1

myapp = App()
myapp.run()
<|endoftext|>


<commit_before># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from enum import Enum
from typing import Dict, List, Union, Any
import logging
from apache_beam.typehints.decorators import with_output_types

class DestinationType(Enum):
    (
        CM_OFFLINE_CONVERSION,
        ADS_OFFLINE_CONVERSION,
        ADS_OFFLINE_CONVERSION_CALLS,
        ADS_SSD_UPLOAD,
        ADS_ENHANCED_CONVERSION,
        ADS_ENHANCED_CONVERSION_LEADS,
        ADS_CUSTOMER_MATCH_CONTACT_INFO_UPLOAD,
        ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD,
        ADS_CUSTOMER_MATCH_USER_ID_UPLOAD,
        GA_USER_LIST_UPLOAD,
        APPSFLYER_S2S_EVENTS,
        GA_MEASUREMENT_PROTOCOL,
        GA_DATA_IMPORT,
        GA_4_MEASUREMENT_PROTOCOL,
        DV_CUSTOMER_MATCH_CONTACT_INFO_UPLOAD,
        DV_CUSTOMER_MATCH_DEVICE_ID_UPLOAD,
        UPLOADED_UUID,  # schema verification purposes
        UPLOADED_GCLID_TIME  # schema verification purposes
    ) = range(17)

    def __eq__(self, other):
        if other is None:
            return False
        return self.name == other.name

class SourceType(Enum):
    BIG_QUERY, FILE = range(2)

class TransactionalType(Enum):
    """
        Distinct types to handle data uploading deduplication.
        NOT_TRANSACTION: don't handle.
        UUID: Expect a 'uuid' field in the source table as a unique identifier to each row.
        GCLID_DATE_TIME: Expect 'gclid' and 'time' fields in the source table as unique identifiers to each row.
    """
    (
        NOT_TRANSACTIONAL,
        UUID,
        GCLID_TIME,
    ) = range(3)

class AccountConfig:
    def __init__(
        self,
        google_ads_account_id: str,
        mcc: bool,
        google_analytics_account_id: str,
        campaign_manager_profile_id: str,
        app_id: str,
    ):
        self._google_ads_account_id = google_ads_account_id
        self._mcc = mcc
        self._google_analytics_account_id = google_analytics_account_id
        self._campaign_manager_profile_id = campaign_manager_profile_id
        self._app_id = app_id

    @property
    def google_ads_account_id(self) -> str:
        return self._google_ads_account_id

    @property
    def mcc(self) -> bool:
        return self._mcc

    @property
    def google_analytics_account_id(self) -> str:
        return self._google_analytics_account_id

    @property
    def campaign_manager_profile_id(self) -> str:
        return self._campaign_manager_profile_id

    @property
    def app_id(self) -> str:
        return self._app_id

    def to_dict(self):
        return {
            'google_ads_account_id': self.google_ads_account_id,
            'mcc': self.mcc,
            'google_analytics_account_id': self.google_analytics_account_id,
            'campaign_manager_profile_id': self.campaign_manager_profile_id,
            'app_id': self.app_id,
        }

    @staticmethod
    def from_dict(dict_account_config):
        return AccountConfig(
            dict_account_config['google_ads_account_id'],
            dict_account_config['mcc'],
            dict_account_config['google_analytics_account_id'],
            dict_account_config['campaign_manager_profile_id'],
            dict_account_config['app_id'],
        )

    def __str__(self) -> str:
        return (
            f"\n[Account Config]\n\t"
            f"Google Ads Customer Id: {self.google_ads_account_id}\n\t"
            f"Google Ads MCC: {self._mcc}\n\t"
            f"Google Analytics Account Id: {self.google_analytics_account_id}\n\t"
            f"Campaign Manager Account Id: {self.campaign_manager_profile_id}\n\t"
            f"Play Store App Id: {self.app_id}"
        )

    def __eq__(self, other):
        return (
            self.google_ads_account_id == other.google_ads_account_id
            and self.google_analytics_account_id == other.google_analytics_account_id
            and self.campaign_manager_profile_id == other.campaign_manager_profile_id
            and self.app_id == other.app_id
        )

    def __hash__(self):
        return hash(
            (
                self.google_ads_account_id,
                self.google_analytics_account_id,
                self.campaign_manager_profile_id,
                self.app_id,
            )
        )

class Source:
    def __init__(
        self, source_name: str, source_type: SourceType, source_metadata: List[str]
    ):
        self._source_name = source_name
        self._source_type = source_type
        self._source_metadata = source_metadata

    @property
    def source_name(self) -> str:
        return self._source_name

    @property
    def source_type(self) -> SourceType:
        return self._source_type

    @property
    def source_metadata(self) -> List[str]:
        return self._source_metadata

    def to_dict(self):
        return {
            'source_name': self.source_name,
            'source_type': self.source_type.name,
            'source_metadata': self.source_metadata,
        }

    @staticmethod
    def from_dict(dict_source):
        return Source(
            dict_source['source_name'],
            SourceType[dict_source['source_type']],
            dict_source['source_metadata']
        )

    def __eq__(self, other):
        return (
            self.source_name == other.source_name
            and self.source_type == other.source_type
            and self.source_metadata == other.source_metadata
        )

    def __hash__(self):
        return hash(
            (
                self.source_name,
                self.source_type,
                self.source_metadata[0],
                self.source_metadata[1],
            )
        )

class Destination:
    def __init__(
        self,
        destination_name: str,
        destination_type: DestinationType,
        destination_metadata: List[str],
    ):
        self._destination_name = destination_name
        self._destination_type = destination_type
        self._destination_metadata = destination_metadata

    @property
    def destination_name(self) -> str:
        return self._destination_name

    @property
    def destination_type(self) -> DestinationType:
        return self._destination_type

    @property
    def destination_metadata(self) -> List[str]:
        return self._destination_metadata

    def to_dict(self):
        return {
            'destination_name': self.destination_name,
            'destination_type': self.destination_type.name,
            'destination_metadata': self.destination_metadata,
        }

    @staticmethod
    def from_dict(dict_destination):
        return Destination(
            dict_destination['destination_name'],
            DestinationType[dict_destination['destination_type']],
            dict_destination['destination_metadata'],
        )

    def __eq__(self, other) -> bool:
        return bool(
            self.destination_name == other.destination_name
            and self.destination_metadata[0] == other.destination_metadata[0]
        )

    def __hash__(self) -> int:
        return hash(
            (
                self.destination_name,
                self.destination_type.name,
                self.destination_metadata[0],
            )
        )

class Execution:
    def __init__(
        self, account_config: AccountConfig, source: Source, destination: Destination
    ):
        self._account_config = account_config
        self._source = source
        self._destination = destination

    @property
    def source(self) -> Source:
        return self._source

    @property
    def destination(self) -> Destination:
        return self._destination

    @property
    def account_config(self) -> AccountConfig:
        return self._account_config

    def to_dict(self):
        return {
            'account_config': self.account_config.to_dict(),
            'source': self.source.to_dict(),
            'destination': self.destination.to_dict()
        }

    @staticmethod
    def from_dict(dict_execution):
        return Execution(
            AccountConfig.from_dict(dict_execution['account_config']),
            Source.from_dict(dict_execution['source']),
            Destination.from_dict(dict_execution['destination']),
        )

    def __str__(self):
        return f"Origin name: {self.source.source_name}. Action: {self.destination.destination_type}. Destination name: {self.destination.destination_name}"

    def __eq__(self, other):
        if other is None:
            return False
        return (
            self.source == other.source
            and self.destination == other.destination
            and self.account_config == other.account_config
        )

    def __hash__(self):
        return hash((self.source, self.destination, self.account_config))

class ExecutionsGroupedBySource:
    def __init__(
        self,
        source_name: str,
        executions: List[Execution]
    ):
        self._source_name = source_name
        self._executions = executions

    @property
    def executions(self) -> List[Execution]:
        return self._executions

    @property
    def source_name(self) -> str:
        return self._source_name

    @property
    def source(self) -> Source:
        return self._executions[0].source

    @property
    def destinations(self) -> List[Destination]:
        return list([exec.destination for exec in self._executions])

    def __getitem__(self, i):
        return self._executions[i]

    def to_dict(self):
        executions_json = [exec.to_dict() for exec in self.executions]
        return {
            'source_name': self._source_name,
            'executions': executions_json
        }

    @staticmethod
    def from_dict(dict_executions):
        executions = list([Execution.from_dict(exec_json)
                          for exec_json in dict_executions['executions']])

        return ExecutionsGroupedBySource(
            dict_executions['source_name'],
            executions
        )

    def __str__(self):
        return f"Source: {self._source_name}. Executions: {','.join(['(' + str(exec) + ')' for exec in self._executions])}"

    def __eq__(self, other):
        if other is None:
            return False
        return self.source_name == other.source_name

    def __hash__(self):
        return hash(("ExecutionsGroupedBySource", self.source_name))

class DataRow(Dict[str, Any]):
    pass

class DataRowsGroupedBySource:
    def __init__(
        self,
        executions: ExecutionsGroupedBySource,
        rows: List[DataRow]
    ):
        self._executions = executions
        self._rows = rows

    @property
    def rows(self) -> List[DataRow]:
        return self._rows

    @property
    def executions(self) -> ExecutionsGroupedBySource:
        return self._executions

    @property
    def source(self) -> Source:
        return self._executions.source

    @property
    def source_name(self) -> str:
        return self._executions.source.source_name

    @property
    def destinations(self) -> List[Destination]:
        return self._executions.destinations

    def to_dict(self):
        return {
            'rows': self._rows,
            'executions': self._executions.to_dict()
        }

    @staticmethod
    def from_dict(dict_rows):
        return DataRowsGroupedBySource(
            ExecutionsGroupedBySource.from_dict(dict_rows.executions),
            dict_rows.rows
        )

    def __str__(self):
        return f"Source: {self.source_name}. Executions: {self._executions}. Rows: {self.rows}"

    def __eq__(self, other):
        if other is None:
            return False
        return self.source_name == other.source_name

    def __hash__(self):
        return hash(("DataRowsGroupedBySource", self.source_name))

class Batch:
    def __init__(
        self,
        execution: Execution,
        elements: List[Dict[str, Union[str, Dict[str, str]]]],
        iteration: int = 1,
    ):
        self._execution = execution
        self._elements = elements
        self._iteration = iteration

    @property
    def execution(self) -> Execution:
        return self._execution

    @property
    def elements(self) -> List[Dict[str, Union[str, Dict[str, str]]]]:
        return self._elements

    @property
    def iteration(self) -> int:
        return self._iteration

    def __str__(self):
        return f"Execution: {self._execution}. Elements: {self._elements}"

    def __eq__(self, other):
        if other is None:
            return False
        return self.execution == other.execution and self.elements == other.elements

    def __hash__(self):
        return hash(("Batch", self.execution))

class BatchesGroupedBySource:
    def __init__(
        self,
        source_name: str,
        batches: List[Batch]
    ):
        self._source_name = source_name
        self._batches = batches

    @property
    def batches(self) -> List[Batch]:
        return self._batches

    @property
    def source_name(self) -> str:
        return self._source_name

    def __getitem__(self, i):
        return self._batches[i]

    def __str__(self):
        return f"Source: {self._source_name}. Batches: {self._batches}"

    def __eq__(self, other):
        if other is None:
            return False
        return self.source_name == other.source_name

    def __hash__(self):
        return hash(("ExecutionsGroupedBySource", self.source_name))
<commit_msg>EC4Leads new structure<commit_after># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from enum import Enum
from typing import Dict, List, Union, Any
import logging
from apache_beam.typehints.decorators import with_output_types

class DestinationType(Enum):
    (
        CM_OFFLINE_CONVERSION,
        ADS_OFFLINE_CONVERSION,
        ADS_OFFLINE_CONVERSION_CALLS,
        ADS_SSD_UPLOAD,
        ADS_ENHANCED_CONVERSION,
        ADS_ENHANCED_CONVERSION_LEADS,
        ADS_CUSTOMER_MATCH_CONTACT_INFO_UPLOAD,
        ADS_CUSTOMER_MATCH_MOBILE_DEVICE_ID_UPLOAD,
        ADS_CUSTOMER_MATCH_USER_ID_UPLOAD,
        GA_USER_LIST_UPLOAD,
        APPSFLYER_S2S_EVENTS,
        GA_MEASUREMENT_PROTOCOL,
        GA_DATA_IMPORT,
        GA_4_MEASUREMENT_PROTOCOL,
        DV_CUSTOMER_MATCH_CONTACT_INFO_UPLOAD,
        DV_CUSTOMER_MATCH_DEVICE_ID_UPLOAD,
        UPLOADED_UUID,  # schema verification purposes
        UPLOADED_GCLID_TIME  # schema verification purposes
    ) = range(18)

    def __eq__(self, other):
        if other is None:
            return False
        return self.name == other.name

class SourceType(Enum):
    BIG_QUERY, FILE = range(2)

class TransactionalType(Enum):
    """
        Distinct types to handle data uploading deduplication.
        NOT_TRANSACTION: don't handle.
        UUID: Expect a 'uuid' field in the source table as a unique identifier to each row.
        GCLID_DATE_TIME: Expect 'gclid' and 'time' fields in the source table as unique identifiers to each row.
    """
    (
        NOT_TRANSACTIONAL,
        UUID,
        GCLID_TIME,
    ) = range(3)

class AccountConfig:
    def __init__(
        self,
        google_ads_account_id: str,
        mcc: bool,
        google_analytics_account_id: str,
        campaign_manager_profile_id: str,
        app_id: str,
    ):
        self._google_ads_account_id = google_ads_account_id
        self._mcc = mcc
        self._google_analytics_account_id = google_analytics_account_id
        self._campaign_manager_profile_id = campaign_manager_profile_id
        self._app_id = app_id

    @property
    def google_ads_account_id(self) -> str:
        return self._google_ads_account_id

    @property
    def mcc(self) -> bool:
        return self._mcc

    @property
    def google_analytics_account_id(self) -> str:
        return self._google_analytics_account_id

    @property
    def campaign_manager_profile_id(self) -> str:
        return self._campaign_manager_profile_id

    @property
    def app_id(self) -> str:
        return self._app_id

    def to_dict(self):
        return {
            'google_ads_account_id': self.google_ads_account_id,
            'mcc': self.mcc,
            'google_analytics_account_id': self.google_analytics_account_id,
            'campaign_manager_profile_id': self.campaign_manager_profile_id,
            'app_id': self.app_id,
        }

    @staticmethod
    def from_dict(dict_account_config):
        return AccountConfig(
            dict_account_config['google_ads_account_id'],
            dict_account_config['mcc'],
            dict_account_config['google_analytics_account_id'],
            dict_account_config['campaign_manager_profile_id'],
            dict_account_config['app_id'],
        )

    def __str__(self) -> str:
        return (
            f"\n[Account Config]\n\t"
            f"Google Ads Customer Id: {self.google_ads_account_id}\n\t"
            f"Google Ads MCC: {self._mcc}\n\t"
            f"Google Analytics Account Id: {self.google_analytics_account_id}\n\t"
            f"Campaign Manager Account Id: {self.campaign_manager_profile_id}\n\t"
            f"Play Store App Id: {self.app_id}"
        )

    def __eq__(self, other):
        return (
            self.google_ads_account_id == other.google_ads_account_id
            and self.google_analytics_account_id == other.google_analytics_account_id
            and self.campaign_manager_profile_id == other.campaign_manager_profile_id
            and self.app_id == other.app_id
        )

    def __hash__(self):
        return hash(
            (
                self.google_ads_account_id,
                self.google_analytics_account_id,
                self.campaign_manager_profile_id,
                self.app_id,
            )
        )

class Source:
    def __init__(
        self, source_name: str, source_type: SourceType, source_metadata: List[str]
    ):
        self._source_name = source_name
        self._source_type = source_type
        self._source_metadata = source_metadata

    @property
    def source_name(self) -> str:
        return self._source_name

    @property
    def source_type(self) -> SourceType:
        return self._source_type

    @property
    def source_metadata(self) -> List[str]:
        return self._source_metadata

    def to_dict(self):
        return {
            'source_name': self.source_name,
            'source_type': self.source_type.name,
            'source_metadata': self.source_metadata,
        }

    @staticmethod
    def from_dict(dict_source):
        return Source(
            dict_source['source_name'],
            SourceType[dict_source['source_type']],
            dict_source['source_metadata']
        )

    def __eq__(self, other):
        return (
            self.source_name == other.source_name
            and self.source_type == other.source_type
            and self.source_metadata == other.source_metadata
        )

    def __hash__(self):
        return hash(
            (
                self.source_name,
                self.source_type,
                self.source_metadata[0],
                self.source_metadata[1],
            )
        )

class Destination:
    def __init__(
        self,
        destination_name: str,
        destination_type: DestinationType,
        destination_metadata: List[str],
    ):
        self._destination_name = destination_name
        self._destination_type = destination_type
        self._destination_metadata = destination_metadata

    @property
    def destination_name(self) -> str:
        return self._destination_name

    @property
    def destination_type(self) -> DestinationType:
        return self._destination_type

    @property
    def destination_metadata(self) -> List[str]:
        return self._destination_metadata

    def to_dict(self):
        return {
            'destination_name': self.destination_name,
            'destination_type': self.destination_type.name,
            'destination_metadata': self.destination_metadata,
        }

    @staticmethod
    def from_dict(dict_destination):
        return Destination(
            dict_destination['destination_name'],
            DestinationType[dict_destination['destination_type']],
            dict_destination['destination_metadata'],
        )

    def __eq__(self, other) -> bool:
        return bool(
            self.destination_name == other.destination_name
            and self.destination_metadata[0] == other.destination_metadata[0]
        )

    def __hash__(self) -> int:
        return hash(
            (
                self.destination_name,
                self.destination_type.name,
                self.destination_metadata[0],
            )
        )

class Execution:
    def __init__(
        self, account_config: AccountConfig, source: Source, destination: Destination
    ):
        self._account_config = account_config
        self._source = source
        self._destination = destination

    @property
    def source(self) -> Source:
        return self._source

    @property
    def destination(self) -> Destination:
        return self._destination

    @property
    def account_config(self) -> AccountConfig:
        return self._account_config

    def to_dict(self):
        return {
            'account_config': self.account_config.to_dict(),
            'source': self.source.to_dict(),
            'destination': self.destination.to_dict()
        }

    @staticmethod
    def from_dict(dict_execution):
        return Execution(
            AccountConfig.from_dict(dict_execution['account_config']),
            Source.from_dict(dict_execution['source']),
            Destination.from_dict(dict_execution['destination']),
        )

    def __str__(self):
        return f"Origin name: {self.source.source_name}. Action: {self.destination.destination_type}. Destination name: {self.destination.destination_name}"

    def __eq__(self, other):
        if other is None:
            return False
        return (
            self.source == other.source
            and self.destination == other.destination
            and self.account_config == other.account_config
        )

    def __hash__(self):
        return hash((self.source, self.destination, self.account_config))

class ExecutionsGroupedBySource:
    def __init__(
        self,
        source_name: str,
        executions: List[Execution]
    ):
        self._source_name = source_name
        self._executions = executions

    @property
    def executions(self) -> List[Execution]:
        return self._executions

    @property
    def source_name(self) -> str:
        return self._source_name

    @property
    def source(self) -> Source:
        return self._executions[0].source

    @property
    def destinations(self) -> List[Destination]:
        return list([exec.destination for exec in self._executions])

    def __getitem__(self, i):
        return self._executions[i]

    def to_dict(self):
        executions_json = [exec.to_dict() for exec in self.executions]
        return {
            'source_name': self._source_name,
            'executions': executions_json
        }

    @staticmethod
    def from_dict(dict_executions):
        executions = list([Execution.from_dict(exec_json)
                          for exec_json in dict_executions['executions']])

        return ExecutionsGroupedBySource(
            dict_executions['source_name'],
            executions
        )

    def __str__(self):
        return f"Source: {self._source_name}. Executions: {','.join(['(' + str(exec) + ')' for exec in self._executions])}"

    def __eq__(self, other):
        if other is None:
            return False
        return self.source_name == other.source_name

    def __hash__(self):
        return hash(("ExecutionsGroupedBySource", self.source_name))

class DataRow(Dict[str, Any]):
    pass

class DataRowsGroupedBySource:
    def __init__(
        self,
        executions: ExecutionsGroupedBySource,
        rows: List[DataRow]
    ):
        self._executions = executions
        self._rows = rows

    @property
    def rows(self) -> List[DataRow]:
        return self._rows

    @property
    def executions(self) -> ExecutionsGroupedBySource:
        return self._executions

    @property
    def source(self) -> Source:
        return self._executions.source

    @property
    def source_name(self) -> str:
        return self._executions.source.source_name

    @property
    def destinations(self) -> List[Destination]:
        return self._executions.destinations

    def to_dict(self):
        return {
            'rows': self._rows,
            'executions': self._executions.to_dict()
        }

    @staticmethod
    def from_dict(dict_rows):
        return DataRowsGroupedBySource(
            ExecutionsGroupedBySource.from_dict(dict_rows.executions),
            dict_rows.rows
        )

    def __str__(self):
        return f"Source: {self.source_name}. Executions: {self._executions}. Rows: {self.rows}"

    def __eq__(self, other):
        if other is None:
            return False
        return self.source_name == other.source_name

    def __hash__(self):
        return hash(("DataRowsGroupedBySource", self.source_name))

class Batch:
    def __init__(
        self,
        execution: Execution,
        elements: List[Dict[str, Union[str, Dict[str, str]]]],
        iteration: int = 1,
    ):
        self._execution = execution
        self._elements = elements
        self._iteration = iteration

    @property
    def execution(self) -> Execution:
        return self._execution

    @property
    def elements(self) -> List[Dict[str, Union[str, Dict[str, str]]]]:
        return self._elements

    @property
    def iteration(self) -> int:
        return self._iteration

    def __str__(self):
        return f"Execution: {self._execution}. Elements: {self._elements}"

    def __eq__(self, other):
        if other is None:
            return False
        return self.execution == other.execution and self.elements == other.elements

    def __hash__(self):
        return hash(("Batch", self.execution))

class BatchesGroupedBySource:
    def __init__(
        self,
        source_name: str,
        batches: List[Batch]
    ):
        self._source_name = source_name
        self._batches = batches

    @property
    def batches(self) -> List[Batch]:
        return self._batches

    @property
    def source_name(self) -> str:
        return self._source_name

    def __getitem__(self, i):
        return self._batches[i]

    def __str__(self):
        return f"Source: {self._source_name}. Batches: {self._batches}"

    def __eq__(self, other):
        if other is None:
            return False
        return self.source_name == other.source_name

    def __hash__(self):
        return hash(("ExecutionsGroupedBySource", self.source_name))
<|endoftext|>