<commit_before>
#
# rpclib - Copyright (C) Rpclib contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
#

import logging
logger = logging.getLogger(__name__)

import copy

from lxml import etree

from rpclib.protocol import ProtocolBase

clock = etree.fromstring(open('clock.svg','r').read())
ns = {'x': 'http://www.w3.org/2000/svg'}

class SvgClock(ProtocolBase):
    mime_type = 'image/svg+xml'

    def __init__(self, app=None, length=500):
        """Protocol that returns a PNG Clock picture based on a received datetime
        object.

        :param app: A rpclib.application.Application instance.
        :param length: The length of the edge of the produced square image, in pixels.
        """

        ProtocolBase.__init__(self, app, validator=None)

        self.length = length

    def serialize(self, ctx, message):
        """Uses ctx.out_object, ctx.out_header or ctx.out_error to set
        ctx.out_body_doc, ctx.out_header_doc and ctx.out_document.
        """

        assert message in (self.RESPONSE,)

        self.event_manager.fire_event('before_serialize', ctx)
        ctx.out_header_doc = None
        ctx.out_body_doc = copy.deepcopy(clock)

        ctx.out_body_doc.xpath("//x:flowPara[@id='date_text']", namespaces=ns)[0] \
                .text = '%04d-%02d-%02d' % (d.year, d.month, d.day)

        d = ctx.out_object[0]
        yelkovan_deg = d.minute * 360 / 60;
        akrep_deg = (d.hour % 12) * 360.0 / 12 + yelkovan_deg / 12;
        ctx.out_body_doc.xpath("//x:path[@id='akrep']", namespaces=ns)[0] \
            .attrib['transform'] += \
            ' rotate(%d, %d, %d)' % (akrep_deg, self.length /2, self.length / 2)
        ctx.out_body_doc.xpath("//x:path[@id='yelkovan']", namespaces=ns)[0] \
            .attrib['transform'] += \
            ' rotate(%d, %d, %d)' % (yelkovan_deg, self.length /2, self.length / 2)

        ctx.out_document = ctx.out_body_doc

        self.event_manager.fire_event('after_serialize', ctx)

    def create_out_string(self, ctx, charset=None):
        """Sets an iterable of string fragments to ctx.out_string"""

        ctx.out_string = [etree.tostring(ctx.out_document, pretty_print=True,
                                         encoding='utf8', xml_declaration=True)]

    def decompose_incoming_envelope(self, ctx, message):
        raise NotImplementedError("This is an output-only protocol.")
<commit_msg>implement PngClock protocol.<commit_after>
#
# rpclib - Copyright (C) Rpclib contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301
#

import logging
logger = logging.getLogger(__name__)

import copy

from lxml import etree

from rpclib.protocol import ProtocolBase

clock = etree.fromstring(open('clock.svg','r').read())
ns = {'x': 'http://www.w3.org/2000/svg'}

class SvgClock(ProtocolBase):
    mime_type = 'image/svg+xml'

    def __init__(self, app=None):
        ProtocolBase.__init__(self, app, validator=None)

        self.length = 500 # if you change this, you should re-scale the svg file
                          # as well.

    def serialize(self, ctx, message):
        """Uses ctx.out_object, ctx.out_header or ctx.out_error to set
        ctx.out_body_doc, ctx.out_header_doc and ctx.out_document.
        """

        assert message in (self.RESPONSE,)

        self.event_manager.fire_event('before_serialize', ctx)
        ctx.out_header_doc = None
        ctx.out_body_doc = copy.deepcopy(clock)

        d = ctx.out_object[0] # this has to be a datetime.datetime() instance.

        ctx.out_body_doc.xpath("//x:flowPara[@id='date_text']", namespaces=ns)[0] \
                .text = '%04d-%02d-%02d' % (d.year, d.month, d.day)

        yelkovan_deg = d.minute * 360 / 60;
        akrep_deg = (d.hour % 12) * 360.0 / 12 + yelkovan_deg / 12;
        ctx.out_body_doc.xpath("//x:path[@id='akrep']", namespaces=ns)[0] \
            .attrib['transform'] += \
            ' rotate(%d, %d, %d)' % (akrep_deg, self.length /2, self.length / 2)
        ctx.out_body_doc.xpath("//x:path[@id='yelkovan']", namespaces=ns)[0] \
            .attrib['transform'] += \
            ' rotate(%d, %d, %d)' % (yelkovan_deg, self.length /2, self.length /2)

        ctx.out_document = ctx.out_body_doc

        self.event_manager.fire_event('after_serialize', ctx)

    def create_out_string(self, ctx, charset=None):
        """Sets an iterable of string fragments to ctx.out_string"""

        ctx.out_string = [etree.tostring(ctx.out_document, pretty_print=True,
                                         encoding='utf8', xml_declaration=True)]

    def decompose_incoming_envelope(self, ctx, message):
        raise NotImplementedError("This is an output-only protocol.")

class PngClock(SvgClock):
    mime_type = 'image/png'

    def create_out_string(self, ctx, charset=None):
        """Sets an iterable of string fragments to ctx.out_string"""

        import rsvg
        from gtk import gdk

        h = rsvg.Handle()
        h.write(etree.tostring(ctx.out_document))
        h.close()

        pixbuf = h.get_pixbuf()

        ctx.out_string= []

        def cb(buf, data=None):
            ctx.out_string.append(buf)
            return True

        pixbuf.save_to_callback(cb, 'png')

{'fraction_non_alphanumeric': 0.11610543958555539, 'fraction_numerical': 0.015541673015389303, 'mean_word_length': 2.8657243816254416, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 6}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1773470', 'n_tokens_mistral': 2137, 'n_tokens_neox': 2009, 'n_words': 591}