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

import re
import logging
from itertools import chain

from devlib.trace.ftrace import TRACE_MARKER_START, TRACE_MARKER_STOP

from wa.utils.misc import isiterable
from wa.utils.types import numeric

logger = logging.getLogger('trace-cmd')

class TraceCmdEvent(object):
    """
    A single trace-cmd event. This will appear in the trace cmd report in the format ::

          <idle>-0     [000]  3284.126993: sched_rq_runnable_load: cpu=0 load=54
             |           |         |              |                |___________|
             |           |         |              |                      |
          thread        cpu    timestamp        name                    body

    """

    __slots__ = ['thread', 'reporting_cpu_id', 'timestamp', 'name', 'text', 'fields']

    def __init__(self, thread, cpu_id, ts, name, body, parser=None):
        """
        parameters:

        :thread: thread which generated the event
        :cpu: cpu on which the event has occurred
        :ts: timestamp of the event
        :name: the name of the event
        :bodytext: a string with the rest of the event text
        :parser: optionally, a function that will parse body text to populate
                 this event's attributes

        The parser can be any callable that can be invoked with

            parser(event, text)

        Where ``event`` is this TraceCmdEvent instance, and ``text`` is the body text to be
        parsed. The parser should updated the passed event instance and not return anything
        (the return value will be ignored). Any exceptions raised by the parser will be silently
        ignored (note that this means that the event's attributes may be partially initialized).

        """
        self.thread = thread
        self.reporting_cpu_id = int(cpu_id)
        self.timestamp = numeric(ts)
        self.name = name
        self.text = body
        self.fields = {}

        if parser:
            try:
                parser(self, self.text)
            except Exception:  # pylint: disable=broad-except
                # unknown format assume user does not care or know how to
                # parse self.text
                pass

    def __getattr__(self, name):
        try:
            return self.fields[name]
        except KeyError:
            raise AttributeError(name)

    def __str__(self):
        return 'TE({} @ {})'.format(self.name, self.timestamp)

    __repr__ = __str__

class DroppedEventsEvent(object):

    __slots__ = ['thread', 'reporting_cpu_id', 'timestamp', 'name', 'text', 'fields']

    def __init__(self, cpu_id):
        self.thread = None
        self.reporting_cpu_id = None
        self.timestamp = None
        self.name = 'DROPPED EVENTS DETECTED'
        self.text = None
        self.fields = {'cpu_id': int(cpu_id)}

    def __getattr__(self, name):
        try:
            return self.fields[name]
        except KeyError:
            raise AttributeError(name)

    def __str__(self):
        return 'DROPPED_EVENTS_ON_CPU{}'.format(self.cpu_id)

    __repr__ = __str__

def try_convert_to_numeric(v):
    try:
        if isiterable(v):
            return map(numeric, v)
        else:
            return numeric(v)
    except ValueError:
        return v

def default_body_parser(event, text):
    """
    Default parser to attempt to use to parser body text for the event (i.e. after
    the "header" common to all events has been parsed). This assumes that the body is
    a whitespace-separated list of key=value pairs. The parser will attempt to convert
    the value into a numeric type, and failing that, keep it as string.

    """
    parts = [e.rsplit(' ', 1) for e in text.strip().split('=')]
    parts = [p.strip() for p in chain.from_iterable(parts)]
    if not len(parts) % 2:
        i = iter(parts)
        for k, v in zip(i, i):
            try:
                v = int(v)
            except ValueError:
                pass
            event.fields[k] = v

def regex_body_parser(regex, flags=0):
    """
    Creates an event body parser form the specified regular expression (could be an
    ``re.RegexObject``, or a string). The regular expression should contain some named
    groups, as those will be extracted as the event attributes (unnamed groups and the
    reset of the match will be ignored).

    If the specified regex is a string, it will be compiled, in which case ``flags`` may
    be provided for the resulting regex object (see ``re`` standard module documentation).
    If regex is a pre-compiled object, flags will be ignored.

    """
    if isinstance(regex, basestring):
        regex = re.compile(regex, flags)

    def regex_parser_func(event, text):
        match = regex.search(text)
        if match:
            for k, v in match.groupdict().iteritems():
                try:
                    event.fields[k] = int(v)
                except ValueError:
                    event.fields[k] = v

    return regex_parser_func

def sched_switch_parser(event, text):
    """
    Sched switch output may be presented in a couple of different formats. One is handled
    by a regex. The other format can *almost* be handled by the default parser, if it
    weren't for the ``==>`` that appears in the middle.
    """
    if text.count('=') == 2:  # old format
        regex = re.compile(
            r'(?P<prev_comm>\S.*):(?P<prev_pid>\d+) \[(?P<prev_prio>\d+)\] (?P<status>\S+)'
            r' ==> '
            r'(?P<next_comm>\S.*):(?P<next_pid>\d+) \[(?P<next_prio>\d+)\]'
        )
        parser_func = regex_body_parser(regex)
        return parser_func(event, text)
    else:  # there are more than two "=" -- new format
        return default_body_parser(event, text.replace('==>', ''))

def sched_stat_parser(event, text):
    """
    sched_stat_* events unclude the units, "[ns]", in an otherwise
    regular key=value sequence; so the units  need to be stripped out first.
    """
    return default_body_parser(event, text.replace(' [ns]', ''))

def sched_wakeup_parser(event, text):
    regex = re.compile(r'(?P<comm>\S+):(?P<pid>\d+) \[(?P<prio>\d+)\] success=(?P<success>\d) CPU:(?P<cpu>\d+)')
    parse_func = regex_body_parser(regex)
    return parse_func(event, text)

# Maps event onto the corresponding parser for its body text. A parser may be
# a callable with signature
#
#   parser(event, bodytext)
#
# a re.RegexObject, or a string (in which case it will be compiled into a
# regex). In case of a string/regex, its named groups will be used to populate
# the event's attributes.
EVENT_PARSER_MAP = {
    'sched_stat_blocked': sched_stat_parser,
    'sched_stat_iowait': sched_stat_parser,
    'sched_stat_runtime': sched_stat_parser,
    'sched_stat_sleep': sched_stat_parser,
    'sched_stat_wait': sched_stat_parser,
    'sched_switch': sched_switch_parser,
    'sched_wakeup': sched_wakeup_parser,
    'sched_wakeup_new': sched_wakeup_parser,
}

TRACE_EVENT_REGEX = re.compile(r'^\s+(?P<thread>\S+.*?\S+)\s+\[(?P<cpu_id>\d+)\]\s+(?P<ts>[\d.]+):\s+'
                               r'(?P<name>[^:]+):\s+(?P<body>.*?)\s*$')

HEADER_REGEX = re.compile(r'^\s*(?:version|cpus)\s*=\s*([\d.]+)\s*$')

DROPPED_EVENTS_REGEX = re.compile(r'CPU:(?P<cpu_id>\d+) \[\d*\s*EVENTS DROPPED\]')

EMPTY_CPU_REGEX = re.compile(r'CPU \d+ is empty')

class TraceCmdParser(object):
    """
    A parser for textual representation of ftrace as reported by trace-cmd

    """

    def __init__(self, filter_markers=True, check_for_markers=True, events=None):
        """
        Initialize a new trace parser.

        :param filter_markers: Specifies whether the trace before the start
                               marker and after the stop marker should be
                               filtered out (so only events between the two
                               markers will be reported). This maybe overriden
                               based on `check_for_markers` parameter of
                               `parse()`
        :param check_for_markers: Check if the start/stop markers are present
                                  in the trace and ensure that `filter_markers`
                                  is `False` if they aren't
        :param events: A list of event names to be reported; if not specified,
                       all events will be reported.

        """
        self.filter_markers = filter_markers
        self.check_for_markers = check_for_markers
        self.events = events

    def parse(self, filepath):  # pylint: disable=too-many-branches,too-many-locals
        """
        This is a generator for the trace event stream.

        :param filepath: The path to the file containg text trace as reported
                         by trace-cmd
        """
        inside_maked_region = False
        filters = [re.compile('^{}$'.format(e)) for e in (self.events or [])]
        filter_markers = self.filter_markers
        if filter_markers and self.check_for_markers:
            with open(filepath) as fh:
                for line in fh:
                    if TRACE_MARKER_START in line:
                        break
                else:
                    # maker not found force filtering by marker to False
                    filter_markers = False

        with open(filepath) as fh:
            for line in fh:
                # if processing trace markers, skip marker lines as well as all
                # lines outside marked region
                if filter_markers:
                    if not inside_maked_region:
                        if TRACE_MARKER_START in line:
                            inside_maked_region = True
                        continue
                    elif TRACE_MARKER_STOP in line:
                        inside_maked_region = False
                        continue

                match = DROPPED_EVENTS_REGEX.search(line)
                if match:
                    yield DroppedEventsEvent(match.group('cpu_id'))
                    continue

                matched = False
                for rx in [HEADER_REGEX, EMPTY_CPU_REGEX]:
                    match = rx.search(line)
                    if match:
                        logger.debug(line.strip())
                        matched = True
                        break
                if matched:
                    continue

                match = TRACE_EVENT_REGEX.search(line)
                if not match:
                    logger.warning('Invalid trace event: "{}"'.format(line))
                    continue

                event_name = match.group('name')

                if filters:
                    found = False
                    for f in filters:
                        if f.search(event_name):
                            found = True
                            break
                    if not found:
                        continue

                body_parser = EVENT_PARSER_MAP.get(event_name, default_body_parser)
                if isinstance(body_parser, basestring) or isinstance(body_parser, re._pattern_type):  # pylint: disable=protected-access
                    body_parser = regex_body_parser(body_parser)
                yield TraceCmdEvent(parser=body_parser, **match.groupdict())

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

import re
import logging
from itertools import chain

from devlib.trace.ftrace import TRACE_MARKER_START, TRACE_MARKER_STOP

from wa.utils.misc import isiterable
from wa.utils.types import numeric

logger = logging.getLogger('trace-cmd')

class TraceCmdEvent(object):
    """
    A single trace-cmd event. This will appear in the trace cmd report in the format ::

          <idle>-0     [000]  3284.126993: sched_rq_runnable_load: cpu=0 load=54
             |           |         |              |                |___________|
             |           |         |              |                      |
          thread        cpu    timestamp        name                    body

    """

    __slots__ = ['thread', 'reporting_cpu_id', 'timestamp', 'name', 'text', 'fields']

    def __init__(self, thread, cpu_id, ts, name, body, parser=None):
        """
        parameters:

        :thread: thread which generated the event
        :cpu: cpu on which the event has occurred
        :ts: timestamp of the event
        :name: the name of the event
        :bodytext: a string with the rest of the event text
        :parser: optionally, a function that will parse body text to populate
                 this event's attributes

        The parser can be any callable that can be invoked with

            parser(event, text)

        Where ``event`` is this TraceCmdEvent instance, and ``text`` is the body text to be
        parsed. The parser should updated the passed event instance and not return anything
        (the return value will be ignored). Any exceptions raised by the parser will be silently
        ignored (note that this means that the event's attributes may be partially initialized).

        """
        self.thread = thread
        self.reporting_cpu_id = int(cpu_id)
        self.timestamp = numeric(ts)
        self.name = name
        self.text = body
        self.fields = {}

        if parser:
            try:
                parser(self, self.text)
            except Exception:  # pylint: disable=broad-except
                # unknown format assume user does not care or know how to
                # parse self.text
                pass

    def __getattr__(self, name):
        try:
            return self.fields[name]
        except KeyError:
            raise AttributeError(name)

    def __str__(self):
        return 'TE({} @ {})'.format(self.name, self.timestamp)

    __repr__ = __str__

class DroppedEventsEvent(object):

    __slots__ = ['thread', 'reporting_cpu_id', 'timestamp', 'name', 'text', 'fields']

    def __init__(self, cpu_id):
        self.thread = None
        self.reporting_cpu_id = None
        self.timestamp = None
        self.name = 'DROPPED EVENTS DETECTED'
        self.text = None
        self.fields = {'cpu_id': int(cpu_id)}

    def __getattr__(self, name):
        try:
            return self.fields[name]
        except KeyError:
            raise AttributeError(name)

    def __str__(self):
        return 'DROPPED_EVENTS_ON_CPU{}'.format(self.cpu_id)

    __repr__ = __str__

def try_convert_to_numeric(v):
    try:
        if isiterable(v):
            return map(numeric, v)
        else:
            return numeric(v)
    except ValueError:
        return v

def default_body_parser(event, text):
    """
    Default parser to attempt to use to parser body text for the event (i.e. after
    the "header" common to all events has been parsed). This assumes that the body is
    a whitespace-separated list of key=value pairs. The parser will attempt to convert
    the value into a numeric type, and failing that, keep it as string.

    """
    parts = [e.rsplit(' ', 1) for e in text.strip().split('=')]
    parts = [p.strip() for p in chain.from_iterable(parts)]
    if not len(parts) % 2:
        i = iter(parts)
        for k, v in zip(i, i):
            try:
                v = int(v)
            except ValueError:
                pass
            event.fields[k] = v

def regex_body_parser(regex, flags=0):
    """
    Creates an event body parser form the specified regular expression (could be an
    ``re.RegexObject``, or a string). The regular expression should contain some named
    groups, as those will be extracted as the event attributes (unnamed groups and the
    reset of the match will be ignored).

    If the specified regex is a string, it will be compiled, in which case ``flags`` may
    be provided for the resulting regex object (see ``re`` standard module documentation).
    If regex is a pre-compiled object, flags will be ignored.

    """
    if isinstance(regex, basestring):
        regex = re.compile(regex, flags)

    def regex_parser_func(event, text):
        match = regex.search(text)
        if match:
            for k, v in match.groupdict().iteritems():
                try:
                    event.fields[k] = int(v)
                except ValueError:
                    event.fields[k] = v

    return regex_parser_func

def sched_switch_parser(event, text):
    """
    Sched switch output may be presented in a couple of different formats. One is handled
    by a regex. The other format can *almost* be handled by the default parser, if it
    weren't for the ``==>`` that appears in the middle.
    """
    if text.count('=') == 2:  # old format
        regex = re.compile(
            r'(?P<prev_comm>\S.*):(?P<prev_pid>\d+) \[(?P<prev_prio>\d+)\] (?P<status>\S+)'
            r' ==> '
            r'(?P<next_comm>\S.*):(?P<next_pid>\d+) \[(?P<next_prio>\d+)\]'
        )
        parser_func = regex_body_parser(regex)
        return parser_func(event, text)
    else:  # there are more than two "=" -- new format
        return default_body_parser(event, text.replace('==>', ''))

def sched_stat_parser(event, text):
    """
    sched_stat_* events unclude the units, "[ns]", in an otherwise
    regular key=value sequence; so the units  need to be stripped out first.
    """
    return default_body_parser(event, text.replace(' [ns]', ''))

def sched_wakeup_parser(event, text):
    regex = re.compile(r'(?P<comm>\S+):(?P<pid>\d+) \[(?P<prio>\d+)\] success=(?P<success>\d) CPU:(?P<cpu>\d+)')
    parse_func = regex_body_parser(regex)
    return parse_func(event, text)

# Maps event onto the corresponding parser for its body text. A parser may be
# a callable with signature
#
#   parser(event, bodytext)
#
# a re.RegexObject, or a string (in which case it will be compiled into a
# regex). In case of a string/regex, its named groups will be used to populate
# the event's attributes.
EVENT_PARSER_MAP = {
    'sched_stat_blocked': sched_stat_parser,
    'sched_stat_iowait': sched_stat_parser,
    'sched_stat_runtime': sched_stat_parser,
    'sched_stat_sleep': sched_stat_parser,
    'sched_stat_wait': sched_stat_parser,
    'sched_switch': sched_switch_parser,
    'sched_wakeup': sched_wakeup_parser,
    'sched_wakeup_new': sched_wakeup_parser,
}

TRACE_EVENT_REGEX = re.compile(r'^\s+(?P<thread>\S+.*?\S+)\s+\[(?P<cpu_id>\d+)\]\s+(?P<ts>[\d.]+):\s+'
                               r'(?P<name>[^:]+):\s+(?P<body>.*?)\s*$')

HEADER_REGEX = re.compile(r'^\s*(?:version|cpus)\s*=\s*([\d.]+)\s*$')

DROPPED_EVENTS_REGEX = re.compile(r'CPU:(?P<cpu_id>\d+) \[\d*\s*EVENTS DROPPED\]')

EMPTY_CPU_REGEX = re.compile(r'CPU \d+ is empty')

class TraceCmdParser(object):
    """
    A parser for textual representation of ftrace as reported by trace-cmd

    """

    def __init__(self, filter_markers=True, check_for_markers=True, events=None):
        """
        Initialize a new trace parser.

        :param filter_markers: Specifies whether the trace before the start
                               marker and after the stop marker should be
                               filtered out (so only events between the two
                               markers will be reported). This maybe overriden
                               based on `check_for_markers` parameter of
                               `parse()`
        :param check_for_markers: Check if the start/stop markers are present
                                  in the trace and ensure that `filter_markers`
                                  is `False` if they aren't
        :param events: A list of event names to be reported; if not specified,
                       all events will be reported.

        """
        self.filter_markers = filter_markers
        self.check_for_markers = check_for_markers
        self.events = events

    def parse(self, filepath):  # pylint: disable=too-many-branches,too-many-locals
        """
        This is a generator for the trace event stream.

        :param filepath: The path to the file containg text trace as reported
                         by trace-cmd
        """
        inside_maked_region = False
        filters = [re.compile('^{}$'.format(e)) for e in (self.events or [])]
        filter_markers = self.filter_markers
        if filter_markers and self.check_for_markers:
            with open(filepath) as fh:
                for line in fh:
                    if TRACE_MARKER_START in line:
                        break
                else:
                    # maker not found force filtering by marker to False
                    filter_markers = False

        with open(filepath) as fh:
            for line in fh:
                # if processing trace markers, skip marker lines as well as all
                # lines outside marked region
                if filter_markers:
                    if not inside_maked_region:
                        if TRACE_MARKER_START in line:
                            inside_maked_region = True
                        continue
                    elif TRACE_MARKER_STOP in line:
                        inside_maked_region = False
                        continue

                match = DROPPED_EVENTS_REGEX.search(line)
                if match:
                    yield DroppedEventsEvent(match.group('cpu_id'))
                    continue

                matched = False
                for rx in [HEADER_REGEX, EMPTY_CPU_REGEX]:
                    match = rx.search(line)
                    if match:
                        logger.debug(line.strip())
                        matched = True
                        break
                if matched:
                    continue

                match = TRACE_EVENT_REGEX.search(line)
                if not match:
                    logger.warning('Invalid trace event: "{}"'.format(line))
                    continue

                event_name = match.group('name')

                if filters:
                    found = False
                    for f in filters:
                        if f.search(event_name):
                            found = True
                            break
                    if not found:
                        continue

                body_parser = EVENT_PARSER_MAP.get(event_name, default_body_parser)
                if isinstance(body_parser, basestring) or isinstance(body_parser, re._pattern_type):  # pylint: disable=protected-access
                    body_parser = regex_body_parser(body_parser)
                yield TraceCmdEvent(parser=body_parser, **match.groupdict())

def trace_has_marker(filepath, max_lines_to_check=2000000):
    with open(filepath) as fh:
        for i, line in enumerate(fh):
            if TRACE_MARKER_START in line:
                return True
            if i >= max_lines_to_check:
                break
    return False
<|endoftext|>


<commit_before>import socket
import time
import picamera
import thread

print "Openning single-client H264 streaming server:"+8000
with picamera.PiCamera() as camera:
    camera.resolution = (640, 480)
    camera.framerate = 10
    camera.color_effects = (128,128)

    server_socket = socket.socket()
    server_socket.bind(('0.0.0.0', 8000))
    server_socket.listen(0)

    # Accept a single connection and make a file-like object out of it
    connection = server_socket.accept()[0].makefile('wb')
    try:
        camera.start_recording(connection, format='h264')
        camera.wait_recording(100000)
        camera.stop_recording()
    finally:
        camera.close()
        connection.close()
        server_socket.close()
        print 'Connection closed.  Camera released.'
<commit_msg>Using h264 stream server<commit_after>import socket
import time
import picamera
import thread

print "Openning single-client H264 streaming server:"+str(8000)
with picamera.PiCamera() as camera:
    camera.resolution = (640, 480)
    camera.framerate = 10
    camera.color_effects = (128,128)

    server_socket = socket.socket()
    server_socket.bind(('0.0.0.0', 8000))
    server_socket.listen(0)

    # Accept a single connection and make a file-like object out of it
    connection = server_socket.accept()[0].makefile('wb')
    try:
        camera.start_recording(connection, format='h264')
        camera.wait_recording(100000)
        camera.stop_recording()
    finally:
        camera.close()
        connection.close()
        server_socket.close()
        print 'Connection closed.  Camera released.'
<|endoftext|>


<commit_before>from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.template.defaultfilters import slugify

from markitup.fields import MarkupField

from wafer.kv.models import KeyValue

# constants to make things clearer elsewhere
ACCEPTED = 'A'
PENDING = 'P'
REJECTED = 'R'
CANCELLED = 'C'

# Utility functions used in the forms
def render_author(author):
    return '%s (%s)' % (author.userprofile.display_name(), author)

@python_2_unicode_compatible
class TalkType(models.Model):
    """A type of talk."""
    name = models.CharField(max_length=255)
    description = models.TextField(max_length=1024)
    order = models.IntegerField(default=1)
    disable_submission = models.BooleanField(default=False,
            help_text="Don't allow users to submit talks of this type.")

    def __str__(self):
        return u'%s' % (self.name,)

    class Meta:
        ordering = ['order', 'id']

    def css_class(self):
        """Return a string for use as a css class name"""
        # While css can represent complicated strings
        # using escaping, we want simplicity and obvious predictablity
        return u'talk-type-%s' % slugify(self.name)

    css_class.admin_order_field = 'name'
    css_class.short_description = 'CSS class name'

@python_2_unicode_compatible
class Talk(models.Model):

    class Meta:
        permissions = (
            ("view_all_talks", "Can see all talks"),
            ("edit_private_notes", "Can edit the private notes fields"),
        )

    TALK_STATUS = (
        (ACCEPTED, 'Accepted'),
        (REJECTED, 'Not Accepted'),
        (CANCELLED, 'Talk Cancelled'),
        (PENDING, 'Under Consideration'),
    )

    talk_id = models.AutoField(primary_key=True)
    talk_type = models.ForeignKey(TalkType, null=True)

    title = models.CharField(max_length=1024)

    abstract = MarkupField(
        help_text=_("Write two or three paragraphs describing your talk. "
                    "Who is your audience? What will they get out of it? "
                    "What will you cover?
"
                    "You can use Markdown syntax."))

    notes = models.TextField(
        null=True, blank=True,
        help_text=_("Any notes for the conference organisers?"))

    private_notes = models.TextField(
        null=True, blank=True,
        help_text=_("Note space for the conference organisers (not visible "
                    "to submitter)"))

    status = models.CharField(max_length=1, choices=TALK_STATUS,
                              default=PENDING)

    corresponding_author = models.ForeignKey(
        settings.AUTH_USER_MODEL, related_name='contact_talks',
        help_text=_(
            "The person submitting the talk (and who questions regarding the "
            "talk should be addressed to)."))

    authors = models.ManyToManyField(
        settings.AUTH_USER_MODEL, related_name='talks',
        help_text=_(
            "The speakers presenting the talk."))

    kv = models.ManyToManyField(KeyValue)

    def __str__(self):
        return u'%s: %s' % (self.corresponding_author, self.title)

    def get_absolute_url(self):
        return reverse('wafer_talk', args=(self.talk_id,))

    def get_corresponding_author_contact(self):
        email = self.corresponding_author.email
        profile = self.corresponding_author.userprofile
        if profile.contact_number:
            contact = profile.contact_number
        else:
            # Should we wrap this in a span for styling?
            contact = 'NO CONTACT INFO'
        return '%s - %s' % (email, contact)
    get_corresponding_author_contact.short_description = 'Contact Details'

    def get_corresponding_author_name(self):
        return render_author(self.corresponding_author)

    get_corresponding_author_name.admin_order_field = 'corresponding_author'
    get_corresponding_author_name.short_description = 'Corresponding Author'

    def get_authors_display_name(self):
        authors = list(self.authors.all())
        # Corresponding authors first
        authors.sort(
            key=lambda author: u'' if author == self.corresponding_author
                               else author.userprofile.display_name())
        names = [author.userprofile.display_name() for author in authors]
        if len(names) <= 2:
            return u' & '.join(names)
        return u'%s, et al.' % names[0]

    def get_in_schedule(self):
        if self.scheduleitem_set.all():
            return True
        return False

    get_in_schedule.short_description = 'Added to schedule'
    get_in_schedule.boolean = True

    def has_url(self):
        """Test if the talk has urls associated with it"""
        if self.talkurl_set.all():
            return True
        return False

    has_url.boolean = True

    # Helpful properties for the templates
    accepted = property(fget=lambda x: x.status == ACCEPTED)
    pending = property(fget=lambda x: x.status == PENDING)
    reject = property(fget=lambda x: x.status == REJECTED)
    cancelled = property(fget=lambda x: x.status == CANCELLED)

    def _is_among_authors(self, user):
        if self.corresponding_author.username == user.username:
            return True
        # not chaining with logical-or to avoid evaluation of the queryset
        return self.authors.filter(username=user.username).exists()

    def can_view(self, user):
        if user.has_perm('talks.view_all_talks'):
            return True
        if self._is_among_authors(user):
            return True
        if self.accepted:
            return True
        return False

    @classmethod
    def can_view_all(cls, user):
        return user.has_perm('talks.view_all_talks')

    def can_edit(self, user):
        if user.has_perm('talks.change_talk'):
            return True
        if self.pending:
            if self._is_among_authors(user):
                return True
        return False

class TalkUrl(models.Model):
    """An url to stuff relevant to the talk - videos, slides, etc.

       Note that these are explicitly not intended to be exposed to the
       user, but exist for use by the conference organisers."""

    description = models.CharField(max_length=256)
    url = models.URLField()
    talk = models.ForeignKey(Talk)
<commit_msg>PEP8 fixes.<commit_after>from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.template.defaultfilters import slugify

from markitup.fields import MarkupField

from wafer.kv.models import KeyValue

# constants to make things clearer elsewhere
ACCEPTED = 'A'
PENDING = 'P'
REJECTED = 'R'
CANCELLED = 'C'

# Utility functions used in the forms
def render_author(author):
    return '%s (%s)' % (author.userprofile.display_name(), author)

@python_2_unicode_compatible
class TalkType(models.Model):
    """A type of talk."""
    name = models.CharField(max_length=255)
    description = models.TextField(max_length=1024)
    order = models.IntegerField(default=1)
    disable_submission = models.BooleanField(
        default=False,
        help_text="Don't allow users to submit talks of this type.")

    def __str__(self):
        return u'%s' % (self.name,)

    class Meta:
        ordering = ['order', 'id']

    def css_class(self):
        """Return a string for use as a css class name"""
        # While css can represent complicated strings
        # using escaping, we want simplicity and obvious predictablity
        return u'talk-type-%s' % slugify(self.name)

    css_class.admin_order_field = 'name'
    css_class.short_description = 'CSS class name'

@python_2_unicode_compatible
class Talk(models.Model):

    class Meta:
        permissions = (
            ("view_all_talks", "Can see all talks"),
            ("edit_private_notes", "Can edit the private notes fields"),
        )

    TALK_STATUS = (
        (ACCEPTED, 'Accepted'),
        (REJECTED, 'Not Accepted'),
        (CANCELLED, 'Talk Cancelled'),
        (PENDING, 'Under Consideration'),
    )

    talk_id = models.AutoField(primary_key=True)
    talk_type = models.ForeignKey(TalkType, null=True)

    title = models.CharField(max_length=1024)

    abstract = MarkupField(
        help_text=_("Write two or three paragraphs describing your talk. "
                    "Who is your audience? What will they get out of it? "
                    "What will you cover?
"
                    "You can use Markdown syntax."))

    notes = models.TextField(
        null=True, blank=True,
        help_text=_("Any notes for the conference organisers?"))

    private_notes = models.TextField(
        null=True, blank=True,
        help_text=_("Note space for the conference organisers (not visible "
                    "to submitter)"))

    status = models.CharField(max_length=1, choices=TALK_STATUS,
                              default=PENDING)

    corresponding_author = models.ForeignKey(
        settings.AUTH_USER_MODEL, related_name='contact_talks',
        help_text=_(
            "The person submitting the talk (and who questions regarding the "
            "talk should be addressed to)."))

    authors = models.ManyToManyField(
        settings.AUTH_USER_MODEL, related_name='talks',
        help_text=_(
            "The speakers presenting the talk."))

    kv = models.ManyToManyField(KeyValue)

    def __str__(self):
        return u'%s: %s' % (self.corresponding_author, self.title)

    def get_absolute_url(self):
        return reverse('wafer_talk', args=(self.talk_id,))

    def get_corresponding_author_contact(self):
        email = self.corresponding_author.email
        profile = self.corresponding_author.userprofile
        if profile.contact_number:
            contact = profile.contact_number
        else:
            # Should we wrap this in a span for styling?
            contact = 'NO CONTACT INFO'
        return '%s - %s' % (email, contact)
    get_corresponding_author_contact.short_description = 'Contact Details'

    def get_corresponding_author_name(self):
        return render_author(self.corresponding_author)

    get_corresponding_author_name.admin_order_field = 'corresponding_author'
    get_corresponding_author_name.short_description = 'Corresponding Author'

    def get_authors_display_name(self):
        authors = list(self.authors.all())
        # Corresponding authors first
        authors.sort(
            key=lambda author: u'' if author == self.corresponding_author
                               else author.userprofile.display_name())
        names = [author.userprofile.display_name() for author in authors]
        if len(names) <= 2:
            return u' & '.join(names)
        return u'%s, et al.' % names[0]

    def get_in_schedule(self):
        if self.scheduleitem_set.all():
            return True
        return False

    get_in_schedule.short_description = 'Added to schedule'
    get_in_schedule.boolean = True

    def has_url(self):
        """Test if the talk has urls associated with it"""
        if self.talkurl_set.all():
            return True
        return False

    has_url.boolean = True

    # Helpful properties for the templates
    accepted = property(fget=lambda x: x.status == ACCEPTED)
    pending = property(fget=lambda x: x.status == PENDING)
    reject = property(fget=lambda x: x.status == REJECTED)
    cancelled = property(fget=lambda x: x.status == CANCELLED)

    def _is_among_authors(self, user):
        if self.corresponding_author.username == user.username:
            return True
        # not chaining with logical-or to avoid evaluation of the queryset
        return self.authors.filter(username=user.username).exists()

    def can_view(self, user):
        if user.has_perm('talks.view_all_talks'):
            return True
        if self._is_among_authors(user):
            return True
        if self.accepted:
            return True
        return False

    @classmethod
    def can_view_all(cls, user):
        return user.has_perm('talks.view_all_talks')

    def can_edit(self, user):
        if user.has_perm('talks.change_talk'):
            return True
        if self.pending:
            if self._is_among_authors(user):
                return True
        return False

class TalkUrl(models.Model):
    """An url to stuff relevant to the talk - videos, slides, etc.

       Note that these are explicitly not intended to be exposed to the
       user, but exist for use by the conference organisers."""

    description = models.CharField(max_length=256)
    url = models.URLField()
    talk = models.ForeignKey(Talk)
<|endoftext|>


<commit_before>import math

from pyjamas.ui import Event
from pyjamas.ui.Button import Button
from pyjamas.ui.DialogBox import DialogBox
from pyjamas.ui.DockPanel import DockPanel
from pyjamas.ui.FlexTable import FlexTable
from pyjamas.ui import HasHorizontalAlignment
from pyjamas.ui.HorizontalPanel import HorizontalPanel
from pyjamas.ui.ListBox import ListBox
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.chart.GChart import GChart
from pyjamas.chart import AnnotationLocation
from pyjamas.chart import SymbolType
from pyjamas.chart import TouchedPointUpdateOption

LABEL_COL = 0;  # for the label/object pairs
OBJECT_COL = 1; # associated with the property
N_COLS = 2;     # editing form

N_SLICES = 5

"""*
* This example displays a pie chart that, when you click on any slice,
* opens a dialog that lets you modify the color, shading pattern, and
* size of of that slice. That dialog also contains "Prev Slice" and "Next
* Slice" buttons that, by invoking GChart's <tt>touch</tt> method,
* programmatically emulate the user sequentially "touching" (selecting)
* slices with their mouse.
*
*

*
* The slice properties dialog in this example is an ordinary GWT modal
* dialog (a <tt>DialogBox</tt> with modal=True, autoHide=True). It self.gets
* GChart to inform it of click events on the chart by implementing the
* standard GWT <tt>ClickHandler</tt> interface, and then passing
* itself to GChart's <tt>addClickHandler</tt> method. The dialog's
* <tt>onClick</tt> method shows itself (via <tt>DialogBox.show</tt>)
* and then uses GChart's <tt>getTouchedPoint</tt> method to self.get a
* reference to the clicked-on slice that it uses to load that slice's
* properties into the form. As the user makes changes via the form,
* they are copied back into the chart and the chart's <tt>update</tt>
* method is invoked to immediately show the changes on the chart.
*

*
* GChart's "currently touched point" (available via
* <tt>getTouchedPoint</tt>) ordinarily moves in lock-step with current
* mouse location, and thus falls short of a True point selection
* capability. This example works around this limitation by exploiting
* the fact that a GWT modal dialog "eats" all mouse events while it is
* open. So, when the modal dialog is opened, the mouse location seen by
* GChart, and hence the "currently touched" point is frozen. This lets
* us use GChart's currently touched point as if it were the "selected"
* point in this example.
*
"""

"""
* A helper class to facilitate property editing via drop-down
* lists in this example (there's nothing GChart-specific here):
"""
class ObjectSelectorDropdownList(ListBox):

    def __init__(self, labelObjectPairs):
        ListBox.__init__(self)
        self.labelObjectPairs = labelObjectPairs
        self.setVisibleItemCount(1); # makes it a drop-down list
        # add each label as an item on the drop-down list
        for i in range(len(labelObjectPairs)):
            self.addItem( labelObjectPairs[i][LABEL_COL])

    #  returns object at given index
    def getObject(self, index):
        result = self.labelObjectPairs[index][OBJECT_COL]
        return result

    # returns the currently selected object in the drop-down list
    def getSelectedObject(self):
        result = self.getObject(getSelectedIndex())
        return result

    # makes given object the selected one (assumes it's on list--once)
    def setSelectedObject(self, selectedObject):
        for i in range(len(self.labelObjectPairs)):
            if selectedObject == labelObjectPairs[i][OBJECT_COL]:
                self.setSelectedIndex(i)
                return

        raise IllegalArgumentException(
        "selectedObject specified was not found on the labelObjectPairs list.")

    # number of label, object pairs
    def getNObjects(self):
        return len(self.labelObjectPairs)

 # class ObjectSelectorDropdownList
#
# holds color information associated with color selection drop-down
class ColorSpec:
    def __init__(self, backgroundColor, borderColor):
        self.backgroundColor = backgroundColor
        self.borderColor =borderColor

# the modal dialog that pops up when they click on a slice to edit it
class SliceEditor(DialogBox):
    def __init__(self, chart):
        """ DialogBox CSS Style self.settings used with this example for reference:

        Note: These simplified CSS styles make the dialog's title bar behave a
        little quirkily in IE6 when dragging. For more sophisticated CSS that
        fixes this problem (and also provides a more professional look) see the
        CSS tab of the DialogBox example in the GWT  Showcase of
        Features (I just didn't want to copy 5 pages of obscure DialogBox
        CSS into what is after all a Client-side GChart example).

        .gwt-DialogBox .Caption {
            font-size: 18
            color: #eef
            background: #00f repeat-x 0px -2003px
            padding: 4px 4px 4px 8px
            cursor: default
            border-bottom: 2px solid #008
            border-top: 3px solid #448

        .gwt-DialogBox .dialogContent {
            border: 1px solid #008
            background: #ddd
            padding: 3px

        """
        DialogBox.__init__(self, autoHide=True, modal=True)
        self.chart = chart
        self.isFirstTime = True
        mainPanel = VerticalPanel()
        propertyForm = FlexTable()
        commandBar = DockPanel()
        sliceSwitcher = HorizontalPanel()
        self.prevSlice = Button("<Prev Slice")
        self.nextSlice = Button("Next Slice>")
        self.closeButton = Button("Close")

        self.chart.colorSelector.addChangeListener(self)
        self.chart.sliceSizeSelector.addChangeListener(self)
        self.chart.shadingSelector.addChangeListener(self)

        def onChange(self, sender):
            self.chart.copyFormPropertiesIntoChart(self.chart.getTouchedPoint())
            # Changes in slice size can place a different, or no, slice under
            # GChart's "current mouse position". Such chart changes "underneath the
            # mouse" would normally result in a change in the touched point; the
            # TOUCHED_POINT_LOCKED update option keeps that from happening.
            self.chart.update(TouchedPointUpdateOption.TOUCHED_POINT_LOCKED)

        # slice properties table (slice color, shading and size)
        propertyForm.setText(  0, 0, "Color:")
        propertyForm.setWidget(0, 1, self.chart.colorSelector)
        propertyForm.setText(  1, 0, "Shading Pattern:")
        propertyForm.setWidget(1, 1, self.chart.shadingSelector)
        propertyForm.setText(  2, 0, "Slice Size:")
        propertyForm.setWidget(2, 1, self.chart.sliceSizeSelector)
        # add additional properties here, if desired

        # buttons for changing the selected slice from the form
        sliceSwitcher.add(self.prevSlice)
        sliceSwitcher.add(self.nextSlice)

        commandBar.add(sliceSwitcher, DockPanel.WEST)
        commandBar.add(closeButton, DockPanel.EAST)
        commandBar.setCellHorizontalAlignment(self.closeButton,
                        HasHorizontalAlignment.ALIGN_RIGHT)
        commandBar.setWidth("100%"); # pushes close button to right edge

        # create main form and place it in DialogBox
        mainPanel.add(propertyForm)
        mainPanel.add(commandBar)
        self.add(mainPanel);  # add the DialogBox' single, defining, widget

    # loads properties associated with point/slice into form
    def copyChartPropertiesIntoForm(self, p):
        # dialog title bar caption:
        self.setText("Slice " + self.getCurveIndex(p.getParent()) +
                                    " Properties")
        colorSelector.setSelectedObject(
        self.getColorSpec( p.getParent().getSymbol().getBackgroundColor(),
                           p.getParent().getSymbol().getBorderColor()))
        shadingSelector.setSelectedObject(
                        p.getParent().getSymbol().getSymbolType())
        sliceSize = math.round(100*p.getParent().getSymbol().getPieSliceSize())
        sliceSizeSelector.setSelectedObject( int(sliceSize))

    # saves current form self.settings into associated point/slice of chart
    def copyFormPropertiesIntoChart(self, p):
        p.getParent().getSymbol().setBackgroundColor(
                    colorSelector.getSelectedObject().backgroundColor)
        p.getParent().getSymbol().setBorderColor(
                    colorSelector.getSelectedObject().borderColor)

        # selection flips border and background colors
        p.getParent().getSymbol().setHoverSelectionBorderColor(
                    colorSelector.getSelectedObject().backgroundColor)
        p.getParent().getSymbol().setHoverSelectionBackgroundColor(
                    colorSelector.getSelectedObject().borderColor)
        p.getParent().getSymbol().setSymbolType(
                                shadingSelector.getSelectedObject())
        sliceSize = int(sliceSizeSelector.getSelectedObject())
        p.getParent().getSymbol().setPieSliceSize(sliceSize/100.)

    def onClick(self, sender):
        if sender == self.prevSlice:
            self.chart.onClickPrevSlice(sender)
        elif sender == self.nextSlice:
            self.chart.onClickNextSlice(sender)
        else:
            self.onClickClose(sender)

    def onClickClose(self, event):
        self.hide()
        self.chart.touch(None);  # clears any selected slice
        self.chart.update(TouchedPointUpdateOption.TOUCHED_POINT_LOCKED)

    # Retrieves an existing ColorSpec object reference, given its colors
    def getColorSpec(self, backgroundColor, borderColor):
        for i in range(colorSelector.getNObjects()):
            cs =  self.chart.colorSelector.getObject(i)
            if backgroundColor == cs.backgroundColor and  borderColor == cs.borderColor:
                return cs

        raise IllegalArgumentException(
        "Attempt to retrieve a non-existing color combination.")

    def onClick(self, event):
        # don't shown property editor if they clicked on nothing
        if None == self.getTouchedPoint():
            return

        # load properties of clicked-on slice into form
        copyChartPropertiesIntoForm(getTouchedPoint())
        if isFirstTime:
            # initially put upper left corner wherever they clicked...
            self.setPopupPosition(
            Window.getScrollLeft()+Event.getCurrentEvent().getClientX(),
            Window.getScrollTop() + Event.getCurrentEvent().getClientY())
            self.show()
            self.isFirstTime= False

        else:
            # ...thereafter, just stay whereever they dragged it to
            self.show()

class GChartExample20 (GChart):

    # the single dialog box that self.gets used to edit any slice
    def __init__(self):

        # labels/values for color selection drop-down list:
        self.colorSelector = ObjectSelectorDropdownList( \
                            [["Red", ColorSpec("red", "#F88")],
                            ["Fuchsia", ColorSpec("#F0F", "#F8F")],
                            ["Lime", ColorSpec("#0F0", "#8F8")],
                            ["Blue", ColorSpec("#00F", "#88F")],
                            ["Aqua", ColorSpec("#0FF", "#8FF")],
                            ["Maroon", ColorSpec("#800", "#C88")],
                            ["Purple", ColorSpec("#808", "#C8C")],
                            ["Green", ColorSpec("#080", "#8C8")],
                            ["Olive", ColorSpec("#880", "#CC8")],
                            ["Navy", ColorSpec("#008", "#88C")],
                            ["Teal", ColorSpec("#088", "#8CC")]])

        # labels/values for slice shading pattern drop-down list
        self.shadingSelector = ObjectSelectorDropdownList( \
            [["Vertical shading", SymbolType.PIE_SLICE_VERTICAL_SHADING],
            ["Horizontal shading", SymbolType.PIE_SLICE_HORIZONTAL_SHADING],
            ["Optimal shading", SymbolType.PIE_SLICE_OPTIMAL_SHADING]])

        # labels/values for pie slice size (as percentage) drop-down list
        self.sliceSizeSelector = ObjectSelectorDropdownList([
                                            ["0%", int(0)],
                                            ["5%", int(5)],
                                            ["10%", int(10)],
                                            ["15%", int(15)],
                                            ["20%", int(20)],
                                            ["25%", int(25)],
                                            ["30%", int(30)],
                                            ["35%", int(35)],
                                            ["40%", int(40)],
                                            ["45%", int(45)],
                                            ["50%", int(50)],
                                            ["55%", int(55)],
                                            ["60%", int(60)],
                                            ["65%", int(65)],
                                            ["70%", int(70)],
                                            ["75%", int(75)],
                                            ["80%", int(80)],
                                            ["85%", int(85)],
                                            ["90%", int(90)],
                                            ["95%", int(95)],
                                            ["100%", int(100)]])

        self.theSliceEditor = SliceEditor(self)

        SOURCE_CODE_LINK = \
        "Source code"
        self.setChartSize(100, 100)
        self.setBorderStyle("none")
        self.setChartTitle("<big>Click pie to edit!</big>")
        self.setChartTitleThickness(20)
        self.setChartFootnotes(SOURCE_CODE_LINK)
        self.setChartFootnotesThickness(20)
        # initial slice sizes
        initSliceSize = [0.3, 0.2, 0.1, 0.2, 0.2]

        self.addClickListener(self.theSliceEditor)

        for iCurve in range(N_SLICES):
            self.addCurve()
            self.getCurve().getSymbol().setBorderWidth(1)
            self.getCurve().getSymbol().setFillThickness(4)
            self.getCurve().getSymbol().setFillSpacing(4)
            self.getCurve().getSymbol().setHoverLocation(
            AnnotationLocation.ON_PIE_ARC)
            self.getCurve().getSymbol().setBorderColor(
                    self.colorSelector.getObject(iCurve).borderColor)
            self.getCurve().getSymbol().setBackgroundColor(
                    self.colorSelector.getObject(iCurve).backgroundColor)
            # selection flips border and background colors
            self.getCurve().getSymbol().setHoverSelectionBackgroundColor(
                    self.colorSelector.getObject(iCurve).borderColor)
            self.getCurve().getSymbol().setHoverSelectionBorderColor(
                    self.colorSelector.getObject(iCurve).backgroundColor)
            self.getCurve().getSymbol().setSymbolType(
                    SymbolType.PIE_SLICE_OPTIMAL_SHADING)
            self.getCurve().getSymbol().setPieSliceSize(initSliceSize[iCurve])
            self.getCurve().getSymbol().setModelHeight(1.0); #diameter = yMax-yMin
            self.getCurve().getSymbol().setModelWidth(0)
            self.getCurve().addPoint(0.5, 0.5);  # pie centered in world units

        self.getXAxis().setAxisMin(0);  # so 0.5,0.5 (see above) centers pie
        self.getXAxis().setAxisMax(1)
        self.getYAxis().setAxisMin(0)
        self.getYAxis().setAxisMax(1)
        self.getXAxis().setHasGridlines(False); # hides axes, ticks, etc.
        self.getXAxis().setAxisVisible(False);  # (not needed for the pie)
        self.getXAxis().setTickCount(0)
        self.getYAxis().setHasGridlines(False)
        self.getYAxis().setAxisVisible(False)
        self.getYAxis().setTickCount(0)
        self.update()

    def onClickPrevSlice(self, event):
        iCurve = self.getCurveIndex(self.getTouchedCurve())
        if (iCurve == 0) :
            iPrev = self.getNCurves()-1
        else:
            iPrev = (iCurve-1)
        self.touch(self.getCurve(iPrev).getPoint(0))
        self.copyChartPropertiesIntoForm(self.getTouchedPoint())
        self.update(TouchedPointUpdateOption.TOUCHED_POINT_LOCKED)

    def onClickNextSlice(self, event):
        iCurve = self.getCurveIndex(self.getTouchedCurve())
        if (iCurve+1 == self.getNCurves()) :
            iNext = 0
        else:
            iNext = (iCurve+1)
        self.touch(self.getCurve(iNext).getPoint(0))
        self.copyChartPropertiesIntoForm(self.getTouchedPoint())
        self.update(TouchedPointUpdateOption.TOUCHED_POINT_LOCKED)

<commit_msg>more gchart update<commit_after>import math

from pyjamas.ui import Event
from pyjamas.ui.Button import Button
from pyjamas.ui.DialogBox import DialogBox
from pyjamas.ui.DockPanel import DockPanel
from pyjamas.ui.FlexTable import FlexTable
from pyjamas.ui import HasHorizontalAlignment
from pyjamas.ui.HorizontalPanel import HorizontalPanel
from pyjamas.ui.ListBox import ListBox
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.chart.GChart import GChart
from pyjamas.chart import AnnotationLocation
from pyjamas.chart import SymbolType
from pyjamas.chart import TouchedPointUpdateOption

LABEL_COL = 0;  # for the label/object pairs
OBJECT_COL = 1; # associated with the property
N_COLS = 2;     # editing form

N_SLICES = 5

"""*
* This example displays a pie chart that, when you click on any slice,
* opens a dialog that lets you modify the color, shading pattern, and
* size of of that slice. That dialog also contains "Prev Slice" and "Next
* Slice" buttons that, by invoking GChart's <tt>touch</tt> method,
* programmatically emulate the user sequentially "touching" (selecting)
* slices with their mouse.
*
*

*
* The slice properties dialog in this example is an ordinary GWT modal
* dialog (a <tt>DialogBox</tt> with modal=True, autoHide=True). It self.gets
* GChart to inform it of click events on the chart by implementing the
* standard GWT <tt>ClickHandler</tt> interface, and then passing
* itself to GChart's <tt>addClickHandler</tt> method. The dialog's
* <tt>onClick</tt> method shows itself (via <tt>DialogBox.show</tt>)
* and then uses GChart's <tt>getTouchedPoint</tt> method to self.get a
* reference to the clicked-on slice that it uses to load that slice's
* properties into the form. As the user makes changes via the form,
* they are copied back into the chart and the chart's <tt>update</tt>
* method is invoked to immediately show the changes on the chart.
*

*
* GChart's "currently touched point" (available via
* <tt>getTouchedPoint</tt>) ordinarily moves in lock-step with current
* mouse location, and thus falls short of a True point selection
* capability. This example works around this limitation by exploiting
* the fact that a GWT modal dialog "eats" all mouse events while it is
* open. So, when the modal dialog is opened, the mouse location seen by
* GChart, and hence the "currently touched" point is frozen. This lets
* us use GChart's currently touched point as if it were the "selected"
* point in this example.
*
"""

"""
* A helper class to facilitate property editing via drop-down
* lists in this example (there's nothing GChart-specific here):
"""
class ObjectSelectorDropdownList(ListBox):

    def __init__(self, labelObjectPairs):
        ListBox.__init__(self)
        self.labelObjectPairs = labelObjectPairs
        self.setVisibleItemCount(1); # makes it a drop-down list
        # add each label as an item on the drop-down list
        for i in range(len(labelObjectPairs)):
            self.addItem( labelObjectPairs[i][LABEL_COL])

    #  returns object at given index
    def getObject(self, index):
        result = self.labelObjectPairs[index][OBJECT_COL]
        return result

    # returns the currently selected object in the drop-down list
    def getSelectedObject(self):
        result = self.getObject(getSelectedIndex())
        return result

    # makes given object the selected one (assumes it's on list--once)
    def setSelectedObject(self, selectedObject):
        for i in range(len(self.labelObjectPairs)):
            if selectedObject == labelObjectPairs[i][OBJECT_COL]:
                self.setSelectedIndex(i)
                return

        raise IllegalArgumentException(
        "selectedObject specified was not found on the labelObjectPairs list.")

    # number of label, object pairs
    def getNObjects(self):
        return len(self.labelObjectPairs)

 # class ObjectSelectorDropdownList
#
# holds color information associated with color selection drop-down
class ColorSpec:
    def __init__(self, backgroundColor, borderColor):
        self.backgroundColor = backgroundColor
        self.borderColor =borderColor

# the modal dialog that pops up when they click on a slice to edit it
class SliceEditor(DialogBox):
    def __init__(self, chart):
        """ DialogBox CSS Style self.settings used with this example for reference:

        Note: These simplified CSS styles make the dialog's title bar behave a
        little quirkily in IE6 when dragging. For more sophisticated CSS that
        fixes this problem (and also provides a more professional look) see the
        CSS tab of the DialogBox example in the GWT  Showcase of
        Features (I just didn't want to copy 5 pages of obscure DialogBox
        CSS into what is after all a Client-side GChart example).

        .gwt-DialogBox .Caption {
            font-size: 18
            color: #eef
            background: #00f repeat-x 0px -2003px
            padding: 4px 4px 4px 8px
            cursor: default
            border-bottom: 2px solid #008
            border-top: 3px solid #448

        .gwt-DialogBox .dialogContent {
            border: 1px solid #008
            background: #ddd
            padding: 3px

        """
        DialogBox.__init__(self, autoHide=True, modal=True)
        self.chart = chart
        self.isFirstTime = True
        mainPanel = VerticalPanel()
        propertyForm = FlexTable()
        commandBar = DockPanel()
        sliceSwitcher = HorizontalPanel()
        self.prevSlice = Button("<Prev Slice")
        self.nextSlice = Button("Next Slice>")
        self.closeButton = Button("Close")

        self.chart.colorSelector.addChangeListener(self)
        self.chart.sliceSizeSelector.addChangeListener(self)
        self.chart.shadingSelector.addChangeListener(self)

        def onChange(self, sender):
            self.chart.copyFormPropertiesIntoChart(self.chart.getTouchedPoint())
            # Changes in slice size can place a different, or no, slice under
            # GChart's "current mouse position". Such chart changes "underneath the
            # mouse" would normally result in a change in the touched point; the
            # TOUCHED_POINT_LOCKED update option keeps that from happening.
            self.chart.update(TouchedPointUpdateOption.TOUCHED_POINT_LOCKED)

        # slice properties table (slice color, shading and size)
        propertyForm.setText(  0, 0, "Color:")
        propertyForm.setWidget(0, 1, self.chart.colorSelector)
        propertyForm.setText(  1, 0, "Shading Pattern:")
        propertyForm.setWidget(1, 1, self.chart.shadingSelector)
        propertyForm.setText(  2, 0, "Slice Size:")
        propertyForm.setWidget(2, 1, self.chart.sliceSizeSelector)
        # add additional properties here, if desired

        # buttons for changing the selected slice from the form
        sliceSwitcher.add(self.prevSlice)
        sliceSwitcher.add(self.nextSlice)

        commandBar.add(sliceSwitcher, DockPanel.WEST)
        commandBar.add(self.closeButton, DockPanel.EAST)
        commandBar.setCellHorizontalAlignment(self.closeButton,
                        HasHorizontalAlignment.ALIGN_RIGHT)
        commandBar.setWidth("100%"); # pushes close button to right edge

        # create main form and place it in DialogBox
        mainPanel.add(propertyForm)
        mainPanel.add(commandBar)
        self.add(mainPanel);  # add the DialogBox' single, defining, widget

    # loads properties associated with point/slice into form
    def copyChartPropertiesIntoForm(self, p):
        # dialog title bar caption:
        self.setText("Slice " + self.getCurveIndex(p.getParent()) +
                                    " Properties")
        colorSelector.setSelectedObject(
        self.getColorSpec( p.getParent().getSymbol().getBackgroundColor(),
                           p.getParent().getSymbol().getBorderColor()))
        shadingSelector.setSelectedObject(
                        p.getParent().getSymbol().getSymbolType())
        sliceSize = math.round(100*p.getParent().getSymbol().getPieSliceSize())
        sliceSizeSelector.setSelectedObject( int(sliceSize))

    # saves current form self.settings into associated point/slice of chart
    def copyFormPropertiesIntoChart(self, p):
        p.getParent().getSymbol().setBackgroundColor(
                    colorSelector.getSelectedObject().backgroundColor)
        p.getParent().getSymbol().setBorderColor(
                    colorSelector.getSelectedObject().borderColor)

        # selection flips border and background colors
        p.getParent().getSymbol().setHoverSelectionBorderColor(
                    colorSelector.getSelectedObject().backgroundColor)
        p.getParent().getSymbol().setHoverSelectionBackgroundColor(
                    colorSelector.getSelectedObject().borderColor)
        p.getParent().getSymbol().setSymbolType(
                                shadingSelector.getSelectedObject())
        sliceSize = int(sliceSizeSelector.getSelectedObject())
        p.getParent().getSymbol().setPieSliceSize(sliceSize/100.)

    def onClick(self, sender):
        if sender == self.prevSlice:
            self.chart.onClickPrevSlice(sender)
        elif sender == self.nextSlice:
            self.chart.onClickNextSlice(sender)
        else:
            self.onClickClose(sender)

    def onClickClose(self, event):
        self.hide()
        self.chart.touch(None);  # clears any selected slice
        self.chart.update(TouchedPointUpdateOption.TOUCHED_POINT_LOCKED)

    # Retrieves an existing ColorSpec object reference, given its colors
    def getColorSpec(self, backgroundColor, borderColor):
        for i in range(colorSelector.getNObjects()):
            cs =  self.chart.colorSelector.getObject(i)
            if backgroundColor == cs.backgroundColor and  borderColor == cs.borderColor:
                return cs

        raise IllegalArgumentException(
        "Attempt to retrieve a non-existing color combination.")

    def onClick(self, event):
        # don't shown property editor if they clicked on nothing
        if None == self.getTouchedPoint():
            return

        # load properties of clicked-on slice into form
        copyChartPropertiesIntoForm(getTouchedPoint())
        if isFirstTime:
            # initially put upper left corner wherever they clicked...
            self.setPopupPosition(
            Window.getScrollLeft()+Event.getCurrentEvent().getClientX(),
            Window.getScrollTop() + Event.getCurrentEvent().getClientY())
            self.show()
            self.isFirstTime= False

        else:
            # ...thereafter, just stay whereever they dragged it to
            self.show()

class GChartExample20 (GChart):

    # the single dialog box that self.gets used to edit any slice
    def __init__(self):

        # labels/values for color selection drop-down list:
        self.colorSelector = ObjectSelectorDropdownList( \
                            [["Red", ColorSpec("red", "#F88")],
                            ["Fuchsia", ColorSpec("#F0F", "#F8F")],
                            ["Lime", ColorSpec("#0F0", "#8F8")],
                            ["Blue", ColorSpec("#00F", "#88F")],
                            ["Aqua", ColorSpec("#0FF", "#8FF")],
                            ["Maroon", ColorSpec("#800", "#C88")],
                            ["Purple", ColorSpec("#808", "#C8C")],
                            ["Green", ColorSpec("#080", "#8C8")],
                            ["Olive", ColorSpec("#880", "#CC8")],
                            ["Navy", ColorSpec("#008", "#88C")],
                            ["Teal", ColorSpec("#088", "#8CC")]])

        # labels/values for slice shading pattern drop-down list
        self.shadingSelector = ObjectSelectorDropdownList( \
            [["Vertical shading", SymbolType.PIE_SLICE_VERTICAL_SHADING],
            ["Horizontal shading", SymbolType.PIE_SLICE_HORIZONTAL_SHADING],
            ["Optimal shading", SymbolType.PIE_SLICE_OPTIMAL_SHADING]])

        # labels/values for pie slice size (as percentage) drop-down list
        self.sliceSizeSelector = ObjectSelectorDropdownList([
                                            ["0%", int(0)],
                                            ["5%", int(5)],
                                            ["10%", int(10)],
                                            ["15%", int(15)],
                                            ["20%", int(20)],
                                            ["25%", int(25)],
                                            ["30%", int(30)],
                                            ["35%", int(35)],
                                            ["40%", int(40)],
                                            ["45%", int(45)],
                                            ["50%", int(50)],
                                            ["55%", int(55)],
                                            ["60%", int(60)],
                                            ["65%", int(65)],
                                            ["70%", int(70)],
                                            ["75%", int(75)],
                                            ["80%", int(80)],
                                            ["85%", int(85)],
                                            ["90%", int(90)],
                                            ["95%", int(95)],
                                            ["100%", int(100)]])

        self.theSliceEditor = SliceEditor(self)

        SOURCE_CODE_LINK = \
        "Source code"
        self.setChartSize(100, 100)
        self.setBorderStyle("none")
        self.setChartTitle("<big>Click pie to edit!</big>")
        self.setChartTitleThickness(20)
        self.setChartFootnotes(SOURCE_CODE_LINK)
        self.setChartFootnotesThickness(20)
        # initial slice sizes
        initSliceSize = [0.3, 0.2, 0.1, 0.2, 0.2]

        self.addClickListener(self.theSliceEditor)

        for iCurve in range(N_SLICES):
            self.addCurve()
            self.getCurve().getSymbol().setBorderWidth(1)
            self.getCurve().getSymbol().setFillThickness(4)
            self.getCurve().getSymbol().setFillSpacing(4)
            self.getCurve().getSymbol().setHoverLocation(
            AnnotationLocation.ON_PIE_ARC)
            self.getCurve().getSymbol().setBorderColor(
                    self.colorSelector.getObject(iCurve).borderColor)
            self.getCurve().getSymbol().setBackgroundColor(
                    self.colorSelector.getObject(iCurve).backgroundColor)
            # selection flips border and background colors
            self.getCurve().getSymbol().setHoverSelectionBackgroundColor(
                    self.colorSelector.getObject(iCurve).borderColor)
            self.getCurve().getSymbol().setHoverSelectionBorderColor(
                    self.colorSelector.getObject(iCurve).backgroundColor)
            self.getCurve().getSymbol().setSymbolType(
                    SymbolType.PIE_SLICE_OPTIMAL_SHADING)
            self.getCurve().getSymbol().setPieSliceSize(initSliceSize[iCurve])
            self.getCurve().getSymbol().setModelHeight(1.0); #diameter = yMax-yMin
            self.getCurve().getSymbol().setModelWidth(0)
            self.getCurve().addPoint(0.5, 0.5);  # pie centered in world units

        self.getXAxis().setAxisMin(0);  # so 0.5,0.5 (see above) centers pie
        self.getXAxis().setAxisMax(1)
        self.getYAxis().setAxisMin(0)
        self.getYAxis().setAxisMax(1)
        self.getXAxis().setHasGridlines(False); # hides axes, ticks, etc.
        self.getXAxis().setAxisVisible(False);  # (not needed for the pie)
        self.getXAxis().setTickCount(0)
        self.getYAxis().setHasGridlines(False)
        self.getYAxis().setAxisVisible(False)
        self.getYAxis().setTickCount(0)
        self.update()

    def onClickPrevSlice(self, event):
        iCurve = self.getCurveIndex(self.getTouchedCurve())
        if (iCurve == 0) :
            iPrev = self.getNCurves()-1
        else:
            iPrev = (iCurve-1)
        self.touch(self.getCurve(iPrev).getPoint(0))
        self.copyChartPropertiesIntoForm(self.getTouchedPoint())
        self.update(TouchedPointUpdateOption.TOUCHED_POINT_LOCKED)

    def onClickNextSlice(self, event):
        iCurve = self.getCurveIndex(self.getTouchedCurve())
        if (iCurve+1 == self.getNCurves()) :
            iNext = 0
        else:
            iNext = (iCurve+1)
        self.touch(self.getCurve(iNext).getPoint(0))
        self.copyChartPropertiesIntoForm(self.getTouchedPoint())
        self.update(TouchedPointUpdateOption.TOUCHED_POINT_LOCKED)

<|endoftext|>


<commit_before>#!/usr/bin/env python
'''
    Quick and dirty create application check for v3
'''

# Adding the ignore because it does not like the naming of the script
# to be different than the class name
# pylint: disable=invalid-name

import subprocess
import json
import time
import re
import urllib2
import os
import atexit
import shutil
import string
import random
import argparse
import datetime

# Our jenkins server does not include these rpms.
# In the future we might move this to a container where these
# libs might exist
#pylint: disable=import-error
from openshift_tools.monitoring.zagg_sender import ZaggSender

# pylint: disable=bare-except
def cleanup_file(inc_file):
    ''' clean up '''
    try:
        os.unlink(inc_file)
    except:
        pass

def copy_kubeconfig(config):
    ''' make a copy of the kubeconfig '''
    file_name = os.path.join('/tmp',
                             ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7)))
    shutil.copy(config, file_name)
    atexit.register(cleanup_file, file_name)

    return file_name

class OpenShiftOC(object):
    ''' Class to wrap the oc command line tools '''
    def __init__(self, namespace, kubeconfig, args, verbose=False):
        ''' Constructor for OpenShiftOC '''
        self.namespace = namespace
        self.verbose = verbose
        self.kubeconfig = kubeconfig
        self.args = args

    def get_pod(self):
        '''return a pod by name'''
        pods = self.get_pods()
        podname = pod_name(self.args.name)
        # this will match on build pods but not deploy pods
        regex = re.compile('%s-[0-9]-[a-z0-9]{5}$' % podname)
        for pod in pods['items']:
            results = regex.search(pod['metadata']['name'])
            if results:
                # only report on running build pods, we'll wait if build pod is pending
                if "build" in pod['metadata']['name'] and pod['status']['phase'] != 'Running':
                    continue
                else: return pod

    def get_pods(self):
        '''return all pods '''
        cmd = ['get', 'pods', '--no-headers', '-o', 'json', '-n', self.namespace]
        results = self.oc_cmd(cmd)

        return json.loads(results)

    def new_app(self, path):
        '''run new-app '''
        cmd = ['new-app', path, '-n', self.namespace]
        return self.oc_cmd(cmd)

    def delete_project(self):
        '''delete project '''
        cmd = ['delete', 'project', self.namespace]
        results = self.oc_cmd(cmd)
        time.sleep(5)
        return results

    def new_project(self):
        '''create new project '''
        version = self.get_version()
        cmd = ['new-project', self.namespace]
        if "v3.2" in version:  ## remove this after BZ1333049 resolved in OSE
            rval = self.oadm_cmd(cmd)
        else:
            rval = self.oc_cmd(cmd)
        return rval

    def get_logs(self):
        '''get all pod logs'''
        pods = self.get_pods()
        result = ""
        for pod in pods['items']:
            result = result + self.oc_cmd(['logs', pod['metadata']['name'], '-n', self.namespace])

        if result == "":
            return 'Could not get logs for pod.  Could not determine pod name.'

        return result

    def get_route(self):
        '''get route to check if app is running'''
        cmd = ['get', 'route', '--no-headers', '-o', 'json', '-n', self.namespace]
        results = self.oc_cmd(cmd)
        return json.loads(results)

    def get_service(self):
        '''get service to check if app is running'''
        return json.loads(self.oc_cmd(['get', 'service', '--no-headers', '-n', self.namespace, '-o', 'json']))

    def get_events(self):
        '''get all events'''
        return self.oc_cmd(['get', 'events', '-n', self.namespace])

    def get_projects(self):
        '''get all projects '''
        cmd = ['get', 'projects', '--no-headers']
        results = [proj.split()[0] for proj in self.oc_cmd(cmd).split('\n') if proj and len(proj) > 0]

        return results

    def get_version(self):
        '''get openshift version'''
        return self.oc_cmd(['version'])

    def oc_cmd(self, cmd):
        '''Base command for oc '''
        cmds = ['/usr/bin/oc']
        cmds.extend(cmd)
        print ' '.join(cmds)
        proc = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \
                                env={'KUBECONFIG': self.kubeconfig, \
                                     'PATH': os.environ["PATH"]})
        stdout, stderr = proc.communicate()
        if proc.returncode == 0:
            if self.verbose:
                print "Stdout:"
                print stdout
                print "Stderr:"
                print stderr
            return stdout

        return "Error: %s.  Return: %s" % (proc.returncode, stderr)

    def oadm_cmd(self, cmd):
        '''Base command for oadm '''
        cmds = ['/usr/bin/oadm']
        cmds.extend(cmd)
        print ' '.join(cmds)
        proc = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \
                                env={'KUBECONFIG': self.kubeconfig, \
                                     'PATH': os.environ["PATH"]})
        stdout, stderr = proc.communicate()
        if proc.returncode == 0:
            if self.verbose:
                print "Stdout:"
                print stdout
                print "Stderr:"
                print stderr
            return stdout

        return "Error: %s.  Return: %s" % (proc.returncode, stderr)

def curl(ip_addr, port):
    ''' Open an http connection to the url and read
    '''
    code = 0
    timeout = 30 ## only wait this number of seconds for a response
    try:
        code = urllib2.urlopen( \
            'http://%s:%s' % (ip_addr, port), timeout=timeout).getcode()
    except urllib2.HTTPError, e:
        code = e.fp.getcode()
    except urllib2.URLError, e:
        print "timed out in %s seconds opening http://%s:%s" % \
            (timeout, ip_addr, port)
    return code

def parse_args():
    """ parse the args from the cli """

    parser = argparse.ArgumentParser(description='OpenShift app create end-to-end test')
    parser.add_argument('-v', '--verbose', action='store_true', default=None, help='Verbose?')
    parser.add_argument('--debug', action='store_true', default=None, help='Debug?')
    parser.add_argument('--name', default="openshift/hello-openshift:v1.0.6", help='app template')
    return parser.parse_args()

def pod_name(name):
    """ strip pre/suffices from app name to get pod name """
    # for app deploy "https://github.com/openshift/hello-openshift:latest", pod name is hello-openshift
    if 'http' in name:
        name = name.rsplit('/')[-1]
    if 'git' in name:
        name = name.replace('.git', '')
    if '/' in name:
        name = name.split('/')[1]
    if ':' in name:
        name = name.split(':')[0]
    return name

def send_zagg_data(build_ran, create_app, http_code, run_time):
    ''' send data to Zagg'''
    zgs = ZaggSender()
    print "Send data to Zagg"
    if build_ran == 1:
        zgs.add_zabbix_keys({'openshift.master.app.build.create': create_app})
        zgs.add_zabbix_keys({'openshift.master.app.build.create.code': http_code})
        zgs.add_zabbix_keys({'openshift.master.app.build.create.time': run_time})
    else:
        zgs.add_zabbix_keys({'openshift.master.app.create': create_app})
        zgs.add_zabbix_keys({'openshift.master.app.create.code': http_code})
        zgs.add_zabbix_keys({'openshift.master.app.create.time': run_time})
    zgs.send_metrics()

def handle_fail(run_time, oocmd, pod):
    ''' Print failure info '''
    print 'Finished.'
    print 'State: Fail'
    print 'Time: %s' % run_time
    print 'Fetching Events:'
    oocmd.verbose = True
    print oocmd.get_events()
    print 'Fetching Logs:'
    print oocmd.get_logs()
    print 'Fetching Pod:'
    print pod

def main():
    ''' Do the application creation
    '''
    print '################################################################################'
    print '  Starting App Create - %s' % datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
    print '################################################################################'
    kubeconfig = copy_kubeconfig('/tmp/admin.kubeconfig')
    args = parse_args()
    namespace = 'ops-' + pod_name(args.name) + '-' + os.environ['ZAGG_CLIENT_HOSTNAME']
    oocmd = OpenShiftOC(namespace, kubeconfig, args, verbose=False)
    app = args.name

    start_time = time.time()
    if namespace in  oocmd.get_projects():
        oocmd.delete_project()

    oocmd.new_project()

    oocmd.new_app(app)

    create_app = 1
    build_ran = 0
    pod = None
    http_code = 0
    run_time = 0

    # Now we wait until the pod comes up
    for _ in range(120):
        time.sleep(5)
        pod = oocmd.get_pod()
        if pod and pod['status'] and not "build" in pod['metadata']['name']:
            print 'Polling Pod status: %s' % pod['status']['phase']
        if pod and pod['status'] and "build" in pod['metadata']['name']:
            print 'Polling Build Pod status: %s' % pod['status']['phase']
            build_ran = 1
        if pod \
            and pod['status']['phase'] == 'Running' \
            and pod['status'].has_key('podIP') \
            and not "build" in pod['metadata']['name']:
            route = oocmd.get_route()
            if route['items']:
                # FIXME: no port in the route object, is 80 a safe assumption?
                http_code = curl(route['items'][0]['spec']['host'], 80)
            else:
                service = oocmd.get_service()
                http_code = curl(service['items'][0]['spec']['clusterIP'], \
                    service['items'][0]['spec']['ports'][0]['port'])
            print 'Finished.'
            print 'Deploy State: Success'
            print 'Service HTTP response code: %s' % http_code
            run_time = str(time.time() - start_time)
            print 'Time: %s' % run_time
            create_app = 0
            break

    else:
        run_time = str(time.time() - start_time)
        handle_fail(run_time, oocmd, pod)

    if namespace in oocmd.get_projects():
        oocmd.delete_project()

    send_zagg_data(build_ran, create_app, http_code, run_time)

if __name__ == "__main__":
    main()
<commit_msg>add try and timestamps around zgs_send<commit_after>#!/usr/bin/env python
'''
    Quick and dirty create application check for v3
'''

# Adding the ignore because it does not like the naming of the script
# to be different than the class name
# pylint: disable=invalid-name

import subprocess
import json
import time
import re
import urllib2
import os
import atexit
import shutil
import string
import random
import argparse
import datetime
import sys

# Our jenkins server does not include these rpms.
# In the future we might move this to a container where these
# libs might exist
#pylint: disable=import-error
from openshift_tools.monitoring.zagg_sender import ZaggSender

# pylint: disable=bare-except
def cleanup_file(inc_file):
    ''' clean up '''
    try:
        os.unlink(inc_file)
    except:
        pass

def copy_kubeconfig(config):
    ''' make a copy of the kubeconfig '''
    file_name = os.path.join('/tmp',
                             ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7)))
    shutil.copy(config, file_name)
    atexit.register(cleanup_file, file_name)

    return file_name

class OpenShiftOC(object):
    ''' Class to wrap the oc command line tools '''
    def __init__(self, namespace, kubeconfig, args, verbose=False):
        ''' Constructor for OpenShiftOC '''
        self.namespace = namespace
        self.verbose = verbose
        self.kubeconfig = kubeconfig
        self.args = args

    def get_pod(self):
        '''return a pod by name'''
        pods = self.get_pods()
        podname = pod_name(self.args.name)
        # this will match on build pods but not deploy pods
        regex = re.compile('%s-[0-9]-[a-z0-9]{5}$' % podname)
        for pod in pods['items']:
            results = regex.search(pod['metadata']['name'])
            if results:
                # only report on running build pods, we'll wait if build pod is pending
                if "build" in pod['metadata']['name'] and pod['status']['phase'] != 'Running':
                    continue
                else: return pod

    def get_pods(self):
        '''return all pods '''
        cmd = ['get', 'pods', '--no-headers', '-o', 'json', '-n', self.namespace]
        results = self.oc_cmd(cmd)

        return json.loads(results)

    def new_app(self, path):
        '''run new-app '''
        cmd = ['new-app', path, '-n', self.namespace]
        return self.oc_cmd(cmd)

    def delete_project(self):
        '''delete project '''
        cmd = ['delete', 'project', self.namespace]
        results = self.oc_cmd(cmd)
        time.sleep(5)
        return results

    def new_project(self):
        '''create new project '''
        version = self.get_version()
        cmd = ['new-project', self.namespace]
        if "v3.2" in version:  ## remove this after BZ1333049 resolved in OSE
            rval = self.oadm_cmd(cmd)
        else:
            rval = self.oc_cmd(cmd)
        return rval

    def get_logs(self):
        '''get all pod logs'''
        pods = self.get_pods()
        result = ""
        for pod in pods['items']:
            result = result + self.oc_cmd(['logs', pod['metadata']['name'], '-n', self.namespace])

        if result == "":
            return 'Could not get logs for pod.  Could not determine pod name.'

        return result

    def get_route(self):
        '''get route to check if app is running'''
        cmd = ['get', 'route', '--no-headers', '-o', 'json', '-n', self.namespace]
        results = self.oc_cmd(cmd)
        return json.loads(results)

    def get_service(self):
        '''get service to check if app is running'''
        return json.loads(self.oc_cmd(['get', 'service', '--no-headers', '-n', self.namespace, '-o', 'json']))

    def get_events(self):
        '''get all events'''
        return self.oc_cmd(['get', 'events', '-n', self.namespace])

    def get_projects(self):
        '''get all projects '''
        cmd = ['get', 'projects', '--no-headers']
        results = [proj.split()[0] for proj in self.oc_cmd(cmd).split('\n') if proj and len(proj) > 0]

        return results

    def get_version(self):
        '''get openshift version'''
        return self.oc_cmd(['version'])

    def oc_cmd(self, cmd):
        '''Base command for oc '''
        cmds = ['/usr/bin/oc']
        cmds.extend(cmd)
        print ' '.join(cmds)
        proc = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \
                                env={'KUBECONFIG': self.kubeconfig, \
                                     'PATH': os.environ["PATH"]})
        stdout, stderr = proc.communicate()
        if proc.returncode == 0:
            if self.verbose:
                print "Stdout:"
                print stdout
                print "Stderr:"
                print stderr
            return stdout

        return "Error: %s.  Return: %s" % (proc.returncode, stderr)

    def oadm_cmd(self, cmd):
        '''Base command for oadm '''
        cmds = ['/usr/bin/oadm']
        cmds.extend(cmd)
        print ' '.join(cmds)
        proc = subprocess.Popen(cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \
                                env={'KUBECONFIG': self.kubeconfig, \
                                     'PATH': os.environ["PATH"]})
        stdout, stderr = proc.communicate()
        if proc.returncode == 0:
            if self.verbose:
                print "Stdout:"
                print stdout
                print "Stderr:"
                print stderr
            return stdout

        return "Error: %s.  Return: %s" % (proc.returncode, stderr)

def curl(ip_addr, port):
    ''' Open an http connection to the url and read
    '''
    code = 0
    timeout = 30 ## only wait this number of seconds for a response
    try:
        code = urllib2.urlopen( \
            'http://%s:%s' % (ip_addr, port), timeout=timeout).getcode()
    except urllib2.HTTPError, e:
        code = e.fp.getcode()
    except urllib2.URLError, e:
        print "timed out in %s seconds opening http://%s:%s" % \
            (timeout, ip_addr, port)
    return code

def parse_args():
    """ parse the args from the cli """

    parser = argparse.ArgumentParser(description='OpenShift app create end-to-end test')
    parser.add_argument('-v', '--verbose', action='store_true', default=None, help='Verbose?')
    parser.add_argument('--debug', action='store_true', default=None, help='Debug?')
    parser.add_argument('--name', default="openshift/hello-openshift:v1.0.6", help='app template')
    return parser.parse_args()

def pod_name(name):
    """ strip pre/suffices from app name to get pod name """
    # for app deploy "https://github.com/openshift/hello-openshift:latest", pod name is hello-openshift
    if 'http' in name:
        name = name.rsplit('/')[-1]
    if 'git' in name:
        name = name.replace('.git', '')
    if '/' in name:
        name = name.split('/')[1]
    if ':' in name:
        name = name.split(':')[0]
    return name

def send_zagg_data(build_ran, create_app, http_code, run_time):
    ''' send data to Zagg'''
    zgs_time = time.time()
    zgs = ZaggSender()
    print "Send data to Zagg"
    if build_ran == 1:
        zgs.add_zabbix_keys({'openshift.master.app.build.create': create_app})
        zgs.add_zabbix_keys({'openshift.master.app.build.create.code': http_code})
        zgs.add_zabbix_keys({'openshift.master.app.build.create.time': run_time})
    else:
        zgs.add_zabbix_keys({'openshift.master.app.create': create_app})
        zgs.add_zabbix_keys({'openshift.master.app.create.code': http_code})
        zgs.add_zabbix_keys({'openshift.master.app.create.time': run_time})
    try:
        zgs.send_metrics()
    except:
        print "Error sending to Zagg: %s \n %s " % sys.exc_info()[0], sys.exc_info()[1]
    print "Data sent in %s seconds" % str(time.time() - zgs_time)

def handle_fail(run_time, oocmd, pod):
    ''' Print failure info '''
    print 'Finished.'
    print 'State: Fail'
    print 'Time: %s' % run_time
    print 'Fetching Events:'
    oocmd.verbose = True
    print oocmd.get_events()
    print 'Fetching Logs:'
    print oocmd.get_logs()
    print 'Fetching Pod:'
    print pod

def main():
    ''' Do the application creation
    '''
    print '################################################################################'
    print '  Starting App Create - %s' % datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
    print '################################################################################'
    kubeconfig = copy_kubeconfig('/tmp/admin.kubeconfig')
    args = parse_args()
    namespace = 'ops-' + pod_name(args.name) + '-' + os.environ['ZAGG_CLIENT_HOSTNAME']
    oocmd = OpenShiftOC(namespace, kubeconfig, args, verbose=False)
    app = args.name

    start_time = time.time()
    if namespace in  oocmd.get_projects():
        oocmd.delete_project()

    oocmd.new_project()

    oocmd.new_app(app)

    create_app = 1
    build_ran = 0
    pod = None
    http_code = 0
    run_time = 0

    # Now we wait until the pod comes up
    for _ in range(120):
        time.sleep(5)
        pod = oocmd.get_pod()
        if pod and pod['status'] and not "build" in pod['metadata']['name']:
            print 'Polling Pod status: %s' % pod['status']['phase']
        if pod and pod['status'] and "build" in pod['metadata']['name']:
            print 'Polling Build Pod status: %s' % pod['status']['phase']
            build_ran = 1
        if pod \
            and pod['status']['phase'] == 'Running' \
            and pod['status'].has_key('podIP') \
            and not "build" in pod['metadata']['name']:
            route = oocmd.get_route()
            if route['items']:
                # FIXME: no port in the route object, is 80 a safe assumption?
                http_code = curl(route['items'][0]['spec']['host'], 80)
            else:
                service = oocmd.get_service()
                http_code = curl(service['items'][0]['spec']['clusterIP'], \
                    service['items'][0]['spec']['ports'][0]['port'])
            print 'Finished.'
            print 'Deploy State: Success'
            print 'Service HTTP response code: %s' % http_code
            run_time = str(time.time() - start_time)
            print 'Time: %s' % run_time
            create_app = 0
            break

    else:
        run_time = str(time.time() - start_time)
        handle_fail(run_time, oocmd, pod)

    if namespace in oocmd.get_projects():
        oocmd.delete_project()

    send_zagg_data(build_ran, create_app, http_code, run_time)

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


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# PCEF - Python/Qt Code Editing Framework
# Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com>
#
# This software is released under the LGPLv3 license.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Integrates the generic editor using the pcef qt designer plugin.
"""
import os
import sys
from pcef.qt import QtCore, QtGui
usePyQt4 = os.environ['QT_API'] == "PyQt"
usePySide = os.environ['QT_API'] == "PySide"
if sys.version_info[0] == 3:
    if usePyQt4:
        from ui.simple_editor_ui3_pyqt import Ui_MainWindow
    elif usePySide:
        from ui.simple_editor_ui3_pyside import Ui_MainWindow
else:
    if usePyQt4:
        from ui.simple_editor_ui_pyqt import Ui_MainWindow
    elif usePySide:
        from ui.simple_editor_ui_pyside import Ui_MainWindow
print(os.environ["QT_API"])
print("Python {}".format(sys.version_info[0]))

class SimpleEditorWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setupUi(self)
        self.editor.dirtyChanged.connect(self.actionSave.setEnabled)
        self.actionSave.triggered.connect(self.editor.saveToFile)
        # edit menu
        self.menubar.addMenu(self.editor.contextMenu)
        # Add modes to the modes menu
        for k, v in self.editor.modes().items():
            a = QtGui.QAction(self.menuModes)
            a.setText(k)
            a.setCheckable(True)
            a.setChecked(True)
            a.changed.connect(self.onModeCheckStateChanged)
            a.mode = v
            self.menuModes.addAction(a)
        # Add panels to the panels menu
        for zones, panel_dic in self.editor.panels().items():
            for k, v in panel_dic.items():
                a = QtGui.QAction(self.menuModes)
                a.setText(k)
                a.setCheckable(True)
                a.setChecked(True)
                a.changed.connect(self.onPanelCheckStateChanged)
                a.panel = v
                self.menuPanels.addAction(a)
        try:
            self.editor.openFile(__file__)
        except (OSError, IOError) as e:
            pass
        except AttributeError:
            pass

    @QtCore.Slot()
    def on_actionOpen_triggered(self):
        filePath = QtGui.QFileDialog.getOpenFileName(
            self, "Choose a file", os.path.expanduser("~"))
        if filePath:
            self.editor.openFile(filePath)

    def onPanelCheckStateChanged(self):
        action = self.sender()
        action.panel.enabled = action.isChecked()

    def onModeCheckStateChanged(self):
        action = self.sender()
        action.mode.enabled = action.isChecked()

def main():
    app = QtGui.QApplication(sys.argv)
    win = SimpleEditorWindow()
    win.show()
    app.exec_()

if __name__ == "__main__":
    main()

<commit_msg>Fix open file action in example when run with pyside<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# PCEF - Python/Qt Code Editing Framework
# Copyright 2013, Colin Duquesnoy <colin.duquesnoy@gmail.com>
#
# This software is released under the LGPLv3 license.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Integrates the generic editor using the pcef qt designer plugin.
"""
import os
import sys
from pcef.qt import QtCore, QtGui
usePyQt4 = os.environ['QT_API'] == "PyQt"
usePySide = os.environ['QT_API'] == "PySide"
if sys.version_info[0] == 3:
    if usePyQt4:
        from ui.simple_editor_ui3_pyqt import Ui_MainWindow
    elif usePySide:
        from ui.simple_editor_ui3_pyside import Ui_MainWindow
else:
    if usePyQt4:
        from ui.simple_editor_ui_pyqt import Ui_MainWindow
    elif usePySide:
        from ui.simple_editor_ui_pyside import Ui_MainWindow
print(os.environ["QT_API"])
print("Python {}".format(sys.version_info[0]))

class SimpleEditorWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setupUi(self)
        self.editor.dirtyChanged.connect(self.actionSave.setEnabled)
        self.actionSave.triggered.connect(self.editor.saveToFile)
        # edit menu
        self.menubar.addMenu(self.editor.contextMenu)
        # Add modes to the modes menu
        for k, v in self.editor.modes().items():
            a = QtGui.QAction(self.menuModes)
            a.setText(k)
            a.setCheckable(True)
            a.setChecked(True)
            a.changed.connect(self.onModeCheckStateChanged)
            a.mode = v
            self.menuModes.addAction(a)
        # Add panels to the panels menu
        for zones, panel_dic in self.editor.panels().items():
            for k, v in panel_dic.items():
                a = QtGui.QAction(self.menuModes)
                a.setText(k)
                a.setCheckable(True)
                a.setChecked(True)
                a.changed.connect(self.onPanelCheckStateChanged)
                a.panel = v
                self.menuPanels.addAction(a)
        try:
            self.editor.openFile(__file__)
        except (OSError, IOError) as e:
            pass
        except AttributeError:
            pass

    @QtCore.Slot()
    def on_actionOpen_triggered(self):
        filePath = QtGui.QFileDialog.getOpenFileName(
            self, "Choose a file", os.path.expanduser("~"))
        if os.environ['QT_API'] == 'PySide':
            if filePath[0]:
                self.editor.openFile(filePath[0])
        else:
            if filePath:
                self.editor.openFile(filePath)

    def onPanelCheckStateChanged(self):
        action = self.sender()
        action.panel.enabled = action.isChecked()

    def onModeCheckStateChanged(self):
        action = self.sender()
        action.mode.enabled = action.isChecked()

def main():
    app = QtGui.QApplication(sys.argv)
    win = SimpleEditorWindow()
    win.show()
    app.exec_()

if __name__ == "__main__":
    main()

<|endoftext|>