<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2005 Edgewall Software
# Copyright (C) 2005 Christopher Lenz <cmlenz@gmx.de>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://projects.edgewall.com/trac/.
#
# Author: Christopher Lenz <cmlenz@gmx.de>

import os
import re

from trac import mimeview
from trac.config import *
from trac.core import *
from trac.env import IEnvironmentSetupParticipant
from trac.util.markup import html
from trac.web.api import IRequestHandler, HTTPNotFound
from trac.web.href import Href
from trac.wiki import IWikiSyntaxProvider

def add_link(req, rel, href, title=None, mimetype=None, classname=None):
    """Add a link to the HDF data set that will be inserted as <link> element in
    the <head> of the generated HTML
    """
    link = {'href': href}
    if title:
        link['title'] = title
    if mimetype:
        link['type'] = mimetype
    if classname:
        link['class'] = classname
    idx = 0
    while req.hdf.get('chrome.links.%s.%d.href' % (rel, idx)):
        idx += 1
    req.hdf['chrome.links.%s.%d' % (rel, idx)] = link

def add_stylesheet(req, filename, mimetype='text/css'):
    """Add a link to a style sheet to the HDF data set so that it gets included
    in the generated HTML page.
    """
    if filename.startswith('common/') and 'htdocs_location' in req.hdf:
        href = Href(req.hdf['htdocs_location'])
        filename = filename[7:]
    else:
        href = Href(req.base_path).chrome
    add_link(req, 'stylesheet', href(filename), mimetype=mimetype)

def add_javascript(req, filename):
    """ Include Javascript in the current template. """
    if filename.startswith('common/') and 'htdocs_location' in req.hdf:
        href = Href(req.hdf['htdocs_location'])
        filename = filename[7:]
    else:
        href = Href(req.base_path).chrome
    href = href(filename)
    idx = 0
    while True:
        js = req.hdf.get('chrome.js.%i' % idx)
        if not js: break
        if js == href: return
        idx += 1
    req.hdf['chrome.js.%i' % idx] = href

class INavigationContributor(Interface):
    """Extension point interface for components that contribute items to the
    navigation.
    """

    def get_active_navigation_item(req):
        """This method is only called for the `IRequestHandler` processing the
        request.

        It should return the name of the navigation item that should be
        highlighted as active/current.
        """

    def get_navigation_items(req):
        """Should return an iterable object over the list of navigation items to
        add, each being a tuple in the form (category, name, text).
        """

class ITemplateProvider(Interface):
    """Extension point interface for components that provide their own
    ClearSilver templates and accompanying static resources.
    """

    def get_htdocs_dirs():
        """Return a list of directories with static resources (such as style
        sheets, images, etc.)

        Each item in the list must be a `(prefix, abspath)` tuple. The
        `prefix` part defines the path in the URL that requests to these
        resources are prefixed with.

        The `abspath` is the absolute path to the directory containing the
        resources on the local file system.
        """

    def get_templates_dirs():
        """Return a list of directories containing the provided ClearSilver
        templates.
        """

class Chrome(Component):
    """Responsible for assembling the web site chrome, i.e. everything that
    is not actual page content.
    """
    implements(IEnvironmentSetupParticipant, IRequestHandler, ITemplateProvider,
               IWikiSyntaxProvider)

    navigation_contributors = ExtensionPoint(INavigationContributor)
    template_providers = ExtensionPoint(ITemplateProvider)

    templates_dir = Option('trac', 'templates_dir', default_dir('templates'),
        """Path to the !ClearSilver templates.""")

    htdocs_location = Option('trac', 'htdocs_location', '',
        """Base URL of the core static resources.""")

    metanav_order = ListOption('trac', 'metanav',
                               'login,logout,settings,help,about', doc=
        """List of items IDs to display in the navigation bar `metanav`.""")

    mainnav_order = ListOption('trac', 'mainnav',
                               'wiki,timeline,roadmap,browser,tickets,'
                               'newticket,search', doc=
        """List of item IDs to display in the navigation bar `mainnav`.""")

    logo_link = Option('header_logo', 'link', 'http://example.org/',
        """URL to link to from header logo.""")

    logo_src = Option('header_logo', 'src', 'common/trac_banner.png',
        """URL of the image to use as header logo.""")

    logo_alt = Option('header_logo', 'alt', '',
        """Alternative text for the header logo.""")

    logo_width = IntOption('header_logo', 'width', 236,
        """Width of the header logo image in pixels.""")

    logo_height = IntOption('header_logo', 'height', 73,
        """Height of the header logo image in pixels.""")

    # IEnvironmentSetupParticipant methods

    def environment_created(self):
        """Create the templates directory and some templates for
        customization.
        """
        def _create_file(filename, data=None):
            fd = open(filename, 'w')
            if data:
                fd.write(data)
            fd.close()

        if self.env.path:
            templates_dir = os.path.join(self.env.path, 'templates')
            if not os.path.exists(templates_dir):
                os.mkdir(templates_dir)
            _create_file(os.path.join(templates_dir, 'README'),
                        'This directory contains project-specific custom '
                        'templates and style sheet.\n')
            _create_file(os.path.join(templates_dir, 'site_header.cs'),
                         """<?cs
####################################################################
# Site header - Contents are automatically inserted above Trac HTML
?>
""")
            _create_file(os.path.join(templates_dir, 'site_footer.cs'),
                         """<?cs
#########################################################################
# Site footer - Contents are automatically inserted after main Trac HTML
?>
""")
            _create_file(os.path.join(templates_dir, 'site_css.cs'),
                         """<?cs
##################################################################
# Site CSS - Place custom CSS, including overriding styles here.
?>
""")

    def environment_needs_upgrade(self, db):
        return False

    def upgrade_environment(self, db):
        pass

    # IRequestHandler methods

    anonymous_request = True
    use_template = False

    def match_request(self, req):
        match = re.match(r'/chrome/(?P<prefix>[^/]+)/(?P<filename>[/\w\-\.]+)',
                         req.path_info)
        if match:
            req.args['prefix'] = match.group('prefix')
            req.args['filename'] = match.group('filename')
            return True

    def process_request(self, req):
        prefix = req.args['prefix']
        filename = req.args['filename']

        dirs = []
        for provider in self.template_providers:
            for dir in [os.path.normpath(dir[1]) for dir
                        in provider.get_htdocs_dirs() if dir[0] == prefix]:
                dirs.append(dir)
                path = os.path.normpath(os.path.join(dir, filename))
                assert os.path.commonprefix([dir, path]) == dir
                if os.path.isfile(path):
                    req.send_file(path)

        self.log.warning('File %s not found in any of %s', filename, dirs)
        raise HTTPNotFound('File %s not found', filename)

    # ITemplateProvider methods

    def get_htdocs_dirs(self):
        from trac.config import default_dir
        return [('common', default_dir('htdocs')),
                ('site', self.env.get_htdocs_dir())]

    def get_templates_dirs(self):
        return [self.env.get_templates_dir(), self.templates_dir]

    # IWikiSyntaxProvider methods

    def get_wiki_syntax(self):
        return []

    def get_link_resolvers(self):
        yield ('htdocs', self._format_link)

    def _format_link(self, formatter, ns, file, label):
        href = self.env.href.chrome('site', file)
        return html.A(href=formatter.href.chrome('site', file))[label]

    # Public API methods

    def get_all_templates_dirs(self):
        """Return a list of the names of all known templates directories."""
        dirs = []
        for provider in self.template_providers:
            dirs += provider.get_templates_dirs()
        return dirs

    def populate_hdf(self, req, handler):
        """Add chrome-related data to the HDF."""

        # Provided for template customization
        req.hdf['HTTP.PathInfo'] = req.path_info

        href = Href(req.base_path)
        req.hdf['chrome.href'] = href.chrome()
        htdocs_location = self.htdocs_location or href.chrome('common')
        req.hdf['htdocs_location'] = htdocs_location.rstrip('/') + '/'

        # HTML <head> links
        add_link(req, 'start', self.env.href.wiki())
        add_link(req, 'search', self.env.href.search())
        add_link(req, 'help', self.env.href.wiki('TracGuide'))
        add_stylesheet(req, 'common/css/trac.css')
        add_javascript(req, 'common/js/trac.js')
        icon = self.env.project_icon
        if icon:
            if not icon.startswith('/') and icon.find('://') == -1:
                if '/' in icon:
                    icon = href.chrome(icon)
                else:
                    icon = href.chrome('common', icon)
            mimetype = mimeview.get_mimetype(icon)
            add_link(req, 'icon', icon, mimetype=mimetype)
            add_link(req, 'shortcut icon', icon, mimetype=mimetype)

        # Logo image
        logo_src = self.logo_src
        if logo_src:
            logo_src_abs = logo_src.startswith('http://') or \
                           logo_src.startswith('https://')
            if not logo_src.startswith('/') and not logo_src_abs:
                if '/' in logo_src:
                    logo_src = href.chrome(logo_src)
                else:
                    logo_src = href.chrome('common', logo_src)
            req.hdf['chrome.logo'] = {
                'link': self.logo_link, 'src': logo_src,
                'src_abs': logo_src_abs, 'alt': self.logo_alt,
                'width': self.logo_width, 'height': self.logo_height
            }
        else:
            req.hdf['chrome.logo.link'] = self.logo_link

        # Navigation links
        navigation = {}
        active = None
        for contributor in self.navigation_contributors:
            for category, name, text in contributor.get_navigation_items(req):
                navigation.setdefault(category, {})[name] = text
            if contributor is handler:
                active = contributor.get_active_navigation_item(req)

        for category, items in [(k, v.items()) for k, v in navigation.items()]:
            order = getattr(self, category + '_order')
            def navcmp(x, y):
                if x[0] not in order:
                    return int(y[0] in order)
                if y[0] not in order:
                    return -int(x[0] in order)
                return cmp(order.index(x[0]), order.index(y[0]))
            items.sort(navcmp)

            for name, text in items:
                req.hdf['chrome.nav.%s.%s' % (category, name)] = text
                if name == active:
                    req.hdf['chrome.nav.%s.%s.active' % (category, name)] = 1
<commit_msg>If unspecified in TracIni, the width and height of the logo won't be specified in the <img> tag either. Fixes #2767.<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2005 Edgewall Software
# Copyright (C) 2005 Christopher Lenz <cmlenz@gmx.de>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://projects.edgewall.com/trac/.
#
# Author: Christopher Lenz <cmlenz@gmx.de>

import os
import re

from trac import mimeview
from trac.config import *
from trac.core import *
from trac.env import IEnvironmentSetupParticipant
from trac.util.markup import html
from trac.web.api import IRequestHandler, HTTPNotFound
from trac.web.href import Href
from trac.wiki import IWikiSyntaxProvider

def add_link(req, rel, href, title=None, mimetype=None, classname=None):
    """Add a link to the HDF data set that will be inserted as <link> element in
    the <head> of the generated HTML
    """
    link = {'href': href}
    if title:
        link['title'] = title
    if mimetype:
        link['type'] = mimetype
    if classname:
        link['class'] = classname
    idx = 0
    while req.hdf.get('chrome.links.%s.%d.href' % (rel, idx)):
        idx += 1
    req.hdf['chrome.links.%s.%d' % (rel, idx)] = link

def add_stylesheet(req, filename, mimetype='text/css'):
    """Add a link to a style sheet to the HDF data set so that it gets included
    in the generated HTML page.
    """
    if filename.startswith('common/') and 'htdocs_location' in req.hdf:
        href = Href(req.hdf['htdocs_location'])
        filename = filename[7:]
    else:
        href = Href(req.base_path).chrome
    add_link(req, 'stylesheet', href(filename), mimetype=mimetype)

def add_javascript(req, filename):
    """ Include Javascript in the current template. """
    if filename.startswith('common/') and 'htdocs_location' in req.hdf:
        href = Href(req.hdf['htdocs_location'])
        filename = filename[7:]
    else:
        href = Href(req.base_path).chrome
    href = href(filename)
    idx = 0
    while True:
        js = req.hdf.get('chrome.js.%i' % idx)
        if not js: break
        if js == href: return
        idx += 1
    req.hdf['chrome.js.%i' % idx] = href

class INavigationContributor(Interface):
    """Extension point interface for components that contribute items to the
    navigation.
    """

    def get_active_navigation_item(req):
        """This method is only called for the `IRequestHandler` processing the
        request.

        It should return the name of the navigation item that should be
        highlighted as active/current.
        """

    def get_navigation_items(req):
        """Should return an iterable object over the list of navigation items to
        add, each being a tuple in the form (category, name, text).
        """

class ITemplateProvider(Interface):
    """Extension point interface for components that provide their own
    ClearSilver templates and accompanying static resources.
    """

    def get_htdocs_dirs():
        """Return a list of directories with static resources (such as style
        sheets, images, etc.)

        Each item in the list must be a `(prefix, abspath)` tuple. The
        `prefix` part defines the path in the URL that requests to these
        resources are prefixed with.

        The `abspath` is the absolute path to the directory containing the
        resources on the local file system.
        """

    def get_templates_dirs():
        """Return a list of directories containing the provided ClearSilver
        templates.
        """

class Chrome(Component):
    """Responsible for assembling the web site chrome, i.e. everything that
    is not actual page content.
    """
    implements(IEnvironmentSetupParticipant, IRequestHandler, ITemplateProvider,
               IWikiSyntaxProvider)

    navigation_contributors = ExtensionPoint(INavigationContributor)
    template_providers = ExtensionPoint(ITemplateProvider)

    templates_dir = Option('trac', 'templates_dir', default_dir('templates'),
        """Path to the !ClearSilver templates.""")

    htdocs_location = Option('trac', 'htdocs_location', '',
        """Base URL of the core static resources.""")

    metanav_order = ListOption('trac', 'metanav',
                               'login,logout,settings,help,about', doc=
        """List of items IDs to display in the navigation bar `metanav`.""")

    mainnav_order = ListOption('trac', 'mainnav',
                               'wiki,timeline,roadmap,browser,tickets,'
                               'newticket,search', doc=
        """List of item IDs to display in the navigation bar `mainnav`.""")

    logo_link = Option('header_logo', 'link', 'http://example.org/',
        """URL to link to from header logo.""")

    logo_src = Option('header_logo', 'src', 'common/trac_banner.png',
        """URL of the image to use as header logo.""")

    logo_alt = Option('header_logo', 'alt', '',
        """Alternative text for the header logo.""")

    logo_width = IntOption('header_logo', 'width', -1,
        """Width of the header logo image in pixels.""")

    logo_height = IntOption('header_logo', 'height', -1,
        """Height of the header logo image in pixels.""")

    # IEnvironmentSetupParticipant methods

    def environment_created(self):
        """Create the templates directory and some templates for
        customization.
        """
        def _create_file(filename, data=None):
            fd = open(filename, 'w')
            if data:
                fd.write(data)
            fd.close()

        if self.env.path:
            templates_dir = os.path.join(self.env.path, 'templates')
            if not os.path.exists(templates_dir):
                os.mkdir(templates_dir)
            _create_file(os.path.join(templates_dir, 'README'),
                        'This directory contains project-specific custom '
                        'templates and style sheet.\n')
            _create_file(os.path.join(templates_dir, 'site_header.cs'),
                         """<?cs
####################################################################
# Site header - Contents are automatically inserted above Trac HTML
?>
""")
            _create_file(os.path.join(templates_dir, 'site_footer.cs'),
                         """<?cs
#########################################################################
# Site footer - Contents are automatically inserted after main Trac HTML
?>
""")
            _create_file(os.path.join(templates_dir, 'site_css.cs'),
                         """<?cs
##################################################################
# Site CSS - Place custom CSS, including overriding styles here.
?>
""")

    def environment_needs_upgrade(self, db):
        return False

    def upgrade_environment(self, db):
        pass

    # IRequestHandler methods

    anonymous_request = True
    use_template = False

    def match_request(self, req):
        match = re.match(r'/chrome/(?P<prefix>[^/]+)/(?P<filename>[/\w\-\.]+)',
                         req.path_info)
        if match:
            req.args['prefix'] = match.group('prefix')
            req.args['filename'] = match.group('filename')
            return True

    def process_request(self, req):
        prefix = req.args['prefix']
        filename = req.args['filename']

        dirs = []
        for provider in self.template_providers:
            for dir in [os.path.normpath(dir[1]) for dir
                        in provider.get_htdocs_dirs() if dir[0] == prefix]:
                dirs.append(dir)
                path = os.path.normpath(os.path.join(dir, filename))
                assert os.path.commonprefix([dir, path]) == dir
                if os.path.isfile(path):
                    req.send_file(path)

        self.log.warning('File %s not found in any of %s', filename, dirs)
        raise HTTPNotFound('File %s not found', filename)

    # ITemplateProvider methods

    def get_htdocs_dirs(self):
        from trac.config import default_dir
        return [('common', default_dir('htdocs')),
                ('site', self.env.get_htdocs_dir())]

    def get_templates_dirs(self):
        return [self.env.get_templates_dir(), self.templates_dir]

    # IWikiSyntaxProvider methods

    def get_wiki_syntax(self):
        return []

    def get_link_resolvers(self):
        yield ('htdocs', self._format_link)

    def _format_link(self, formatter, ns, file, label):
        href = self.env.href.chrome('site', file)
        return html.A(href=formatter.href.chrome('site', file))[label]

    # Public API methods

    def get_all_templates_dirs(self):
        """Return a list of the names of all known templates directories."""
        dirs = []
        for provider in self.template_providers:
            dirs += provider.get_templates_dirs()
        return dirs

    def populate_hdf(self, req, handler):
        """Add chrome-related data to the HDF."""

        # Provided for template customization
        req.hdf['HTTP.PathInfo'] = req.path_info

        href = Href(req.base_path)
        req.hdf['chrome.href'] = href.chrome()
        htdocs_location = self.htdocs_location or href.chrome('common')
        req.hdf['htdocs_location'] = htdocs_location.rstrip('/') + '/'

        # HTML <head> links
        add_link(req, 'start', self.env.href.wiki())
        add_link(req, 'search', self.env.href.search())
        add_link(req, 'help', self.env.href.wiki('TracGuide'))
        add_stylesheet(req, 'common/css/trac.css')
        add_javascript(req, 'common/js/trac.js')
        icon = self.env.project_icon
        if icon:
            if not icon.startswith('/') and icon.find('://') == -1:
                if '/' in icon:
                    icon = href.chrome(icon)
                else:
                    icon = href.chrome('common', icon)
            mimetype = mimeview.get_mimetype(icon)
            add_link(req, 'icon', icon, mimetype=mimetype)
            add_link(req, 'shortcut icon', icon, mimetype=mimetype)

        # Logo image
        logo_src = self.logo_src
        if logo_src:
            logo_src_abs = logo_src.startswith('http://') or \
                           logo_src.startswith('https://')
            if not logo_src.startswith('/') and not logo_src_abs:
                if '/' in logo_src:
                    logo_src = href.chrome(logo_src)
                else:
                    logo_src = href.chrome('common', logo_src)
            width = self.logo_width > -1 or None
            height = self.logo_height > -1 or None
            req.hdf['chrome.logo'] = {
                'link': self.logo_link, 'src': logo_src,
                'src_abs': logo_src_abs, 'alt': self.logo_alt,
                'width': width, 'height': height
            }
        else:
            req.hdf['chrome.logo.link'] = self.logo_link

        # Navigation links
        navigation = {}
        active = None
        for contributor in self.navigation_contributors:
            for category, name, text in contributor.get_navigation_items(req):
                navigation.setdefault(category, {})[name] = text
            if contributor is handler:
                active = contributor.get_active_navigation_item(req)

        for category, items in [(k, v.items()) for k, v in navigation.items()]:
            order = getattr(self, category + '_order')
            def navcmp(x, y):
                if x[0] not in order:
                    return int(y[0] in order)
                if y[0] not in order:
                    return -int(x[0] in order)
                return cmp(order.index(x[0]), order.index(y[0]))
            items.sort(navcmp)

            for name, text in items:
                req.hdf['chrome.nav.%s.%s' % (category, name)] = text
                if name == active:
                    req.hdf['chrome.nav.%s.%s.active' % (category, name)] = 1
<|endoftext|>


<commit_before>import sys, pygame, assets
from pygame import Rect
from assets import Player
from assets import Platform
from assets import Camera

pygame.init()

HALF_WIDTH = 400
HALF_HEIGHT = 300

def camera_update(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    return Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)

class Goal(pygame.sprite.Sprite):
	def __init__(self, image):
	    pygame.sprite.Sprite.__init__(self)
	    self.image = pygame.image.load(image)
	    self.rect = self.image.get_rect()
	    self.rect.topleft = 500,40

def main():
    size = width, height = 800, 600
    black = 0, 0, 0

    screen = pygame.display.set_mode(size)

    player = Player(15, 580)

    platformList = []
    for i in range (0, 10):
        platform = Platform(i*50, 600 - (i*50))
        platformList.append(platform)

    platformSprites = pygame.sprite.RenderPlain(platformList)
    goal = Goal("images/goal.png")

    clock = pygame.time.Clock()

    camera = Camera(camera_update, 300, 600)

    platformList.extend([player, goal])

    while 1:
        screen.fill(black)
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            else:
                player.move(event)

        if (not pygame.sprite.spritecollide(player, platformSprites, False)):
            player.isFalling = 1
        else:
            player.isFalling = 0

        player.update()
        camera.update(player)
        for e in platformList:
            try:
                s = e.image
            except:
                pass
            if s:
                screen.blit(s, camera.scroll(e))

        pygame.display.flip()

        if (player.rect.left < -10 and player.rect.top > 600):
            print "You win"
            return

        if (player.rect.colliderect(goal.rect)):
            player.rect.topleft = 100,100
	    main()
            return

	if (player.rect.left >= 0 and player.rect.top > 650):
	    player.rect.topleft = 100,100
	    main()
	    return

if __name__ == '__main__': main()
<commit_msg>added broken parallax<commit_after>import sys, pygame, assets, parallax
from pygame import Rect
from assets import Player
from assets import Platform
from assets import Camera
from pygame.locals import *

pygame.init()

HALF_WIDTH = 400
HALF_HEIGHT = 300

def camera_update(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    return Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)

class Goal(pygame.sprite.Sprite):
	def __init__(self, image):
	    pygame.sprite.Sprite.__init__(self)
	    self.image = pygame.image.load(image)
	    self.rect = self.image.get_rect()
	    self.rect.topleft = 500,40

size = width, height = 800, 600
screen = pygame.display.set_mode((size), pygame.DOUBLEBUF)

bg = parallax.ParallaxSurface([800,600])
bg.add('images/rockyBackground.png', 2)
bgSpeed = 0
t_ref = 0

def main():
    black = 0, 0, 0

    bgSpeed = 0

    player = Player(15, 580)

    platformList = []
    for i in range (0, 10):
        platform = Platform(i*50, 600 - (i*50))
        platformList.append(platform)

    platformSprites = pygame.sprite.RenderPlain(platformList)
    goal = Goal("images/goal.png")

    clock = pygame.time.Clock()

    camera = Camera(camera_update, 300, 600)

    platformList.extend([player, goal])

    while 1:
        screen.fill(black)
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
	    elif event.type == KEYDOWN and event.key == K_RIGHT:
		    bgSpeed += 10
		    player.move(event)
	    elif event.type == KEYUP and event.key == K_RIGHT:
		    bgSpeed -= 10
		    player.move(event)
	    elif event.type == KEYDOWN and event.key == K_LEFT:
		    bgSpeed -= 10
		    player.move(event)
	    elif event.type == KEYUP and event.key == K_LEFT:
		    bgSpeed += 10
		    player.move(event)
	    elif event.type == KEYDOWN and event.key == K_UP:
		    player.move(event)

	bg.scroll(bgSpeed)
	t = pygame.time.get_ticks()
	if (t - t_ref) > 60:
		bg.draw(screen)

        if (not pygame.sprite.spritecollide(player, platformSprites, False)):
            player.isFalling = 1
        else:
            player.isFalling = 0

        player.update()
        camera.update(player)
        for e in platformList:
            try:
                s = e.image
            except:
                pass
            if s:
                screen.blit(s, camera.scroll(e))

        pygame.display.flip()

	if (player.rect.left < -10 and player.rect.top > 600):
            print "You win"
            return

        if (player.rect.colliderect(goal.rect)):
            player.rect.topleft = 100,100
	    print(bgSpeed)
	    bgSpeed -= 10
	    main()
            return

	if (player.rect.left >= 0 and player.rect.top > 650):
	    player.rect.topleft = 100,100
	    print(bgSpeed)
	    bgSpeed = 0
	    main()
	    return

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


<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/.

from datetime import datetime
import os.path
import pkg_resources
import sys

from trac.admin import *
from trac.core import *
from trac.wiki import model
from trac.wiki.api import WikiSystem, validate_page_name
from trac.util import read_file
from trac.util.datefmt import format_datetime, from_utimestamp, \
                              to_utimestamp, utc
from trac.util.text import path_to_unicode, print_table, printout, \
                           to_unicode, unicode_quote, unicode_unquote
from trac.util.translation import _

class WikiAdmin(Component):
    """trac-admin command provider for wiki administration."""

    implements(IAdminCommandProvider)

    # IAdminCommandProvider methods

    def get_admin_commands(self):
        yield ('wiki list', '',
               'List wiki pages',
               None, self._do_list)
        yield ('wiki rename', '<page> <new_name>',
               'Rename wiki page',
               self._complete_page, self._do_rename)
        yield ('wiki remove', '<page>',
               'Remove wiki page',
               self._complete_page, self._do_remove)
        yield ('wiki export', '<page> [file]',
               'Export wiki page to file or stdout',
               self._complete_import_export, self._do_export)
        yield ('wiki import', '<page> [file]',
               'Import wiki page from file or stdin',
               self._complete_import_export, self._do_import)
        yield ('wiki dump', '<directory> [page] [...]',
               """Export wiki pages to files named by title

               Individual wiki page names can be specified after the directory.
               A name ending with a * means that all wiki pages starting with
               that prefix should be dumped. If no name is specified, all wiki
               pages are dumped.""",
               self._complete_dump, self._do_dump)
        yield ('wiki load', '<path> [...]',
               """Import wiki pages from files

               If a given path is a file, it is imported as a page with the
               name of the file. If a path is a directory, all files in that
               directory are imported.""",
               self._complete_load_replace, self._do_load)
        yield ('wiki replace', '<path> [...]',
               """Replace the content of wiki pages from files (DANGEROUS!)

               This command replaces the content of the last version of one
               or more wiki pages with new content. The previous content is
               lost, and no new entry is created in the page history. The
               metadata of the page (time, author) is not changed either.

               If a given path is a file, it is imported as a page with the
               name of the file. If a path is a directory, all files in that
               directory are imported.

               WARNING: This operation results in the loss of the previous
               content and cannot be undone. It may be advisable to backup
               the current content using "wiki dump" beforehand.""",
               self._complete_load_replace, self._do_replace)
        yield ('wiki upgrade', '',
               'Upgrade default wiki pages to current version',
               None, self._do_upgrade)

    def get_wiki_list(self):
        return list(WikiSystem(self.env).get_pages())

    def export_page(self, page, filename, cursor=None):
        """
        :since 1.0: the `cursor` parameter is no longer needed and will be
        removed in version 1.1.1
        """
        for text, in self.env.db_query("""
                SELECT text FROM wiki WHERE name=%s
                ORDER BY version DESC LIMIT 1
                """, (page,)):
            if not filename:
                printout(text)
            else:
                if os.path.isfile(filename):
                    raise AdminCommandError(_("File '%(name)s' exists",
                                              name=path_to_unicode(filename)))
                with open(filename, 'w') as f:
                    f.write(text.encode('utf-8'))
            break
        else:
            raise AdminCommandError(_("Page '%(page)s' not found", page=page))

    def import_page(self, filename, title, create_only=[],
                    replace=False):
        if not validate_page_name(title):
            raise AdminCommandError(_("Invalid Wiki page name '%(name)s'",
                                      name=title))
        if filename:
            if not os.path.isfile(filename):
                raise AdminCommandError(_("'%(name)s' is not a file",
                                          name=path_to_unicode(filename)))
            data = read_file(filename)
        else:
            data = sys.stdin.read()
        data = to_unicode(data, 'utf-8')

        with self.env.db_transaction as db:
            # Make sure we don't insert the exact same page twice
            old = db("""SELECT text FROM wiki WHERE name=%s
                        ORDER BY version DESC LIMIT 1
                        """, (title,))
            if old and title in create_only:
                printout(_("  %(title)s already exists", title=title))
                return False
            if old and data == old[0][0]:
                printout(_("  %(title)s is already up to date", title=title))
                return False

            if replace and old:
                db("""UPDATE wiki SET text=%s
                      WHERE name=%s
                        AND version=(SELECT max(version) FROM wiki
                                     WHERE name=%s)
                      """, (data, title, title))
            else:
                db("""INSERT INTO wiki(version, name, time, author, ipnr, text)
                      SELECT 1 + COALESCE(max(version), 0), %s, %s, 'trac',
                             '127.0.0.1', %s FROM wiki WHERE name=%s
                      """, (title, to_utimestamp(datetime.now(utc)), data,
                            title))
            if not old:
                del WikiSystem(self.env).pages
        return True

    def load_pages(self, dir, ignore=[], create_only=[], replace=False):
        with self.env.db_transaction:
            for page in os.listdir(dir):
                if page in ignore:
                    continue
                filename = os.path.join(dir, page)
                page = unicode_unquote(page.encode('utf-8'))
                if os.path.isfile(filename):
                    if self.import_page(filename, page, create_only, replace):
                        printout(_("  %(page)s imported from %(filename)s",
                                   filename=path_to_unicode(filename),
                                   page=page))

    def _complete_page(self, args):
        if len(args) == 1:
            return self.get_wiki_list()

    def _complete_import_export(self, args):
        if len(args) == 1:
            return self.get_wiki_list()
        elif len(args) == 2:
            return get_dir_list(args[-1])

    def _complete_dump(self, args):
        if len(args) == 1:
            return get_dir_list(args[-1], dirs_only=True)
        elif len(args) >= 2:
            return self.get_wiki_list()

    def _complete_load_replace(self, args):
        if len(args) >= 1:
            return get_dir_list(args[-1])

    def _do_list(self):
        print_table(
            [(title, int(edits), format_datetime(from_utimestamp(modified),
                                                 console_datetime_format))
             for title, edits, modified in self.env.db_query("""
                    SELECT name, max(version), max(time)
                    FROM wiki GROUP BY name ORDER BY name""")
             ], [_("Title"), _("Edits"), _("Modified")])

    def _do_rename(self, name, new_name):
        if new_name == name:
            return
        if not new_name:
            raise AdminCommandError(_("A new name is mandatory for a rename."))
        if not validate_page_name(new_name):
            raise AdminCommandError(_("The new name is invalid."))
        with self.env.db_transaction:
            if model.WikiPage(self.env, new_name).exists:
                raise AdminCommandError(_("The page %(name)s already exists.",
                                          name=new_name))
            page = model.WikiPage(self.env, name)
            page.rename(new_name)

    def _do_remove(self, name):
        with self.env.db_transaction:
            if name.endswith('*'):
                pages = list(WikiSystem(self.env).get_pages(name.rstrip('*')
                                                            or None))
                for p in pages:
                    page = model.WikiPage(self.env, p)
                    page.delete()
                print_table(((p,) for p in pages), [_('Deleted pages')])
            else:
                page = model.WikiPage(self.env, name)
                page.delete()

    def _do_export(self, page, filename=None):
        self.export_page(page, filename)

    def _do_import(self, page, filename=None):
        self.import_page(filename, page)

    def _do_dump(self, directory, *names):
        if not names:
            names = ['*']
        pages = self.get_wiki_list()
        if not os.path.isdir(directory):
            if not os.path.exists(directory):
                os.mkdir(directory)
            else:
                raise AdminCommandError(_("'%(name)s' is not a directory",
                                          name=path_to_unicode(directory)))
        for p in pages:
            if any(p == name or (name.endswith('*')
                                 and p.startswith(name[:-1]))
                   for name in names):
                dst = os.path.join(directory, unicode_quote(p, ''))
                printout(' %s => %s' % (p, dst))
                self.export_page(p, dst)

    def _load_or_replace(self, paths, replace):
        with self.env.db_transaction:
            for path in paths:
                if os.path.isdir(path):
                    self.load_pages(path, replace=replace)
                else:
                    page = os.path.basename(path)
                    page = unicode_unquote(page.encode('utf-8'))
                    if self.import_page(path, page, replace=replace):
                        printout(_("  %(page)s imported from %(filename)s",
                                   filename=path_to_unicode(path), page=page))

    def _do_load(self, *paths):
        self._load_or_replace(paths, replace=False)

    def _do_replace(self, *paths):
        self._load_or_replace(paths, replace=True)

    def _do_upgrade(self):
        self.load_pages(pkg_resources.resource_filename('trac.wiki',
                                                        'default-pages'),
                        ignore=['WikiStart', 'checkwiki.py'],
                        create_only=['InterMapTxt'])
<commit_msg>1.1.2dev: Removed deprecated parameter. Refs #11605.<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/.

from datetime import datetime
import os.path
import pkg_resources
import sys

from trac.admin import *
from trac.core import *
from trac.wiki import model
from trac.wiki.api import WikiSystem, validate_page_name
from trac.util import read_file
from trac.util.datefmt import format_datetime, from_utimestamp, \
                              to_utimestamp, utc
from trac.util.text import path_to_unicode, print_table, printout, \
                           to_unicode, unicode_quote, unicode_unquote
from trac.util.translation import _

class WikiAdmin(Component):
    """trac-admin command provider for wiki administration."""

    implements(IAdminCommandProvider)

    # IAdminCommandProvider methods

    def get_admin_commands(self):
        yield ('wiki list', '',
               'List wiki pages',
               None, self._do_list)
        yield ('wiki rename', '<page> <new_name>',
               'Rename wiki page',
               self._complete_page, self._do_rename)
        yield ('wiki remove', '<page>',
               'Remove wiki page',
               self._complete_page, self._do_remove)
        yield ('wiki export', '<page> [file]',
               'Export wiki page to file or stdout',
               self._complete_import_export, self._do_export)
        yield ('wiki import', '<page> [file]',
               'Import wiki page from file or stdin',
               self._complete_import_export, self._do_import)
        yield ('wiki dump', '<directory> [page] [...]',
               """Export wiki pages to files named by title

               Individual wiki page names can be specified after the directory.
               A name ending with a * means that all wiki pages starting with
               that prefix should be dumped. If no name is specified, all wiki
               pages are dumped.""",
               self._complete_dump, self._do_dump)
        yield ('wiki load', '<path> [...]',
               """Import wiki pages from files

               If a given path is a file, it is imported as a page with the
               name of the file. If a path is a directory, all files in that
               directory are imported.""",
               self._complete_load_replace, self._do_load)
        yield ('wiki replace', '<path> [...]',
               """Replace the content of wiki pages from files (DANGEROUS!)

               This command replaces the content of the last version of one
               or more wiki pages with new content. The previous content is
               lost, and no new entry is created in the page history. The
               metadata of the page (time, author) is not changed either.

               If a given path is a file, it is imported as a page with the
               name of the file. If a path is a directory, all files in that
               directory are imported.

               WARNING: This operation results in the loss of the previous
               content and cannot be undone. It may be advisable to backup
               the current content using "wiki dump" beforehand.""",
               self._complete_load_replace, self._do_replace)
        yield ('wiki upgrade', '',
               'Upgrade default wiki pages to current version',
               None, self._do_upgrade)

    def get_wiki_list(self):
        return list(WikiSystem(self.env).get_pages())

    def export_page(self, page, filename):

        for text, in self.env.db_query("""
                SELECT text FROM wiki WHERE name=%s
                ORDER BY version DESC LIMIT 1
                """, (page,)):
            if not filename:
                printout(text)
            else:
                if os.path.isfile(filename):
                    raise AdminCommandError(_("File '%(name)s' exists",
                                              name=path_to_unicode(filename)))
                with open(filename, 'w') as f:
                    f.write(text.encode('utf-8'))
            break
        else:
            raise AdminCommandError(_("Page '%(page)s' not found", page=page))

    def import_page(self, filename, title, create_only=[],
                    replace=False):
        if not validate_page_name(title):
            raise AdminCommandError(_("Invalid Wiki page name '%(name)s'",
                                      name=title))
        if filename:
            if not os.path.isfile(filename):
                raise AdminCommandError(_("'%(name)s' is not a file",
                                          name=path_to_unicode(filename)))
            data = read_file(filename)
        else:
            data = sys.stdin.read()
        data = to_unicode(data, 'utf-8')

        with self.env.db_transaction as db:
            # Make sure we don't insert the exact same page twice
            old = db("""SELECT text FROM wiki WHERE name=%s
                        ORDER BY version DESC LIMIT 1
                        """, (title,))
            if old and title in create_only:
                printout(_("  %(title)s already exists", title=title))
                return False
            if old and data == old[0][0]:
                printout(_("  %(title)s is already up to date", title=title))
                return False

            if replace and old:
                db("""UPDATE wiki SET text=%s
                      WHERE name=%s
                        AND version=(SELECT max(version) FROM wiki
                                     WHERE name=%s)
                      """, (data, title, title))
            else:
                db("""INSERT INTO wiki(version, name, time, author, ipnr, text)
                      SELECT 1 + COALESCE(max(version), 0), %s, %s, 'trac',
                             '127.0.0.1', %s FROM wiki WHERE name=%s
                      """, (title, to_utimestamp(datetime.now(utc)), data,
                            title))
            if not old:
                del WikiSystem(self.env).pages
        return True

    def load_pages(self, dir, ignore=[], create_only=[], replace=False):
        with self.env.db_transaction:
            for page in os.listdir(dir):
                if page in ignore:
                    continue
                filename = os.path.join(dir, page)
                page = unicode_unquote(page.encode('utf-8'))
                if os.path.isfile(filename):
                    if self.import_page(filename, page, create_only, replace):
                        printout(_("  %(page)s imported from %(filename)s",
                                   filename=path_to_unicode(filename),
                                   page=page))

    def _complete_page(self, args):
        if len(args) == 1:
            return self.get_wiki_list()

    def _complete_import_export(self, args):
        if len(args) == 1:
            return self.get_wiki_list()
        elif len(args) == 2:
            return get_dir_list(args[-1])

    def _complete_dump(self, args):
        if len(args) == 1:
            return get_dir_list(args[-1], dirs_only=True)
        elif len(args) >= 2:
            return self.get_wiki_list()

    def _complete_load_replace(self, args):
        if len(args) >= 1:
            return get_dir_list(args[-1])

    def _do_list(self):
        print_table(
            [(title, int(edits), format_datetime(from_utimestamp(modified),
                                                 console_datetime_format))
             for title, edits, modified in self.env.db_query("""
                    SELECT name, max(version), max(time)
                    FROM wiki GROUP BY name ORDER BY name""")
             ], [_("Title"), _("Edits"), _("Modified")])

    def _do_rename(self, name, new_name):
        if new_name == name:
            return
        if not new_name:
            raise AdminCommandError(_("A new name is mandatory for a rename."))
        if not validate_page_name(new_name):
            raise AdminCommandError(_("The new name is invalid."))
        with self.env.db_transaction:
            if model.WikiPage(self.env, new_name).exists:
                raise AdminCommandError(_("The page %(name)s already exists.",
                                          name=new_name))
            page = model.WikiPage(self.env, name)
            page.rename(new_name)

    def _do_remove(self, name):
        with self.env.db_transaction:
            if name.endswith('*'):
                pages = list(WikiSystem(self.env).get_pages(name.rstrip('*')
                                                            or None))
                for p in pages:
                    page = model.WikiPage(self.env, p)
                    page.delete()
                print_table(((p,) for p in pages), [_('Deleted pages')])
            else:
                page = model.WikiPage(self.env, name)
                page.delete()

    def _do_export(self, page, filename=None):
        self.export_page(page, filename)

    def _do_import(self, page, filename=None):
        self.import_page(filename, page)

    def _do_dump(self, directory, *names):
        if not names:
            names = ['*']
        pages = self.get_wiki_list()
        if not os.path.isdir(directory):
            if not os.path.exists(directory):
                os.mkdir(directory)
            else:
                raise AdminCommandError(_("'%(name)s' is not a directory",
                                          name=path_to_unicode(directory)))
        for p in pages:
            if any(p == name or (name.endswith('*')
                                 and p.startswith(name[:-1]))
                   for name in names):
                dst = os.path.join(directory, unicode_quote(p, ''))
                printout(' %s => %s' % (p, dst))
                self.export_page(p, dst)

    def _load_or_replace(self, paths, replace):
        with self.env.db_transaction:
            for path in paths:
                if os.path.isdir(path):
                    self.load_pages(path, replace=replace)
                else:
                    page = os.path.basename(path)
                    page = unicode_unquote(page.encode('utf-8'))
                    if self.import_page(path, page, replace=replace):
                        printout(_("  %(page)s imported from %(filename)s",
                                   filename=path_to_unicode(path), page=page))

    def _do_load(self, *paths):
        self._load_or_replace(paths, replace=False)

    def _do_replace(self, *paths):
        self._load_or_replace(paths, replace=True)

    def _do_upgrade(self):
        self.load_pages(pkg_resources.resource_filename('trac.wiki',
                                                        'default-pages'),
                        ignore=['WikiStart', 'checkwiki.py'],
                        create_only=['InterMapTxt'])
<|endoftext|>


<commit_before>#
# Author    : Manuel Bernal Llinares
# Project   : trackhub-creator
# Timestamp : 03-08-2017 15:44
# ---
# © 2017 Manuel Bernal Llinares <mbdebian@gmail.com>
# All rights reserved.
#

"""
These are the models for representing and dealing with trackhubs
DISCLAIMER - This is the first iteration of the software to create the trackhubs. In this iteration we are going for the
simple version of the hubs, "trackhub quickstart guide" at https://genome.ucsc.edu/goldenpath/help/hubQuickStart.html
"""

# Application imports
import config_manager

# Now, different trackhub builders for the different types of trackhubs (quickstart, custom, etc.)
# DISCLAIMER - I'm aware this first iteration may look a little bit patchy, but it needs to be acknowledged that the
# documentation for modeling this is not very developer friendly, this module it is not meant to be a general module for
# building all sorts of trackhubs and this is the first iteration, so we're not very sure what we want
# TODO - How and where to define the building directors?

def key_value_to_str_if_not_none(key, value, separator=' ', suffix='\n'):
    """
    Helper method that, given a key, value, separator and suffix, it will return the string
    '<key><separator><value><suffix>' if value is not None, otherwise it will return the empty string ''
    :param key: key
    :param value: value
    :param separator: character to use as separator, default ' '
    :param suffix: character to use as suffix, default '\n'
    :return: '<key><separator><value><suffix>' if value not None, '' otherwise
    """
    if value:
        return "{}{}{}{}".format(key, separator, value, suffix)
    return ""

# Modeling TrackHubs
class TrackHubGenomeAssembly:
    # TODO
    pass

class TrackCollector:
    # TODO
    pass

# Model for a Track
class BaseTrack:
    _SEPARATOR_CHAR = ' '

    def __init__(self, track, short_label, long_label):
        # Client side of the model
        self.__track = track
        self.__short_label = short_label
        self.__long_label = long_label
        # Builder side of the model
        self.__type = None
        self.__big_data_url = None

    def __str__(self):
        return "{}{}{}{}{}" \
            .format(key_value_to_str_if_not_none('track', self.get_track(), self._SEPARATOR_CHAR, '\n'),
                    key_value_to_str_if_not_none('type', self.get_type(), self._SEPARATOR_CHAR, '\n'),
                    key_value_to_str_if_not_none('bigDataUrl', self.get_big_data_url(), self._SEPARATOR_CHAR, '\n'),
                    key_value_to_str_if_not_none('shortLabel', self.get_short_label(), self._SEPARATOR_CHAR, '\n'),
                    key_value_to_str_if_not_none('longLabel', self.get_long_label(), self._SEPARATOR_CHAR, ''))

    def __identify_track_type_from_file(self, file_path):
        # TODO - We return the default type right now, but this will change in the future
        return 'bed'

    def set_type(self, file_path):
        self.__type = self.__identify_track_type_from_file(file_path)

    def set_big_data_url(self, big_data_url):
        self.__big_data_url = big_data_url

    def get_track(self):
        return self.__track

    def get_short_label(self):
        return self.__short_label

    def get_long_label(self):
        return self.__long_label

    def get_type(self):
        return self.__type

    def get_big_data_url(self):
        return self.__big_data_url

    def dump_to_track_db_file(self, file_path):
        with open(file_path, 'w') as f:
            f.write(str(self))

# Model for a trackhub
class TrackHub:
    _SEPARATOR_CHAR = ' '

    def __init__(self, hub, short_label, long_label, email, description_url):
        self.__hub = hub
        self.__short_label = short_label
        self.__long_label = long_label
        self.__email = email
        self.__description_url = description_url
        # Default genomes file
        self.__genomes_file = 'genomes.txt'

    def __str__(self):
        return "hub{}{}\n" \
               "shortLabel{}{}\n" \
               "longLabel{}{}\n" \
               "genomesFile{}{}\n" \
               "email{}{}\n" \
               "descriptionUrl{}{}" \
            .format(self._SEPARATOR_CHAR, self.get_hub(),
                    self._SEPARATOR_CHAR, self.get_short_label(),
                    self._SEPARATOR_CHAR, self.get_long_label(),
                    self._SEPARATOR_CHAR, self.get_genomes_file(),
                    self._SEPARATOR_CHAR, self.get_email(),
                    self._SEPARATOR_CHAR, self.get_description_url())

    def get_hub(self):
        return self.__hub

    def get_short_label(self):
        return self.__short_label

    def get_long_label(self):
        return self.__long_label

    def get_email(self):
        return self.__email

    def get_description_url(self):
        return self.__description_url

    def get_genomes_file(self):
        return self.__genomes_file

    def dump_to_file(self, file_path):
        with open(file_path, 'w') as f:
            f.write(str(self))

if __name__ == '__main__':
    print("ERROR: This script is part of a pipeline collection and it is not meant to be run in stand alone mode")
<commit_msg>Track Collector TODO<commit_after>#
# Author    : Manuel Bernal Llinares
# Project   : trackhub-creator
# Timestamp : 03-08-2017 15:44
# ---
# © 2017 Manuel Bernal Llinares <mbdebian@gmail.com>
# All rights reserved.
#

"""
These are the models for representing and dealing with trackhubs
DISCLAIMER - This is the first iteration of the software to create the trackhubs. In this iteration we are going for the
simple version of the hubs, "trackhub quickstart guide" at https://genome.ucsc.edu/goldenpath/help/hubQuickStart.html
"""

# Application imports
import config_manager

# Now, different trackhub builders for the different types of trackhubs (quickstart, custom, etc.)
# DISCLAIMER - I'm aware this first iteration may look a little bit patchy, but it needs to be acknowledged that the
# documentation for modeling this is not very developer friendly, this module it is not meant to be a general module for
# building all sorts of trackhubs and this is the first iteration, so we're not very sure what we want
# TODO - How and where to define the building directors?

def key_value_to_str_if_not_none(key, value, separator=' ', suffix='\n'):
    """
    Helper method that, given a key, value, separator and suffix, it will return the string
    '<key><separator><value><suffix>' if value is not None, otherwise it will return the empty string ''
    :param key: key
    :param value: value
    :param separator: character to use as separator, default ' '
    :param suffix: character to use as suffix, default '\n'
    :return: '<key><separator><value><suffix>' if value not None, '' otherwise
    """
    if value:
        return "{}{}{}{}".format(key, separator, value, suffix)
    return ""

# Modeling TrackHubs
class TrackHubGenomeAssembly:
    # TODO
    pass

class TrackCollector:
    # TODO - This will be a superclass for possible different track collectors I implement in the future
    pass

# Model for a Track
class BaseTrack:
    _SEPARATOR_CHAR = ' '

    def __init__(self, track, short_label, long_label):
        # Client side of the model
        self.__track = track
        self.__short_label = short_label
        self.__long_label = long_label
        # Builder side of the model
        self.__type = None
        self.__big_data_url = None

    def __str__(self):
        return "{}{}{}{}{}" \
            .format(key_value_to_str_if_not_none('track', self.get_track(), self._SEPARATOR_CHAR, '\n'),
                    key_value_to_str_if_not_none('type', self.get_type(), self._SEPARATOR_CHAR, '\n'),
                    key_value_to_str_if_not_none('bigDataUrl', self.get_big_data_url(), self._SEPARATOR_CHAR, '\n'),
                    key_value_to_str_if_not_none('shortLabel', self.get_short_label(), self._SEPARATOR_CHAR, '\n'),
                    key_value_to_str_if_not_none('longLabel', self.get_long_label(), self._SEPARATOR_CHAR, ''))

    def __identify_track_type_from_file(self, file_path):
        # TODO - We return the default type right now, but this will change in the future
        return 'bed'

    def set_type(self, file_path):
        self.__type = self.__identify_track_type_from_file(file_path)

    def set_big_data_url(self, big_data_url):
        self.__big_data_url = big_data_url

    def get_track(self):
        return self.__track

    def get_short_label(self):
        return self.__short_label

    def get_long_label(self):
        return self.__long_label

    def get_type(self):
        return self.__type

    def get_big_data_url(self):
        return self.__big_data_url

    def dump_to_track_db_file(self, file_path):
        with open(file_path, 'w') as f:
            f.write(str(self))

# Model for a trackhub
class TrackHub:
    _SEPARATOR_CHAR = ' '

    def __init__(self, hub, short_label, long_label, email, description_url):
        self.__hub = hub
        self.__short_label = short_label
        self.__long_label = long_label
        self.__email = email
        self.__description_url = description_url
        # Default genomes file
        self.__genomes_file = 'genomes.txt'

    def __str__(self):
        return "hub{}{}\n" \
               "shortLabel{}{}\n" \
               "longLabel{}{}\n" \
               "genomesFile{}{}\n" \
               "email{}{}\n" \
               "descriptionUrl{}{}" \
            .format(self._SEPARATOR_CHAR, self.get_hub(),
                    self._SEPARATOR_CHAR, self.get_short_label(),
                    self._SEPARATOR_CHAR, self.get_long_label(),
                    self._SEPARATOR_CHAR, self.get_genomes_file(),
                    self._SEPARATOR_CHAR, self.get_email(),
                    self._SEPARATOR_CHAR, self.get_description_url())

    def get_hub(self):
        return self.__hub

    def get_short_label(self):
        return self.__short_label

    def get_long_label(self):
        return self.__long_label

    def get_email(self):
        return self.__email

    def get_description_url(self):
        return self.__description_url

    def get_genomes_file(self):
        return self.__genomes_file

    def dump_to_file(self, file_path):
        with open(file_path, 'w') as f:
            f.write(str(self))

if __name__ == '__main__':
    print("ERROR: This script is part of a pipeline collection and it is not meant to be run in stand alone mode")
<|endoftext|>


<commit_before>import tempfile
import os
import sys
import shlex
import subprocess as sp
import logging
from . import track
from . import genome
from . import base
from . import trackdb

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

RSYNC_OPTIONS = '--progress -rvL'

def run(cmds, **kwargs):
    """
    Wrapper around subprocess.run, with unicode decoding of output.

    Additional kwargs are passed to subprocess.run.
    """
    proc = sp.Popen(cmds, bufsize=-1, stdout=sp.PIPE, stderr=sp.STDOUT,
                    close_fds=sys.platform != 'win32')
    for line in proc.stdout:
        print(line[:-1].decode())
    retcode = proc.wait()
    if retcode:
        raise sp.CalledProcessError(retcode, cmd)

def symlink(target, linkname):
    """
    Create a symlink to `target` called `linkname`.

    Converts `target` and `linkname` to absolute paths; creates
    `dirname(linkname)` if needed.
    """
    target = os.path.abspath(target)
    linkname = os.path.abspath(linkname)
    if not os.path.exists(target):
        raise ValueError("target {} not found".format(target))

    link_dir = os.path.dirname(linkname)
    if not os.path.exists(link_dir):
        os.makedirs(link_dir)

    run(['ln', '-s', '-f', target, linkname])
    return linkname

def upload(host, user, local_dir, remote_dir, rsync_options=RSYNC_OPTIONS):
    """
    Upload a file or directory via rsync.

    Parameters
    ----------
    host : str or None
        If None, omit the host part and just transfer locally

    user : str or None
        If None, omit the user part

    local_dir : str
        If a directory, a trailing "/" will be added.

    remote_dir : str
        If a directory, a trailing "/" will be added.
    """
    if user is None:
        user = ""
    else:
        user = user + "@"
    if host is None or host == 'localhost':
        host = ""
    else:
        host = host + ":"

    if not local_dir.endswith('/'):
        local_dir = local_dir + '/'

    if not remote_dir.endswith('/'):
        remote_dir = remote_dir + '/'

    remote_string = '{user}{host}{remote_dir}'.format(**locals())
    cmds = ['rsync']
    cmds += shlex.split(rsync_options)
    cmds += [local_dir, remote_string]
    run(cmds)
    return [remote_string]

def local_link(local_fn, remote_fn, staging):
    """
    Creates a symlink to a local staging area.

    The link name is built from `remote_fn`, but the absolute path is put
    inside the staging directory.

    Example
    -------

    If we have the following initial setup::

        cwd="/home/user"
        local="data/sample1.bw"
        remote="/hubs/hg19/a.bw"
        staging="__staging__"

    Then this function does the equivalent of::

        mkdir -p __staging__/hubs/hg19
        ln -sf \\
            /home/user/data/sample1.bw \\
            /home/user/__staging__/hubs/hg19/a.bw
    """
    linkname = os.path.join(staging, remote_fn.lstrip(os.path.sep))
    return symlink(local_fn, linkname)

def stage(x, staging):
    """
    Stage an object to the `staging` directory.

    If the object is a Track and is one of the types that needs an index file
    (bam, vcfTabix), then the index file will be staged as well.

    Returns a list of the linknames created.
    """
    non_file_objects = (
        track.ViewTrack,
        track.CompositeTrack,
        genome.Genome,
    )

    if isinstance(x, non_file_objects):
        return []

    if not x.remote_fn:
        raise ValueError("Object does not have a valid `remote_fn` value")

    if not x.local_fn:
        raise ValueError("Object does not have a valid `local_fn` value")

    linknames = []

    def _stg(x, ext=''):
        linknames.append(
            local_link(x.local_fn + ext, x.remote_fn + ext, staging)
        )

    _stg(x)

    if isinstance(x, track.Track):
        if x.tracktype == 'bam':
            _stg(x, ext='.bai')
        if x.tracktype == 'vcfTabix':
            _stg(x, ext='.tbi')

    if isinstance(x, track.CompositeTrack):
        if x._html:
            _stg(x._html)

    return linknames

def stage_hub(hub, staging=None):
    """
    Stage a hub by symlinking all its connected files to a local directory.
    """
    linknames = []
    if staging is None:
        staging = tempfile.mkdtemp()
    for obj, level in hub.leaves(base.HubComponent, intermediate=True):
        linknames.extend(stage(obj, staging))
    return linknames

def upload_hub(host, user, hub, port=22, rsync_options=RSYNC_OPTIONS, staging=None):
    """
    Stages a hub and then uploads it.
    """
    if staging is None:
        staging = tempfile.mkdtemp()
    linknames = stage_hub(hub, staging=staging)
    hub_dir = os.path.dirname(hub.remote_fn)
    local_dir = os.path.join(staging, hub_dir.lstrip('/'))
    remote_dir = hub_dir
    upload(host, user, local_dir=local_dir, remote_dir=remote_dir, rsync_options=rsync_options)
    return linknames
<commit_msg>add additional non-file objs<commit_after>import tempfile
import os
import sys
import shlex
import subprocess as sp
import logging
from . import track
from . import genome
from . import base
from . import trackdb

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

RSYNC_OPTIONS = '--progress -rvL'

def run(cmds, **kwargs):
    """
    Wrapper around subprocess.run, with unicode decoding of output.

    Additional kwargs are passed to subprocess.run.
    """
    proc = sp.Popen(cmds, bufsize=-1, stdout=sp.PIPE, stderr=sp.STDOUT,
                    close_fds=sys.platform != 'win32')
    for line in proc.stdout:
        print(line[:-1].decode())
    retcode = proc.wait()
    if retcode:
        raise sp.CalledProcessError(retcode, cmd)

def symlink(target, linkname):
    """
    Create a symlink to `target` called `linkname`.

    Converts `target` and `linkname` to absolute paths; creates
    `dirname(linkname)` if needed.
    """
    target = os.path.abspath(target)
    linkname = os.path.abspath(linkname)
    if not os.path.exists(target):
        raise ValueError("target {} not found".format(target))

    link_dir = os.path.dirname(linkname)
    if not os.path.exists(link_dir):
        os.makedirs(link_dir)

    run(['ln', '-s', '-f', target, linkname])
    return linkname

def upload(host, user, local_dir, remote_dir, rsync_options=RSYNC_OPTIONS):
    """
    Upload a file or directory via rsync.

    Parameters
    ----------
    host : str or None
        If None, omit the host part and just transfer locally

    user : str or None
        If None, omit the user part

    local_dir : str
        If a directory, a trailing "/" will be added.

    remote_dir : str
        If a directory, a trailing "/" will be added.
    """
    if user is None:
        user = ""
    else:
        user = user + "@"
    if host is None or host == 'localhost':
        host = ""
    else:
        host = host + ":"

    if not local_dir.endswith('/'):
        local_dir = local_dir + '/'

    if not remote_dir.endswith('/'):
        remote_dir = remote_dir + '/'

    remote_string = '{user}{host}{remote_dir}'.format(**locals())
    cmds = ['rsync']
    cmds += shlex.split(rsync_options)
    cmds += [local_dir, remote_string]
    run(cmds)
    return [remote_string]

def local_link(local_fn, remote_fn, staging):
    """
    Creates a symlink to a local staging area.

    The link name is built from `remote_fn`, but the absolute path is put
    inside the staging directory.

    Example
    -------

    If we have the following initial setup::

        cwd="/home/user"
        local="data/sample1.bw"
        remote="/hubs/hg19/a.bw"
        staging="__staging__"

    Then this function does the equivalent of::

        mkdir -p __staging__/hubs/hg19
        ln -sf \\
            /home/user/data/sample1.bw \\
            /home/user/__staging__/hubs/hg19/a.bw
    """
    linkname = os.path.join(staging, remote_fn.lstrip(os.path.sep))
    return symlink(local_fn, linkname)

def stage(x, staging):
    """
    Stage an object to the `staging` directory.

    If the object is a Track and is one of the types that needs an index file
    (bam, vcfTabix), then the index file will be staged as well.

    Returns a list of the linknames created.
    """
    non_file_objects = (
        track.ViewTrack,
        track.CompositeTrack,
        track.AggregateTrack,
        track.SuperTrack,
        genome.Genome,
    )

    if isinstance(x, non_file_objects):
        return []

    if not x.remote_fn:
        raise ValueError("Object does not have a valid `remote_fn` value")

    if not x.local_fn:
        raise ValueError("Object does not have a valid `local_fn` value")

    linknames = []

    def _stg(x, ext=''):
        linknames.append(
            local_link(x.local_fn + ext, x.remote_fn + ext, staging)
        )

    _stg(x)

    if isinstance(x, track.Track):
        if x.tracktype == 'bam':
            _stg(x, ext='.bai')
        if x.tracktype == 'vcfTabix':
            _stg(x, ext='.tbi')

    if isinstance(x, track.CompositeTrack):
        if x._html:
            _stg(x._html)

    return linknames

def stage_hub(hub, staging=None):
    """
    Stage a hub by symlinking all its connected files to a local directory.
    """
    linknames = []
    if staging is None:
        staging = tempfile.mkdtemp()
    for obj, level in hub.leaves(base.HubComponent, intermediate=True):
        linknames.extend(stage(obj, staging))
    return linknames

def upload_hub(host, user, hub, port=22, rsync_options=RSYNC_OPTIONS, staging=None):
    """
    Stages a hub and then uploads it.
    """
    if staging is None:
        staging = tempfile.mkdtemp()
    linknames = stage_hub(hub, staging=staging)
    hub_dir = os.path.dirname(hub.remote_fn)
    local_dir = os.path.join(staging, hub_dir.lstrip('/'))
    remote_dir = hub_dir
    upload(host, user, local_dir=local_dir, remote_dir=remote_dir, rsync_options=rsync_options)
    return linknames
<|endoftext|>


<commit_before>__version__ = '0.2.1'
default_app_config = 'uuid_contour.apps.DefaultConfig'
<commit_msg>uped version<commit_after>__version__ = '0.2.2'
default_app_config = 'uuid_contour.apps.DefaultConfig'
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#     This file is part of mass_mailing_distribution_list, an Odoo module.
#
#     Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
#     mass_mailing_distribution_list 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.
#
#     mass_mailing_distribution_list 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 mass_mailing_distribution_list.
#     If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
    'name': 'Mass Mailing Distribution List',
    'version': '1.0',
    'author': 'ACSONE SA/NV',
    'maintainer': 'ACSONE SA/NV',
    'website': 'http://www.acsone.eu',
    'category': 'Marketing',
    'depends': [
        'distribution_list',
        'mass_mailing',
    ],
    'description': """
Mass Mailing Distribution List
==============================

This module make a link between distribution list and mass mailing.

It allows:
* to declare a distribution list as a newsletter to also define
  static lists of partners (opt In/Out)
* to unsubscribe partner (i.e. add it to the opt Out list) through
  the unsubscribe link added to the mailing
* to receive an external mail and forward it to all recipients filtered by
  the distribution list
""",
    'images': [
    ],
    'data': [
        'views/mass_mailing.xml',
        'views/distribution_list_view.xml',
        'wizard/merge_distribution_list_view.xml',
    ],
    'qweb': [
    ],
    'demo': [
    ],
    'test': [
    ],
    'license': 'AGPL-3',
    'installable': True,
    'auto_install': True,
}
<commit_msg>[IMP] remove auto_install for mass_mailing_distribution_list<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#     This file is part of mass_mailing_distribution_list, an Odoo module.
#
#     Copyright (c) 2015 ACSONE SA/NV (<http://acsone.eu>)
#
#     mass_mailing_distribution_list 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.
#
#     mass_mailing_distribution_list 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 mass_mailing_distribution_list.
#     If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
    'name': 'Mass Mailing Distribution List',
    'version': '1.0',
    'author': 'ACSONE SA/NV',
    'maintainer': 'ACSONE SA/NV',
    'website': 'http://www.acsone.eu',
    'category': 'Marketing',
    'depends': [
        'distribution_list',
        'mass_mailing',
    ],
    'description': """
Mass Mailing Distribution List
==============================

This module make a link between distribution list and mass mailing.

It allows:
* to declare a distribution list as a newsletter to also define
  static lists of partners (opt In/Out)
* to unsubscribe partner (i.e. add it to the opt Out list) through
  the unsubscribe link added to the mailing
* to receive an external mail and forward it to all recipients filtered by
  the distribution list
""",
    'images': [
    ],
    'data': [
        'views/mass_mailing.xml',
        'views/distribution_list_view.xml',
        'wizard/merge_distribution_list_view.xml',
    ],
    'qweb': [
    ],
    'demo': [
    ],
    'test': [
    ],
    'license': 'AGPL-3',
    'installable': True,
    'auto_install': False,
}
<|endoftext|>


<commit_before><commit_msg>Removed pkg_resources since it confuses libraries like pygments<commit_after><|endoftext|>


<commit_before># Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from master import master_config
from master.factory import chromium_factory

defaults = {}

helper = master_config.Helper(defaults)
B = helper.Builder
F = helper.Factory
S = helper.Scheduler
T = helper.Triggerable

def ios():
  return chromium_factory.ChromiumFactory('src/xcodebuild', 'darwin')
def mac():
  return chromium_factory.ChromiumFactory('src/xcodebuild', 'darwin')
def mac_tester():
  return chromium_factory.ChromiumFactory(
      'src/xcodebuild', 'darwin', nohooks_on_update=True)
def mac_out():
  return chromium_factory.ChromiumFactory('src/out', 'darwin')

# Tests that are single-machine shard-safe.
sharded_tests = [
  'aura_unittests',
  'base_unittests',
  'browser_tests',
  'cacheinvalidation_unittests',
  'cc_unittests',
  'chromedriver2_tests',
  'chromedriver2_unittests',
  'components_unittests',
  'content_browsertests',
  'content_unittests',
  'crypto_unittests',
  'device_unittests',
  'gpu_unittests',
  'jingle_unittests',
  'media_unittests',
  'net_unittests',
  'ppapi_unittests',
  'printing_unittests',
  'remoting_unittests',
  'sync_integration_tests',
  'sync_unit_tests',
  'ui_unittests',
  'unit_tests',
  'views_unittests',
  'webkit_compositor_bindings_unittests',
]

################################################################################
## Release
################################################################################

defaults['category'] = '3mac'

# Archive location
rel_archive = master_config.GetArchiveUrl('ChromiumMac', 'Mac Builder',
                                          'cr-mac-rel', 'mac')

#
# Main debug scheduler for src/
#
S('mac_rel', branch='src', treeStableTimer=60)

#
# Triggerable scheduler for the dbg builder
#
T('mac_rel_trigger')

#
# Mac Rel Builder
#
B('Mac Builder', 'rel', 'compile', 'mac_rel', builddir='cr-mac-rel',
  auto_reboot=False, notify_on_missing=True)
F('rel', mac().ChromiumFactory(
    slave_type='Builder',
    options=[
        '--compiler=goma-clang', '--', '-target', 'chromium_builder_tests'],
    factory_properties={
        'trigger': 'mac_rel_trigger',
    }))

#
# Mac Rel testers
#
B('Mac10.6 Tests (1)', 'rel_unit_1', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
F('rel_unit_1', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=rel_archive,
  tests=[
    'base_unittests',
    'browser_tests',
    'cacheinvalidation_unittests',
    'cc_unittests',
    'chromedriver2_unittests',
    'content_browsertests',
    'crypto_unittests',
    'googleurl',
    'gpu',
    'interactive_ui_tests',
    'jingle',
    'media',
    'nacl_integration',
    'ppapi_unittests',
    'printing',
    'remoting',
    'webkit_compositor_bindings_unittests',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 3, 'browser_shard_index': 1,})
)

B('Mac10.6 Tests (2)', 'rel_unit_2', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
F('rel_unit_2', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=rel_archive,
  tests=[
    'browser_tests',
    'components_unittests',
    'unit',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 3, 'browser_shard_index': 2,})
)

B('Mac10.6 Tests (3)', 'rel_unit_3', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
F('rel_unit_3', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=rel_archive,
  tests=[
    'browser_tests',
    'net',
    'message_center_unittests',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 3, 'browser_shard_index': 3,})
)

B('Mac10.7 Tests (1)', 'rel_unit_1', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
B('Mac10.7 Tests (2)', 'rel_unit_2', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
B('Mac10.7 Tests (3)', 'rel_unit_3', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)

B('Mac10.6 Sync', 'rel_sync', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
F('rel_sync', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=rel_archive,
  tests=['sync_integration'],
  factory_properties={'generate_gtest_json': True}))

################################################################################
## Debug
################################################################################

# Archive location
dbg_archive = master_config.GetArchiveUrl('ChromiumMac', 'Mac Builder (dbg)',
                                          'Mac_Builder__dbg_', 'mac')

#
# Main debug scheduler for src/
#
S('mac_dbg', branch='src', treeStableTimer=60)

#
# Triggerable scheduler for the dbg builder
#
T('mac_dbg_trigger')

#
# Mac Dbg Builder
#
B('Mac Builder (dbg)', 'dbg', 'compile', 'mac_dbg',
  auto_reboot=False, notify_on_missing=True)
F('dbg', mac_out().ChromiumFactory(
    target='Debug',
    slave_type='Builder',
    options=[
        '--compiler=goma-clang', '--build-tool=ninja', '--',
        'chromium_builder_tests'],
    factory_properties={
        'trigger': 'mac_dbg_trigger',
        'gclient_env': {
            'GYP_GENERATORS':'ninja',
            'GYP_DEFINES':'clang=1 clang_use_chrome_plugins=1'
        },
    }))

#
# Mac Dbg Unit testers
#

B('Mac 10.6 Tests (dbg)(1)', 'dbg_unit_1', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
F('dbg_unit_1', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=dbg_archive,
  target='Debug',
  tests=[
    'browser_tests',
    'cacheinvalidation_unittests',
    'cc_unittests',
    'chromedriver2_unittests',
    'content_browsertests',
    'crypto_unittests',
    'googleurl',
    'gpu',
    'jingle',
    'nacl_integration',
    'ppapi_unittests',
    'printing',
    'remoting',
    'webkit_compositor_bindings_unittests',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 4, 'browser_shard_index': 1,}))

B('Mac 10.6 Tests (dbg)(2)', 'dbg_unit_2', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
F('dbg_unit_2', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=dbg_archive,
  target='Debug',
  tests=[
    'browser_tests',
    'check_deps',
    'media',
    'net',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 4, 'browser_shard_index': 2,}))

B('Mac 10.6 Tests (dbg)(3)', 'dbg_unit_3', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
F('dbg_unit_3', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=dbg_archive,
  target='Debug',
  tests=[
    'base_unittests',
    'browser_tests',
    'interactive_ui_tests',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 4, 'browser_shard_index': 3,}))

B('Mac 10.6 Tests (dbg)(4)', 'dbg_unit_4', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
F('dbg_unit_4', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=dbg_archive,
  target='Debug',
  tests=[
    'browser_tests',
    'components_unittests',
    'unit',
    'message_center_unittests',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 4, 'browser_shard_index': 4,}))

B('Mac 10.7 Tests (dbg)(1)', 'dbg_unit_1', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
B('Mac 10.7 Tests (dbg)(2)', 'dbg_unit_2', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
B('Mac 10.7 Tests (dbg)(3)', 'dbg_unit_3', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
B('Mac 10.7 Tests (dbg)(4)', 'dbg_unit_4', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)

################################################################################
## iOS
################################################################################

#
# Main scheduler for src/
#
S('ios', branch='src', treeStableTimer=60)

#
# iOS Release iphoneos BuilderTester
#
B('iOS Device', 'ios_rel', gatekeeper='ios_rel', scheduler='ios',
  auto_reboot=True, notify_on_missing=True)
F('ios_rel', ios().ChromiumFactory(
  # TODO(lliabraa): Need to upstream support for running tests on devices
  # before we can actually run any tests.
  tests=[],
  options = [
    '--', '-project', '../build/all.xcodeproj', '-sdk',
    'iphoneos6.1', '-target' , 'All'],
  factory_properties={
    'app_name': 'Chromium.app',
    'gclient_deps': 'ios',
    'gclient_env': {
      'GYP_DEFINES': 'component=static_library OS=ios chromium_ios_signing=0',
      'GYP_GENERATOR_FLAGS': 'xcode_project_version=3.2',
    },
  }))

#
# iOS Debug iphonesimulator BuilderTester
#
B('iOS Simulator (dbg)', 'ios_dbg', gatekeeper='ios_dbg', scheduler='ios',
  auto_reboot=True, notify_on_missing=True)
F('ios_dbg', ios().ChromiumFactory(
  target='Debug',
  tests=[
    'base_unittests',
    'content_unittests',
    'crypto_unittests',
    'googleurl',
    'media',
    'net',
    'ui_unittests',
    'unit_sql',
    'unit_sync',
    'unit_tests',
  ],
  options = [
    '--', '-project', '../build/all.xcodeproj', '-sdk',
    'iphonesimulator6.1', '-target', 'All',],
  factory_properties={
    'app_name': 'Chromium.app',
    'test_platform': 'ios-simulator',
    'gclient_deps': 'ios',
    'gclient_env': {
      'GYP_DEFINES': 'component=static_library OS=ios chromium_ios_signing=0',
      'GYP_GENERATOR_FLAGS': 'xcode_project_version=3.2',
    },
  }))

def Update(config, active_master, c):
  return helper.Update(c)
<commit_msg>Try Mac Builder as ninja to see if it improves performance at all.<commit_after># Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from master import master_config
from master.factory import chromium_factory

defaults = {}

helper = master_config.Helper(defaults)
B = helper.Builder
F = helper.Factory
S = helper.Scheduler
T = helper.Triggerable

def ios():
  return chromium_factory.ChromiumFactory('src/xcodebuild', 'darwin')
def mac():
  return chromium_factory.ChromiumFactory('src/xcodebuild', 'darwin')
def mac_tester():
  return chromium_factory.ChromiumFactory(
      'src/xcodebuild', 'darwin', nohooks_on_update=True)
def mac_out():
  return chromium_factory.ChromiumFactory('src/out', 'darwin')

# Tests that are single-machine shard-safe.
sharded_tests = [
  'aura_unittests',
  'base_unittests',
  'browser_tests',
  'cacheinvalidation_unittests',
  'cc_unittests',
  'chromedriver2_tests',
  'chromedriver2_unittests',
  'components_unittests',
  'content_browsertests',
  'content_unittests',
  'crypto_unittests',
  'device_unittests',
  'gpu_unittests',
  'jingle_unittests',
  'media_unittests',
  'net_unittests',
  'ppapi_unittests',
  'printing_unittests',
  'remoting_unittests',
  'sync_integration_tests',
  'sync_unit_tests',
  'ui_unittests',
  'unit_tests',
  'views_unittests',
  'webkit_compositor_bindings_unittests',
]

################################################################################
## Release
################################################################################

defaults['category'] = '3mac'

# Archive location
rel_archive = master_config.GetArchiveUrl('ChromiumMac', 'Mac Builder',
                                          'cr-mac-rel', 'mac')

#
# Main debug scheduler for src/
#
S('mac_rel', branch='src', treeStableTimer=60)

#
# Triggerable scheduler for the dbg builder
#
T('mac_rel_trigger')

#
# Mac Rel Builder
#
B('Mac Builder', 'rel', 'compile', 'mac_rel', builddir='cr-mac-rel',
  auto_reboot=False, notify_on_missing=True)
F('rel', mac().ChromiumFactory(
    slave_type='Builder',
    options=[
        '--compiler=goma-clang', '--build-tool=ninja', '--',
        '-target', 'chromium_builder_tests'],
    factory_properties={
        'trigger': 'mac_rel_trigger',
        'gclient_env': {
            'GYP_GENERATORS':'ninja',
            'GYP_DEFINES':'clang=1 clang_use_chrome_plugins=1'
        },
    }))

#
# Mac Rel testers
#
B('Mac10.6 Tests (1)', 'rel_unit_1', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
F('rel_unit_1', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=rel_archive,
  tests=[
    'base_unittests',
    'browser_tests',
    'cacheinvalidation_unittests',
    'cc_unittests',
    'chromedriver2_unittests',
    'content_browsertests',
    'crypto_unittests',
    'googleurl',
    'gpu',
    'interactive_ui_tests',
    'jingle',
    'media',
    'nacl_integration',
    'ppapi_unittests',
    'printing',
    'remoting',
    'webkit_compositor_bindings_unittests',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 3, 'browser_shard_index': 1,})
)

B('Mac10.6 Tests (2)', 'rel_unit_2', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
F('rel_unit_2', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=rel_archive,
  tests=[
    'browser_tests',
    'components_unittests',
    'unit',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 3, 'browser_shard_index': 2,})
)

B('Mac10.6 Tests (3)', 'rel_unit_3', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
F('rel_unit_3', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=rel_archive,
  tests=[
    'browser_tests',
    'net',
    'message_center_unittests',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 3, 'browser_shard_index': 3,})
)

B('Mac10.7 Tests (1)', 'rel_unit_1', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
B('Mac10.7 Tests (2)', 'rel_unit_2', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
B('Mac10.7 Tests (3)', 'rel_unit_3', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)

B('Mac10.6 Sync', 'rel_sync', 'testers', 'mac_rel_trigger',
  notify_on_missing=True)
F('rel_sync', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=rel_archive,
  tests=['sync_integration'],
  factory_properties={'generate_gtest_json': True}))

################################################################################
## Debug
################################################################################

# Archive location
dbg_archive = master_config.GetArchiveUrl('ChromiumMac', 'Mac Builder (dbg)',
                                          'Mac_Builder__dbg_', 'mac')

#
# Main debug scheduler for src/
#
S('mac_dbg', branch='src', treeStableTimer=60)

#
# Triggerable scheduler for the dbg builder
#
T('mac_dbg_trigger')

#
# Mac Dbg Builder
#
B('Mac Builder (dbg)', 'dbg', 'compile', 'mac_dbg',
  auto_reboot=False, notify_on_missing=True)
F('dbg', mac_out().ChromiumFactory(
    target='Debug',
    slave_type='Builder',
    options=[
        '--compiler=goma-clang', '--build-tool=ninja', '--',
        'chromium_builder_tests'],
    factory_properties={
        'trigger': 'mac_dbg_trigger',
        'gclient_env': {
            'GYP_GENERATORS':'ninja',
            'GYP_DEFINES':'clang=1 clang_use_chrome_plugins=1'
        },
    }))

#
# Mac Dbg Unit testers
#

B('Mac 10.6 Tests (dbg)(1)', 'dbg_unit_1', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
F('dbg_unit_1', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=dbg_archive,
  target='Debug',
  tests=[
    'browser_tests',
    'cacheinvalidation_unittests',
    'cc_unittests',
    'chromedriver2_unittests',
    'content_browsertests',
    'crypto_unittests',
    'googleurl',
    'gpu',
    'jingle',
    'nacl_integration',
    'ppapi_unittests',
    'printing',
    'remoting',
    'webkit_compositor_bindings_unittests',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 4, 'browser_shard_index': 1,}))

B('Mac 10.6 Tests (dbg)(2)', 'dbg_unit_2', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
F('dbg_unit_2', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=dbg_archive,
  target='Debug',
  tests=[
    'browser_tests',
    'check_deps',
    'media',
    'net',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 4, 'browser_shard_index': 2,}))

B('Mac 10.6 Tests (dbg)(3)', 'dbg_unit_3', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
F('dbg_unit_3', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=dbg_archive,
  target='Debug',
  tests=[
    'base_unittests',
    'browser_tests',
    'interactive_ui_tests',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 4, 'browser_shard_index': 3,}))

B('Mac 10.6 Tests (dbg)(4)', 'dbg_unit_4', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
F('dbg_unit_4', mac_tester().ChromiumFactory(
  slave_type='Tester',
  build_url=dbg_archive,
  target='Debug',
  tests=[
    'browser_tests',
    'components_unittests',
    'unit',
    'message_center_unittests',
  ],
  factory_properties={'generate_gtest_json': True,
                      'sharded_tests': sharded_tests,
                      'browser_total_shards': 4, 'browser_shard_index': 4,}))

B('Mac 10.7 Tests (dbg)(1)', 'dbg_unit_1', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
B('Mac 10.7 Tests (dbg)(2)', 'dbg_unit_2', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
B('Mac 10.7 Tests (dbg)(3)', 'dbg_unit_3', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)
B('Mac 10.7 Tests (dbg)(4)', 'dbg_unit_4', 'testers', 'mac_dbg_trigger',
  notify_on_missing=True)

################################################################################
## iOS
################################################################################

#
# Main scheduler for src/
#
S('ios', branch='src', treeStableTimer=60)

#
# iOS Release iphoneos BuilderTester
#
B('iOS Device', 'ios_rel', gatekeeper='ios_rel', scheduler='ios',
  auto_reboot=True, notify_on_missing=True)
F('ios_rel', ios().ChromiumFactory(
  # TODO(lliabraa): Need to upstream support for running tests on devices
  # before we can actually run any tests.
  tests=[],
  options = [
    '--', '-project', '../build/all.xcodeproj', '-sdk',
    'iphoneos6.1', '-target' , 'All'],
  factory_properties={
    'app_name': 'Chromium.app',
    'gclient_deps': 'ios',
    'gclient_env': {
      'GYP_DEFINES': 'component=static_library OS=ios chromium_ios_signing=0',
      'GYP_GENERATOR_FLAGS': 'xcode_project_version=3.2',
    },
  }))

#
# iOS Debug iphonesimulator BuilderTester
#
B('iOS Simulator (dbg)', 'ios_dbg', gatekeeper='ios_dbg', scheduler='ios',
  auto_reboot=True, notify_on_missing=True)
F('ios_dbg', ios().ChromiumFactory(
  target='Debug',
  tests=[
    'base_unittests',
    'content_unittests',
    'crypto_unittests',
    'googleurl',
    'media',
    'net',
    'ui_unittests',
    'unit_sql',
    'unit_sync',
    'unit_tests',
  ],
  options = [
    '--', '-project', '../build/all.xcodeproj', '-sdk',
    'iphonesimulator6.1', '-target', 'All',],
  factory_properties={
    'app_name': 'Chromium.app',
    'test_platform': 'ios-simulator',
    'gclient_deps': 'ios',
    'gclient_env': {
      'GYP_DEFINES': 'component=static_library OS=ios chromium_ios_signing=0',
      'GYP_GENERATOR_FLAGS': 'xcode_project_version=3.2',
    },
  }))

def Update(config, active_master, c):
  return helper.Update(c)
<|endoftext|>