text:
import pytest

import numpy as np
from matplotlib.ticker import AutoLocator, MaxNLocator, LogLocator
from matplotlib.ticker import LogFormatterMathtext, ScalarFormatter, FuncFormatter
from mock import MagicMock
from timeit import timeit
from functools import partial

from ...tests import example_data
from ... import core
from ...core.data import ComponentID
from ...core.edit_subset_mode import EditSubsetMode
from ..scatter_client import ScatterClient
from .util import renderless_figure

# share matplotlib instance, and disable rendering, for speed
FIGURE = renderless_figure()

class TestScatterClient(object):

    def setup_method(self, method):
        self.data = example_data.test_data()
        self.ids = [self.data[0].find_component_id('a'),
                    self.data[0].find_component_id('b'),
                    self.data[1].find_component_id('c'),
                    self.data[1].find_component_id('d')]
        self.roi_limits = (0.5, 0.5, 1.5, 1.5)
        self.roi_points = (np.array([1]), np.array([1]))
        self.collect = core.data_collection.DataCollection()
        EditSubsetMode().data_collection = self.collect

        self.hub = self.collect.hub

        FIGURE.clf()
        axes = FIGURE.add_subplot(111)
        self.client = ScatterClient(self.collect, axes=axes)

        self.connect()

    def teardown_method(self, methdod):
        self.assert_properties_correct()
        self.assert_axes_ticks_correct()

    def assert_properties_correct(self):
        ax = self.client.axes
        cl = self.client
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        assert abs(cl.xmin - min(xlim)) < 1e-2
        assert abs(cl.xmax - max(xlim)) < 1e-2
        assert abs(cl.ymin - min(ylim)) < 1e-2
        assert abs(cl.ymax - max(ylim)) < 1e-2
        assert cl.xflip == (xlim[1] < xlim[0])
        assert cl.yflip == (ylim[1] < ylim[0])
        assert cl.xlog == (ax.get_xscale() == 'log')
        assert cl.ylog == (ax.get_yscale() == 'log')
        assert (self.client.xatt is None) or isinstance(
            self.client.xatt, ComponentID)
        assert (self.client.yatt is None) or isinstance(
            self.client.yatt, ComponentID)

    def check_ticks(self, axis, is_log, is_cat):
        locator = axis.get_major_locator()
        formatter = axis.get_major_formatter()
        if is_log:
            assert isinstance(locator, LogLocator)
            assert isinstance(formatter, LogFormatterMathtext)
        elif is_cat:
            assert isinstance(locator, MaxNLocator)
            assert isinstance(formatter, FuncFormatter)
        else:
            assert isinstance(locator, AutoLocator)
            assert isinstance(formatter, ScalarFormatter)

    def assert_axes_ticks_correct(self):
        ax = self.client.axes
        client = self.client
        if client.xatt is not None:
            self.check_ticks(ax.xaxis,
                             client.xlog,
                             client._check_categorical(client.xatt))
        if client.yatt is not None:
            self.check_ticks(ax.yaxis,
                             client.ylog,
                             client._check_categorical(client.yatt))

    def plot_data(self, layer):
        """ Return the data bounds for a given layer (data or subset)
        Output format: [xmin, xmax], [ymin, ymax]
        """
        client = self.client
        x, y = client.artists[layer][0].get_data()
        xmin = x.min()
        xmax = x.max()
        ymin = y.min()
        ymax = y.max()
        return [xmin, xmax], [ymin, ymax]

    def plot_limits(self):
        """ Return the plot limits
        Output format [xmin, xmax], [ymin, ymax]
        """
        ax = self.client.axes
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        return (min(xlim), max(xlim)), (min(ylim), max(ylim))

    def assert_layer_inside_limits(self, layer):
        """Assert that points of a layer are within plot limits """
        xydata = self.plot_data(layer)
        xylimits = self.plot_limits()
        assert xydata[0][0] >= xylimits[0][0]
        assert xydata[1][0] >= xylimits[1][0]
        assert xydata[0][1] <= xylimits[0][1]
        assert xydata[1][1] <= xylimits[1][1]

    def setup_2d_data(self):
        d = core.Data(x=[[1, 2], [3, 4]], y=[[2, 4], [6, 8]])
        self.collect.append(d)
        self.client.add_layer(d)
        self.client.xatt = d.id['x']
        self.client.yatt = d.id['y']
        return d

    def add_data(self, data=None):
        if data is None:
            data = self.data[0]
        data.edit_subset = data.new_subset()
        self.collect.append(data)
        self.client.add_data(data)
        return data

    def add_data_and_attributes(self):
        data = self.add_data()
        data.edit_subset = data.new_subset()
        self.client.xatt = self.ids[0]
        self.client.yatt = self.ids[1]
        return data

    def is_first_in_front(self, front, back):
        z1 = self.client.get_layer_order(front)
        z2 = self.client.get_layer_order(back)
        return z1 > z2

    def connect(self):
        self.client.register_to_hub(self.hub)
        self.collect.register_to_hub(self.hub)

    def layer_drawn(self, layer):
        return self.client.is_layer_present(layer) and \
            all(a.enabled and a.visible for a in self.client.artists[layer])

    def layer_data_correct(self, layer, x, y):
        xx, yy = self.client.artists[layer][0].get_data()
        if max(abs(xx - x)) > .01:
            return False
        if max(abs(yy - y)) > .01:
            return False
        return True

    def test_empty_on_creation(self):
        for d in self.data:
            assert not self.client.is_layer_present(d)

    def test_add_external_data_raises_exception(self):
        data = core.data.Data()
        with pytest.raises(TypeError) as exc:
            self.client.add_data(data)
        assert exc.value.args[0] == "Layer not in data collection"

    def test_valid_add(self):
        layer = self.add_data()
        assert self.client.is_layer_present(self.data[0])

    def test_axis_labels_sync_with_setters(self):
        layer = self.add_data()
        self.client.xatt = self.ids[1]
        assert self.client.axes.get_xlabel() == self.ids[1].label
        self.client.yatt = self.ids[0]
        assert self.client.axes.get_ylabel() == self.ids[0].label

    def test_setters_require_componentID(self):
        layer = self.add_data()
        with pytest.raises(TypeError):
            self.client.xatt = self.ids[1]._label
        self.client.xatt = self.ids[1]

    def test_logs(self):
        layer = self.add_data()
        self.client.xlog = True
        assert self.client.axes.get_xscale() == 'log'

        self.client.xlog = False
        assert self.client.axes.get_xscale() == 'linear'

        self.client.ylog = True
        assert self.client.axes.get_yscale() == 'log'

        self.client.ylog = False
        assert self.client.axes.get_yscale() == 'linear'

    def test_flips(self):
        layer = self.add_data()

        self.client.xflip = True
        self.assert_flips(True, False)

        self.client.xflip = False
        self.assert_flips(False, False)

        self.client.yflip = True
        self.assert_flips(False, True)

        self.client.yflip = False
        self.assert_flips(False, False)

    def assert_flips(self, xflip, yflip):
        ax = self.client.axes
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        assert (xlim[1] < xlim[0]) == xflip
        assert (ylim[1] < ylim[0]) == yflip

    def test_double_add(self):
        n0 = len(self.client.axes.lines)
        layer = self.add_data_and_attributes()
        # data present
        assert len(self.client.axes.lines) == n0 + 1 + len(layer.subsets)
        layer = self.add_data()
        # data still present
        assert len(self.client.axes.lines) == n0 + 1 + len(layer.subsets)

    def test_data_updates_propagate(self):
        layer = self.add_data_and_attributes()
        assert self.layer_drawn(layer)
        self.client._layer_updated = False
        layer.style.color = 'k'
        assert self.client._layer_updated

    def test_data_removal(self):
        layer = self.add_data()
        subset = layer.new_subset()
        self.collect.remove(layer)
        assert not self.client.is_layer_present(layer)
        assert not self.client.is_layer_present(subset)

    def test_add_subset_while_connected(self):
        layer = self.add_data()
        subset = layer.new_subset()
        assert self.client.is_layer_present(subset)

    def test_subset_removal(self):
        layer = self.add_data()
        subset = layer.new_subset()
        assert self.client.is_layer_present(layer)
        subset.delete()
        assert not self.client.is_layer_present(subset)

    def test_subset_removal_removes_from_plot(self):
        layer = self.add_data_and_attributes()
        subset = layer.new_subset()
        ct0 = len(self.client.axes.lines)
        subset.delete()
        assert len(self.client.axes.lines) == ct0 - 1

    def test_add_subset_to_untracked_data(self):
        subset = self.data[0].new_subset()
        assert not self.client.is_layer_present(subset)

    def test_valid_plot_data(self):
        layer = self.add_data_and_attributes()
        x = layer[self.ids[0]]
        y = layer[self.ids[1]]
        assert self.layer_data_correct(layer, x, y)

    def test_attribute_update_plot_data(self):
        layer = self.add_data_and_attributes()
        x = layer[self.ids[0]]
        y = layer[self.ids[0]]
        self.client.yatt = self.ids[0]
        assert self.layer_data_correct(layer, x, y)

    def test_invalid_plot(self):
        layer = self.add_data_and_attributes()
        assert self.layer_drawn(layer)
        c = core.data.ComponentID('bad id')
        self.client.xatt = c
        assert not self.layer_drawn(layer)
        self.client.xatt = self.ids[0]

    def test_redraw_called_on_invalid_plot(self):
        """ Plot should be updated when given invalid data,
        to sync layers' disabled/invisible states"""
        ctr = MagicMock()
        layer = self.add_data_and_attributes()
        assert self.layer_drawn(layer)
        c = core.data.ComponentID('bad id')
        self.client._redraw = ctr
        ct0 = ctr.call_count
        self.client.xatt = c
        ct1 = ctr.call_count
        ncall = ct1 - ct0
        expected = len(self.client.artists)
        assert ncall >= expected
        self.client.xatt = self.ids[0]

    def test_two_incompatible_data(self):
        d0 = self.add_data(self.data[0])
        d1 = self.add_data(self.data[1])
        self.client.xatt = self.ids[0]
        self.client.yatt = self.ids[1]
        x = d0[self.ids[0]]
        y = d0[self.ids[1]]
        assert self.layer_drawn(d0)
        assert self.layer_data_correct(d0, x, y)
        assert not self.layer_drawn(d1)

        self.client.xatt = self.ids[2]
        self.client.yatt = self.ids[3]
        x = d1[self.ids[2]]
        y = d1[self.ids[3]]
        assert self.layer_drawn(d1)
        assert self.layer_data_correct(d1, x, y)
        assert not self.layer_drawn(d0)

    def test_subsets_connect_with_data(self):
        data = self.data[0]
        s1 = data.new_subset()
        s2 = data.new_subset()
        self.collect.append(data)
        self.client.add_data(data)
        assert self.client.is_layer_present(s1)
        assert self.client.is_layer_present(s2)
        assert self.client.is_layer_present(data)

        # should also work with add_layer
        self.collect.remove(data)
        assert data not in self.collect
        assert not self.client.is_layer_present(s1)
        self.collect.append(data)
        self.client.add_layer(data)
        assert self.client.is_layer_present(s1)

    def test_edit_subset_connect_with_data(self):
        data = self.add_data()
        assert self.client.is_layer_present(data.edit_subset)

    def test_edit_subset_removed_with_data(self):
        data = self.add_data()
        self.collect.remove(data)
        assert not self.client.is_layer_present(data.edit_subset)

    def test_apply_roi(self):
        data = self.add_data_and_attributes()
        roi = core.roi.RectangularROI()
        roi.update_limits(*self.roi_limits)
        x, y = self.roi_points
        self.client.apply_roi(roi)
        assert self.layer_data_correct(data.edit_subset, x, y)

    def test_apply_roi_adds_on_empty(self):
        data = self.add_data_and_attributes()
        data._subsets = []
        data.edit_subset = None
        roi = core.roi.RectangularROI()
        roi.update_limits(*self.roi_limits)
        x, y = self.roi_points
        self.client.apply_roi(roi)
        assert data.edit_subset is not None

    def test_apply_roi_applies_to_all_editable_subsets(self):
        d1 = self.add_data_and_attributes()
        d2 = self.add_data()
        state1 = d1.edit_subset.subset_state
        state2 = d2.edit_subset.subset_state
        roi = core.roi.RectangularROI()
        roi.update_limits(*self.roi_limits)
        x, y = self.roi_points
        self.client.apply_roi(roi)
        assert d1.edit_subset.subset_state is not state1
        assert d1.edit_subset.subset_state is not state2

    def test_apply_roi_doesnt_add_if_any_selection(self):
        d1 = self.add_data_and_attributes()
        d2 = self.add_data()
        d1.edit_subset = None
        d2.edit_subset = d2.new_subset()
        ct = len(d1.subsets)
        roi = core.roi.RectangularROI()
        roi.update_limits(*self.roi_limits)
        x, y = self.roi_points
        self.client.apply_roi(roi)
        assert len(d1.subsets) == ct

    def test_subsets_drawn_over_data(self):
        data = self.add_data_and_attributes()
        subset = data.new_subset()
        assert self.is_first_in_front(subset, data)

    def test_log_sticky(self):
        data = self.add_data_and_attributes()
        self.assert_logs(False, False)

        self.client.xlog = True
        self.client.ylog = True
        self.assert_logs(True, True)

        self.client.xatt = self.ids[1]
        self.client.yatt = self.ids[0]
        self.assert_logs(True, True)

    def assert_logs(self, xlog, ylog):
        ax = self.client.axes
        assert ax.get_xscale() == ('log' if xlog else 'linear')
        assert ax.get_yscale() == ('log' if ylog else 'linear')

    def test_flip_sticky(self):
        data = self.add_data_and_attributes()
        self.client.xflip = True
        self.assert_flips(True, False)
        self.client.xatt = self.ids[1]
        self.assert_flips(True, False)
        self.client.xatt = self.ids[0]
        self.assert_flips(True, False)

    def test_visibility_sticky(self):
        data = self.add_data_and_attributes()
        roi = core.roi.RectangularROI()
        roi.update_limits(*self.roi_limits)
        assert self.client.is_visible(data.edit_subset)
        self.client.apply_roi(roi)
        self.client.set_visible(data.edit_subset, False)
        assert not self.client.is_visible(data.edit_subset)
        self.client.apply_roi(roi)
        assert not self.client.is_visible(data.edit_subset)

    def test_2d_data(self):
        """Should be abple to plot 2d data"""
        data = self.setup_2d_data()
        assert self.layer_data_correct(data, [1, 2, 3, 4], [2, 4, 6, 8])

    def test_2d_data_limits_with_subset(self):
        """visible limits should work with subsets and 2d data"""
        d = self.setup_2d_data()
        state = d.id['x'] > 2
        s = d.new_subset()
        s.subset_state = state
        assert self.client._visible_limits(0) == (1, 4)
        assert self.client._visible_limits(1) == (2, 8)

    def test_limits_nans(self):
        d = core.Data()
        x = core.Component(np.array([[1, 2], [np.nan, 4]]))
        y = core.Component(np.array([[2, 4], [np.nan, 8]]))
        xid = d.add_component(x, 'x')
        yid = d.add_component(y, 'y')
        self.collect.append(d)
        self.client.add_layer(d)
        self.client.xatt = xid
        self.client.yatt = yid

        assert self.client._visible_limits(0) == (1, 4)
        assert self.client._visible_limits(1) == (2, 8)

    def test_limits_inf(self):
        d = core.Data()
        x = core.Component(np.array([[1, 2], [np.infty, 4]]))
        y = core.Component(np.array([[2, 4], [-np.infty, 8]]))
        xid = d.add_component(x, 'x')
        yid = d.add_component(y, 'y')
        self.collect.append(d)
        self.client.add_layer(d)
        self.client.xatt = xid
        self.client.yatt = yid

        assert self.client._visible_limits(0) == (1, 4)
        assert self.client._visible_limits(1) == (2, 8)

    def test_xlog_relimits_if_negative(self):
        self.add_data_and_attributes()
        self.client.xflip = False
        self.client.xlog = False

        self.client.axes.set_xlim(-5, 5)
        self.client.xlog = True
        assert self.client.axes.get_xlim()[0] > .9

    def test_ylog_relimits_if_negative(self):
        self.add_data_and_attributes()
        self.client.yflip = False
        self.client.ylog = False
        self.client.axes.set_ylim(-5, 5)

        self.client.ylog = True
        assert self.client.axes.get_ylim()[0] > .9

    def test_subset_added_only_if_data_layer_present(self):
        self.collect.append(self.data[0])
        assert self.data[0] not in self.client.artists
        s = self.data[0].new_subset()
        assert s not in self.client.artists

    def test_pull_properties(self):
        ax = self.client.axes
        ax.set_xlim(6, 5)
        ax.set_ylim(8, 7)
        ax.set_xscale('log')
        ax.set_yscale('log')

        self.client._pull_properties()
        self.assert_properties_correct()

    def test_rescaled_on_init(self):
        layer = self.setup_2d_data()
        self.assert_layer_inside_limits(layer)

    def test_set_limits(self):
        self.client.xmin = 3
        self.client.xmax = 4
        self.client.ymin = 5
        self.client.ymax = 6
        ax = self.client.axes
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()

        assert xlim[0] == self.client.xmin
        assert xlim[1] == self.client.xmax
        assert ylim[0] == self.client.ymin
        assert ylim[1] == self.client.ymax

    def test_ignore_duplicate_updates(self):
        """Need not create new artist on every draw. Enforce this"""
        layer = self.setup_2d_data()

        m = MagicMock()
        self.client.artists[layer][0].clear = m

        self.client._update_layer(layer)
        ct0 = m.call_count

        self.client._update_layer(layer)
        ct1 = m.call_count

        assert ct1 == ct0

class TestCategoricalScatterClient(TestScatterClient):

    def setup_method(self, method):
        self.data = example_data.test_categorical_data()
        self.ids = [self.data[0].find_component_id('x1'),
                    self.data[0].find_component_id('y1'),
                    self.data[1].find_component_id('x2'),
                    self.data[1].find_component_id('y2')]
        self.roi_limits = (0.5, 0.5, 4, 4)
        self.roi_points = (np.array([1]), np.array([3]))
        self.collect = core.data_collection.DataCollection()
        self.hub = self.collect.hub

        FIGURE.clf()
        axes = FIGURE.add_subplot(111)
        self.client = ScatterClient(self.collect, axes=axes)

        self.connect()

    def test_get_category_tick(self):

        self.add_data()
        self.client.xatt = self.ids[0]
        self.client.yatt = self.ids[0]
        axes = self.client.axes
        xformat = axes.xaxis.get_major_formatter()
        yformat = axes.yaxis.get_major_formatter()

        xlabels = [xformat.format_data(pos) for pos in range(2)]
        ylabels = [yformat.format_data(pos) for pos in range(2)]
        assert xlabels == ['a', 'b']
        assert ylabels == ['a', 'b']

    def test_axis_labels_sync_with_setters(self):
        layer = self.add_data()
        self.client.xatt = self.ids[0]
        assert self.client.axes.get_xlabel() == self.ids[0].label
        self.client.yatt = self.ids[1]
        assert self.client.axes.get_ylabel() == self.ids[1].label

    def test_jitter_with_setter_change(self):

        grab_data = lambda client: client.data[0][client.xatt].copy()
        layer = self.add_data()
        self.client.xatt = self.ids[0]
        self.client.yatt = self.ids[1]
        orig_data = grab_data(self.client)
        self.client.jitter = None
        np.testing.assert_equal(orig_data, grab_data(self.client))
        self.client.jitter = 'uniform'
        delta = np.abs(orig_data - grab_data(self.client))
        assert np.all((delta > 0) & (delta < 1))
        self.client.jitter = None
        np.testing.assert_equal(orig_data, grab_data(self.client))

    def test_ticks_go_back_after_changing(self):
        """ If you change to a categorical axis and then change back
        to a numeric, the axis ticks should fix themselves properly.
        """
        data = core.Data()
        data.add_component(core.Component(np.arange(100)), 'y')
        data.add_component(
            core.data.CategoricalComponent(['a'] * 50 + ['b'] * 50), 'xcat')
        data.add_component(core.Component(2 * np.arange(100)), 'xcont')

        self.add_data(data=data)
        self.client.yatt = data.find_component_id('y')
        self.client.xatt = data.find_component_id('xcat')
        self.check_ticks(self.client.axes.xaxis, False, True)
        self.check_ticks(self.client.axes.yaxis, False, False)

        self.client.xatt = data.find_component_id('xcont')
        self.check_ticks(self.client.axes.yaxis, False, False)
        self.check_ticks(self.client.axes.xaxis, False, False)

    def test_high_cardinatility_timing(self):

        card = 50000
        data = core.Data()
        card_data = [str(num) for num in range(card)]
        data.add_component(core.Component(np.arange(card * 5)), 'y')
        data.add_component(
            core.data.CategoricalComponent([card_data] * 5), 'xcat')
        self.add_data(data)
        comp = data.find_component_id('xcat')
        timer_func = partial(self.client._set_xydata, 'x', comp)

        timer = timeit(timer_func, number=1)
        assert timer < 3  # this is set for Travis speed

    # REMOVED TESTS
    def test_invalid_plot(self):
        """ This fails because the axis ticks shouldn't reset after
        invalid plot. Current testing logic can't cope with this."""
        pass

    def test_redraw_called_on_invalid_plot(self):
        """ This fails because the axis ticks shouldn't reset after
        invalid plot. Current testing logic can't cope with this."""
        pass

    def test_xlog_relimits_if_negative(self):
        """ Log-based tests don't make sense here."""
        pass

    def test_log_sticky(self):
        """ Log-based tests don't make sense here."""
        pass

    def test_logs(self):
        """ Log-based tests don't make sense here."""
        pass


text:
<?php

namespace Upao\FundoBundle\Twig;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\Container;

class FundoExtension extends \Twig_Extension
{
    /**
     * @var Container
     */
    private $container;

    /**
     * @var ObjectManager
     */
    private $em;

    public function __construct($container){
        $this->container = $container;
        $this->em = $this->container->get('doctrine')->getManager();
    }

    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('convertirLetra', array($this, 'convertirLetra')),
            new \Twig_SimpleFilter('buscarPlanta', array($this, 'buscarPlanta')),
        );
    }

    public function buscarPlanta($codigo, $columna, $fila)
    {

        $planta =  $this->em->getRepository('UpaoFundoBundle:Planta')
            ->findOneBy(
                array(
                    'fila' => $fila,
                    'columna' => $columna,
                    'estado' => 'SEMBRADA'
                ));

        return $planta;
    }

    public function convertirLetra($number, $uppercase = true)
    {
        $number -= 1;
        $letter = chr(($number % 26) + 97);
        $letter .= (floor($number / 26) > 0) ? str_repeat($letter, floor($number / 26)) : '';
        return ($uppercase ? strtoupper($letter) : $letter);

    }

    public function getName()
    {
        return 'fundo_extension';
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
    OpenID authentication for web2py

    Allowed using OpenID login together with web2py built-in login.

    By default, to support OpenID login, put this in your db.py

    >>> from gluon.contrib.login_methods.openid_auth import OpenIDAuth
    >>> auth.settings.login_form = OpenIDAuth(auth)

    To show OpenID list in user profile, you can add the following code
    before the end of function user() of your_app/controllers/default.py

    +     if (request.args and request.args(0) == "profile"):
    +         form = DIV(form, openid_login_form.list_user_openids())
        return dict(form=form, login_form=login_form, register_form=register_form, self_registration=self_registration)

    More detail in the description of the class OpenIDAuth.

    Requirements:
        python-openid version 2.2.5 or later

    Reference:
        * w2p openID
          http://w2popenid.appspot.com/init/default/wiki/w2popenid
        * RPX and web2py auth module
          http://www.web2pyslices.com/main/slices/take_slice/28
        * built-in file: gluon/contrib/login_methods/rpx_account.py
        * built-in file: gluon/tools.py (Auth class)
"""
import time
from datetime import datetime, timedelta

from gluon import *
from gluon.storage import Storage, Messages

try:
    import openid.consumer.consumer
    from openid.association import Association
    from openid.store.interface import OpenIDStore
    from openid.extensions.sreg import SRegRequest, SRegResponse
    from openid.store import nonce
    from openid.consumer.discover import DiscoveryFailure
except ImportError, err:
    raise ImportError("OpenIDAuth requires python-openid package")

DEFAULT = lambda: None

class OpenIDAuth(object):
    """
    OpenIDAuth

    It supports the logout_url, implementing the get_user and login_form
    for cas usage of gluon.tools.Auth.

    It also uses the ExtendedLoginForm to allow the OpenIDAuth login_methods
    combined with the standard logon/register procedure.

    It uses OpenID Consumer when render the form and begins the OpenID
    authentication.

    Example: (put these code after auth.define_tables() in your models.)

    auth = Auth(globals(), db)                # authentication/authorization
    ...
    auth.define_tables()                      # creates all needed tables
    ...

    #include in your model after auth has been defined
    from gluon.contrib.login_methods.openid_auth import OpenIDAuth
    openid_login_form = OpenIDAuth(request, auth, db)

    from gluon.contrib.login_methods.extended_login_form import ExtendedLoginForm
    extended_login_form = ExtendedLoginForm(request, auth, openid_login_form,
                                            signals=['oid','janrain_nonce'])

    auth.settings.login_form = extended_login_form
    """

    def __init__(self, auth):
        self.auth = auth
        self.db = auth.db

        request = current.request
        self.nextvar = '_next'
        self.realm = 'http://%s' % request.env.http_host
        self.login_url = URL(r=request, f='user', args=['login'])
        self.return_to_url = self.realm + self.login_url

        self.table_alt_logins_name = "alt_logins"
        if not auth.settings.table_user:
            raise
        self.table_user = self.auth.settings.table_user
        self.openid_expiration = 15  # minutes

        self.messages = self._define_messages()

        if not self.table_alt_logins_name in self.db.tables:
            self._define_alt_login_table()

    def _define_messages(self):
        messages = Messages(current.T)
        messages.label_alt_login_username = 'Sign-in with OpenID: '
        messages.label_add_alt_login_username = 'Add a new OpenID: '
        messages.submit_button = 'Sign in'
        messages.submit_button_add = 'Add'
        messages.a_delete = 'Delete'
        messages.comment_openid_signin = 'What is OpenID?'
        messages.comment_openid_help_title = 'Start using your OpenID'
        messages.comment_openid_help_url = 'http://openid.net/get-an-openid/start-using-your-openid/'
        messages.openid_fail_discover = 'Failed to discover OpenID service. Check your OpenID or "More about OpenID"?'
        messages.flash_openid_expired = 'OpenID expired. Please login or authenticate OpenID again. Sorry for the inconvenient.'
        messages.flash_openid_associated = 'OpenID associated'
        messages.flash_associate_openid = 'Please login or register an account for this OpenID.'
        messages.p_openid_not_registered = "This Open ID haven't be registered. " \
            + "Please login to associate with it or register an account for it."
        messages.flash_openid_authenticated = 'OpenID authenticated successfully.'
        messages.flash_openid_fail_authentication = 'OpenID authentication failed. (Error message: %s)'
        messages.flash_openid_canceled = 'OpenID authentication canceled by user.'
        messages.flash_openid_need_setup = 'OpenID authentication needs to be setup by the user with the provider first.'
        messages.h_openid_login = 'OpenID Login'
        messages.h_openid_list = 'OpenID List'
        return messages

    def _define_alt_login_table(self):
        """
        Define the OpenID login table.
        Note: type is what I used for our project. We're going to support 'fackbook' and
              'plurk' alternate login methods. Otherwise it's always 'openid' and you
              may not need it. This should be easy to changed.
              (Just remove the field of "type" and remove the
               "and db.alt_logins.type == type_" in _find_matched_openid function)
        """
        db = self.db
        table = db.define_table(
            self.table_alt_logins_name,
            Field('username', length=512, default=''),
            Field('type', length=128, default='openid', readable=False),
            Field('user', self.table_user, readable=False),
        )
        table.username.requires = IS_NOT_IN_DB(db, table.username)
        self.table_alt_logins = table

    def logout_url(self, next):
        """
        Delete the w2popenid record in session as logout
        """
        if current.session.w2popenid:
            del(current.session.w2popenid)
        return next

    def login_form(self):
        """
        Start to process the OpenID response if 'janrain_nonce' in request parameters
        and not processed yet. Else return the OpenID form for login.
        """
        request = current.request
        if 'janrain_nonce' in request.vars and not self._processed():
            self._process_response()
            return self.auth()
        return self._form()

    def get_user(self):
        """
        It supports the logout_url, implementing the get_user and login_form
        for cas usage of gluon.tools.Auth.
        """
        request = current.request
        args = request.args

        if args[0] == 'logout':
            return True  # Let logout_url got called

        if current.session.w2popenid:
            w2popenid = current.session.w2popenid
            db = self.db
            if (w2popenid.ok is True and w2popenid.oid):  # OpenID authenticated
                if self._w2popenid_expired(w2popenid):
                    del(current.session.w2popenid)
                    flash = self.messages.flash_openid_expired
                    current.session.warning = flash
                    redirect(self.auth.settings.login_url)
                oid = self._remove_protocol(w2popenid.oid)
                alt_login = self._find_matched_openid(db, oid)

                nextvar = self.nextvar
                # This OpenID not in the database. If user logged in then add it
                # into database, else ask user to login or register.
                if not alt_login:
                    if self.auth.is_logged_in():
                        # TODO: ask first maybe
                        self._associate_user_openid(self.auth.user, oid)
                        if current.session.w2popenid:
                            del(current.session.w2popenid)
                        current.session.flash = self.messages.flash_openid_associated
                        if nextvar in request.vars:
                            redirect(request.vars[nextvar])
                        redirect(self.auth.settings.login_next)

                    if nextvar not in request.vars:
                        # no next var, add it and do login again
                        # so if user login or register can go back here to associate the OpenID
                        redirect(URL(r=request,
                                     args=['login'],
                                     vars={nextvar: self.login_url}))
                    self.login_form = self._form_with_notification()
                    current.session.flash = self.messages.flash_associate_openid
                    return None  # need to login or register to associate this openid

                # Get existed OpenID user
                user = db(
                    self.table_user.id == alt_login.user).select().first()
                if user:
                    if current.session.w2popenid:
                        del(current.session.w2popenid)
                if 'username' in self.table_user.fields():
                    username = 'username'
                elif 'email' in self.table_user.fields():
                    username = 'email'
                return {username: user[username]} if user else None  # login success (almost)

        return None  # just start to login

    def _find_matched_openid(self, db, oid, type_='openid'):
        """
        Get the matched OpenID for given
        """
        query = (
            (db.alt_logins.username == oid) & (db.alt_logins.type == type_))
        alt_login = db(query).select().first()  # Get the OpenID record
        return alt_login

    def _associate_user_openid(self, user, oid):
        """
        Associate the user logged in with given OpenID
        """
        # print "[DB] %s authenticated" % oid
        self.db.alt_logins.insert(username=oid, user=user.id)

    def _form_with_notification(self):
        """
        Render the form for normal login with a notice of OpenID authenticated
        """
        form = DIV()
        # TODO: check when will happen
        if self.auth.settings.login_form in (self.auth, self):
            self.auth.settings.login_form = self.auth
            form = DIV(self.auth())

        register_note = DIV(P(self.messages.p_openid_not_registered))
        form.components.append(register_note)
        return lambda: form

    def _remove_protocol(self, oid):
        """
        Remove https:// or http:// from oid url
        """
        protocol = 'https://'
        if oid.startswith(protocol):
            oid = oid[len(protocol):]
            return oid
        protocol = 'http://'
        if oid.startswith(protocol):
            oid = oid[len(protocol):]
            return oid
        return oid

    def _init_consumerhelper(self):
        """
        Initialize the ConsumerHelper
        """
        if not hasattr(self, "consumerhelper"):
            self.consumerhelper = ConsumerHelper(current.session,
                                                 self.db)
        return self.consumerhelper

    def _form(self, style=None):
        form = DIV(H3(self.messages.h_openid_login), self._login_form(style))
        return form

    def _login_form(self,
                    openid_field_label=None,
                    submit_button=None,
                    _next=None,
                    style=None):
        """
        Render the form for OpenID login
        """
        def warning_openid_fail(session):
            session.warning = messages.openid_fail_discover

        style = style or """
background-attachment: scroll;
background-repeat: no-repeat;
background-image: url("http://wiki.openid.net/f/openid-16x16.gif");
background-position: 0% 50%;
background-color: transparent;
padding-left: 18px;
width: 400px;
"""
        style = style.replace("\n", "")

        request = current.request
        session = current.session
        messages = self.messages
        hidden_next_input = ""
        if _next == 'profile':
            profile_url = URL(r=request, f='user', args=['profile'])
            hidden_next_input = INPUT(
                _type="hidden", _name="_next", _value=profile_url)
        form = FORM(
            openid_field_label or self.messages.label_alt_login_username,
            INPUT(_type="input", _name="oid",
                  requires=IS_NOT_EMPTY(
                  error_message=messages.openid_fail_discover),
                  _style=style),
            hidden_next_input,
            INPUT(_type="submit",
                  _value=submit_button or messages.submit_button),
            " ",
            A(messages.comment_openid_signin,
              _href=messages.comment_openid_help_url,
              _title=messages.comment_openid_help_title,
              _class='openid-identifier',
              _target="_blank"),
            _action=self.login_url
        )
        if form.accepts(request.vars, session):
            oid = request.vars.oid
            consumerhelper = self._init_consumerhelper()
            url = self.login_url
            return_to_url = self.return_to_url
            if not oid:
                warning_openid_fail(session)
                redirect(url)
            try:
                if '_next' in request.vars:
                    return_to_url = self.return_to_url + \
                        '?_next=' + request.vars._next
                url = consumerhelper.begin(oid, self.realm, return_to_url)
            except DiscoveryFailure:
                warning_openid_fail(session)
            redirect(url)
        return form

    def _processed(self):
        """
        Check if w2popenid authentication is processed.
        Return True if processed else False.
        """
        processed = (hasattr(current.session, 'w2popenid') and
                     current.session.w2popenid.ok is True)
        return processed

    def _set_w2popenid_expiration(self, w2popenid):
        """
        Set expiration for OpenID authentication.
        """
        w2popenid.expiration = datetime.now(
        ) + timedelta(minutes=self.openid_expiration)

    def _w2popenid_expired(self, w2popenid):
        """
        Check if w2popenid authentication is expired.
        Return True if expired else False.
        """
        return (not w2popenid.expiration) or (datetime.now() > w2popenid.expiration)

    def _process_response(self):
        """
        Process the OpenID by ConsumerHelper.
        """
        request = current.request
        request_vars = request.vars
        consumerhelper = self._init_consumerhelper()
        process_status = consumerhelper.process_response(
            request_vars, self.return_to_url)
        if process_status == "success":
            w2popenid = current.session.w2popenid
            user_data = self.consumerhelper.sreg()
            current.session.w2popenid.ok = True
            self._set_w2popenid_expiration(w2popenid)
            w2popenid.user_data = user_data
            current.session.flash = self.messages.flash_openid_authenticated
        elif process_status == "failure":
            flash = self.messages.flash_openid_fail_authentication % consumerhelper.error_message
            current.session.warning = flash
        elif process_status == "cancel":
            current.session.warning = self.messages.flash_openid_canceled
        elif process_status == "setup_needed":
            current.session.warning = self.messages.flash_openid_need_setup

    def list_user_openids(self):
        messages = self.messages
        request = current.request
        if 'delete_openid' in request.vars:
            self.remove_openid(request.vars.delete_openid)

        query = self.db.alt_logins.user == self.auth.user.id
        alt_logins = self.db(query).select()
        l = []
        for alt_login in alt_logins:
            username = alt_login.username
            delete_href = URL(r=request, f='user',
                              args=['profile'],
                              vars={'delete_openid': username})
            delete_link = A(messages.a_delete, _href=delete_href)
            l.append(LI(username, " ", delete_link))

        profile_url = URL(r=request, f='user', args=['profile'])
        #return_to_url = self.return_to_url + '?' + self.nextvar + '=' + profile_url
        openid_list = DIV(H3(messages.h_openid_list), UL(l),
                          self._login_form(
                              _next='profile',
                              submit_button=messages.submit_button_add,
                              openid_field_label=messages.label_add_alt_login_username)
                          )
        return openid_list

    def remove_openid(self, openid):
        query = self.db.alt_logins.username == openid
        self.db(query).delete()

class ConsumerHelper(object):
    """
    ConsumerHelper knows the python-openid and
    """

    def __init__(self, session, db):
        self.session = session
        store = self._init_store(db)
        self.consumer = openid.consumer.consumer.Consumer(session, store)

    def _init_store(self, db):
        """
        Initialize Web2pyStore
        """
        if not hasattr(self, "store"):
            store = Web2pyStore(db)
            session = self.session
            if 'w2popenid' not in session:
                session.w2popenid = Storage()
            self.store = store
        return self.store

    def begin(self, oid, realm, return_to_url):
        """
        Begin the OpenID authentication
        """
        w2popenid = self.session.w2popenid
        w2popenid.oid = oid
        auth_req = self.consumer.begin(oid)
        auth_req.addExtension(SRegRequest(required=['email', 'nickname']))
        url = auth_req.redirectURL(return_to=return_to_url, realm=realm)
        return url

    def process_response(self, request_vars, return_to_url):
        """
        Complete the process and
        """
        resp = self.consumer.complete(request_vars, return_to_url)
        if resp:
            if resp.status == openid.consumer.consumer.SUCCESS:
                self.resp = resp
                if hasattr(resp, "identity_url"):
                    self.session.w2popenid.oid = resp.identity_url
                return "success"
            if resp.status == openid.consumer.consumer.FAILURE:
                self.error_message = resp.message
                return "failure"
            if resp.status == openid.consumer.consumer.CANCEL:
                return "cancel"
            if resp.status == openid.consumer.consumer.SETUP_NEEDED:
                return "setup_needed"
        return "no resp"

    def sreg(self):
        """
        Try to get OpenID Simple Registation
        http://openid.net/specs/openid-simple-registration-extension-1_0.html
        """
        if self.resp:
            resp = self.resp
            sreg_resp = SRegResponse.fromSuccessResponse(resp)
            return sreg_resp.data if sreg_resp else None
        else:
            return None

class Web2pyStore(OpenIDStore):
    """
    Web2pyStore

    This class implements the OpenIDStore interface. OpenID stores take care
    of persisting nonces and associations. The Janrain Python OpenID library
    comes with implementations for file and memory storage. Web2pyStore uses
    the web2py db abstration layer. See the source code docs of OpenIDStore
    for a comprehensive description of this interface.
    """

    def __init__(self, database):
        self.database = database
        self.table_oid_associations_name = 'oid_associations'
        self.table_oid_nonces_name = 'oid_nonces'
        self._initDB()

    def _initDB(self):

        if self.table_oid_associations_name not in self.database:
            self.database.define_table(self.table_oid_associations_name,
                                       Field('server_url',
                                             'string', length=2047, required=True),
                                       Field('handle',
                                             'string', length=255, required=True),
                                       Field('secret', 'blob', required=True),
                                       Field('issued',
                                             'integer', required=True),
                                       Field('lifetime',
                                             'integer', required=True),
                                       Field('assoc_type',
                                             'string', length=64, required=True)
                                       )
        if self.table_oid_nonces_name not in self.database:
            self.database.define_table(self.table_oid_nonces_name,
                                       Field('server_url',
                                             'string', length=2047, required=True),
                                       Field('timestamp',
                                             'integer', required=True),
                                       Field('salt', 'string',
                                             length=40, required=True)
                                       )

    def storeAssociation(self, server_url, association):
        """
        Store associations. If there already is one with the same
        server_url and handle in the table replace it.
        """

        db = self.database
        query = (db.oid_associations.server_url == server_url) & (
            db.oid_associations.handle == association.handle)
        db(query).delete()
        db.oid_associations.insert(server_url=server_url,
                                   handle=association.handle,
                                   secret=association.secret,
                                   issued=association.issued,
                                   lifetime=association.lifetime,
                                   assoc_type=association.assoc_type), 'insert ' * 10

    def getAssociation(self, server_url, handle=None):
        """
        Return the association for server_url and handle. If handle is
        not None return the latests associations for that server_url.
        Return None if no association can be found.
        """

        db = self.database
        query = (db.oid_associations.server_url == server_url)
        if handle:
            query &= (db.oid_associations.handle == handle)
        rows = db(query).select(orderby=db.oid_associations.issued)
        keep_assoc, _ = self._removeExpiredAssocations(rows)
        if len(keep_assoc) == 0:
            return None
        else:
            assoc = keep_assoc.pop(
            )  # pop the last one as it should be the latest one
            return Association(assoc['handle'],
                               assoc['secret'],
                               assoc['issued'],
                               assoc['lifetime'],
                               assoc['assoc_type'])

    def removeAssociation(self, server_url, handle):
        db = self.database
        query = (db.oid_associations.server_url == server_url) & (
            db.oid_associations.handle == handle)
        return db(query).delete() is not None

    def useNonce(self, server_url, timestamp, salt):
        """
        This method returns Falase if a nonce has been used before or its
        timestamp is not current.
        """

        db = self.database
        if abs(timestamp - time.time()) > nonce.SKEW:
            return False
        query = (db.oid_nonces.server_url == server_url) & (db.oid_nonces.timestamp == timestamp) & (db.oid_nonces.salt == salt)
        if db(query).count() > 0:
            return False
        else:
            db.oid_nonces.insert(server_url=server_url,
                                 timestamp=timestamp,
                                 salt=salt)
            return True

    def _removeExpiredAssocations(self, rows):
        """
        This helper function is not part of the interface. Given a list of
        association rows it checks which associations have expired and
        deletes them from the db. It returns a tuple of the form
        ([valid_assoc], no_of_expired_assoc_deleted).
        """

        db = self.database
        keep_assoc = []
        remove_assoc = []
        t1970 = time.time()
        for r in rows:
            if r['issued'] + r['lifetime'] < t1970:
                remove_assoc.append(r)
            else:
                keep_assoc.append(r)
        for r in remove_assoc:
            del db.oid_associations[r['id']]
        return (keep_assoc, len(remove_assoc))  # return tuple (list of valid associations, number of deleted associations)

    def cleanupNonces(self):
        """
        Remove expired nonce entries from DB and return the number
        of entries deleted.
        """

        db = self.database
        query = (db.oid_nonces.timestamp < time.time() - nonce.SKEW)
        return db(query).delete()

    def cleanupAssociations(self):
        """
        Remove expired associations from db and return the number
        of entries deleted.
        """

        db = self.database
        query = (db.oid_associations.id > 0)
        return self._removeExpiredAssocations(db(query).select())[1]  # return number of assoc removed

    def cleanup(self):
        """
        This method should be run periodically to free the db from
        expired nonce and association entries.
        """

        return self.cleanupNonces(), self.cleanupAssociations()


text:
package our.company.name.loan.designed.ui.implementations;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import our.company.name.application.utils.BooleanAndMessages;
import our.company.name.application.utils.StringConstants;
import our.company.name.loan.application.pojos.User;
import our.company.name.loan.dao.NewUserDao;
import our.company.name.loan.designed.ui.interfaces.INavigate;
import our.company.name.spring.SpringContextHelper;

import com.vaadin.annotations.AutoGenerated;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;

@SuppressWarnings("serial")
public class NewUserView extends CustomComponent implements View, INavigate {

	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */

	@AutoGenerated
	private AbsoluteLayout mainLayout;
	@AutoGenerated
	private Label messageLbl;
	@AutoGenerated
	private Button forgotPasswordBtn;
	@AutoGenerated
	private Button backBtn;
	@AutoGenerated
	private Button submitBtn;
	@AutoGenerated
	private PasswordField passwordField2;
	@AutoGenerated
	private PasswordField passwordField1;
	@AutoGenerated
	private TextField mobileTextField;
	@AutoGenerated
	private Label passwordLbl2;
	@AutoGenerated
	private Label passwordLbl1;
	@AutoGenerated
	private Label mobileLbl;
	@AutoGenerated
	private Label emailLbl;
	@AutoGenerated
	private TextField emailTextField;
	@AutoGenerated
	private TextField nameTextField;
	@AutoGenerated
	private Label nameLbl;

	/** Non UI Variables Declaration (START) */
	static Logger log = LoggerFactory.getLogger(NewUserView.class);
	public static final String NAME = "newUserRegistration";

	SpringContextHelper helper = null;
	NewUserDao newUserDao = null;

	/** Non UI Variables Declaration (END) */

	/**
	 * The constructor should first build the main layout, set the composition
	 * root and then do any custom initialization.
	 *
	 * The constructor will not be automatically regenerated by the visual
	 * editor.
	 */
	public NewUserView() {
		buildMainLayout();
		setCompositionRoot(mainLayout);

		helper = new SpringContextHelper(VaadinServlet.getCurrent()
				.getServletContext());

		newUserDao = (NewUserDao) helper.getBean("newUserDao");

		addAllButtonClickListeners();

	}

	@Override
	public void addAllButtonClickListeners() {
		/** Button Click Listeners Code (START) */

		forgotPasswordBtn.addClickListener(new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {

				// Navigate again to Forgot Password Page
				navigateTo(ForgotPasswordView.NAME);

			}
		});

		backBtn.addClickListener(new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {

				// Navigate again to Login Page
				navigateTo(LoginView.NAME);

			}
		});

		submitBtn.addClickListener(new Button.ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {

				// Step 1: Check whether user has entered valid password.

				boolean isPasswordValid = checkPasswordFields();

				if (isPasswordValid) {

					// Step 2: Collect Data from all text fields.

					User user = new User();

					user.firstname = nameTextField.getValue();

					// This is temporary arrangement
					user.lastname = user.firstname;

					user.email = emailTextField.getValue();
					user.mobile = mobileTextField.getValue();
					user.password = passwordField1.getValue();

					// Step 3: Create new User

					BooleanAndMessages status = newUserDao.createNewUser(user);

					if (status.state) {

						Notification
								.show(status.priorityMessage1,
										status.priorityMessage2,
										Type.HUMANIZED_MESSAGE);

						navigateTo(LoginView.NAME);

					} else {
						/*
						 * Email-ID provided is already in use by some other
						 * user / Some other problem has occurred
						 */
						Notification.show(status.priorityMessage1,
								status.priorityMessage2, Type.ERROR_MESSAGE);

						resetAllTextFields();

						return;

					}

					// Step 4: Insert the user object into database

				} else {
					messageLbl
							.setValue("Please Enter a Valid Password and enter same password in both the password fields.");
					return;

				}

			}

			private boolean checkPasswordFields() {

				if (passwordField1.getValue().equals(passwordField2.getValue())) {
					return true;
				} else {
					return false;
				}
			}
		});

		/** Button Click Listeners Code (END) */

	}

	private void resetAllTextFields() {

		this.nameTextField.setValue(StringConstants.EMPTY_STRING);
		this.mobileTextField.setValue(StringConstants.EMPTY_STRING);
		this.emailTextField.setValue(StringConstants.EMPTY_STRING);
		this.passwordField1.setValue(StringConstants.BLANK_SPACE);
		this.passwordField2.setValue(StringConstants.BLANK_SPACE);
	}

	@AutoGenerated
	private AbsoluteLayout buildMainLayout() {
		// common part: create layout
		mainLayout = new AbsoluteLayout();
		mainLayout.setImmediate(false);
		mainLayout.setWidth("100%");
		mainLayout.setHeight("100%");

		// top-level component properties
		setWidth("100.0%");
		setHeight("100.0%");

		// nameLbl
		nameLbl = new Label();
		nameLbl.setImmediate(false);
		nameLbl.setWidth("-1px");
		nameLbl.setHeight("-1px");
		nameLbl.setValue("Name:");
		mainLayout.addComponent(nameLbl, "top:40.0px;left:87.0px;");

		// nameTextField
		nameTextField = new TextField();
		nameTextField.setImmediate(false);
		nameTextField.setWidth("240px");
		nameTextField.setHeight("-1px");
		nameTextField.setInputPrompt("Enter your name");
		mainLayout.addComponent(nameTextField, "top:40.0px;left:140.0px;");

		// emailTextField
		emailTextField = new TextField();
		emailTextField.setImmediate(false);
		emailTextField.setWidth("240px");
		emailTextField.setHeight("-1px");
		emailTextField.setInputPrompt("Enter valid Email ID");
		mainLayout.addComponent(emailTextField, "top:80.0px;left:140.0px;");

		// emailLbl
		emailLbl = new Label();
		emailLbl.setImmediate(false);
		emailLbl.setWidth("-1px");
		emailLbl.setHeight("-1px");
		emailLbl.setValue("Email :");
		mainLayout.addComponent(emailLbl, "top:80.0px;left:87.0px;");

		// mobileLbl
		mobileLbl = new Label();
		mobileLbl.setImmediate(false);
		mobileLbl.setWidth("-1px");
		mobileLbl.setHeight("-1px");
		mobileLbl.setValue("Mobile :");
		mainLayout.addComponent(mobileLbl, "top:120.0px;left:80.0px;");

		// passwordLbl1
		passwordLbl1 = new Label();
		passwordLbl1.setImmediate(false);
		passwordLbl1.setWidth("-1px");
		passwordLbl1.setHeight("-1px");
		passwordLbl1.setValue("Password :");
		mainLayout.addComponent(passwordLbl1, "top:160.0px;left:60.0px;");

		// passwordLbl2
		passwordLbl2 = new Label();
		passwordLbl2.setImmediate(false);
		passwordLbl2.setWidth("-1px");
		passwordLbl2.setHeight("-1px");
		passwordLbl2.setValue("Reenter Password :");
		mainLayout.addComponent(passwordLbl2, "top:200.0px;left:20.0px;");

		// mobileTextField
		mobileTextField = new TextField();
		mobileTextField.setImmediate(false);
		mobileTextField.setWidth("240px");
		mobileTextField.setHeight("-1px");
		mobileTextField.setInputPrompt("Enter your 10 digit mobile number");
		mainLayout.addComponent(mobileTextField, "top:120.0px;left:140.0px;");

		// passwordField1
		passwordField1 = new PasswordField();
		passwordField1.setImmediate(false);
		passwordField1.setWidth("240px");
		passwordField1.setHeight("-1px");
		mainLayout.addComponent(passwordField1, "top:160.0px;left:140.0px;");

		// passwordField2
		passwordField2 = new PasswordField();
		passwordField2.setImmediate(false);
		passwordField2.setWidth("240px");
		passwordField2.setHeight("-1px");
		mainLayout.addComponent(passwordField2, "top:200.0px;left:140.0px;");

		// submitBtn
		submitBtn = new Button();
		submitBtn.setCaption("Submit");
		submitBtn.setImmediate(true);
		submitBtn.setWidth("100px");
		submitBtn.setHeight("-1px");
		mainLayout.addComponent(submitBtn, "top:240.0px;left:200.0px;");

		// backBtn
		backBtn = new Button();
		backBtn.setCaption("Login");
		backBtn.setImmediate(true);
		backBtn.setWidth("100px");
		backBtn.setHeight("-1px");
		mainLayout.addComponent(backBtn, "top:280.0px;left:140.0px;");

		// forgotPasswordBtn
		forgotPasswordBtn = new Button();
		forgotPasswordBtn.setCaption("Forgot Password?");
		forgotPasswordBtn.setImmediate(true);
		forgotPasswordBtn.setWidth("-1px");
		forgotPasswordBtn.setHeight("-1px");
		mainLayout.addComponent(forgotPasswordBtn, "top:280.0px;left:249.0px;");

		// messageLbl
		messageLbl = new Label();
		messageLbl.setImmediate(false);
		messageLbl.setWidth("-1px");
		messageLbl.setHeight("18px");
		messageLbl.setValue("Hello New User");
		mainLayout.addComponent(messageLbl, "top:20.0px;left:429.0px;");

		return mainLayout;
	}

	@Override
	public void enter(ViewChangeEvent event) {

	}

	@Override
	public void navigateTo(String vaadinPageName) {
		getUI().getNavigator().navigateTo(vaadinPageName);
	}

}


text:
package de.tum.in.niedermr.ta.extensions.analysis.workflows.coverage.parser;

import java.util.List;

import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import de.tum.in.niedermr.ta.core.analysis.result.receiver.IResultReceiver;
import de.tum.in.niedermr.ta.core.execution.id.IExecutionId;
import de.tum.in.niedermr.ta.runner.analysis.result.presentation.sql.SqlMultiInsertStatementBuilder;

/** Coverage parser for JaCoCo XML files. */
public class JaCoCoLineLevelParser extends AbstractJaCoCoParser {

	/** Logger. */
	private static final Logger LOGGER = LogManager.getLogger(JaCoCoLineLevelParser.class);

	private static final String SQL_INSERT_INTO_COMMIT_INFO = "INSERT IGNORE INTO Commit_Info "
			+ "(projectKey, commitHash) " + "VALUES (@projectKey, @commitHash);";
	private static final String SQL_INSERT_INTO_METHOD_LOCATION_INFORMATION = "INSERT INTO Method_Location_Import "
			+ "(projectKey, commitHash, className, methodShortName, methodDesc, startLine) "
			+ "VALUES (@projectKey, @commitHash, '%s', '%s', '%s', %s);";
	private static final String SQL_INSERT_INTO_LINE_COVERAGE_SHALLOW = "INSERT INTO Line_Coverage_Import "
			+ "(projectKey, commitHash, sessionNumber, packageName, sourceFileName, lineNumber, coverageState) VALUES %s;";
	private static final String SQL_INSERT_INTO_LINE_COVERAGE_VALUES = "(@projectKey, @commitHash, @sessionNumber, '%s', '%s', %s, '%s')";

	private XPathExpression m_classNameAttributeXPath;
	private XPathExpression m_methodNameAttributeXPath;
	private XPathExpression m_methodDescAttributeXPath;
	private XPathExpression m_methodLineAttributeXPath;

	private XPathExpression m_allPackagesXPath;
	private XPathExpression m_packageNameAttributeXPath;
	private XPathExpression m_sourceFilesOfPackageXPath;
	private XPathExpression m_sourceFileNameAttributeXPath;
	private XPathExpression m_sourceLinesOfFileXPath;
	private XPathExpression m_numberOfSourceLineAttributeXPath;
	private XPathExpression m_coveredInstructionsAttributeXPath;
	private XPathExpression m_missedInstructionsAttributeXPath;

	/** Constructor. */
	public JaCoCoLineLevelParser(IExecutionId executionId) {
		super(executionId);
	}

	/** {@inheritDoc} */
	@Override
	protected void execCompileXPathExpressions() throws XPathExpressionException {
		super.execCompileXPathExpressions();

		m_classNameAttributeXPath = compileXPath("@name");
		m_methodNameAttributeXPath = compileXPath("@name");
		m_methodDescAttributeXPath = compileXPath("@desc");
		m_methodLineAttributeXPath = compileXPath("@line");
		m_allPackagesXPath = compileXPath("//package");
		m_packageNameAttributeXPath = compileXPath("@name");
		m_sourceFilesOfPackageXPath = compileXPath("./sourcefile");
		m_sourceFileNameAttributeXPath = compileXPath("@name");
		m_sourceLinesOfFileXPath = compileXPath("./line");
		m_numberOfSourceLineAttributeXPath = compileXPath("@nr");
		m_coveredInstructionsAttributeXPath = compileXPath("@ci");
		m_missedInstructionsAttributeXPath = compileXPath("@mi");
	}

	/** {@inheritDoc} */
	@Override
	protected void parse(Document document, IResultReceiver resultReceiver) throws XPathExpressionException {
		LOGGER.info("Begin parsing method location information");
		parseMethodLocationInformation(document, resultReceiver);
		LOGGER.info("Completed parsing method location information");

		resultReceiver.markResultAsPartiallyComplete();

		LOGGER.info("Begin parsing line level information");
		parseLineCoverage(document, resultReceiver);
		LOGGER.info("Completed parsing line level information");

		resultReceiver.markResultAsComplete();
	}

	/** {@inheritDoc} */
	@Override
	protected void execAppendToOutputFileHeader(List<String> header) {
		super.execAppendToOutputFileHeader(header);

		header.add("");
		header.add(getResultPresentation().formatLineComment("BEGIN VARIABLES"));
		header.add("SET @projectKey = '###';");
		header.add("SET @commitHash = '###';");
		header.add("SET @sessionNumber = '###';");
		header.add(getResultPresentation().formatLineComment("END VARIABLES"));
		header.add("");

		header.add(SQL_INSERT_INTO_COMMIT_INFO);
	}

	private void parseMethodLocationInformation(Document document, IResultReceiver resultReceiver)
			throws XPathExpressionException {
		visitClassNodes(document, new INodeVisitor() {
			/** {@inheritDoc} */
			@Override
			public void visitNode(Node classNode, int nodeIndex) throws XPathExpressionException {
				parseClassNode(classNode, resultReceiver);
			}
		});
	}

	private void parseClassNode(Node classNode, IResultReceiver resultReceiver) throws XPathExpressionException {
		String className = evaluateStringValue(classNode, m_classNameAttributeXPath);

		visitMethodNodes(classNode, new INodeVisitor() {
			/** {@inheritDoc} */
			@Override
			public void visitNode(Node methodNode, int nodeIndex) throws XPathExpressionException {
				parseMethodNode(className, methodNode, resultReceiver);
			}
		});

		LOGGER.info("Parsed coverage of methods of class: " + className);
		resultReceiver.markResultAsPartiallyComplete();
	}

	private void parseMethodNode(String className, Node methodNode, IResultReceiver resultReceiver)
			throws XPathExpressionException {
		String methodName = evaluateStringValue(methodNode, m_methodNameAttributeXPath);
		String methodDesc = evaluateStringValue(methodNode, m_methodDescAttributeXPath);
		String methodLine = evaluateStringValue(methodNode, m_methodLineAttributeXPath);

		resultReceiver.append(String.format(SQL_INSERT_INTO_METHOD_LOCATION_INFORMATION, className, methodName,
				methodDesc, methodLine));
	}

	private void parseLineCoverage(Document document, IResultReceiver resultReceiver) throws XPathExpressionException {
		NodeList packages = evaluateNodeList(document, m_allPackagesXPath);

		visitNodes(packages, new INodeVisitor() {
			/** {@inheritDoc} */
			@Override
			public void visitNode(Node packageNode, int nodeIndex) throws XPathExpressionException {
				parsePackageNode(packageNode, resultReceiver);
			}
		});
	}

	private void parsePackageNode(Node packageNode, IResultReceiver resultReceiver) throws XPathExpressionException {
		String packageName = evaluateStringValue(packageNode, m_packageNameAttributeXPath);
		NodeList sourceFiles = evaluateNodeList(packageNode, m_sourceFilesOfPackageXPath);

		visitNodes(sourceFiles, new INodeVisitor() {
			/** {@inheritDoc} */
			@Override
			public void visitNode(Node sourceFileNode, int nodeIndex) throws XPathExpressionException {
				parseSourceFile(packageName, sourceFileNode, resultReceiver);
			}
		});

		LOGGER.info("Parsed package: " + packageName);
	}

	private void parseSourceFile(String packageName, Node sourceFileNode, IResultReceiver resultReceiver)
			throws XPathExpressionException {
		String sourceFileName = evaluateStringValue(sourceFileNode, m_sourceFileNameAttributeXPath);
		String sourceFileNameWithoutEnding = sourceFileName.replaceAll("\\.java$", "");
		NodeList sourceLines = evaluateNodeList(sourceFileNode, m_sourceLinesOfFileXPath);

		SqlMultiInsertStatementBuilder sqlStatementBuilder = new SqlMultiInsertStatementBuilder(
				SQL_INSERT_INTO_LINE_COVERAGE_SHALLOW);

		visitNodes(sourceLines, new INodeVisitor() {
			/** {@inheritDoc} */
			@Override
			public void visitNode(Node sourceLineNode, int nodeIndex) throws XPathExpressionException {
				parseSourceLineNode(packageName, sourceFileNameWithoutEnding, sourceLineNode, sqlStatementBuilder);
			}
		});

		resultReceiver.append(sqlStatementBuilder.toSql());
	}

	private void parseSourceLineNode(String packageName, String sourceFileName, Node sourceLineNode,
			SqlMultiInsertStatementBuilder sqlStatementBuilder) throws XPathExpressionException {
		String lineNumber = evaluateStringValue(sourceLineNode, m_numberOfSourceLineAttributeXPath);
		int countCoveredInstructions = evaluateIntValue(sourceLineNode, m_coveredInstructionsAttributeXPath);
		int countMissedInstructions = evaluateIntValue(sourceLineNode, m_missedInstructionsAttributeXPath);

		ELineCoverageState lineCoverageState = ELineCoverageState.get(countCoveredInstructions,
				countMissedInstructions);

		String sqlValuesStatementPart = String.format(SQL_INSERT_INTO_LINE_COVERAGE_VALUES, packageName, sourceFileName,
				lineNumber, lineCoverageState.getName());
		sqlStatementBuilder.addValuesStatementPart(sqlValuesStatementPart);
	}
}


text:
class CL1ImageComparator: public CImageComparator
{
public:
    using CImageComparator::CImageComparator;

    virtual bool Equal(const CImagePatch& patch1, const CImagePatch& patch2) const
    {
        CImage normPatch1;
        patch1.GrayImage().copyTo(normPatch1);

        CImage normPatch2;
        patch2.GrayImage().copyTo(normPatch2);

        _equalizer->EqualizeBrightness(normPatch1, normPatch2);

        CImage result;
        cv::absdiff(normPatch1, normPatch2, result);

        double sum = _summator->Sum(result);

        return sum < _eps;
    }
};


text:
namespace content {

// Preload VideoToolbox libraries, needed for sandbox warmup.
bool InitializeVideoToolbox();

// VideoToolbox.framework implementation of the VideoDecodeAccelerator
// interface for Mac OS X (currently limited to 10.9+).
class VTVideoDecodeAccelerator : public media::VideoDecodeAccelerator {
 public:
  explicit VTVideoDecodeAccelerator(
      const base::Callback<bool(void)>& make_context_current,
      const base::Callback<
          void(uint32_t, uint32_t, scoped_refptr<gl::GLImage>)>& bind_image);
  ~VTVideoDecodeAccelerator() override;

  // VideoDecodeAccelerator implementation.
  bool Initialize(const Config& config, Client* client) override;
  void Decode(const media::BitstreamBuffer& bitstream) override;
  void AssignPictureBuffers(
      const std::vector<media::PictureBuffer>& pictures) override;
  void ReusePictureBuffer(int32_t picture_id) override;
  void Flush() override;
  void Reset() override;
  void Destroy() override;
  bool CanDecodeOnIOThread() override;

  // Called by OutputThunk() when VideoToolbox finishes decoding a frame.
  void Output(
      void* source_frame_refcon,
      OSStatus status,
      CVImageBufferRef image_buffer);

  static media::VideoDecodeAccelerator::SupportedProfiles
      GetSupportedProfiles();

 private:
  // Logged to UMA, so never reuse values. Make sure to update
  // VTVDASessionFailureType in histograms.xml to match.
  enum VTVDASessionFailureType {
    SFT_SUCCESSFULLY_INITIALIZED = 0,
    SFT_PLATFORM_ERROR = 1,
    SFT_INVALID_STREAM = 2,
    SFT_UNSUPPORTED_STREAM_PARAMETERS = 3,
    SFT_DECODE_ERROR = 4,
    SFT_UNSUPPORTED_STREAM = 5,
    // Must always be equal to largest entry logged.
    SFT_MAX = SFT_UNSUPPORTED_STREAM
  };

  enum State {
    STATE_DECODING,
    STATE_ERROR,
    STATE_DESTROYING,
  };

  enum TaskType {
    TASK_FRAME,
    TASK_FLUSH,
    TASK_RESET,
    TASK_DESTROY,
  };

  struct Frame {
    explicit Frame(int32_t bitstream_id);
    ~Frame();

    // ID of the bitstream buffer this Frame will be decoded from.
    int32_t bitstream_id;

    // Relative presentation order of this frame (see AVC spec).
    int32_t pic_order_cnt;

    // Whether this frame is an IDR.
    bool is_idr;

    // Number of frames after this one in decode order that can appear before
    // before it in presentation order.
    int32_t reorder_window;

    // Size of the decoded frame.
    // TODO(sandersd): visible_rect.
    gfx::Size coded_size;

    // VideoToolbox decoded image, if decoding was successful.
    base::ScopedCFTypeRef<CVImageBufferRef> image;
  };

  struct Task {
    Task(TaskType type);
    ~Task();

    TaskType type;
    linked_ptr<Frame> frame;
  };

  struct PictureInfo {
    PictureInfo(uint32_t client_texture_id, uint32_t service_texture_id);
    ~PictureInfo();

    // Image buffer, kept alive while they are bound to pictures.
    base::ScopedCFTypeRef<CVImageBufferRef> cv_image;

    // The GLImage representation of |cv_image|. This is kept around to ensure
    // that Destroy is called on it before it hits its destructor (there is a
    // DCHECK that requires this).
    scoped_refptr<gl::GLImageIOSurface> gl_image;

    // Texture IDs for the image buffer.
    const uint32_t client_texture_id;
    const uint32_t service_texture_id;

   private:
    DISALLOW_COPY_AND_ASSIGN(PictureInfo);
  };

  //
  // Methods for interacting with VideoToolbox. Run on |decoder_thread_|.
  //

  // Compute the |pic_order_cnt| for a frame. Returns true or calls
  // NotifyError() before returning false.
  bool ComputePicOrderCnt(
      const media::H264SPS* sps,
      const media::H264SliceHeader& slice_hdr,
      Frame* frame);

  // Set up VideoToolbox using the current SPS and PPS. Returns true or calls
  // NotifyError() before returning false.
  bool ConfigureDecoder();

  // Wait for VideoToolbox to output all pending frames. Returns true or calls
  // NotifyError() before returning false.
  bool FinishDelayedFrames();

  // |frame| is owned by |pending_frames_|.
  void DecodeTask(const media::BitstreamBuffer&, Frame* frame);
  void DecodeDone(Frame* frame);

  //
  // Methods for interacting with |client_|. Run on |gpu_task_runner_|.
  //
  void NotifyError(
      Error vda_error_type,
      VTVDASessionFailureType session_failure_type);

  // |type| is the type of task that the flush will complete, one of TASK_FLUSH,
  // TASK_RESET, or TASK_DESTROY.
  void QueueFlush(TaskType type);
  void FlushTask(TaskType type);
  void FlushDone(TaskType type);

  // Try to make progress on tasks in the |task_queue_| or sending frames in the
  // |reorder_queue_|.
  void ProcessWorkQueues();

  // These methods returns true if a task was completed, false otherwise.
  bool ProcessTaskQueue();
  bool ProcessReorderQueue();
  bool ProcessFrame(const Frame& frame);
  bool SendFrame(const Frame& frame);

  //
  // GPU thread state.
  //
  base::Callback<bool(void)> make_context_current_;
  base::Callback<void(uint32_t, uint32_t, scoped_refptr<gl::GLImage>)>
      bind_image_;
  media::VideoDecodeAccelerator::Client* client_;
  State state_;

  // Queue of pending flush tasks. This is used to drop frames when a reset
  // is pending.
  std::queue<TaskType> pending_flush_tasks_;

  // Queue of tasks to complete in the GPU thread.
  std::queue<Task> task_queue_;

  // Utility class to define the order of frames in the reorder queue.
  struct FrameOrder {
    bool operator()(
        const linked_ptr<Frame>& lhs,
        const linked_ptr<Frame>& rhs) const;
  };

  // Queue of decoded frames in presentation order.
  std::priority_queue<linked_ptr<Frame>,
                      std::vector<linked_ptr<Frame>>,
                      FrameOrder> reorder_queue_;

  // Size of assigned picture buffers.
  gfx::Size picture_size_;

  // Frames that have not yet been decoded, keyed by bitstream ID; maintains
  // ownership of Frame objects while they flow through VideoToolbox.
  std::map<int32_t, linked_ptr<Frame>> pending_frames_;

  // Set of assigned bitstream IDs, so that Destroy() can release them all.
  std::set<int32_t> assigned_bitstream_ids_;

  // All picture buffers assigned to us. Used to check if reused picture buffers
  // should be added back to the available list or released. (They are not
  // released immediately because we need the reuse event to free the binding.)
  std::set<int32_t> assigned_picture_ids_;

  // Texture IDs and image buffers of assigned pictures.
  std::map<int32_t, scoped_ptr<PictureInfo>> picture_info_map_;

  // Pictures ready to be rendered to.
  std::vector<int32_t> available_picture_ids_;

  //
  // Decoder thread state.
  //
  VTDecompressionOutputCallbackRecord callback_;
  base::ScopedCFTypeRef<CMFormatDescriptionRef> format_;
  base::ScopedCFTypeRef<VTDecompressionSessionRef> session_;
  media::H264Parser parser_;
  gfx::Size coded_size_;

  int last_sps_id_;
  std::vector<uint8_t> last_sps_;
  std::vector<uint8_t> last_spsext_;
  int last_pps_id_;
  std::vector<uint8_t> last_pps_;
  bool config_changed_;
  bool missing_idr_logged_;
  media::H264POC poc_;

  //
  // Shared state (set up and torn down on GPU thread).
  //
  scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner_;
  base::ThreadChecker gpu_thread_checker_;
  base::WeakPtr<VTVideoDecodeAccelerator> weak_this_;
  base::Thread decoder_thread_;

  // Declared last to ensure that all weak pointers are invalidated before
  // other destructors run.
  base::WeakPtrFactory<VTVideoDecodeAccelerator> weak_this_factory_;

  DISALLOW_COPY_AND_ASSIGN(VTVideoDecodeAccelerator);
};

}  // namespace content

#endif  // CONTENT_COMMON_GPU_MEDIA_VT_VIDEO_DECODE_ACCELERATOR_H_


text:
import akka.actor._
import akka.util.Timeout
import java.util.concurrent.TimeUnit
import scala.concurrent.Await

/**
 * Created with IntelliJ IDEA.
 * User: hooxin
 * Date: 13-12-2
 * Time: 下午9:24
 * To change this template use File | Settings | File Templates.
 */
object AkkaTest extends App {
  val system=ActorSystem("myakkaSys")
  val manager=system.actorOf(Props[MyAkkaActorManager],"myakkamanager")
  manager!Start

}

class MyAkkaActorManager extends Actor with ActorLogging {
  override def preStart(): Unit = {
    log.info("MyAkkaActorManager is prestart.")
    log.info("MyAkkaActor is starting..")
    context.actorOf(Props[MyAkkaActor],"myakka")
    log.info("MyAkkaActor is started")
  }

  def receive: Actor.Receive = {
    case Start => context.actorFor("/user/myakkamanager/myakka")!Done
    case Done =>
      log.info("MyAkkaActorManager receive 'Done'")
      log.info("MyAkkaActor is stopping..")
      context.stop(context.actorFor("/user/myakkamanager/myakka"))
      log.info("MyAkkaActor is stopped..")
      log.info("MyAkkaActorManager will be stopped")
      context.stop(self)
      log.info("MyAkkaActorManager is stopped")
      context.system.shutdown()
      log.info("system is done")

  }
}
class MyAkkaActor extends Actor {
  def receive: Actor.Receive = {
    case Done => println("MyAkkaActor is done!")
      sender!Done
  }

}

sealed  class Commander
case class Done() extends Commander
case class Start() extends Commander


text:
package ql;
import antlr4.*;
//import ql.ast.*;

import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;

import java.io.File;
import java.io.FileInputStream;

public class Compilert {
	public static void main(String args[]) throws Exception {
		File file = new File(System.getProperty("user.dir") + "/src/questions.txt");
		FileInputStream fis = new FileInputStream(file);
		// create a CharStream that reads from standard input
		ANTLRInputStream input = new ANTLRInputStream(fis);
		// create a lexer that feeds off of input CharStream
		QLLexer lexer = new QLLexer(input);
		// create a buffer of tokens pulled from the lexer
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		// create a parser that feeds off the tokens buffer
		QLParser parser = new QLParser(tokens);
		ParseTree tree = parser.questionnaire();// begin parsing
		System.out.println(tree.toStringTree(parser));// print LISP-style tree
		// Create visitor
		//MyQLVisitor visitor = new MyQLVisitor();
		//visitor.visit(tree);
		// Etc.........
	}
}


text:
#ifdef PADDLE_WITH_CUDA
#include <nccl.h>
#endif
#include <memory>
#include <thread>  // NOLINT

#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/operators/distributed/sendrecvop_utils.h"
#include "paddle/fluid/operators/distributed/variable_response.h"
#include "paddle/fluid/platform/port.h"

DEFINE_bool(rpc_disable_reuse_port, false, "Disable SO_REUSEPORT or not.");

namespace paddle {
namespace operators {
namespace distributed {

using VarMsg = sendrecv::VariableMessage;

static TensorPayload GetCommunicationAllocationFromTensor(
    const platform::DeviceContext& ctx, const framework::Tensor& tensor) {
  if (is_gpu_place(ctx.GetPlace())) {
#ifdef PADDLE_WITH_CUDA
    PADDLE_ENFORCE(is_gpu_place(tensor.place()));
    auto& gpu_dev_ctx =
        reinterpret_cast<const platform::CUDADeviceContext&>(ctx);
    auto copy_size = tensor.numel() * framework::SizeOfType(tensor.type());
    platform::CUDAPinnedPlace cuda_pinned;
    auto result = memory::AllocShared(cuda_pinned, copy_size);

    memory::Copy(cuda_pinned, result->ptr(),
                 boost::get<platform::CUDAPlace>(tensor.place()),
                 tensor.data<void>(), copy_size, gpu_dev_ctx.stream());
    ctx.Wait();
    return TensorPayload(result);
#else
    PADDLE_THROW("This situation should not be happened");
#endif
  } else {
    return TensorPayload(tensor);
  }
}
TensorPayload GetTensorPayload(framework::Variable* var,
                               const platform::DeviceContext& ctx,
                               VarMsg* request) {
  auto tensor = var->Get<framework::LoDTensor>();
  // FIXME(wuyi): data types in send_recv.proto is copied from
  // framework.proto
  request->set_data_type(static_cast<VarMsg::Type>(tensor.type()));
  for (auto& dim : framework::vectorize(tensor.dims())) {
    request->add_dims(dim);
  }
  const framework::LoD lod = tensor.lod();
  if (lod.size() > 0) {
    request->set_lod_level(lod.size());
    for (auto& each : lod) {
      VarMsg::LodData* lod_inner = request->add_lod();
      for (auto& d : each) {
        lod_inner->add_lod_data(d);
      }
    }
  }
  return GetCommunicationAllocationFromTensor(ctx, tensor);
}

TensorPayload GetSelectedRowsPayload(framework::Variable* var,
                                     const platform::DeviceContext& ctx,
                                     VarMsg* request) {
  auto* slr = var->GetMutable<framework::SelectedRows>();
  request->set_data_type(static_cast<VarMsg::Type>(slr->value().type()));
  request->set_lod_level(0);
  request->set_slr_height(slr->height());

  for (auto& dim : framework::vectorize(slr->value().dims())) {
    request->add_dims(dim);
  }

  auto* tensor = slr->mutable_value();
  return GetCommunicationAllocationFromTensor(ctx, *tensor);
}

TensorPayload::TensorPayload(std::shared_ptr<memory::Allocation> allocation)
    : allocation_(allocation), offset_(0), memory_size_(allocation->size()) {}
TensorPayload::TensorPayload(const framework::Tensor& tensor)
    : allocation_(tensor.Holder()),
      offset_(tensor.offset()),
      memory_size_(tensor.numel() * framework::SizeOfType(tensor.type())) {}
void* TensorPayload::ptr() const {
  return reinterpret_cast<void*>(
      reinterpret_cast<uintptr_t>(allocation_->ptr()) + offset_);
}
size_t TensorPayload::memory_size() const { return memory_size_; }
}  // namespace distributed
}  // namespace operators
}  // namespace paddle


text:
import React, {useCallback, useMemo} from 'react';
import {useIntl} from 'react-intl';
import {Alert, TouchableOpacity, View} from 'react-native';

import {updateTeamThreadsAsRead} from '@actions/remote/thread';
import CompassIcon from '@components/compass_icon';
import FormattedText from '@components/formatted_text';
import {useServerUrl} from '@context/server';
import {useTheme} from '@context/theme';
import {preventDoubleTap} from '@utils/tap';
import {changeOpacity, makeStyleSheetFromTheme} from '@utils/theme';
import {typography} from '@utils/typography';

export type Props = {
    setTab: (tab: GlobalThreadsTab) => void;
    tab: GlobalThreadsTab;
    teamId: string;
    testID: string;
    unreadsCount: number;
};

const getStyleSheet = makeStyleSheetFromTheme((theme) => {
    return {
        container: {
            alignItems: 'center',
            borderBottomColor: changeOpacity(theme.centerChannelColor, 0.08),
            borderBottomWidth: 1,
            flexDirection: 'row',
        },
        menuContainer: {
            alignItems: 'center',
            flexGrow: 1,
            flexDirection: 'row',
            paddingLeft: 12,
            marginVertical: 12,
        },
        menuItemContainer: {
            paddingVertical: 8,
            paddingHorizontal: 16,
        },
        menuItemContainerSelected: {
            backgroundColor: changeOpacity(theme.buttonBg, 0.08),
            borderRadius: 4,
        },
        menuItem: {
            color: changeOpacity(theme.centerChannelColor, 0.56),
            alignSelf: 'center',
            ...typography('Body', 200, 'SemiBold'),
        },
        menuItemSelected: {
            color: theme.buttonBg,
        },
        unreadsDot: {
            position: 'absolute',
            width: 6,
            height: 6,
            borderRadius: 3,
            backgroundColor: theme.sidebarTextActiveBorder,
            right: -6,
            top: 4,
        },

        markAllReadIconContainer: {
            paddingHorizontal: 20,
        },
        markAllReadIcon: {
            fontSize: 28,
            lineHeight: 28,
            color: changeOpacity(theme.centerChannelColor, 0.56),
        },
        markAllReadIconDisabled: {
            opacity: 0.5,
        },
    };
});

const Header = ({setTab, tab, teamId, testID, unreadsCount}: Props) => {
    const theme = useTheme();
    const styles = getStyleSheet(theme);
    const intl = useIntl();
    const serverUrl = useServerUrl();

    const hasUnreads = unreadsCount > 0;
    const viewingUnreads = tab === 'unreads';

    const handleMarkAllAsRead = useCallback(preventDoubleTap(() => {
        Alert.alert(
            intl.formatMessage({
                id: 'global_threads.markAllRead.title',
                defaultMessage: 'Are you sure you want to mark all threads as read?',
            }),
            intl.formatMessage({
                id: 'global_threads.markAllRead.message',
                defaultMessage: 'This will clear any unread status for all of your threads shown here',
            }),
            [{
                text: intl.formatMessage({
                    id: 'global_threads.markAllRead.cancel',
                    defaultMessage: 'Cancel',
                }),
                style: 'cancel',
            }, {
                text: intl.formatMessage({
                    id: 'global_threads.markAllRead.markRead',
                    defaultMessage: 'Mark read',
                }),
                style: 'default',
                onPress: () => {
                    updateTeamThreadsAsRead(serverUrl, teamId);
                },
            }],
        );
    }), [intl, serverUrl, teamId]);

    const handleViewAllThreads = useCallback(preventDoubleTap(() => setTab('all')), []);
    const handleViewUnreadThreads = useCallback(preventDoubleTap(() => setTab('unreads')), []);

    const {allThreadsContainerStyle, allThreadsStyle, unreadsContainerStyle, unreadsStyle} = useMemo(() => {
        return {
            allThreadsContainerStyle: [
                styles.menuItemContainer,
                viewingUnreads ? undefined : styles.menuItemContainerSelected,
            ],
            allThreadsStyle: [
                styles.menuItem,
                viewingUnreads ? undefined : styles.menuItemSelected,
            ],
            unreadsContainerStyle: [
                styles.menuItemContainer,
                viewingUnreads ? styles.menuItemContainerSelected : undefined,
            ],
            unreadsStyle: [
                styles.menuItem,
                viewingUnreads ? styles.menuItemSelected : undefined,
            ],
        };
    }, [styles, viewingUnreads]);

    const markAllStyle = useMemo(() => [
        styles.markAllReadIcon,
        hasUnreads ? undefined : styles.markAllReadIconDisabled,
    ], [styles, hasUnreads]);

    return (
        <View style={styles.container}>
            <View style={styles.menuContainer}>
                <TouchableOpacity
                    onPress={handleViewAllThreads}
                    testID={`${testID}.all_threads.button`}
                >
                    <View style={allThreadsContainerStyle}>
                        <FormattedText
                            id='global_threads.allThreads'
                            defaultMessage='All your threads'
                            style={allThreadsStyle}
                        />
                    </View>
                </TouchableOpacity>
                <TouchableOpacity
                    onPress={handleViewUnreadThreads}
                    testID={`${testID}.unread_threads.button`}
                >
                    <View style={unreadsContainerStyle}>
                        <View>
                            <FormattedText
                                id='global_threads.unreads'
                                defaultMessage='Unreads'
                                style={unreadsStyle}
                            />
                            {hasUnreads ? (
                                <View
                                    style={styles.unreadsDot}
                                    testID={`${testID}.unreads_dot.badge`}
                                />
                            ) : null}
                        </View>
                    </View>
                </TouchableOpacity>
            </View>
            <View style={styles.markAllReadIconContainer}>
                <TouchableOpacity
                    disabled={!hasUnreads}
                    onPress={handleMarkAllAsRead}
                    testID={`${testID}.mark_all_as_read.button`}
                >
                    <CompassIcon
                        name='playlist-check'
                        style={markAllStyle}
                    />
                </TouchableOpacity>
            </View>
        </View>
    );
};

export default Header;


text:
/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.validator.internal.metadata.core;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * The list of built-in constraints.
 *

 * We are not using the class directly to avoid loading the class if possible.
 *

 * In the case of composing constraints, you need to define the dependencies manually.
 *

 * When adding a new built-in constraint, please add a test in {@code MessagePropertiesTest} and
 * {@code PredefinedScopeAllConstraintsTest}.
 *
 * @author Guillaume Smet
 */
enum BuiltinConstraint {

	// Specification constraints
	JAKARTA_VALIDATION_CONSTRAINTS_ASSERT_FALSE("jakarta.validation.constraints.AssertFalse"),
	JAKARTA_VALIDATION_CONSTRAINTS_ASSERT_TRUE("jakarta.validation.constraints.AssertTrue"),
	JAKARTA_VALIDATION_CONSTRAINTS_DECIMAL_MAX("jakarta.validation.constraints.DecimalMax"),
	JAKARTA_VALIDATION_CONSTRAINTS_DECIMAL_MIN("jakarta.validation.constraints.DecimalMin"),
	JAKARTA_VALIDATION_CONSTRAINTS_DIGITS("jakarta.validation.constraints.Digits"),
	JAKARTA_VALIDATION_CONSTRAINTS_EMAIL("jakarta.validation.constraints.Email"),
	JAKARTA_VALIDATION_CONSTRAINTS_FUTURE("jakarta.validation.constraints.Future"),
	JAKARTA_VALIDATION_CONSTRAINTS_FUTURE_OR_PRESENT("jakarta.validation.constraints.FutureOrPresent"),
	JAKARTA_VALIDATION_CONSTRAINTS_MIN("jakarta.validation.constraints.Min"),
	JAKARTA_VALIDATION_CONSTRAINTS_MAX("jakarta.validation.constraints.Max"),
	JAKARTA_VALIDATION_CONSTRAINTS_NEGATIVE("jakarta.validation.constraints.Negative"),
	JAKARTA_VALIDATION_CONSTRAINTS_NEGATIVE_OR_ZERO("jakarta.validation.constraints.NegativeOrZero"),
	JAKARTA_VALIDATION_CONSTRAINTS_NOT_BLANK("jakarta.validation.constraints.NotBlank"),
	JAKARTA_VALIDATION_CONSTRAINTS_NOT_EMPTY("jakarta.validation.constraints.NotEmpty"),
	JAKARTA_VALIDATION_CONSTRAINTS_NOT_NULL("jakarta.validation.constraints.NotNull"),
	JAKARTA_VALIDATION_CONSTRAINTS_NULL("jakarta.validation.constraints.Null"),
	JAKARTA_VALIDATION_CONSTRAINTS_PAST("jakarta.validation.constraints.Past"),
	JAKARTA_VALIDATION_CONSTRAINTS_PAST_OR_PRESENT("jakarta.validation.constraints.PastOrPresent"),
	JAKARTA_VALIDATION_CONSTRAINTS_PATTERN("jakarta.validation.constraints.Pattern"),
	JAKARTA_VALIDATION_CONSTRAINTS_POSITIVE("jakarta.validation.constraints.Positive"),
	JAKARTA_VALIDATION_CONSTRAINTS_POSITIVE_OR_ZERO("jakarta.validation.constraints.PositiveOrZero"),
	JAKARTA_VALIDATION_CONSTRAINTS_SIZE("jakarta.validation.constraints.Size"),

	// Hibernate Validator specific constraints
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_CODE_POINT_LENGTH("org.hibernate.validator.constraints.CodePointLength"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_CURRENCY("org.hibernate.validator.constraints.Currency"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_EMAIL("org.hibernate.validator.constraints.Email", Arrays.asList( JAKARTA_VALIDATION_CONSTRAINTS_PATTERN ) ),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_ISBN("org.hibernate.validator.constraints.ISBN"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_LENGTH("org.hibernate.validator.constraints.Length"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_LUHN_CHECK("org.hibernate.validator.constraints.LuhnCheck"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_CREDIT_CARD_NUMBER("org.hibernate.validator.constraints.CreditCardNumber",
			Arrays.asList( ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_LUHN_CHECK ) ),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_MOD10_CHECK("org.hibernate.validator.constraints.Mod10Check"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_MOD11_CHECK("org.hibernate.validator.constraints.Mod11Check"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_MOD_CHECK("org.hibernate.validator.constraints.ModCheck"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_NORMALIZED("org.hibernate.validator.constraints.Normalized"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_EAN("org.hibernate.validator.constraints.EAN", Arrays.asList( ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_MOD10_CHECK ) ),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_NOT_BLANK("org.hibernate.validator.constraints.NotBlank",
			Arrays.asList( JAKARTA_VALIDATION_CONSTRAINTS_NOT_NULL ) ),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_NOT_EMPTY("org.hibernate.validator.constraints.NotEmpty",
			Arrays.asList( JAKARTA_VALIDATION_CONSTRAINTS_NOT_NULL, JAKARTA_VALIDATION_CONSTRAINTS_SIZE )),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_PARAMETER_SCRIPT_ASSERT("org.hibernate.validator.constraints.ParameterScriptAssert"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_RANGE("org.hibernate.validator.constraints.Range",
			Arrays.asList( JAKARTA_VALIDATION_CONSTRAINTS_MIN, JAKARTA_VALIDATION_CONSTRAINTS_MAX )),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_SCRIPT_ASSERT("org.hibernate.validator.constraints.ScriptAssert"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_URL("org.hibernate.validator.constraints.URL",
			Arrays.asList( JAKARTA_VALIDATION_CONSTRAINTS_PATTERN )),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_UNIQUE_ELEMENTS("org.hibernate.validator.constraints.UniqueElements"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_BR_CNPJ("org.hibernate.validator.constraints.br.CNPJ",
			Arrays.asList( JAKARTA_VALIDATION_CONSTRAINTS_PATTERN )),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_BR_CPF("org.hibernate.validator.constraints.br.CPF",
			Arrays.asList( JAKARTA_VALIDATION_CONSTRAINTS_PATTERN )),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_BR_TITULO_ELEITORAL("org.hibernate.validator.constraints.br.TituloEleitoral",
			Arrays.asList( JAKARTA_VALIDATION_CONSTRAINTS_PATTERN, ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_MOD11_CHECK ) ),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_PL_NIP("org.hibernate.validator.constraints.pl.NIP"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_PL_PESEL("org.hibernate.validator.constraints.pl.PESEL"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_PL_REGON("org.hibernate.validator.constraints.pl.REGON"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_RU_INN("org.hibernate.validator.constraints.ru.INN"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_TIME_DURATION_MAX("org.hibernate.validator.constraints.time.DurationMax"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_TIME_DURATION_MIN("org.hibernate.validator.constraints.time.DurationMin"),
	ORG_HIBERNATE_VALIDATOR_CONSTRAINTS_UUID("org.hibernate.validator.constraints.UUID");

	private static final Map<String, Set<BuiltinConstraint>> CONSTRAINT_MAPPING;

	static {
		CONSTRAINT_MAPPING = new HashMap<>();
		for ( BuiltinConstraint constraint : values() ) {
			if ( constraint.constraintDependencies.isEmpty() ) {
				CONSTRAINT_MAPPING.put( constraint.annotationClassName, Collections.singleton( constraint ) );
			}
			else {
				Set<BuiltinConstraint> constraints = new HashSet<>();
				constraints.add( constraint );
				constraints.addAll( constraint.constraintDependencies );
				CONSTRAINT_MAPPING.put( constraint.annotationClassName, constraints );
			}
		}
	}

	private String annotationClassName;
	private List<BuiltinConstraint> constraintDependencies;

	BuiltinConstraint(String constraint) {
		this( constraint, Collections.emptyList() );
	}

	BuiltinConstraint(String constraint, List<BuiltinConstraint> composingConstraints) {
		this.annotationClassName = constraint;
		this.constraintDependencies = composingConstraints;
	}

	static Set<BuiltinConstraint> resolve(Set<String> constraints) {
		Set<BuiltinConstraint> resolvedConstraints = new HashSet<>();
		for ( String constraint : constraints ) {
			Set<BuiltinConstraint> builtinConstraints = CONSTRAINT_MAPPING.get( constraint );
			if ( builtinConstraints != null ) {
				resolvedConstraints.addAll( builtinConstraints );
			}
		}
		return resolvedConstraints;
	}

	static boolean isBuiltin(String constraint) {
		return CONSTRAINT_MAPPING.containsKey( constraint );
	}

	static Set<String> set() {
		return CONSTRAINT_MAPPING.keySet();
	}
}


text:
import Ember from 'ember';
import baseSerializerMixin from 'ember-data-partial-model/mixins/base-serializer';
const { Mixin } = Ember;

export default Mixin.create(baseSerializerMixin, {
  _normalizePartialRelationship: function(modelClass, resourceHash, descriptor) {
    resourceHash.relationships = resourceHash.relationships || {};
    resourceHash.relationships[descriptor.key] = {
      data: {
        type: descriptor.type,
        id: this.extractId(modelClass, resourceHash)
      }
    };
  },

  _copyAttributesFromPartialToParent: function(serializedHash, partialHash) {
    Ember.merge(serializedHash.data.attributes, partialHash.data.attributes);
  }
});