text:
"""
The OffsetBox is a simple container artist. The child artist are meant
to be drawn at a relative position to its parent.  The [VH]Packer,
DrawingArea and TextArea are derived from the OffsetBox.

The [VH]Packer automatically adjust the relative postisions of their
children, which should be instances of the OffsetBox. This is used to
align similar artists together, e.g., in legend.

The DrawingArea can contain any Artist as a child. The
DrawingArea has a fixed width and height. The position of children
relative to the parent is fixed.  The TextArea is contains a single
Text instance. The width and height of the TextArea instance is the
width and height of the its child text.
"""

from __future__ import print_function
import matplotlib.transforms as mtransforms
import matplotlib.artist as martist
import matplotlib.text as mtext
import numpy as np
from matplotlib.transforms import Bbox, BboxBase, TransformedBbox, \
     IdentityTransform, BboxTransformFrom

from matplotlib.font_manager import FontProperties
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch
from matplotlib import rcParams

from matplotlib import docstring
import matplotlib.cbook as cbook

#from bboximage import BboxImage
from matplotlib.image import BboxImage

from matplotlib.patches import bbox_artist as mbbox_artist

DEBUG = False
# for debuging use
def bbox_artist(*args, **kwargs):
    if DEBUG:
        mbbox_artist(*args, **kwargs)

# _get_packed_offsets() and _get_aligned_offsets() are coded assuming
# that we are packing boxes horizontally. But same function will be
# used with vertical packing.

def _get_packed_offsets(wd_list, total, sep, mode="fixed"):
    """
    Geiven a list of (width, xdescent) of each boxes, calculate the
    total width and the x-offset positions of each items according to
    *mode*. xdescent is analagous to the usual descent, but along the
    x-direction. xdescent values are currently ignored.

    *wd_list* : list of (width, xdescent) of boxes to be packed.
    *sep* : spacing between boxes
    *total* : Intended total length. None if not used.
    *mode* : packing mode. 'fixed', 'expand', or 'equal'.
    """

    w_list, d_list = zip(*wd_list)
    # d_list is currently not used.

    if mode == "fixed":
        offsets_ = np.add.accumulate([0] + [w + sep for w in w_list])
        offsets = offsets_[:-1]

        if total is None:
            total = offsets_[-1] - sep

        return total, offsets

    elif mode == "expand":
        sep = (total - sum(w_list)) / (len(w_list) - 1.)
        offsets_ = np.add.accumulate([0] + [w + sep for w in w_list])
        offsets = offsets_[:-1]

        return total, offsets

    elif mode == "equal":
        maxh = max(w_list)
        if total is None:
            total = (maxh + sep) * len(w_list)
        else:
            sep = float(total) / (len(w_list)) - maxh

        offsets = np.array([(maxh + sep) * i for i in range(len(w_list))])

        return total, offsets

    else:
        raise ValueError("Unknown mode : %s" % (mode,))

def _get_aligned_offsets(hd_list, height, align="baseline"):
    """
    Given a list of (height, descent) of each boxes, align the boxes
    with *align* and calculate the y-offsets of each boxes.
    total width and the offset positions of each items according to
    *mode*. xdescent is analogous to the usual descent, but along the
    x-direction. xdescent values are currently ignored.

    *hd_list* : list of (width, xdescent) of boxes to be aligned.
    *sep* : spacing between boxes
    *height* : Intended total length. None if not used.
    *align* : align mode. 'baseline', 'top', 'bottom', or 'center'.
    """

    if height is None:
        height = max([h for h, d in hd_list])

    if align == "baseline":
        height_descent = max([h - d for h, d in hd_list])
        descent = max([d for h, d in hd_list])
        height = height_descent + descent
        offsets = [0. for h, d in hd_list]
    elif align in ["left", "top"]:
        descent = 0.
        offsets = [d for h, d in hd_list]
    elif align in ["right", "bottom"]:
        descent = 0.
        offsets = [height - h + d for h, d in hd_list]
    elif align == "center":
        descent = 0.
        offsets = [(height - h) * .5 + d for h, d in hd_list]
    else:
        raise ValueError("Unknown Align mode : %s" % (align,))

    return height, descent, offsets

class OffsetBox(martist.Artist):
    """
    The OffsetBox is a simple container artist. The child artist are meant
    to be drawn at a relative position to its parent.
    """
    def __init__(self, *args, **kwargs):

        super(OffsetBox, self).__init__(*args, **kwargs)

        self._children = []
        self._offset = (0, 0)

    def __getstate__(self):
        state = martist.Artist.__getstate__(self)

        # pickle cannot save instancemethods, so handle them here
        from cbook import _InstanceMethodPickler
        import inspect

        offset = state['_offset']
        if inspect.ismethod(offset):
            state['_offset'] = _InstanceMethodPickler(offset)
        return state

    def __setstate__(self, state):
        self.__dict__ = state
        from cbook import _InstanceMethodPickler
        if isinstance(self._offset, _InstanceMethodPickler):
            self._offset = self._offset.get_instancemethod()

    def set_figure(self, fig):
        """
        Set the figure

        accepts a class:`~matplotlib.figure.Figure` instance
        """
        martist.Artist.set_figure(self, fig)
        for c in self.get_children():
            c.set_figure(fig)

    def contains(self, mouseevent):
        for c in self.get_children():
            a, b = c.contains(mouseevent)
            if a:
                return a, b
        return False, {}

    def set_offset(self, xy):
        """
        Set the offset

        accepts x, y, tuple, or a callable object.
        """
        self._offset = xy

    def get_offset(self, width, height, xdescent, ydescent, renderer):
        """
        Get the offset

        accepts extent of the box
        """
        if callable(self._offset):
            return self._offset(width, height, xdescent, ydescent, renderer)
        else:
            return self._offset

    def set_width(self, width):
        """
        Set the width

        accepts float
        """
        self.width = width

    def set_height(self, height):
        """
        Set the height

        accepts float
        """
        self.height = height

    def get_visible_children(self):
        """
        Return a list of visible artists it contains.
        """
        return [c for c in self._children if c.get_visible()]

    def get_children(self):
        """
        Return a list of artists it contains.
        """
        return self._children

    def get_extent_offsets(self, renderer):
        raise Exception("")

    def get_extent(self, renderer):
        """
        Return with, height, xdescent, ydescent of box
        """
        w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
        return w, h, xd, yd

    def get_window_extent(self, renderer):
        '''
        get the bounding box in display space.
        '''
        w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
        px, py = self.get_offset(w, h, xd, yd, renderer)
        return mtransforms.Bbox.from_bounds(px - xd, py - yd, w, h)

    def draw(self, renderer):
        """
        Update the location of children if necessary and draw them
        to the given *renderer*.
        """

        width, height, xdescent, ydescent, offsets = self.get_extent_offsets(renderer)

        px, py = self.get_offset(width, height, xdescent, ydescent, renderer)

        for c, (ox, oy) in zip(self.get_visible_children(), offsets):
            c.set_offset((px + ox, py + oy))
            c.draw(renderer)

        bbox_artist(self, renderer, fill=False, props=dict(pad=0.))

class PackerBase(OffsetBox):
    def __init__(self, pad=None, sep=None, width=None, height=None,
                 align=None, mode=None,
                 children=None):
        """
        *pad* : boundary pad
        *sep* : spacing between items
        *width*, *height* : width and height of the container box.
           calculated if None.
        *align* : alignment of boxes. Can be one of 'top', 'bottom',
           'left', 'right', 'center' and 'baseline'
        *mode* : packing mode

        .. note::
          *pad* and *sep* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """
        super(PackerBase, self).__init__()

        self.height = height
        self.width = width
        self.sep = sep
        self.pad = pad
        self.mode = mode
        self.align = align

        self._children = children

class VPacker(PackerBase):
    """
    The VPacker has its children packed vertically. It automatically
    adjust the relative positions of children in the drawing time.
    """
    def __init__(self, pad=None, sep=None, width=None, height=None,
                 align="baseline", mode="fixed",
                 children=None):
        """
        *pad* : boundary pad
        *sep* : spacing between items
        *width*, *height* : width and height of the container box.
           calculated if None.
        *align* : alignment of boxes
        *mode* : packing mode

        .. note::
          *pad* and *sep* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """
        super(VPacker, self).__init__(pad, sep, width, height,
                                      align, mode,
                                      children)

    def get_extent_offsets(self, renderer):
        """
        update offset of childrens and return the extents of the box
        """

        dpicor = renderer.points_to_pixels(1.)
        pad = self.pad * dpicor
        sep = self.sep * dpicor

        if self.width is not None:
            for c in self.get_visible_children():
                if isinstance(c, PackerBase) and c.mode == "expand":
                    c.set_width(self.width)

        whd_list = [c.get_extent(renderer) for c in self.get_visible_children()]
        whd_list = [(w, h, xd, (h - yd)) for w, h, xd, yd in whd_list]

        wd_list = [(w, xd) for w, h, xd, yd in whd_list]
        width, xdescent, xoffsets = _get_aligned_offsets(wd_list,
                                                         self.width,
                                                         self.align)

        pack_list = [(h, yd) for w, h, xd, yd in whd_list]
        height, yoffsets_ = _get_packed_offsets(pack_list, self.height,
                                                sep, self.mode)

        yoffsets = yoffsets_ + [yd for w, h, xd, yd in whd_list]
        ydescent = height - yoffsets[0]
        yoffsets = height - yoffsets

        #w, h, xd, h_yd = whd_list[-1]
        yoffsets = yoffsets - ydescent

        return width + 2 * pad, height + 2 * pad, \
               xdescent + pad, ydescent + pad, \
               zip(xoffsets, yoffsets)

class HPacker(PackerBase):
    """
    The HPacker has its children packed horizontally. It automatically
    adjusts the relative positions of children at draw time.
    """
    def __init__(self, pad=None, sep=None, width=None, height=None,
                 align="baseline", mode="fixed",
                 children=None):
        """
        *pad* : boundary pad
        *sep* : spacing between items
        *width*, *height* : width and height of the container box.
           calculated if None.
        *align* : alignment of boxes
        *mode* : packing mode

        .. note::
          *pad* and *sep* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """
        super(HPacker, self).__init__(pad, sep, width, height,
                                      align, mode, children)

    def get_extent_offsets(self, renderer):
        """
        update offset of children and return the extents of the box
        """
        dpicor = renderer.points_to_pixels(1.)
        pad = self.pad * dpicor
        sep = self.sep * dpicor

        whd_list = [c.get_extent(renderer) for c in self.get_visible_children()]

        if not whd_list:
            return 2 * pad, 2 * pad, pad, pad, []

        if self.height is None:
            height_descent = max([h - yd for w, h, xd, yd in whd_list])
            ydescent = max([yd for w, h, xd, yd in whd_list])
            height = height_descent + ydescent
        else:
            height = self.height - 2 * pad # width w/o pad

        hd_list = [(h, yd) for w, h, xd, yd in whd_list]
        height, ydescent, yoffsets = _get_aligned_offsets(hd_list,
                                                          self.height,
                                                          self.align)

        pack_list = [(w, xd) for w, h, xd, yd in whd_list]

        width, xoffsets_ = _get_packed_offsets(pack_list, self.width,
                                               sep, self.mode)

        xoffsets = xoffsets_ + [xd for w, h, xd, yd in whd_list]

        xdescent = whd_list[0][2]
        xoffsets = xoffsets - xdescent

        return width + 2 * pad, height + 2 * pad, \
               xdescent + pad, ydescent + pad, \
               zip(xoffsets, yoffsets)

class PaddedBox(OffsetBox):
    def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super(PaddedBox, self).__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1, #self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame

    def get_extent_offsets(self, renderer):
        """
        update offset of childrens and return the extents of the box
        """

        dpicor = renderer.points_to_pixels(1.)
        pad = self.pad * dpicor

        w, h, xd, yd = self._children[0].get_extent(renderer)

        return w + 2 * pad, h + 2 * pad, \
               xd + pad, yd + pad, \
               [(0, 0)]

    def draw(self, renderer):
        """
        Update the location of children if necessary and draw them
        to the given *renderer*.
        """

        width, height, xdescent, ydescent, offsets = self.get_extent_offsets(renderer)

        px, py = self.get_offset(width, height, xdescent, ydescent, renderer)

        for c, (ox, oy) in zip(self.get_visible_children(), offsets):
            c.set_offset((px + ox, py + oy))

        self.draw_frame(renderer)

        for c in self.get_visible_children():
            c.draw(renderer)

        #bbox_artist(self, renderer, fill=False, props=dict(pad=0.))

    def update_frame(self, bbox, fontsize=None):
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        if fontsize:
            self.patch.set_mutation_scale(fontsize)

    def draw_frame(self, renderer):
        # update the location and size of the legend
        bbox = self.get_window_extent(renderer)
        self.update_frame(bbox)

        if self._drawFrame:
            self.patch.draw(renderer)

class DrawingArea(OffsetBox):
    """
    The DrawingArea can contain any Artist as a child. The DrawingArea
    has a fixed width and height. The position of children relative to
    the parent is fixed.
    """

    def __init__(self, width, height, xdescent=0.,
                 ydescent=0., clip=True):
        """
        *width*, *height* : width and height of the container box.
        *xdescent*, *ydescent* : descent of the box in x- and y-direction.
        """

        super(DrawingArea, self).__init__()

        self.width = width
        self.height = height
        self.xdescent = xdescent
        self.ydescent = ydescent

        self.offset_transform = mtransforms.Affine2D()
        self.offset_transform.clear()
        self.offset_transform.translate(0, 0)

        self.dpi_transform = mtransforms.Affine2D()

    def get_transform(self):
        """
        Return the :class:`~matplotlib.transforms.Transform` applied
        to the children
        """
        return self.dpi_transform + self.offset_transform

    def set_transform(self, t):
        """
        set_transform is ignored.
        """
        pass

    def set_offset(self, xy):
        """
        set offset of the container.

        Accept : tuple of x,y cooridnate in disokay units.
        """
        self._offset = xy

        self.offset_transform.clear()
        self.offset_transform.translate(xy[0], xy[1])

    def get_offset(self):
        """
        return offset of the container.
        """
        return self._offset

    def get_window_extent(self, renderer):
        '''
        get the bounding box in display space.
        '''
        w, h, xd, yd = self.get_extent(renderer)
        ox, oy = self.get_offset() #w, h, xd, yd)

        return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h)

    def get_extent(self, renderer):
        """
        Return with, height, xdescent, ydescent of box
        """

        dpi_cor = renderer.points_to_pixels(1.)
        return self.width * dpi_cor, self.height * dpi_cor, \
               self.xdescent * dpi_cor, self.ydescent * dpi_cor

    def add_artist(self, a):
        'Add any :class:`~matplotlib.artist.Artist` to the container box'
        self._children.append(a)
        if not a.is_transform_set():
            a.set_transform(self.get_transform())

    def draw(self, renderer):
        """
        Draw the children
        """

        dpi_cor = renderer.points_to_pixels(1.)
        self.dpi_transform.clear()
        self.dpi_transform.scale(dpi_cor, dpi_cor)

        for c in self._children:
            c.draw(renderer)

        bbox_artist(self, renderer, fill=False, props=dict(pad=0.))

class TextArea(OffsetBox):
    """
    The TextArea is contains a single Text instance. The text is
    placed at (0,0) with baseline+left alignment. The width and height
    of the TextArea instance is the width and height of the its child
    text.
    """
    def __init__(self, s,
                 textprops=None,
                 multilinebaseline=None,
                 minimumdescent=True,
                 ):
        """
        *s* : a string to be displayed.
        *textprops* : property dictionary for the text
        *multilinebaseline* : If True, baseline for multiline text is
                              adjusted so that it is (approximatedly)
                              center-aligned with singleline text.
        *minimumdescent*  : If True, the box has a minimum descent of "p".
        """
        if textprops is None:
            textprops = {}

        if "va" not in textprops:
            textprops["va"] = "baseline"

        self._text = mtext.Text(0, 0, s, **textprops)

        OffsetBox.__init__(self)

        self._children = [self._text]

        self.offset_transform = mtransforms.Affine2D()
        self.offset_transform.clear()
        self.offset_transform.translate(0, 0)
        self._baseline_transform = mtransforms.Affine2D()
        self._text.set_transform(self.offset_transform + self._baseline_transform)

        self._multilinebaseline = multilinebaseline
        self._minimumdescent = minimumdescent

    def set_text(self, s):
        "set text"
        self._text.set_text(s)

    def get_text(self):
        "get text"
        return self._text.get_text()

    def set_multilinebaseline(self, t):
        """
        Set multilinebaseline .

        If True, baseline for multiline text is
        adjusted so that it is (approximatedly) center-aligned with
        singleline text.
        """
        self._multilinebaseline = t

    def get_multilinebaseline(self):
        """
        get multilinebaseline .
        """
        return self._multilinebaseline

    def set_minimumdescent(self, t):
        """
        Set minimumdescent .

        If True, extent of the single line text is adjusted so that
        it has minimum descent of "p"
        """
        self._minimumdescent = t

    def get_minimumdescent(self):
        """
        get minimumdescent.
        """
        return self._minimumdescent

    def set_transform(self, t):
        """
        set_transform is ignored.
        """
        pass

    def set_offset(self, xy):
        """
        set offset of the container.

        Accept : tuple of x,y coordinates in display units.
        """
        self._offset = xy

        self.offset_transform.clear()
        self.offset_transform.translate(xy[0], xy[1])

    def get_offset(self):
        """
        return offset of the container.
        """
        return self._offset

    def get_window_extent(self, renderer):
        '''
        get the bounding box in display space.
        '''
        w, h, xd, yd = self.get_extent(renderer)
        ox, oy = self.get_offset() #w, h, xd, yd)
        return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h)

    def get_extent(self, renderer):
        clean_line, ismath = self._text.is_math_text(self._text._text)
        _, h_, d_ = renderer.get_text_width_height_descent(
            "lp", self._text._fontproperties, ismath=False)

        bbox, info = self._text._get_layout(renderer)
        w, h = bbox.width, bbox.height

        line = info[-1][0] # last line
        _, hh, dd = renderer.get_text_width_height_descent(
            line, self._text._fontproperties, ismath=ismath)
        d = dd  # the baseline of the last line

        self._baseline_transform.clear()

        if len(info) > 1 and self._multilinebaseline:
            d_new = 0.5 * h - 0.5 * (h_ - d_)
            self._baseline_transform.translate(0, d - d_new)
            d = d_new

        else: # single line

            h_d = max(h_ - d_, h - d)

            if self.get_minimumdescent():
                ## to have a minimum descent, #i.e., "l" and "p" have same
                ## descents.
                d = max(d, d_)
            #else:
            #    d = d

            h = h_d + d

        return w, h, 0., d

    def draw(self, renderer):
        """
        Draw the children
        """

        self._text.draw(renderer)

        bbox_artist(self, renderer, fill=False, props=dict(pad=0.))

class AuxTransformBox(OffsetBox):
    """
    Offset Box with the aux_transform . Its children will be
    transformed with the aux_transform first then will be
    offseted. The absolute coordinate of the aux_transform is meaning
    as it will be automatically adjust so that the left-lower corner
    of the bounding box of children will be set to (0,0) before the
    offset transform.

    It is similar to drawing area, except that the extent of the box
    is not predetermined but calculated from the window extent of its
    children. Furthermore, the extent of the children will be
    calculated in the transformed coordinate.
    """
    def __init__(self, aux_transform):
        self.aux_transform = aux_transform
        OffsetBox.__init__(self)

        self.offset_transform = mtransforms.Affine2D()
        self.offset_transform.clear()
        self.offset_transform.translate(0, 0)

        # ref_offset_transform is used to make the offset_transform is
        # always reference to the lower-left corner of the bbox of its
        # children.
        self.ref_offset_transform = mtransforms.Affine2D()
        self.ref_offset_transform.clear()

    def add_artist(self, a):
        'Add any :class:`~matplotlib.artist.Artist` to the container box'
        self._children.append(a)
        a.set_transform(self.get_transform())

    def get_transform(self):
        """
        Return the :class:`~matplotlib.transforms.Transform` applied
        to the children
        """
        return self.aux_transform + \
               self.ref_offset_transform + \
               self.offset_transform

    def set_transform(self, t):
        """
        set_transform is ignored.
        """
        pass

    def set_offset(self, xy):
        """
        set offset of the container.

        Accept : tuple of x,y coordinate in disokay units.
        """
        self._offset = xy

        self.offset_transform.clear()
        self.offset_transform.translate(xy[0], xy[1])

    def get_offset(self):
        """
        return offset of the container.
        """
        return self._offset

    def get_window_extent(self, renderer):
        '''
        get the bounding box in display space.
        '''
        w, h, xd, yd = self.get_extent(renderer)
        ox, oy = self.get_offset() #w, h, xd, yd)
        return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h)

    def get_extent(self, renderer):

        # clear the offset transforms
        _off = self.offset_transform.to_values() # to be restored later
        self.ref_offset_transform.clear()
        self.offset_transform.clear()

        # calculate the extent
        bboxes = [c.get_window_extent(renderer) for c in self._children]
        ub = mtransforms.Bbox.union(bboxes)

        # adjust ref_offset_tansform
        self.ref_offset_transform.translate(-ub.x0, -ub.y0)

        # restor offset transform
        mtx = self.offset_transform.matrix_from_values(*_off)
        self.offset_transform.set_matrix(mtx)

        return ub.width, ub.height, 0., 0.

    def draw(self, renderer):
        """
        Draw the children
        """

        for c in self._children:
            c.draw(renderer)

        bbox_artist(self, renderer, fill=False, props=dict(pad=0.))

class AnchoredOffsetbox(OffsetBox):
    """
    An offset box placed according to the legend location
    loc. AnchoredOffsetbox has a single child. When multiple children
    is needed, use other OffsetBox class to enclose them.  By default,
    the offset box is anchored against its parent axes. You may
    explicitly specify the bbox_to_anchor.
    """
    zorder = 5 # zorder of the legend

    def __init__(self, loc,
                 pad=0.4, borderpad=0.5,
                 child=None, prop=None, frameon=True,
                 bbox_to_anchor=None,
                 bbox_transform=None,
                 **kwargs):
        """
        loc is a string or an integer specifying the legend location.
        The valid  location codes are::

        'upper right'  : 1,
        'upper left'   : 2,
        'lower left'   : 3,
        'lower right'  : 4,
        'right'        : 5,
        'center left'  : 6,
        'center right' : 7,
        'lower center' : 8,
        'upper center' : 9,
        'center'       : 10,

        pad : pad around the child for drawing a frame. given in
          fraction of fontsize.

        borderpad : pad between offsetbox frame and the bbox_to_anchor,

        child : OffsetBox instance that will be anchored.

        prop : font property. This is only used as a reference for paddings.

        frameon : draw a frame box if True.

        bbox_to_anchor : bbox to anchor. Use self.axes.bbox if None.

        bbox_transform : with which the bbox_to_anchor will be transformed.

        """
        super(AnchoredOffsetbox, self).__init__(**kwargs)

        self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
        self.set_child(child)

        self.loc = loc
        self.borderpad = borderpad
        self.pad = pad

        if prop is None:
            self.prop = FontProperties(size=rcParams["legend.fontsize"])
        elif isinstance(prop, dict):
            self.prop = FontProperties(**prop)
            if "size" not in prop:
                self.prop.set_size(rcParams["legend.fontsize"])
        else:
            self.prop = prop

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=self.prop.get_size_in_points(),
            snap=True
            )
        self.patch.set_boxstyle("square", pad=0)
        self._drawFrame = frameon

    def set_child(self, child):
        "set the child to be anchored"
        self._child = child

    def get_child(self):
        "return the child"
        return self._child

    def get_children(self):
        "return the list of children"
        return [self._child]

    def get_extent(self, renderer):
        """
        return the extent of the artist. The extent of the child
        added with the pad is returned
        """
        w, h, xd, yd = self.get_child().get_extent(renderer)
        fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
        pad = self.pad * fontsize

        return w + 2 * pad, h + 2 * pad, xd + pad, yd + pad

    def get_bbox_to_anchor(self):
        """
        return the bbox that the legend will be anchored
        """
        if self._bbox_to_anchor is None:
            return self.axes.bbox
        else:
            transform = self._bbox_to_anchor_transform
            if transform is None:
                return self._bbox_to_anchor
            else:
                return TransformedBbox(self._bbox_to_anchor,
                                       transform)

    def set_bbox_to_anchor(self, bbox, transform=None):
        """
        set the bbox that the child will be anchored.

        *bbox* can be a Bbox instance, a list of [left, bottom, width,
        height], or a list of [left, bottom] where the width and
        height will be assumed to be zero. The bbox will be
        transformed to display coordinate by the given transform.
        """
        if bbox is None or isinstance(bbox, BboxBase):
            self._bbox_to_anchor = bbox
        else:
            try:
                l = len(bbox)
            except TypeError:
                raise ValueError("Invalid argument for bbox : %s" % str(bbox))

            if l == 2:
                bbox = [bbox[0], bbox[1], 0, 0]

            self._bbox_to_anchor = Bbox.from_bounds(*bbox)

        self._bbox_to_anchor_transform = transform

    def get_window_extent(self, renderer):
        '''
        get the bounding box in display space.
        '''
        self._update_offset_func(renderer)
        w, h, xd, yd = self.get_extent(renderer)
        ox, oy = self.get_offset(w, h, xd, yd, renderer)
        return Bbox.from_bounds(ox - xd, oy - yd, w, h)

    def _update_offset_func(self, renderer, fontsize=None):
        """
        Update the offset func which depends on the dpi of the
        renderer (because of the padding).
        """
        if fontsize is None:
            fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())

        def _offset(w, h, xd, yd, renderer, fontsize=fontsize, self=self):
            bbox = Bbox.from_bounds(0, 0, w, h)
            borderpad = self.borderpad * fontsize
            bbox_to_anchor = self.get_bbox_to_anchor()

            x0, y0 = self._get_anchored_bbox(self.loc,
                                             bbox,
                                             bbox_to_anchor,
                                             borderpad)
            return x0 + xd, y0 + yd

        self.set_offset(_offset)

    def update_frame(self, bbox, fontsize=None):
            self.patch.set_bounds(bbox.x0, bbox.y0,
                                  bbox.width, bbox.height)

            if fontsize:
                self.patch.set_mutation_scale(fontsize)

    def draw(self, renderer):
        "draw the artist"

        if not self.get_visible(): return

        fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
        self._update_offset_func(renderer, fontsize)

        if self._drawFrame:
            # update the location and size of the legend
            bbox = self.get_window_extent(renderer)
            self.update_frame(bbox, fontsize)
            self.patch.draw(renderer)

        width, height, xdescent, ydescent = self.get_extent(renderer)

        px, py = self.get_offset(width, height, xdescent, ydescent, renderer)

        self.get_child().set_offset((px, py))
        self.get_child().draw(renderer)

    def _get_anchored_bbox(self, loc, bbox, parentbbox, borderpad):
        """
        return the position of the bbox anchored at the parentbbox
        with the loc code, with the borderpad.
        """
        assert loc in range(1, 11) # called only internally

        BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11)

        anchor_coefs = {UR:"NE",
                      UL:"NW",
                      LL:"SW",
                      LR:"SE",
                      R:"E",
                      CL:"W",
                      CR:"E",
                      LC:"S",
                      UC:"N",
                      C:"C"}

        c = anchor_coefs[loc]

        container = parentbbox.padded(-borderpad)
        anchored_box = bbox.anchored(c, container=container)
        return anchored_box.x0, anchored_box.y0

class AnchoredText(AnchoredOffsetbox):
    """
    AnchoredOffsetbox with Text
    """

    def __init__(self, s, loc, pad=0.4, borderpad=0.5, prop=None, **kwargs):
        """
        *s* : string
        *loc* : location code
        *prop* : font property
        *pad* : pad between the text and the frame as fraction of the font size.
        *borderpad* : pad between the frame and the axes (or bbox_to_anchor).

        other keyword parameters of AnchoredOffsetbox are also allowed.
        """

        self.txt = TextArea(s, textprops=prop,
                            minimumdescent=False)
        fp = self.txt._text.get_fontproperties()

        super(AnchoredText, self).__init__(loc, pad=pad, borderpad=borderpad,
                                           child=self.txt,
                                           prop=fp,
                                           **kwargs)

class OffsetImage(OffsetBox):
    def __init__(self, arr,
                 zoom=1,
                 cmap=None,
                 norm=None,
                 interpolation=None,
                 origin=None,
                 filternorm=1,
                 filterrad=4.0,
                 resample=False,
                 dpi_cor=True,
                 **kwargs
                 ):

        self._dpi_cor = dpi_cor

        self.image = BboxImage(bbox=self.get_window_extent,
                               cmap=cmap,
                               norm=norm,
                               interpolation=interpolation,
                               origin=origin,
                               filternorm=filternorm,
                               filterrad=filterrad,
                               resample=resample,
                               **kwargs
                               )

        self._children = [self.image]

        self.set_zoom(zoom)
        self.set_data(arr)

        OffsetBox.__init__(self)

    def set_data(self, arr):
        self._data = np.asarray(arr)
        self.image.set_data(self._data)

    def get_data(self):
        return self._data

    def set_zoom(self, zoom):
        self._zoom = zoom

    def get_zoom(self):
        return self._zoom

#     def set_axes(self, axes):
#         self.image.set_axes(axes)
#         martist.Artist.set_axes(self, axes)

#     def set_offset(self, xy):
#         """
#         set offset of the container.

#         Accept : tuple of x,y coordinate in disokay units.
#         """
#         self._offset = xy

#         self.offset_transform.clear()
#         self.offset_transform.translate(xy[0], xy[1])

    def get_offset(self):
        """
        return offset of the container.
        """
        return self._offset

    def get_children(self):
        return [self.image]

    def get_window_extent(self, renderer):
        '''
        get the bounding box in display space.
        '''
        w, h, xd, yd = self.get_extent(renderer)
        ox, oy = self.get_offset()
        return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h)

    def get_extent(self, renderer):

        if self._dpi_cor: # True, do correction
            dpi_cor = renderer.points_to_pixels(1.)
        else:
            dpi_cor = 1.

        zoom = self.get_zoom()
        data = self.get_data()
        ny, nx = data.shape[:2]
        w, h = nx * zoom, ny * zoom

        return w, h, 0, 0

    def draw(self, renderer):
        """
        Draw the children
        """
        self.image.draw(renderer)
        #bbox_artist(self, renderer, fill=False, props=dict(pad=0.))

from matplotlib.text import _AnnotationBase

class AnnotationBbox(martist.Artist, _AnnotationBase):
    """
    Annotation-like class, but with offsetbox instead of Text.
    """
    zorder = 3

    def __str__(self):
        return "AnnotationBbox(%g,%g)" % (self.xy[0], self.xy[1])
    @docstring.dedent_interpd
    def __init__(self, offsetbox, xy,
                 xybox=None,
                 xycoords='data',
                 boxcoords=None,
                 frameon=True, pad=0.4, # BboxPatch
                 annotation_clip=None,
                 box_alignment=(0.5, 0.5),
                 bboxprops=None,
                 arrowprops=None,
                 fontsize=None,
                 **kwargs):
        """
        *offsetbox* : OffsetBox instance

        *xycoords* : same as Annotation but can be a tuple of two
           strings which are interpreted as x and y coordinates.

        *boxcoords* : similar to textcoords as Annotation but can be a
           tuple of two strings which are interpreted as x and y
           coordinates.

        *box_alignment* : a tuple of two floats for a vertical and
           horizontal alignment of the offset box w.r.t. the *boxcoords*.
           The lower-left corner is (0.0) and upper-right corner is (1.1).

        other parameters are identical to that of Annotation.
        """
        self.offsetbox = offsetbox

        self.arrowprops = arrowprops

        self.set_fontsize(fontsize)

        if arrowprops is not None:
            self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5))
            self.arrow_patch = FancyArrowPatch((0, 0), (1, 1),
                                               **self.arrowprops)
        else:
            self._arrow_relpos = None
            self.arrow_patch = None

        _AnnotationBase.__init__(self,
                                 xy, xytext=xybox,
                                 xycoords=xycoords, textcoords=boxcoords,
                                 annotation_clip=annotation_clip)

        martist.Artist.__init__(self, **kwargs)

        #self._fw, self._fh = 0., 0. # for alignment
        self._box_alignment = box_alignment

        # frame
        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=self.prop.get_size_in_points(),
            snap=True
            )
        self.patch.set_boxstyle("square", pad=pad)
        if bboxprops:
            self.patch.set(**bboxprops)
        self._drawFrame = frameon

    def contains(self, event):
        t, tinfo = self.offsetbox.contains(event)
        #if self.arrow_patch is not None:
        #    a,ainfo=self.arrow_patch.contains(event)
        #    t = t or a

        # self.arrow_patch is currently not checked as this can be a line - JJ

        return t, tinfo

    def get_children(self):
        children = [self.offsetbox, self.patch]
        if self.arrow_patch:
            children.append(self.arrow_patch)
        return children

    def set_figure(self, fig):

        if self.arrow_patch is not None:
            self.arrow_patch.set_figure(fig)
        self.offsetbox.set_figure(fig)
        martist.Artist.set_figure(self, fig)

    def set_fontsize(self, s=None):
        """
        set fontsize in points
        """
        if s is None:
            s = rcParams["legend.fontsize"]

        self.prop = FontProperties(size=s)

    def get_fontsize(self, s=None):
        """
        return fontsize in points
        """
        return self.prop.get_size_in_points()

    def update_positions(self, renderer):
        "Update the pixel positions of the annotated point and the text."
        xy_pixel = self._get_position_xy(renderer)
        self._update_position_xybox(renderer, xy_pixel)

        mutation_scale = renderer.points_to_pixels(self.get_fontsize())
        self.patch.set_mutation_scale(mutation_scale)

        if self.arrow_patch:
            self.arrow_patch.set_mutation_scale(mutation_scale)

    def _update_position_xybox(self, renderer, xy_pixel):
        "Update the pixel positions of the annotation text and the arrow patch."

        x, y = self.xytext
        if isinstance(self.textcoords, tuple):
            xcoord, ycoord = self.textcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.textcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrinked by shirnkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA)

    def draw(self, renderer):
        """
        Draw the :class:`Annotation` object to the given *renderer*.
        """

        if renderer is not None:
            self._renderer = renderer
        if not self.get_visible(): return

        xy_pixel = self._get_position_xy(renderer)

        if not self._check_xy(renderer, xy_pixel):
            return

        self.update_positions(renderer)

        if self.arrow_patch is not None:
            if self.arrow_patch.figure is None and self.figure is not None:
                self.arrow_patch.figure = self.figure
            self.arrow_patch.draw(renderer)

        if self._drawFrame:
            self.patch.draw(renderer)

        self.offsetbox.draw(renderer)

class DraggableBase(object):
    """
    helper code for a draggable artist (legend, offsetbox)
    The derived class must override following two method.

      def saveoffset(self):
          pass

      def update_offset(self, dx, dy):
          pass

    *saveoffset* is called when the object is picked for dragging and it is
    meant to save reference position of the artist.

    *update_offset* is called during the dragging. dx and dy is the pixel
     offset from the point where the mouse drag started.

    Optionally you may override following two methods.

      def artist_picker(self, artist, evt):
          return self.ref_artist.contains(evt)

      def finalize_offset(self):
          pass

    *artist_picker* is a picker method that will be
     used. *finalize_offset* is called when the mouse is released. In
     current implementaion of DraggableLegend and DraggableAnnotation,
     *update_offset* places the artists simply in display
     coordinates. And *finalize_offset* recalculate their position in
     the normalized axes coordinate and set a relavant attribute.

    """
    def __init__(self, ref_artist, use_blit=False):
        self.ref_artist = ref_artist
        self.got_artist = False
        self._use_blit = use_blit

        self.canvas = self.ref_artist.figure.canvas
        c2 = self.canvas.mpl_connect('pick_event', self.on_pick)
        c3 = self.canvas.mpl_connect('button_release_event', self.on_release)

        ref_artist.set_picker(self.artist_picker)
        self.cids = [c2, c3]

    def on_motion(self, evt):
        if self.got_artist:
            dx = evt.x - self.mouse_x
            dy = evt.y - self.mouse_y
            self.update_offset(dx, dy)
            self.canvas.draw()

    def on_motion_blit(self, evt):
        if self.got_artist:
            dx = evt.x - self.mouse_x
            dy = evt.y - self.mouse_y
            self.update_offset(dx, dy)
            self.canvas.restore_region(self.background)
            self.ref_artist.draw(self.ref_artist.figure._cachedRenderer)
            self.canvas.blit(self.ref_artist.figure.bbox)

    def on_pick(self, evt):
        if evt.artist == self.ref_artist:

            self.mouse_x = evt.mouseevent.x
            self.mouse_y = evt.mouseevent.y
            self.got_artist = True

            if self._use_blit:
                self.ref_artist.set_animated(True)
                self.canvas.draw()
                self.background = self.canvas.copy_from_bbox(self.ref_artist.figure.bbox)
                self.ref_artist.draw(self.ref_artist.figure._cachedRenderer)
                self.canvas.blit(self.ref_artist.figure.bbox)
                self._c1 = self.canvas.mpl_connect('motion_notify_event', self.on_motion_blit)
            else:
                self._c1 = self.canvas.mpl_connect('motion_notify_event', self.on_motion)
            self.save_offset()

    def on_release(self, event):
        if self.got_artist:
            self.finalize_offset()
            self.got_artist = False
            self.canvas.mpl_disconnect(self._c1)

            if self._use_blit:
                self.ref_artist.set_animated(False)

    def disconnect(self):
        'disconnect the callbacks'
        for cid in self.cids:
            self.canvas.mpl_disconnect(cid)

    def artist_picker(self, artist, evt):
        return self.ref_artist.contains(evt)

    def save_offset(self):
        pass

    def update_offset(self, dx, dy):
        pass

    def finalize_offset(self):
        pass

class DraggableOffsetBox(DraggableBase):
    def __init__(self, ref_artist, offsetbox, use_blit=False):
        DraggableBase.__init__(self, ref_artist, use_blit=use_blit)
        self.offsetbox = offsetbox

    def save_offset(self):
        offsetbox = self.offsetbox
        renderer = offsetbox.figure._cachedRenderer
        w, h, xd, yd = offsetbox.get_extent(renderer)
        offset = offsetbox.get_offset(w, h, xd, yd, renderer)
        self.offsetbox_x, self.offsetbox_y = offset
        self.offsetbox.set_offset(offset)

    def update_offset(self, dx, dy):
        loc_in_canvas = self.offsetbox_x + dx, self.offsetbox_y + dy
        self.offsetbox.set_offset(loc_in_canvas)

    def get_loc_in_canvas(self):

        offsetbox = self.offsetbox
        renderer = offsetbox.figure._cachedRenderer
        w, h, xd, yd = offsetbox.get_extent(renderer)
        ox, oy = offsetbox._offset
        loc_in_canvas = (ox - xd, oy - yd)

        return loc_in_canvas

class DraggableAnnotation(DraggableBase):
    def __init__(self, annotation, use_blit=False):
        DraggableBase.__init__(self, annotation, use_blit=use_blit)
        self.annotation = annotation

    def save_offset(self):
        ann = self.annotation
        x, y = ann.xytext
        if isinstance(ann.textcoords, tuple):
            xcoord, ycoord = ann.textcoords
            x1, y1 = ann._get_xy(self.canvas.renderer, x, y, xcoord)
            x2, y2 = ann._get_xy(self.canvas.renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = ann._get_xy(self.canvas.renderer, x, y, ann.textcoords)

        self.ox, self.oy = ox0, oy0
        self.annotation.textcoords = "figure pixels"
        self.update_offset(0, 0)

    def update_offset(self, dx, dy):
        ann = self.annotation
        ann.xytext = self.ox + dx, self.oy + dy
        x, y = ann.xytext
        xy = ann._get_xy(self.canvas.renderer, x, y, ann.textcoords)

    def finalize_offset(self):
        loc_in_canvas = self.annotation.xytext
        self.annotation.textcoords = "axes fraction"
        pos_axes_fraction = self.annotation.axes.transAxes.inverted().transform_point(loc_in_canvas)
        self.annotation.xytext = tuple(pos_axes_fraction)

if __name__ == "__main__":
    import matplotlib.pyplot as plt
    fig = plt.figure(1)
    fig.clf()
    ax = plt.subplot(121)

    #txt = ax.text(0.5, 0.5, "Test", size=30, ha="center", color="w")
    kwargs = dict()

    a = np.arange(256).reshape(16, 16) / 256.
    myimage = OffsetImage(a,
                          zoom=2,
                          norm=None,
                          origin=None,
                          **kwargs
                          )
    ax.add_artist(myimage)

    myimage.set_offset((100, 100))

    myimage2 = OffsetImage(a,
                           zoom=2,
                           norm=None,
                           origin=None,
                           **kwargs
                           )
    ann = AnnotationBbox(myimage2, (0.5, 0.5),
                         xybox=(30, 30),
                         xycoords='data',
                         boxcoords="offset points",
                         frameon=True, pad=0.4, # BboxPatch
                         bboxprops=dict(boxstyle="round", fc="y"),
                         fontsize=None,
                         arrowprops=dict(arrowstyle="->"),
                         )

    ax.add_artist(ann)

    plt.draw()
    plt.show()


text:
require "rails_helper"
feature "User sign in" do
  extend SubdomainHelpers

  let!(:account) { FactoryGirl.create(:account) }
  let(:sign_in_url) { "http://#{account.subdomain}.example.com/sign_in" }
  let(:root_url) { "http://#{account.subdomain}.example.com/" }
  within_account_subdomain do
    scenario "signs in as an account owner successfully" do
      visit root_url
      expect(page.current_url).to eq(sign_in_url)
      fill_in "Email", with: account.owner.email
      fill_in "Password", with: "password"
      click_button "Sign in"
      expect(page).to have_content("You are now signed in.")
      expect(page.current_url).to eq(root_url)
    end

    scenario "attempts sign in with an invalid password and fails" do
      visit subscribem.root_url(subdomain: account.subdomain)
      expect(page.current_url).to eq(sign_in_url)
      expect(page).to have_content("Please sign in.")
      fill_in "Email", with: account.owner.email
      fill_in "Password", with: "drowssap"
      click_button "Sign in"
      expect(page).to have_content("Invalid email or password.")
      expect(page.current_url).to eq(sign_in_url)
    end

    scenario "attempts sign in with an invalid email address and fails" do
      visit subscribem.root_url(subdomain: account.subdomain)
      expect(page.current_url).to eq(sign_in_url)
      expect(page).to have_content("Please sign in.")
      fill_in "Email", with: "foo@example.com"
      fill_in "Password", with: "password"
      click_button "Sign in"
      expect(page).to have_content("Invalid email or password.")
      expect(page.current_url).to eq(sign_in_url)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Overview
</TITLE>

<META NAME="date" CONTENT="2009-05-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

    Overview
      Package
      Class
      Tree
      Deprecated
      Index
      Help

MXQuery 0.6.0 API Documentation - Copyright 2006-2009 ETH Zurich

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

MXQuery 0.6.0 API Documentation

Packages

ch.ethz.mxquery.bindings

ch.ethz.mxquery.cmdline

ch.ethz.mxquery.contextConfig

ch.ethz.mxquery.datamodel

ch.ethz.mxquery.datamodel.adm

ch.ethz.mxquery.datamodel.types

ch.ethz.mxquery.datamodel.xdm

ch.ethz.mxquery.exceptions

ch.ethz.mxquery.extensionsModules

ch.ethz.mxquery.extensionsModules.io

ch.ethz.mxquery.extensionsModules.math

ch.ethz.mxquery.extensionsModules.util

ch.ethz.mxquery.extensionsModules.zorbaRest

ch.ethz.mxquery.functions

ch.ethz.mxquery.functions.fn

ch.ethz.mxquery.functions.ft

ch.ethz.mxquery.functions.mxq

ch.ethz.mxquery.functions.xs

ch.ethz.mxquery.iterators

ch.ethz.mxquery.iterators.forseq

ch.ethz.mxquery.iterators.ft

ch.ethz.mxquery.iterators.scripting

ch.ethz.mxquery.iterators.update

ch.ethz.mxquery.model

ch.ethz.mxquery.model.ft

ch.ethz.mxquery.model.updatePrimitives

ch.ethz.mxquery.model.ws

ch.ethz.mxquery.opt.expr

ch.ethz.mxquery.opt.index

ch.ethz.mxquery.parallel

ch.ethz.mxquery.query

ch.ethz.mxquery.query.impl

ch.ethz.mxquery.query.optimizer

ch.ethz.mxquery.query.parser

ch.ethz.mxquery.query.webservice

ch.ethz.mxquery.sms

ch.ethz.mxquery.sms.activeStore

ch.ethz.mxquery.sms.btree

ch.ethz.mxquery.sms.ftstore

ch.ethz.mxquery.sms.interfaces

ch.ethz.mxquery.sms.iterators

ch.ethz.mxquery.sms.MMimpl

ch.ethz.mxquery.update.store.llImpl

ch.ethz.mxquery.util

ch.ethz.mxquery.xdmio

ch.ethz.mxquery.xdmio.xmlAdapters

ch.ethz.mxquery.xqj

examples

    Overview
      Package
      Class
      Tree
      Deprecated
      Index
      Help

MXQuery 0.6.0 API Documentation - Copyright 2006-2009 ETH Zurich

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

MXQuery 0.6.0 API Documentation - Copyright 2006-2009 ETH Zurich


text:
package com.facebook.buck.util.perf;

import com.facebook.buck.event.AbstractBuckEvent;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.EventKey;
import com.facebook.buck.log.GlobalStateManager;
import com.facebook.buck.log.InvocationInfo;
import com.facebook.buck.log.Logger;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.AbstractScheduledService;
import com.google.common.util.concurrent.ServiceManager;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;

/**
 * Periodically probes for process-wide perf-related metrics.
 */
public class PerfStatsTracking extends AbstractScheduledService implements AutoCloseable {
  private final BuckEventBus eventBus;
  private final ServiceManager serviceManager;
  private final InvocationInfo invocationInfo;

  public PerfStatsTracking(
      BuckEventBus eventBus,
      InvocationInfo invocationInfo) {
    this.eventBus = eventBus;
    this.serviceManager = new ServiceManager(ImmutableList.of(this));
    this.invocationInfo = invocationInfo;
    serviceManager.startAsync();
  }

  public void probeMemory() {
    long freeMemoryBytes = Runtime.getRuntime().freeMemory();
    long totalMemoryBytes = Runtime.getRuntime().totalMemory();

    long totalGcTimeMs = 0;
    for (GarbageCollectorMXBean gcMxBean : ManagementFactory.getGarbageCollectorMXBeans()) {
      long collectionTimeMs = gcMxBean.getCollectionTime();
      if (collectionTimeMs == -1) {
        // Gc collection time is not supported on this JVM.
        totalGcTimeMs = -1;
        break;
      }
      totalGcTimeMs += collectionTimeMs;
    }

    eventBus.post(new MemoryPerfStatsEvent(freeMemoryBytes, totalMemoryBytes, totalGcTimeMs));
  }

  @Override
  protected void runOneIteration() throws Exception {
    try {
      GlobalStateManager.singleton().getThreadToCommandRegister().register(
          Thread.currentThread().getId(),
          invocationInfo.getCommandId());
      probeMemory();
    } catch (Exception e) {
      Logger.get(PerfStatsTracking.class).error(e);
      throw e;
    }
  }

  @Override
  protected Scheduler scheduler() {
    return Scheduler.newFixedRateSchedule(
        1L,
        1L,
        TimeUnit.SECONDS);
  }

  @Override
  public void close() {
    serviceManager.stopAsync();
  }

  public static class PerfStatsEvent extends AbstractBuckEvent {

    protected PerfStatsEvent() {
      super(EventKey.unique());
    }

    @Override
    protected String getValueString() {
      return "";
    }

    @Override
    public String getEventName() {
      return "";
    }
  }

  public static class MemoryPerfStatsEvent extends PerfStatsEvent {
    private final long freeMemoryBytes;
    private final long totalMemoryBytes;
    private final long timeSpentInGcMs;

    public MemoryPerfStatsEvent(
        long freeMemoryBytes,
        long totalMemoryBytes,
        long timeSpentInGcMs) {
      this.freeMemoryBytes = freeMemoryBytes;
      this.totalMemoryBytes = totalMemoryBytes;
      this.timeSpentInGcMs = timeSpentInGcMs;
    }

    public long getFreeMemoryBytes() {
      return freeMemoryBytes;
    }

    public long getTotalMemoryBytes() {
      return totalMemoryBytes;
    }

    public long getTimeSpentInGcMs() {
      return timeSpentInGcMs;
    }
  }
}


text:
package org.hisp.dhis.indicator;

import org.hisp.dhis.GenericDhisSpringTest;

/**
 * @author Lars Helge Overland
 * @version $Id$
 */
public class IndicatorGroupSetStoreTest
    extends GenericDhisSpringTest<IndicatorGroupSet>
{
    private IndicatorGroupSet[] objects = {
        new IndicatorGroupSet( "GroupSetA" ),
        new IndicatorGroupSet( "GroupSetB" ),
        new IndicatorGroupSet( "GroupSetC" ) };

    @Override
    protected IndicatorGroupSet[] getObjects()
    {
        return objects;
    }

    @Override
    protected String getGenericBeanId()
    {
        return "org.hisp.dhis.indicator.IndicatorGroupSetStore";
    }
}


text:
package org.kie.config.cli.command.impl;

import org.guvnor.structure.organizationalunit.OrganizationalUnit;
import org.guvnor.structure.organizationalunit.OrganizationalUnitService;
import org.jboss.weld.environment.se.WeldContainer;
import org.kie.config.cli.CliContext;
import org.kie.config.cli.command.CliCommand;
import org.kie.config.cli.support.InputReader;

public class RemoveOrganizationalUnitCliCommand implements CliCommand {

    @Override
    public String getName() {
        return "remove-org-unit";
    }

    @Override
    public String execute( CliContext context ) {
        StringBuffer result = new StringBuffer();
        WeldContainer container = context.getContainer();

        OrganizationalUnitService organizationalUnitService = container.instance().select( OrganizationalUnitService.class ).get();

        InputReader input = context.getInput();
        System.out.print( ">>Organizational Unit name:" );
        String name = input.nextLine();

        OrganizationalUnit organizationalUnit = organizationalUnitService.getOrganizationalUnit( name );
        if ( organizationalUnit == null ) {
            return "No Organizational Unit " + name + " was found, exiting";
        }
        organizationalUnitService.removeOrganizationalUnit( name );
        result.append( "Organizational Unit " + name + " was removed successfully" );

        return result.toString();
    }

}


text:
'use strict';
// logger.js tests
const { expect } = require('chai');
const chalk = require('chalk');
const Logger = require('../app/util/logger');
// Init logger
//const logger = new Logger();

// Tests
describe('logger.js tests', () => {

  it('should check if Logger.getdate() works', (done) => {
    // Date to help with checking
    const date = new Date();
    // Test
    expect(Logger.getdate()).to.equal(chalk.grey(`${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`));
    done();
  });

  it('should check if logger.info() works'/*, (done) => {
    // Patch console.log
    const old = console.log;
    console.log = (txt) => {
      const str = chalk.green.bold('INFO');
      expect(txt).to.equal(`[ ${Logger.getdate()} ${str} ] test`);
    };
    // Test
    logger.info('test');
    // Reset
    console.log = old;
    done();
  }*/);

});


text:
'use strict';

const express = require('abacus-express');
const request = require('abacus-request');

const router = require('..');

/* jshint noyield: true */

describe('abacus-router exceptions', () => {
  let exit;
  let app;
  let routes;

  beforeEach(() => {
    exit = process.exit;
    process.exit = spy();

    app = express();
    routes = router();
  });

  afterEach(() => {
    process.exit = exit;
  });

  context('with generator middleware', () => {
    let server;

    beforeEach(() => {
      routes.get('/err/generator/request/:message', function*(req) {
        throw new Error(req.params.message);
      });

      // Add our router to the app
      app.use(routes);

      // Listen on an ephemeral port
      server = app.listen(0);
    });

    it('handles exceptions', (done) => {
      request.get('http://localhost::p/:v/generator/:r/:m',
        {
          p: server.address().port,
          v: 'err',
          r: 'request',
          m: 'boo'
        },
        (err, val) => {
          expect(err.message).to.equal('boo');
          expect(val).to.equal(undefined);
          done();
        }
      );
    });
  });

  context('with async middleware', () => {
    let server;

    beforeEach(() => {
      routes.get('/err/generator/request/:message', async(req) => {
        throw new Error(req.params.message);
      });

      // Add our router to the app
      app.use(routes);

      // Listen on an ephemeral port
      server = app.listen(0);
    });

    it('handles exceptions', (done) => {
      request.get('http://localhost::p/:v/generator/:r/:m',
        {
          p: server.address().port,
          v: 'err',
          r: 'request',
          m: 'boo'
        },
        (err, val) => {
          expect(err.message).to.equal('boo');
          expect(val).to.equal(undefined);
          done();
        }
      );
    });
  });

});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Antgineers is a life long project">
    <meta name="keyword"  content="">
    <link rel="shortcut icon" href="/img/favicon.ico">

    <title>Example Post - 蚂蚁工程 | Antgineers</title>

    <link rel="canonical" href="http://antgineers.com/2015/04/14/unix-linux-note/">

    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <link rel="stylesheet" href="/css/hux-blog.min.css">

    <link rel="stylesheet" href="/css/syntax.css">

    <link href="http://cdn.staticfile.org/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

            <button type="button" class="navbar-toggle">
                Toggle navigation

            </button>
            antgineers

                        Home

                        About

                        Tags

                        OS

                        Unix

                        Linux

Example Post

不适合人类阅读,非常水的自我笔记

                    Posted by Hux on April 14, 2015

This document is not completed and will be updated anytime.

Catagory

Unix

Bell Labs

Xenix

BSD

FreeBSD & Apple

NeXTStep

Darwin

POSIX

Unix-like

Single Unix Specification

Apple iOS

XNU Kernel

Linux

Linux Kernel

GNU Project

Android

Android Kernel

Android ROM

Chrome OS

Chromium OS

Unix

Unix is a family of multitasking, multiuser computer OS.

Derive from the original AT&T Unix, Developed in the 1970s at Bell Labs (贝尔实验室), initially intended for use inside the Bell System.

Bell Labs

Bell 和 AT&A 在那时已经是一家了,可以看到那时的通信公司真是一线 IT 公司呢。
C 语言也是 Bell Labs 的产物,从一开始就是为了用于 Unix 而设计出来的。所以 Unix (在 73 年用 C 重写)在高校流行后,C 语言也获得了广泛支持。

AT&T licensed Unix to outside parties(第三方) from the late 1970s, leading to a variety of both academic (最有有名的 BSD ) and commercial (Microsoft Xenix, IBM AIX, SunOS Solaris)

Xenix

微软 1979 年从 AT&A 授权来的 Unix OS,配合着 x86 成为当时最受欢迎的 Unix 发行版。后来 M$ 和 IBM 合作开发 OS/2 操作系统后放弃,后来最终转向 Windows NT。

BSD

Barkeley Software Distribution, also called Berkeley Unix. Today the term "BSD" is used to refer to any of the BSD descendants(后代) which together form a branch of the family of Unix-like OS.(共同组成了一个分支)

BSD 最大的贡献是在 BSD 中率先增加了虚拟存储器和 Internet 协议,其 TCP/IP(IPv4 only) 代码仍然在现代 OS 上使用( Microsoft Windows and most of the foundation of Apple's OS X and iOS )

BSD 后来发展出了众多开源后代,包括 FreeBSD, OpenBSD, NetBSD 等等……很多闭源的 vendor Unix 也都从 BSD 衍生而来。

FreeBSD & Apple

FreeBSD 不但是 Open Source BSD 中占有率最高的,还直接影响了 Apple Inc : NeXT Computer 的团队在 FreeBSD 上衍生出了 NeXTSTEP 操作系统,这货后来在 Apple 时期演化成了 Darwin ,这个"达尔文"居然还是个开源系统,而且是 the Core of Mac OS X and iOS.

NeXTSTEP

An object-oriented, multitasking OS. Low-level C but High-level OC language and runtime the first time, combined with an OO aplication layer and including several "kits".

大家都知道 NeXT 是 Steve Jobs 被 forced out of Apple 后和 a few of his coworkers 创办的,所以 NeXTSTEP 绝对是证明 Jobs 实力的作品。

Darwin

Darwin, the core set of components upon which Mac OS X and iOS based, mostly POSIX compatible, but has never, by itself, been certified as being compatible with any version of POSIX. (OS X, since Leopard, has been certified as compatible with the Single UNIX Specification version 3)

所以说 Mac OS X 算是很正统 Unix 的了

POSIX

可移植操作系统接口, Portable Operating System Interface, is a family of standards specified by the IEEE from maintaining compatibility between OS, defines the API along with Command Line Shells and utility interfaces, for software comaptibility with variants of Unix and other OS.

Fully POSIX compliant:

OS X

QNX OS (BlackBerry)

Mostly complicant:

Linux

OpenBSD/FreeBSD

Darwin (Core of iOS & OS X)

Android

Complicant via compatibility feature (通过兼容功能实现兼容)

Windows NT Kernel

Windows Server 2000, 2003, 2008, 2008 R2, 2012

Symbian OS (with PIPS)

Symbian was a closed-source OS.

Unix-like

A Unix-like (sometimes referred to as UN*X or *nix) operating system is one that behaves in a manner similar to a Unix system, while not necessarily conforming to or being certified to any version of the Single UNIX Specification.

There is no standard for defining the term.

其实 Unix-like 是个相对模糊的概念:

最狭义的 Unix 单指 Bell Labs's Unix

稍广义的 Unix 指代所有 Licensed Unix, 即通过了 SUS 的 Unix-like ,比如 OS X

最广义的 Unix 即所有 Unix-like 系统,无论它是否通过过任何 SUS,包括 Linux,BSD Family 等

Single UNIX Specification

The Single UNIX Specification (SUS) is the collective name of a family of standards for computer OS, compliance with which is required to qualify for the name "Unix", like POSIX.

Apple iOS

iOS is a Unix-like OS based on Darwin(BSD) and OS X, which share some frameworks including Core Foundation, Founadtion and the Darwin foundation with OS X, but, Unix-like shell access is not avaliable for users and restricted for apps, making iOS not fully Unix-compatible either.

The iOS kernal is XNU, the kernal of Darwin.

XNU Kernel

XNU, the acronym(首字母缩写) for X is Not Unix, which is the Computer OS Kernel developed at Apple Inc since Dec 1996 for use in the Mac OS X and released as free open source software as part of Darwin.

Linux

Linux is a Unix-like and mostly POSIX-compliant computer OS.

Linux Kernel

严格来讲,术语 Linux 只表示 Linux Kernel 操作系统内核本身,比如说 Android is Based on Linux (Kernel). Linus 编写的也只是这一部分,一个免费的 Unix-like Kernel,并不属于 GNU Project 的一部分。

但通常把 Linux 作为 Linux Kernel 与大量配合使用的 GNU Project Software Kit (包括 Bash, Lib, Compiler, 以及后期的 GUI etc) 所组合成的 OS 的统称。(包括各类 Distribution 发行版)

这类操作系统也被称为 GNU/Linux

GNU Project

The GNU Project is a free software, mass collaboration project, which based on the following freedom rights:

Users are free to run the software, share (copy, distribute), study and modify it.

GNU software guarantees these freedom-rights legally (via its license).

So it is not only FREE but, more important, FREEDOM.

In order to ensure that the entire software of a computer grants its users all freedom rights (use, share, study, modify), even the most fundamental and important part, the operating system, needed to be written.

This OS is decided to called GNU (a recursive acronym meaning "GNU is not Unix"). By 1992, the GNU Project had completed all of the major OS components except for their kernel, GNU Hurd.

With the release of the third-party Linux Kernel, started independently by Linus Torvalds in 1991 and released under the GPLv0.12 in 1992, for the first time it was possible to run an OS composed completely of free software.

Though the Linux kernel is not part of the GNU project, it was developed using GCC and other GNU programming tools and was released as free software under the GPL.

Anyway, there eventually comes to the GNU/Linux

GPL: GNU General Public License

GCC: GNU Compiler Collection

其他与 GPL 相关的自由/开源软件公共许可证:

Mozilla Public License

MIT License

BSD Public License

GPL 强制后续版本必须是自由软件,而 BSD 的后续可以选择继续开源或者封闭

Apache License

Android

Android is a mobile OS based on Linux Kernel, so it's definitely Unix-like.

Linux is under GPL so Android has to be open source.
Android's source code is released by Google under open source licenses, although most Android devices ultimately ship with a combination of open source and proprietary software, including proprietary software developed and licensed by Google (GMS are all proprietary)

Android Kernel

Android's kernel is based on one of the Linux kernel's long-term support (LTS) branches.

Android's variant of the Linux kernel has further architectural changes that are implemented by Google outside the typical Linux kernel development cycle, and, certain features that Google contributed back to the Linux kernel. Google maintains a public code repo that contains their experimental work to re-base Android off the latest stable Linux versions.

Android Kernel 大概是 Linux Kernel 最得意的分支了,Android 也是 Linux 最流行的发行版。不过,也有一些 Google 工程师认为 Android is not Linux in the traditional Unix-like Linux distribution sense. 总之这类东西就算有各种协议也还是很难说清楚,在我理解里 Android Kernel 大概就是 fork Linux Kernel 之后改动和定制比较深的例子。

Android ROM

既然提到 Android 就不得不提提 Android ROM

ROM 的本义实际上是只读内存:

Read-only memory (ROM) is a class of storage medium used in computers and other electronic devices. Data stored in ROM can only be modified slowly, with difficulty, or not at all, so it is mainly used to distribute firmware (固件) (software that is very closely tied to specific hardware, and unlikely to need frequent updates).

ROM 在发展的过程中不断进化,从只读演变成了可编程可擦除,并最终演化成了 Flash

PROM (Programmable read-only memory)

EPROM (Erasable programmable read-only memory)

EEPROM (Electrically erasable programmable read-only memory)

Flash memory (闪存)

Flash 的出现是历史性的,它不但可以作为 ROM 使用,又因其极高的读写速度和稳定性,先后发展成为U盘(USB flash drives)、移动设备主要内置存储,和虐机械硬盘几条街的固态硬盘(SSD),可以说这货基本统一了高端存储市场的技术规格。

所以我们平时习惯说的 ROM 其实还是来源于老单片机时代,那时的 ROM 真的是写了就很难(需要上电复位)、甚至无法修改,所以那时往 ROM 里烧下去的程序就被称作 firmware ,固件。久而久之,虽然技术发展了,固件仍然指代那些不常需要更新的软件,而 ROM 这个词也就这么沿用下来了。

所以在 wiki 里是没有 Android ROM 这个词条的,只有 List of custom Android firmwares

A custom firmware, also known as a custom ROM, ROM, or custom OS, is an aftermarket distribution of the Android operating system. They are based on the Android Open Source Project (AOSP), hence most are open-sourced releases, unlike proprietary modifications by device manufacturers.

各类 Android ROM 在 Android 词类下也都是属于 Forks and distributions 一类的。

所以我说,其实各类 Android ROM 也好,fork Android 之流的 YunOS、FireOS 也好,改了多少东西,碰到多深的 codebase ……其实 ROM 和 Distribution OS 的界限是很模糊的,为什么 Android 就不可以是移动时代的 Linux ,为什么 Devlik/ART 就不能是移动时代的 GCC 呢?

Chrome OS

Chrome OS is an operating system based on the Linux kernel and designed by Google to work with web applications and installed applications.

虽然目前只是个 Web Thin Client OS ,但是 RoadMap 非常酷……

Chrome Packaged Application (Support working offline and installed)

Android App Runtime (run Android applications natively…fxxking awesome)

平复一下激动的心情,还是回到正题来:

Chromium OS

Chrome OS is based on Chromium OS, which is the open-source development version of Chrome OS, which is a Linux distribution designed by Google.

For Detail, Chromium OS based on Gentoo Linux, emm…

                        ← Previous Post

                        Next Post →

FEATURED TAGS

                                    前端开发

                                    JavaScript

                    Copyright © antgineers 2017

                    Theme by Hux |


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Rondeletia galeottii Standl.

### Remarks
null


text:
int main(void)
{
float area , circumference , radius;
printf("What is the radius of the circle.\n");
scanf("%f",&radius);

area = PI * radius * radius;
circumference = 2.0 * PI * radius;

printf("The circumference of the circle is %1.2f.\n",circumference);
printf("The area of the circle is %1.2f.\n",area);

return 0;
}


text:
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { FlexLayoutServerModule } from '@angular/flex-layout/server';
import { INITIAL_STATE, Store, select } from '@ngrx/store';
import { TransferState } from '@angular/platform-browser';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgModule } from '@angular/core';

import { RootState, STORE_STATE_KEY, loadServerInitialState } from './store/app.state';
import { AppComponent } from './components/app/app.component';
import { AppSharedModule } from './app.shared.module';
import { AssetsInterceptor } from './assets-interceptor';
import { StoreTransferStateService } from './store/store-transfer-state.service';

@NgModule({
    imports: [
        ServerModule, ServerTransferStateModule,
        AppSharedModule,
        NoopAnimationsModule,
        // FlexLayoutServerModule,
        ModuleMapLoaderModule
    ],
    bootstrap: [AppComponent],
    providers: [
        StoreTransferStateService,
        {
            provide: INITIAL_STATE,
            useFactory: loadServerInitialState,
            deps: ['USER', 'SYSTEM']
        }, {
            provide: HTTP_INTERCEPTORS,
            useClass: AssetsInterceptor,
            multi: true
        }]
})
export class AppServerModule
{
    constructor(storeTransStateService: StoreTransferStateService)
    {
    }
}


text:
package org.pmw.tinylog.policies;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.pmw.tinylog.hamcrest.ClassMatchers.type;

import java.io.File;
import java.io.IOException;

import org.junit.Test;
import org.pmw.tinylog.util.FileHelper;

/**
 * Tests for yearly policy.
 *
 * @see YearlyPolicy
 */
public class YearlyPolicyTest extends AbstractTimeBasedPolicyTest {

	/**
	 * Test rolling at the end of the year by default constructor.
	 */
	@Test
	public final void testDefaultRollingAtEndOfYear() {
		// 1st January 1970

		Policy policy = new YearlyPolicy();
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(YEAR - DAY); // 31th December 1970
		assertTrue(policy.check((String) null));
		increaseTime(DAY); // 1st January 1971
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test rolling at the end of the year by setting explicitly 1.
	 */
	@Test
	public final void testRollingAtEndOfYear() {
		increaseTime(YEAR - DAY); // 31th December 1970

		Policy policy = new YearlyPolicy(1);
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY - 1L); // 31th December 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // / 1st January 1971
		assertFalse(policy.check((String) null));

		policy.reset();
		assertTrue(policy.check((String) null));
		increaseTime(YEAR - 1L); // 31th December 1971 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st January 1972
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test rolling at the end of December by setting explicitly 12.
	 */
	@Test
	public final void testRollingAtEndOfDecember() {
		increaseTime(YEAR - 31 * DAY - DAY); // 30th November 1970

		Policy policy = new YearlyPolicy(12);
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY - 1L); // 30th November 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // / 1st December 1970
		assertFalse(policy.check((String) null));

		policy.reset();
		assertTrue(policy.check((String) null));
		increaseTime(YEAR - 1L); // 30th November 1971 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st December 1971
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test exception for month = 0.
	 */
	@Test(expected = IllegalArgumentException.class)
	public final void testTooLowMonth() {
		new YearlyPolicy(0);
	}

	/**
	 * Test exception for month = 13.
	 */
	@Test(expected = IllegalArgumentException.class)
	public final void testTooHighMonth() {
		new YearlyPolicy(13);
	}

	/**
	 * Test String parameter for numeric January (= "1").
	 */
	@Test
	public final void testStringParameterForNumericJanuary() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("1");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(YEAR - 1L); // 31th December 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st January 1971
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for numeric December (= "12").
	 */
	@Test
	public final void testStringParameterForNumericDecember() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("12");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(YEAR - 31 * DAY - 1L); // 30th November 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st December 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "january".
	 */
	@Test
	public final void testStringParameterForJanuary() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("january");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(YEAR - 1L); // 31th December 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st January 1971
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "february".
	 */
	@Test
	public final void testStringParameterForFebruary() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("february");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY * 31 - 1L); // 31th January 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st February 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "march".
	 */
	@Test
	public final void testStringParameterForMarch() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("march");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY * (31 + 28) - 1L); // 28th February 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st March 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "april".
	 */
	@Test
	public final void testStringParameterForApril() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("april");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY * (31 + 28 + 31) - 1L); // 31th March 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st April 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "may".
	 */
	@Test
	public final void testStringParameterForMay() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("may");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY * (31 + 28 + 31 + 30) - 1L); // 30th April 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st May 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "june".
	 */
	@Test
	public final void testStringParameterForJune() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("june");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY * (31 + 28 + 31 + 30 + 31) - 1L); // 31th May 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st June 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "july".
	 */
	@Test
	public final void testStringParameterForJuly() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("july");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY * (31 + 28 + 31 + 30 + 31 + 30) - 1L); // 30th June 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st July 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "august".
	 */
	@Test
	public final void testStringParameterForAugust() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("august");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY * (31 + 28 + 31 + 30 + 31 + 30 + 31) - 1L); // 31th July 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st August 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "september".
	 */
	@Test
	public final void testStringParameterForSeptember() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("september");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY * (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31) - 1L); // 31th August 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st September 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "OCTOBER".
	 */
	@Test
	public final void testStringParameterForOctober() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("OCTOBER");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY * (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30) - 1L); // 30th September 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st October 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "NovemBer".
	 */
	@Test
	public final void testStringParameterForNovember() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("NovemBer");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(DAY * (31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31) - 1L); // 31th October 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st November 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test String parameter for "December".
	 */
	@Test
	public final void testStringParameterForDecember() {
		// 1st January 1970

		Policy policy = new YearlyPolicy("December");
		policy.init(null);
		assertTrue(policy.check((String) null));
		increaseTime(YEAR - 31 * DAY - 1L); // 30th November 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st December 1970
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test exception for "0".
	 */
	@Test(expected = IllegalArgumentException.class)
	public final void testStringParameterForInvalidNumericMonth() {
		new YearlyPolicy("0");
	}

	/**
	 * Test exception for "dummy".
	 */
	@Test(expected = IllegalArgumentException.class)
	public final void testStringParameterForInvalidString() {
		new YearlyPolicy("dummy");
	}

	/**
	 * Test continuing log files.
	 *
	 * @throws IOException
	 *             Test failed
	 */
	@Test
	public final void testContinueLogFile() throws IOException {
		setTime(YEAR - DAY); // 31th December 1970 00:00
		File file = FileHelper.createTemporaryFile(null);
		file.setLastModified(getTime());

		Policy policy = new YearlyPolicy();
		policy.init(null);
		assertTrue(policy.check(file));
		assertTrue(policy.check((String) null));
		increaseTime(DAY - 1L); // 31th December 1970 23:59:59,999
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st January 1971 00:00
		assertFalse(policy.check((String) null));

		increaseTime(-1L); // 31th December 1970 23:59:59,999
		policy = new YearlyPolicy();
		policy.init(null);
		assertTrue(policy.check(file));
		assertTrue(policy.check((String) null));
		increaseTime(1L); // 1st January 1971 00:00
		assertFalse(policy.check((String) null));
	}

	/**
	 * Test discontinuing log files.
	 *
	 * @throws IOException
	 *             Test failed
	 */
	@Test
	public final void testDiscontinueLogFile() throws IOException {
		setTime(YEAR - DAY); // 31th December 1970
		File file = FileHelper.createTemporaryFile(null);
		file.setLastModified(getTime());

		Policy policy = new YearlyPolicy();
		policy.init(null);
		assertTrue(policy.check(file));

		increaseTime(DAY); // 1st January 1971

		policy = new YearlyPolicy();
		policy.init(null);
		assertFalse(policy.check(file));

		file.delete();
	}

	/**
	 * Test non-existing log files.
	 *
	 * @throws IOException
	 *             Test failed
	 */
	@Test
	public final void testNonExistingLogFile() throws IOException {
		File file = FileHelper.createTemporaryFile(null);
		file.delete();

		Policy policy = new YearlyPolicy();
		policy.init(null);
		assertTrue(policy.check(file));
	}

	/**
	 * Test reading yearly policy from properties.
	 */
	@Test
	public final void testFromProperties() {
		Policy policy = createFromProperties("yearly");
		assertThat(policy, type(YearlyPolicy.class));
		policy.init(null);
		increaseTime(YEAR - DAY);
		assertTrue(policy.check((String) null));
		increaseTime(DAY);
		assertFalse(policy.check((String) null));

		setTime(0L);

		policy = createFromProperties("yearly: 2");
		assertThat(policy, type(YearlyPolicy.class));
		policy.init(null);
		increaseTime(DAY * 30); // 31th January
		assertTrue(policy.check((String) null));
		increaseTime(DAY); // 1st February
		assertFalse(policy.check((String) null));

		setTime(0L);

		policy = createFromProperties("yearly: march");
		assertThat(policy, type(YearlyPolicy.class));
		policy.init(null);
		increaseTime(DAY * 30 + DAY * 28); // 28th February
		assertTrue(policy.check((String) null));
		increaseTime(DAY); // 1st March
		assertFalse(policy.check((String) null));
	}

}


text:
<?php

namespace OnTimeFlight\Model;

use Zend\Db\TableGateway\TableGateway;

class RecordTable {

    protected $tableGateway;

    public function __construct(TableGateway $tableGateway) {
        $this->tableGateway = $tableGateway;

    }

    public function findByFlightCode($flightCode, $options = array()) {

        $results = $this->tableGateway->select(function($select) use ($flightCode, $options) {
           $select->where(array('flightCode' => $flightCode));

           if (isset($options['order'])) {
                foreach ($options['order'] as $field => $value) {
                    $select->order($field . " " . $value);
                }
           }

        });

        return $results;
    }

}


text:
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;

namespace Sitecore.Remote.Installation.Client.Responses
{
  /// <summary>
  /// Json response
  /// </summary>
  public class JsonResponse
  {
    /// <summary>
    ///   Initializes a new instance of the <see cref="HtmlResponse" /> class.
    /// </summary>
    /// <param name="content">The content.</param>
    public JsonResponse(string content)
    {
      this.Content = content;
      this.CommandsResponse = CommandsResponse.Empty;

      if (!string.IsNullOrEmpty(this.Content))
      {
        using (var stream = new MemoryStream(Encoding.Default.GetBytes(this.Content)))
        {
          var serializer = new DataContractJsonSerializer(typeof(CommandsResponse));

          this.CommandsResponse = serializer.ReadObject(stream) as CommandsResponse;
        }
      }
    }

    /// <summary>
    ///   Gets the content.
    /// </summary>
    /// <value>
    ///   The content.
    /// </value>
    public string Content { get; }

    /// <summary>
    /// Gets the commands response.
    /// </summary>
    /// <value>
    /// The commands response.
    /// </value>
    public CommandsResponse CommandsResponse { get; }

    /// <summary>
    /// Gets the atribute value.
    /// </summary>
    public string GetAtributeValue(string id)
    {
      return this.CommandsResponse?.Commands.FirstOrDefault(c => c.CommandName == "SetAttribute" && c.Id == id)?.Value;
    }
  }
}


text:
package com.ragstorooks.blacktomove.chess.blocks;

public enum Colour {
    White,
    Black;

    public static Colour getColour(String c) {
        switch (c) {
            case "w":
            case "W":
                return Colour.White;
            case "b":
            case "B":
                return Colour.Black;
            default:
                return null;
        }
    }

    public static Colour getOppositeColour(Colour colour) {
        return White.equals(colour)? Black : White;
    }
}


text:
"""Object to represent the information at a node in the DAGCircuit."""

import warnings

from qiskit.exceptions import QiskitError

class DAGDepNode:
    """Object to represent the information at a node in the DAGDependency().

    It is used as the return value from `*_nodes()` functions and can
    be supplied to functions that take a node.
    """

    __slots__ = [
        "type",
        "_op",
        "name",
        "_qargs",
        "cargs",
        "sort_key",
        "node_id",
        "successors",
        "predecessors",
        "reachable",
        "matchedwith",
        "isblocked",
        "successorstovisit",
        "qindices",
        "cindices",
    ]

    def __init__(
        self,
        type=None,
        op=None,
        name=None,
        qargs=(),
        cargs=(),
        condition=None,
        successors=None,
        predecessors=None,
        reachable=None,
        matchedwith=None,
        successorstovisit=None,
        isblocked=None,
        qindices=None,
        cindices=None,
        nid=-1,
    ):

        self.type = type
        self._op = op
        self.name = name
        self._qargs = tuple(qargs) if qargs is not None else ()
        self.cargs = tuple(cargs) if cargs is not None else ()
        if condition:
            warnings.warn(
                "The DAGDepNode 'condition' kwarg and 'condition' attribute are deprecated "
                "as of 0.18.0 and will be removed no earlier than 3 months after the "
                "release date. You can use 'DAGDepNode.op.condition' if the DAGDepNode "
                "is of type 'op'.",
                DeprecationWarning,
                2,
            )
        self.node_id = nid
        self.sort_key = str(self._qargs)
        self.successors = successors if successors is not None else []
        self.predecessors = predecessors if predecessors is not None else []
        self.reachable = reachable
        self.matchedwith = matchedwith if matchedwith is not None else []
        self.isblocked = isblocked
        self.successorstovisit = successorstovisit if successorstovisit is not None else []
        self.qindices = qindices if qindices is not None else []
        self.cindices = cindices if cindices is not None else []

    @property
    def op(self):
        """Returns the Instruction object corresponding to the op for the node, else None"""
        if not self.type or self.type != "op":
            raise QiskitError("The node %s is not an op node" % (str(self)))
        return self._op

    @op.setter
    def op(self, data):
        self._op = data

    @property
    def condition(self):
        """Returns the condition of the node.op"""
        if not self.type or self.type != "op":
            raise QiskitError("The node %s is not an op node" % (str(self)))
        warnings.warn(
            "The DAGDepNode 'condition' attribute is deprecated as of 0.18.0 and "
            "will be removed no earlier than 3 months after the release date. "
            "You can use 'DAGDepNode.op.condition' if the DAGDepNode is of type 'op'.",
            DeprecationWarning,
            2,
        )
        return getattr(self._op, "condition", None)

    @condition.setter
    def condition(self, new_condition):
        """Sets the node.condition which sets the node.op.condition."""
        if not self.type or self.type != "op":
            raise QiskitError("The node %s is not an op node" % (str(self)))
        warnings.warn(
            "The DAGDepNode 'condition' attribute is deprecated as of 0.18.0 and "
            "will be removed no earlier than 3 months after the release date. "
            "You can use 'DAGDepNode.op.condition' if the DAGDepNode is of type 'op'.",
            DeprecationWarning,
            2,
        )
        self._op.condition = new_condition

    @property
    def qargs(self):
        """
        Returns list of Qubit, else an empty list.
        """
        return self._qargs

    @qargs.setter
    def qargs(self, new_qargs):
        """Sets the qargs to be the given list of qargs."""
        self._qargs = tuple(new_qargs)
        self.sort_key = str(new_qargs)

    @staticmethod
    def semantic_eq(node1, node2):
        """
        Check if DAG nodes are considered equivalent, e.g., as a node_match for nx.is_isomorphic.

        Args:
            node1 (DAGDepNode): A node to compare.
            node2 (DAGDepNode): The other node to compare.

        Return:
            Bool: If node1 == node2
        """
        # For barriers, qarg order is not significant so compare as sets
        if "barrier" == node1.name == node2.name:
            return set(node1._qargs) == set(node2._qargs)

        if node1.type == node2.type:
            if node1._op == node2._op:
                if node1.name == node2.name:
                    if node1._qargs == node2._qargs:
                        if node1.cargs == node2.cargs:
                            if node1.type == "op":
                                if getattr(node1._op, "condition", None) != getattr(
                                    node2._op, "condition", None
                                ):
                                    return False
                            return True
        return False

    def copy(self):
        """
        Function to copy a DAGDepNode object.
        Returns:
            DAGDepNode: a copy of a DAGDepNode object.
        """

        dagdepnode = DAGDepNode()

        dagdepnode.type = self.type
        dagdepnode._op = self.op
        dagdepnode.name = self.name
        dagdepnode._qargs = self._qargs
        dagdepnode.cargs = self.cargs
        dagdepnode.node_id = self.node_id
        dagdepnode.sort_key = self.sort_key
        dagdepnode.successors = self.successors
        dagdepnode.predecessors = self.predecessors
        dagdepnode.reachable = self.reachable
        dagdepnode.isblocked = self.isblocked
        dagdepnode.successorstovisit = self.successorstovisit
        dagdepnode.qindices = self.qindices
        dagdepnode.cindices = self.cindices
        dagdepnode.matchedwith = self.matchedwith.copy()

        return dagdepnode


text:
import logging

from .trimesh_class import TriMesh
from .trimeshflow_class import TriMeshFlow
from .trimesh_vtk import TriMesh_Vtk
from .trimeshflow_vtk import TriMeshFlow_Vtk

import trimeshpy.math
import trimeshpy.data

__all__ = ["trimesh_class", "trimeshflow_class",
           "trimesh_vtk", "trimeshflow_vtk", "math", "data"]


text:
package com.microsoft.bingads.v10.adinsight;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ArrayOfKeywordEstimatedPosition complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ArrayOfKeywordEstimatedPosition">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="KeywordEstimatedPosition" type="{http://schemas.datacontract.org/2004/07/Microsoft.BingAds.Advertiser.AdInsight.Api.DataContract.Entity}KeywordEstimatedPosition" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfKeywordEstimatedPosition", propOrder = {
    "keywordEstimatedPositions"
})
public class ArrayOfKeywordEstimatedPosition {

    @XmlElement(name = "KeywordEstimatedPosition", nillable = true)
    protected List<KeywordEstimatedPosition> keywordEstimatedPositions;

    /**
     * Gets the value of the keywordEstimatedPositions property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the keywordEstimatedPositions property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getKeywordEstimatedPositions().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link KeywordEstimatedPosition }
     *
     *
     */
    public List<KeywordEstimatedPosition> getKeywordEstimatedPositions() {
        if (keywordEstimatedPositions == null) {
            keywordEstimatedPositions = new ArrayList<KeywordEstimatedPosition>();
        }
        return this.keywordEstimatedPositions;
    }

}