text:
from __future__ import division

import inspect
import warnings
from functools import wraps
from time import sleep, time
from threading import Event

from RPi import GPIO
from w1thermsensor import W1ThermSensor
from spidev import SpiDev

from .devices import GPIODeviceError, GPIODeviceClosed, GPIODevice, GPIOQueue

def _alias(key, doc=None):
    if doc is None:
        doc = 'Alias for %s' % key
    return property(
        lambda self: getattr(self, key),
        lambda self, val: setattr(self, key, val),
        doc=doc
    )

class InputDeviceError(GPIODeviceError):
    pass

class InputDevice(GPIODevice):
    """
    Represents a generic GPIO input device.

    This class extends `GPIODevice` to add facilities common to GPIO input
    devices.  The constructor adds the optional `pull_up` parameter to specify
    how the pin should be pulled by the internal resistors. The `is_active`
    property is adjusted accordingly so that `True` still means active
    regardless of the `pull_up` setting.

    pin: `None`
        The GPIO pin (in BCM numbering) that the device is connected to. If
        this is `None` a GPIODeviceError will be raised.

    pull_up: `False`
        If `True`, the pin will be pulled high with an internal resistor. If
        `False` (the default), the pin will be pulled low.
    """
    def __init__(self, pin=None, pull_up=False):
        if pin in (2, 3) and not pull_up:
            raise InputDeviceError(
                'GPIO pins 2 and 3 are fitted with physical pull up '
                'resistors; you cannot initialize them with pull_up=False'
            )
        # _pull_up should be assigned first as __repr__ relies upon it to
        # support the case where __repr__ is called during debugging of an
        # instance that has failed to initialize (due to an exception in the
        # super-class __init__)
        self._pull_up = pull_up
        super(InputDevice, self).__init__(pin)
        self._active_edge = GPIO.FALLING if pull_up else GPIO.RISING
        self._inactive_edge = GPIO.RISING if pull_up else GPIO.FALLING
        self._active_state = GPIO.LOW if pull_up else GPIO.HIGH
        self._inactive_state = GPIO.HIGH if pull_up else GPIO.LOW
        pull = GPIO.PUD_UP if pull_up else GPIO.PUD_DOWN

        # NOTE: catch_warnings isn't thread-safe but hopefully no-one's messing
        # around with GPIO init within background threads...
        with warnings.catch_warnings(record=True) as w:
            GPIO.setup(pin, GPIO.IN, pull)
        # The only warning we want to squash is a RuntimeWarning that is thrown
        # when setting pins 2 or 3. Anything else should be replayed
        for warning in w:
            if warning.category != RuntimeWarning or pin not in (2, 3):
                warnings.showwarning(
                    warning.message, warning.category, warning.filename,
                    warning.lineno, warning.file, warning.line
                )

    @property
    def pull_up(self):
        return self._pull_up

    def __repr__(self):
        try:
            return "<gpiozero.%s object on pin=%d, pull_up=%s, is_active=%s>" % (
                self.__class__.__name__, self.pin, self.pull_up, self.is_active)
        except:
            return super(InputDevice, self).__repr__()

class WaitableInputDevice(InputDevice):
    """
    Represents a generic input device with distinct waitable states.

    This class extends `InputDevice` with methods for waiting on the device's
    status (`wait_for_active` and `wait_for_inactive`), and properties that
    hold functions to be called when the device changes state (`when_activated`
    and `when_deactivated`). These are aliased appropriately in various
    subclasses.

    Note that this class provides no means of actually firing its events; it's
    effectively an abstract base class.
    """
    def __init__(self, pin=None, pull_up=False):
        super(WaitableInputDevice, self).__init__(pin, pull_up)
        self._active_event = Event()
        self._inactive_event = Event()
        self._when_activated = None
        self._when_deactivated = None
        self._last_state = None

    def wait_for_active(self, timeout=None):
        """
        Halt the program until the device is activated, or the timeout is
        reached.

        timeout: `None`
            Number of seconds to wait before proceeding. If this is `None` (the
            default), then wait indefinitely until the device is active.
        """
        return self._active_event.wait(timeout)

    def wait_for_inactive(self, timeout=None):
        """
        Halt the program until the device is deactivated, or the timeout is
        reached.

        timeout: `None`
            Number of seconds to wait before proceeding. If this is `None` (the
            default), then wait indefinitely until the device is inactive.
        """
        return self._inactive_event.wait(timeout)

    def _get_when_activated(self):
        return self._when_activated

    def _set_when_activated(self, value):
        self._when_activated = self._wrap_callback(value)

    when_activated = property(_get_when_activated, _set_when_activated, doc="""\
        The function to run when the device changes state from inactive to
        active.

        This can be set to a function which accepts no (mandatory) parameters,
        or a function which accepts a single mandatory parameter (with as many
        optional parameters as you like). If the function accepts a single
        mandatory parameter, the device that activates will be passed as that
        parameter.

        Set this property to `None` (the default) to disable the event.

        See also: when_deactivated.
        """)

    def _get_when_deactivated(self):
        return self._when_deactivated

    def _set_when_deactivated(self, value):
        self._when_deactivated = self._wrap_callback(value)

    when_deactivated = property(_get_when_deactivated, _set_when_deactivated, doc="""\
        The function to run when the device changes state from active to
        inactive.

        This can be set to a function which accepts no (mandatory) parameters,
        or a function which accepts a single mandatory parameter (which as
        many optional parameters as you like). If the function accepts a single
        mandatory parameter, the device the deactives will be passed as that
        parameter.

        Set this property to `None` (the default) to disable the event.

        See also: when_activated.
        """)

    def _wrap_callback(self, fn):
        if fn is None:
            return None
        elif not callable(fn):
            raise InputDeviceError('value must be None or a callable')
        else:
            # Try binding ourselves to the argspec of the provided callable.
            # If this works, assume the function is capable of accepting no
            # parameters
            try:
                inspect.getcallargs(fn)
                return fn
            except TypeError:
                try:
                    # If the above fails, try binding with a single parameter
                    # (ourselves). If this works, wrap the specified callback
                    inspect.getcallargs(fn, self)
                    @wraps(fn)
                    def wrapper():
                        return fn(self)
                    return wrapper
                except TypeError:
                    raise InputDeviceError(
                        'value must be a callable which accepts up to one '
                        'mandatory parameter')

    def _fire_events(self):
        old_state = self._last_state
        new_state = self._last_state = self.is_active
        if old_state is None:
            # Initial "indeterminate" state; set events but don't fire
            # callbacks as there's not necessarily an edge
            if new_state:
                self._active_event.set()
            else:
                self._inactive_event.set()
        else:
            if not old_state and new_state:
                self._inactive_event.clear()
                self._active_event.set()
                if self.when_activated:
                    self.when_activated()
            elif old_state and not new_state:
                self._active_event.clear()
                self._inactive_event.set()
                if self.when_deactivated:
                    self.when_deactivated()

class DigitalInputDevice(WaitableInputDevice):
    """
    Represents a generic input device with typical on/off behaviour.

    This class extends `WaitableInputDevice` with machinery to fire the active
    and inactive events for devices that operate in a typical digital manner:
    straight forward on / off states with (reasonably) clean transitions
    between the two.

    bounce_time: `None`
        Specifies the length of time (in seconds) that the component will
        ignore changes in state after an initial change. This defaults to
        `None` which indicates that no bounce compensation will be performed.
    """
    def __init__(self, pin=None, pull_up=False, bounce_time=None):
        super(DigitalInputDevice, self).__init__(pin, pull_up)
        # Yes, that's really the default bouncetime in RPi.GPIO...
        GPIO.add_event_detect(
            self.pin, GPIO.BOTH, callback=self._fire_events,
            bouncetime=-666 if bounce_time is None else int(bounce_time * 1000)
        )
        # Call _fire_events once to set initial state of events
        super(DigitalInputDevice, self)._fire_events()

    def _fire_events(self, channel):
        super(DigitalInputDevice, self)._fire_events()

class SmoothedInputDevice(WaitableInputDevice):
    """
    Represents a generic input device which takes its value from the mean of a
    queue of historical values.

    This class extends `WaitableInputDevice` with a queue which is filled by a
    background thread which continually polls the state of the underlying
    device. The mean of the values in the queue is compared to a threshold
    which is used to determine the state of the `is_active` property.

    This class is intended for use with devices which either exhibit analog
    behaviour (such as the charging time of a capacitor with an LDR), or those
    which exhibit "twitchy" behaviour (such as certain motion sensors).

    threshold: `0.5`
        The value above which the device will be considered "on".

    queue_len: `5`
        The length of the internal queue which is filled by the background
        thread.

    sample_wait: `0.0`
        The length of time to wait between retrieving the state of the
        underlying device. Defaults to 0.0 indicating that values are retrieved
        as fast as possible.

    partial: `False`
        If `False` (the default), attempts to read the state of the device
        (from the `is_active` property) will block until the queue has filled.
        If `True`, a value will be returned immediately, but be aware that this
        value is likely to fluctuate excessively.
    """
    def __init__(
            self, pin=None, pull_up=False, threshold=0.5,
            queue_len=5, sample_wait=0.0, partial=False):
        self._queue = None
        super(SmoothedInputDevice, self).__init__(pin, pull_up)
        self._queue = GPIOQueue(self, queue_len, sample_wait, partial)
        self.threshold = float(threshold)

    def close(self):
        try:
            self._queue.stop()
        except AttributeError:
            if self._queue is not None:
                raise
        except RuntimeError:
            # Cannot join thread before it starts; we don't care about this
            # because we're trying to close the thread anyway
            pass
        else:
            self._queue = None
        super(SmoothedInputDevice, self).close()

    def __repr__(self):
        try:
            self._check_open()
        except GPIODeviceClosed:
            return super(SmoothedInputDevice, self).__repr__()
        else:
            if self.partial or self._queue.full.wait(0):
                return super(SmoothedInputDevice, self).__repr__()
            else:
                return "<gpiozero.%s object on pin=%d, pull_up=%s>" % (
                    self.__class__.__name__, self.pin, self.pull_up)

    @property
    def queue_len(self):
        """
        The length of the internal queue of values which is averaged to
        determine the overall state of the device. This defaults to `5`.
        """
        self._check_open()
        return self._queue.queue.maxlen

    @property
    def partial(self):
        """
        If `False` (the default), attempts to read the `value` or `is_active`
        properties will block until the queue has filled.
        """
        self._check_open()
        return self._queue.partial

    @property
    def value(self):
        """
        Returns the mean of the values in the internal queue. This is
        compared to `threshold` to determine whether `is_active` is `True`.
        """
        self._check_open()
        return self._queue.value

    def _get_threshold(self):
        return self._threshold

    def _set_threshold(self, value):
        if not (0.0 < value < 1.0):
            raise InputDeviceError(
                'threshold must be between zero and one exclusive'
            )
        self._threshold = float(value)

    threshold = property(_get_threshold, _set_threshold, doc="""\
        If `value` exceeds this amount, then `is_active` will return `True`.
        """)

    @property
    def is_active(self):
        return self.value > self.threshold

class Button(DigitalInputDevice):
    """
    A physical push button or switch.

    A typical configuration of such a device is to connect a GPIO pin to one
    side of the switch, and ground to the other (the default `pull_up` value
    is `True`).
    """
    def __init__(self, pin=None, pull_up=True, bouncetime=None):
        super(Button, self).__init__(pin, pull_up, bouncetime)

    is_pressed = _alias('is_active')

    when_pressed = _alias('when_activated')
    when_released = _alias('when_deactivated')

    wait_for_press = _alias('wait_for_active')
    wait_for_release = _alias('wait_for_inactive')

class MotionSensor(SmoothedInputDevice):
    """
    A PIR (Passive Infra-Red) motion sensor.

    A typical PIR device has a small circuit board with three pins: VCC, OUT,
    and GND. VCC should be connected to the Pi's +5V pin, GND to one of the
    Pi's ground pins, and finally OUT to the GPIO specified as the value of the
    `pin` parameter in the constructor.
    """
    def __init__(
            self, pin=None, queue_len=5, sample_rate=10, threshold=0.5,
            partial=False):
        super(MotionSensor, self).__init__(
            pin, pull_up=False, threshold=threshold,
            queue_len=queue_len, sample_wait=1 / sample_rate, partial=partial
        )
        self._queue.start()

    motion_detected = _alias('is_active')

    when_motion = _alias('when_activated')
    when_no_motion = _alias('when_deactivated')

    wait_for_motion = _alias('wait_for_active')
    wait_for_no_motion = _alias('wait_for_inactive')

class LightSensor(SmoothedInputDevice):
    """
    An LDR (Light Dependent Resistor) Light Sensor.

    A typical LDR circuit connects one side of the LDR to the 3v3 line from the
    Pi, and the other side to a GPIO pin, and a capacitor tied to ground. This
    class repeatedly discharges the capacitor, then times the duration it takes
    to charge (which will vary according to the light falling on the LDR).
    """
    def __init__(
            self, pin=None, queue_len=5, charge_time_limit=0.01,
            threshold=0.1, partial=False):
        super(LightSensor, self).__init__(
            pin, pull_up=False, threshold=threshold,
            queue_len=queue_len, sample_wait=0.0, partial=partial
        )
        self._charge_time_limit = charge_time_limit
        self._charged = Event()
        GPIO.add_event_detect(
            self.pin, GPIO.RISING, lambda channel: self._charged.set()
        )
        self._queue.start()

    @property
    def charge_time_limit(self):
        return self._charge_time_limit

    def _read(self):
        # Drain charge from the capacitor
        GPIO.setup(self.pin, GPIO.OUT)
        GPIO.output(self.pin, GPIO.LOW)
        sleep(0.1)
        # Time the charging of the capacitor
        start = time()
        self._charged.clear()
        GPIO.setup(self.pin, GPIO.IN)
        self._charged.wait(self.charge_time_limit)
        return (
            1.0 - min(self.charge_time_limit, time() - start) /
            self.charge_time_limit
        )

    light_detected = _alias('is_active')

    when_light = _alias('when_activated')
    when_dark = _alias('when_deactivated')

    wait_for_light = _alias('wait_for_active')
    wait_for_dark = _alias('wait_for_inactive')

class TemperatureSensor(W1ThermSensor):
    """
    A Digital Temperature Sensor.
    """
    @property
    def value(self):
        return self.get_temperature()

class MCP3008(object):
    """
    MCP3008 ADC (Analogue-to-Digital converter).
    """
    def __init__(self, bus=0, device=0, channel=0):
        self.bus = bus
        self.device = device
        self.channel = channel
        self.spi = SpiDev()

    def __enter__(self):
        self.open()
        return self

    def open(self):
        self.spi.open(self.bus, self.device)

    def read(self):
        adc = self.spi.xfer2([1, (8 + self.channel) << 4, 0])
        data = ((adc[1] & 3) << 8) + adc[2]
        return data

    def __exit__(self, type, value, traceback):
        self.close()

    def close(self):
        self.spi.close()


text:
package utl

import java.io._
import java.nio.file.Path
import java.util.zip.{ZipEntry, ZipInputStream}

object Unzip {
  def unzip(zipFile: InputStream, destination: Path): Unit = {
    val zis = new ZipInputStream(zipFile)

    Stream.continually(zis.getNextEntry).takeWhile(_ != null).foreach { file =>
      if (!file.isDirectory) {
        val outPath = destination.resolve(file.getName)
        val outPathParent = outPath.getParent
        if (!outPathParent.toFile.exists()) {
          outPathParent.toFile.mkdirs()
        }

        val outFile = outPath.toFile
        println(outFile.getPath)
        val out = new FileOutputStream(outFile)
        val buffer = new Array[Byte](4096)
        Stream.continually(zis.read(buffer)).takeWhile(_ != -1).foreach(out.write(buffer, 0, _))
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.myfaces.trinidad.event;

import javax.faces.component.UIComponent;

import javax.faces.event.FacesEvent;
import javax.faces.event.FacesListener;

/**
 * Event delivered when a renderer-specific attribute has been
 * changed as a result of user interaction.  This event gives
 * advanced Renderers a chance to inform a generic
 * {@link org.apache.myfaces.trinidad.component.UIXComponent} that some portion of it's appearance
 * has been manipulated.  For example, a "splitter" panel renderer
 * could indicate that the proportions of the splitter have changed.
 *

 * AttributeChangeEvents are not delivered in response
 * to programmatic manipulation of a renderer-specific attribute.
 * They must be explicitly queued by a Renderer when
 * it detects that the user had manipulated the component.  Developers
 * should not abuse this event as a one-size-fits-all generic
 * component event.  When a generic component event changes - like
 * "value" or "disclosed", deliver a strongly-typed component event
 * such as ValueChangeEvent or {@link DisclosureEvent}.
 *
 * @version $Name:  $ ($Revision: adfrt/faces/adf-faces-api/src/main/java/oracle/adf/view/faces/event/AttributeChangeEvent.java#0 $) $Date: 10-nov-2005.19:08:59 $
 */
public class AttributeChangeEvent extends FacesEvent
{
  public AttributeChangeEvent(
    UIComponent source,
    String      attribute,
    Object      oldValue,
    Object      newValue)
  {
    super(source);
    _attribute = attribute;
    _oldValue  = oldValue;
    _newValue  = newValue;
  }

  public String getAttribute()
  {
    return _attribute;
  }

  public Object getOldValue()
  {
    return _oldValue;
  }

  public Object getNewValue()
  {
    return _newValue;
  }

  @Override
  public void processListener(FacesListener listener)
  {
    ((AttributeChangeListener) listener).processAttributeChange(this);
  }

  @Override
  public boolean isAppropriateListener(FacesListener listener)
  {
    return (listener instanceof AttributeChangeListener);
  }

  @Override
  public String toString()
  {
    StringBuffer sb = new StringBuffer();
    sb.append(getClass().getName());
    sb.append("[attribute=");
    sb.append(getAttribute());
    sb.append(",component=");
    sb.append(getComponent());
    sb.append(",oldValue=");
    sb.append(getOldValue());
    sb.append(",newValue=");
    sb.append(getNewValue());
    sb.append(']');
    return sb.toString();
  }

  private final String _attribute;
  private final Object _oldValue;
  private final Object _newValue;
  private static final long serialVersionUID = 1L;
}


text:
// Copyright (c) 2009, Willow Garage, Inc.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright
//      notice, this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the Willow Garage, Inc. nor the names of its
//      contributors may be used to endorse or promote products derived from
//      this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// Author: Stuart Glaser

#ifndef REALTIME_TOOLS__REALTIME_BOX_H__
#define REALTIME_TOOLS__REALTIME_BOX_H__

#include <mutex>
#include <string>

namespace realtime_tools
{
/*!

  Strongly suggested that you use an std::shared_ptr in this box to
  guarantee realtime safety.

 */
template <class T>
class RealtimeBox
{
public:
  explicit RealtimeBox(const T & initial = T()) : thing_(initial) {}

  void set(const T & value)
  {
    std::lock_guard<std::mutex> guard(thing_lock_RT_);
    thing_ = value;
  }

  void get(T & ref)
  {
    std::lock_guard<std::mutex> guard(thing_lock_RT_);
    ref = thing_;
  }

private:
  // The thing that's in the box.
  T thing_;

  // Protects access to the thing in the box.  This mutex is
  // guaranteed to be locked for no longer than the duration of the
  // copy, so as long as the copy is realtime safe and the OS has
  // priority inheritance for mutexes, this lock can be safely locked
  // from within realtime.
  std::mutex thing_lock_RT_;
};

}  // namespace realtime_tools

#endif  // REALTIME_TOOLS__REALTIME_BOX_H_


text:
/*
 * Subject: CS6301.022
 * By Dhrupad Kaneria : dck140030
 *
 * Date: 11/23/2014
 * Description: A class to maintain each entry of a score.
 * It provides basic operations for manipulating the high scores.
 */

package com.UIDesign.barrelrace;

public class ScoreDetail implements Comparable<ScoreDetail>
{
	String Name;
	String Time;

	public ScoreDetail(String n, String t)
	{
		Name = n;
		Time = t;
	}
	public String getName()
	{
		return Name;
	}
	public String getTime()
	{
		return Time;
	}

	@Override
	public int compareTo(ScoreDetail another)
	{
		return getTime().compareTo(another.getTime());
	}
}


text:
#ifndef RenderFrameSet_h
#define RenderFrameSet_h

#include "RenderBox.h"

namespace WebCore {

class HTMLFrameSetElement;
class MouseEvent;
class RenderFrame;

enum FrameEdge { LeftFrameEdge, RightFrameEdge, TopFrameEdge, BottomFrameEdge };

struct FrameEdgeInfo {
    explicit FrameEdgeInfo(bool preventResize = false, bool allowBorder = true)
        : m_preventResize(4)
        , m_allowBorder(4)
    {
        m_preventResize.fill(preventResize);
        m_allowBorder.fill(allowBorder);
    }

    bool preventResize(FrameEdge edge) const { return m_preventResize[edge]; }
    bool allowBorder(FrameEdge edge) const { return m_allowBorder[edge]; }

    void setPreventResize(FrameEdge edge, bool preventResize) { m_preventResize[edge] = preventResize; }
    void setAllowBorder(FrameEdge edge, bool allowBorder) { m_allowBorder[edge] = allowBorder; }

private:
    Vector<bool> m_preventResize;
    Vector<bool> m_allowBorder;
};

class RenderFrameSet FINAL : public RenderBox {
public:
    explicit RenderFrameSet(HTMLFrameSetElement&);
    virtual ~RenderFrameSet();

    HTMLFrameSetElement& frameSetElement() const;

    RenderObject* firstChild() const { return m_children.firstChild(); }
    RenderObject* lastChild() const { return m_children.lastChild(); }

    virtual const RenderObjectChildList* children() const OVERRIDE { return &m_children; }
    virtual RenderObjectChildList* children() OVERRIDE { return &m_children; }

    FrameEdgeInfo edgeInfo() const;

    bool userResize(MouseEvent*);

    bool isResizingRow() const;
    bool isResizingColumn() const;

    bool canResizeRow(const IntPoint&) const;
    bool canResizeColumn(const IntPoint&) const;

    void notifyFrameEdgeInfoChanged();

private:
    void element() const WTF_DELETED_FUNCTION;

    static const int noSplit = -1;

    class GridAxis {
        WTF_MAKE_NONCOPYABLE(GridAxis);
    public:
        GridAxis();
        void resize(int);

        Vector<int> m_sizes;
        Vector<int> m_deltas;
        Vector<bool> m_preventResize;
        Vector<bool> m_allowBorder;
        int m_splitBeingResized;
        int m_splitResizeOffset;
    };

    virtual const char* renderName() const OVERRIDE { return "RenderFrameSet"; }
    virtual bool isFrameSet() const OVERRIDE { return true; }

    virtual void layout() OVERRIDE;
    virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
    virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
    virtual CursorDirective getCursor(const LayoutPoint&, Cursor&) const OVERRIDE;

    bool flattenFrameSet() const;

    void setIsResizing(bool);

    void layOutAxis(GridAxis&, const Length*, int availableSpace);
    void computeEdgeInfo();
    void fillFromEdgeInfo(const FrameEdgeInfo& edgeInfo, int r, int c);
    void positionFrames();
    void positionFramesWithFlattening();

    int splitPosition(const GridAxis&, int split) const;
    int hitTestSplit(const GridAxis&, int position) const;

    void startResizing(GridAxis&, int position);
    void continueResizing(GridAxis&, int position);

    void paintRowBorder(const PaintInfo&, const IntRect&);
    void paintColumnBorder(const PaintInfo&, const IntRect&);

    RenderObjectChildList m_children;

    GridAxis m_rows;
    GridAxis m_cols;

    bool m_isResizing;
    bool m_isChildResizing;
};

inline RenderFrameSet* toRenderFrameSet(RenderObject* object)
{
    ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isFrameSet());
    return static_cast<RenderFrameSet*>(object);
}

// This will catch anyone doing an unnecessary cast.
void toRenderFrameSet(const RenderFrameSet*);

} // namespace WebCore

#endif // RenderFrameSet_h


text:
"""
Copyright 2015 Basho Technologies, Inc.
Copyright 2010 Rusty Klophaus <rusty@basho.com>
Copyright 2010 Justin Sheehy <justin@basho.com>
Copyright 2009 Jay Baird <jay@mochimedia.com>

This file is provided to you under the Apache License,
Version 2.0 (the "License"); you may not use this file
except in compliance with the License.  You may obtain
a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
"""

import riak_pb
from riak import RiakError
from riak.transports.transport import RiakTransport
from riak.riak_object import VClock
from riak.util import decode_index_value, str_to_bytes, bytes_to_str
from riak.transports.pbc.connection import RiakPbcConnection
from riak.transports.pbc.stream import (RiakPbcKeyStream,
                                        RiakPbcMapredStream,
                                        RiakPbcBucketStream,
                                        RiakPbcIndexStream)
from riak.transports.pbc.codec import RiakPbcCodec
from six import PY2, PY3

from riak_pb.messages import (
    MSG_CODE_PING_REQ,
    MSG_CODE_PING_RESP,
    MSG_CODE_GET_CLIENT_ID_REQ,
    MSG_CODE_GET_CLIENT_ID_RESP,
    MSG_CODE_SET_CLIENT_ID_REQ,
    MSG_CODE_SET_CLIENT_ID_RESP,
    MSG_CODE_GET_SERVER_INFO_REQ,
    MSG_CODE_GET_SERVER_INFO_RESP,
    MSG_CODE_GET_REQ,
    MSG_CODE_GET_RESP,
    MSG_CODE_PUT_REQ,
    MSG_CODE_PUT_RESP,
    MSG_CODE_DEL_REQ,
    MSG_CODE_DEL_RESP,
    MSG_CODE_LIST_BUCKETS_REQ,
    MSG_CODE_LIST_BUCKETS_RESP,
    MSG_CODE_LIST_KEYS_REQ,
    MSG_CODE_GET_BUCKET_REQ,
    MSG_CODE_GET_BUCKET_RESP,
    MSG_CODE_SET_BUCKET_REQ,
    MSG_CODE_SET_BUCKET_RESP,
    MSG_CODE_GET_BUCKET_TYPE_REQ,
    MSG_CODE_SET_BUCKET_TYPE_REQ,
    MSG_CODE_MAP_RED_REQ,
    MSG_CODE_INDEX_REQ,
    MSG_CODE_INDEX_RESP,
    MSG_CODE_SEARCH_QUERY_REQ,
    MSG_CODE_SEARCH_QUERY_RESP,
    MSG_CODE_RESET_BUCKET_REQ,
    MSG_CODE_RESET_BUCKET_RESP,
    MSG_CODE_COUNTER_UPDATE_REQ,
    MSG_CODE_COUNTER_UPDATE_RESP,
    MSG_CODE_COUNTER_GET_REQ,
    MSG_CODE_COUNTER_GET_RESP,
    MSG_CODE_YOKOZUNA_INDEX_GET_REQ,
    MSG_CODE_YOKOZUNA_INDEX_GET_RESP,
    MSG_CODE_YOKOZUNA_INDEX_PUT_REQ,
    MSG_CODE_YOKOZUNA_INDEX_DELETE_REQ,
    MSG_CODE_YOKOZUNA_SCHEMA_GET_REQ,
    MSG_CODE_YOKOZUNA_SCHEMA_GET_RESP,
    MSG_CODE_YOKOZUNA_SCHEMA_PUT_REQ,
    MSG_CODE_DT_FETCH_REQ,
    MSG_CODE_DT_FETCH_RESP,
    MSG_CODE_DT_UPDATE_REQ,
    MSG_CODE_DT_UPDATE_RESP
)

class RiakPbcTransport(RiakTransport, RiakPbcConnection, RiakPbcCodec):
    """
    The RiakPbcTransport object holds a connection to the protocol
    buffers interface on the riak server.
    """

    def __init__(self,
                 node=None,
                 client=None,
                 timeout=None,
                 *unused_options):
        """
        Construct a new RiakPbcTransport object.
        """
        super(RiakPbcTransport, self).__init__()

        self._client = client
        self._node = node
        self._address = (node.host, node.pb_port)
        self._timeout = timeout
        self._socket = None

    # FeatureDetection API
    def _server_version(self):
        return bytes_to_str(self.get_server_info()['server_version'])

    def ping(self):
        """
        Ping the remote server
        """

        msg_code, msg = self._request(MSG_CODE_PING_REQ)
        if msg_code == MSG_CODE_PING_RESP:
            return True
        else:
            return False

    def get_server_info(self):
        """
        Get information about the server
        """
        msg_code, resp = self._request(MSG_CODE_GET_SERVER_INFO_REQ,
                                       expect=MSG_CODE_GET_SERVER_INFO_RESP)
        return {'node': bytes_to_str(resp.node),
                'server_version': bytes_to_str(resp.server_version)}

    def _get_client_id(self):
        msg_code, resp = self._request(MSG_CODE_GET_CLIENT_ID_REQ,
                                       expect=MSG_CODE_GET_CLIENT_ID_RESP)
        return bytes_to_str(resp.client_id)

    def _set_client_id(self, client_id):
        req = riak_pb.RpbSetClientIdReq()
        req.client_id = str_to_bytes(client_id)

        msg_code, resp = self._request(MSG_CODE_SET_CLIENT_ID_REQ, req,
                                       MSG_CODE_SET_CLIENT_ID_RESP)

        self._client_id = client_id

    client_id = property(_get_client_id, _set_client_id,
                         doc="""the client ID for this connection""")

    def get(self, robj, r=None, pr=None, timeout=None, basic_quorum=None,
            notfound_ok=None):
        """
        Serialize get request and deserialize response
        """
        bucket = robj.bucket

        req = riak_pb.RpbGetReq()
        if r:
            req.r = self._encode_quorum(r)
        if self.quorum_controls():
            if pr:
                req.pr = self._encode_quorum(pr)
            if basic_quorum is not None:
                req.basic_quorum = basic_quorum
            if notfound_ok is not None:
                req.notfound_ok = notfound_ok
        if self.client_timeouts() and timeout:
            req.timeout = timeout
        if self.tombstone_vclocks():
            req.deletedvclock = True

        req.bucket = str_to_bytes(bucket.name)
        self._add_bucket_type(req, bucket.bucket_type)

        req.key = str_to_bytes(robj.key)

        msg_code, resp = self._request(MSG_CODE_GET_REQ, req,
                                       MSG_CODE_GET_RESP)

        if resp is not None:
            if resp.HasField('vclock'):
                robj.vclock = VClock(resp.vclock, 'binary')
            # We should do this even if there are no contents, i.e.
            # the object is tombstoned
            self._decode_contents(resp.content, robj)
        else:
            # "not found" returns an empty message,
            # so let's make sure to clear the siblings
            robj.siblings = []

        return robj

    def put(self, robj, w=None, dw=None, pw=None, return_body=True,
            if_none_match=False, timeout=None):
        bucket = robj.bucket

        req = riak_pb.RpbPutReq()
        if w:
            req.w = self._encode_quorum(w)
        if dw:
            req.dw = self._encode_quorum(dw)
        if self.quorum_controls() and pw:
            req.pw = self._encode_quorum(pw)

        if return_body:
            req.return_body = 1
        if if_none_match:
            req.if_none_match = 1
        if self.client_timeouts() and timeout:
            req.timeout = timeout

        req.bucket = str_to_bytes(bucket.name)
        self._add_bucket_type(req, bucket.bucket_type)

        if robj.key:
            req.key = str_to_bytes(robj.key)
        if robj.vclock:
            req.vclock = robj.vclock.encode('binary')

        self._encode_content(robj, req.content)

        msg_code, resp = self._request(MSG_CODE_PUT_REQ, req,
                                       MSG_CODE_PUT_RESP)

        if resp is not None:
            if resp.HasField('key'):
                robj.key = bytes_to_str(resp.key)
            if resp.HasField("vclock"):
                robj.vclock = VClock(resp.vclock, 'binary')
            if resp.content:
                self._decode_contents(resp.content, robj)
        elif not robj.key:
            raise RiakError("missing response object")

        return robj

    def delete(self, robj, rw=None, r=None, w=None, dw=None, pr=None, pw=None,
               timeout=None):
        req = riak_pb.RpbDelReq()
        if rw:
            req.rw = self._encode_quorum(rw)
        if r:
            req.r = self._encode_quorum(r)
        if w:
            req.w = self._encode_quorum(w)
        if dw:
            req.dw = self._encode_quorum(dw)

        if self.quorum_controls():
            if pr:
                req.pr = self._encode_quorum(pr)
            if pw:
                req.pw = self._encode_quorum(pw)

        if self.client_timeouts() and timeout:
            req.timeout = timeout

        use_vclocks = (self.tombstone_vclocks() and
                       hasattr(robj, 'vclock') and robj.vclock)
        if use_vclocks:
            req.vclock = robj.vclock.encode('binary')

        bucket = robj.bucket
        req.bucket = str_to_bytes(bucket.name)
        self._add_bucket_type(req, bucket.bucket_type)
        req.key = str_to_bytes(robj.key)

        msg_code, resp = self._request(MSG_CODE_DEL_REQ, req,
                                       MSG_CODE_DEL_RESP)
        return self

    def get_keys(self, bucket, timeout=None):
        """
        Lists all keys within a bucket.
        """
        keys = []
        for keylist in self.stream_keys(bucket, timeout=timeout):
            for key in keylist:
                keys.append(bytes_to_str(key))

        return keys

    def stream_keys(self, bucket, timeout=None):
        """
        Streams keys from a bucket, returning an iterator that yields
        lists of keys.
        """
        req = riak_pb.RpbListKeysReq()
        req.bucket = str_to_bytes(bucket.name)
        self._add_bucket_type(req, bucket.bucket_type)
        if self.client_timeouts() and timeout:
            req.timeout = timeout

        self._send_msg(MSG_CODE_LIST_KEYS_REQ, req)

        return RiakPbcKeyStream(self)

    def get_buckets(self, bucket_type=None, timeout=None):
        """
        Serialize bucket listing request and deserialize response
        """
        req = riak_pb.RpbListBucketsReq()
        self._add_bucket_type(req, bucket_type)

        if self.client_timeouts() and timeout:
            req.timeout = timeout

        msg_code, resp = self._request(MSG_CODE_LIST_BUCKETS_REQ, req,
                                       MSG_CODE_LIST_BUCKETS_RESP)
        return resp.buckets

    def stream_buckets(self, bucket_type=None, timeout=None):
        """
        Stream list of buckets through an iterator
        """

        if not self.bucket_stream():
            raise NotImplementedError('Streaming list-buckets is not '
                                      'supported')

        req = riak_pb.RpbListBucketsReq()
        req.stream = True
        self._add_bucket_type(req, bucket_type)
        # Bucket streaming landed in the same release as timeouts, so
        # we don't need to check the capability.
        if timeout:
            req.timeout = timeout

        self._send_msg(MSG_CODE_LIST_BUCKETS_REQ, req)

        return RiakPbcBucketStream(self)

    def get_bucket_props(self, bucket):
        """
        Serialize bucket property request and deserialize response
        """
        req = riak_pb.RpbGetBucketReq()
        req.bucket = str_to_bytes(bucket.name)
        self._add_bucket_type(req, bucket.bucket_type)

        msg_code, resp = self._request(MSG_CODE_GET_BUCKET_REQ, req,
                                       MSG_CODE_GET_BUCKET_RESP)

        return self._decode_bucket_props(resp.props)

    def set_bucket_props(self, bucket, props):
        """
        Serialize set bucket property request and deserialize response
        """
        req = riak_pb.RpbSetBucketReq()
        req.bucket = str_to_bytes(bucket.name)
        self._add_bucket_type(req, bucket.bucket_type)

        if not self.pb_all_bucket_props():
            for key in props:
                if key not in ('n_val', 'allow_mult'):
                    raise NotImplementedError('Server only supports n_val and '
                                              'allow_mult properties over PBC')

        self._encode_bucket_props(props, req)

        msg_code, resp = self._request(MSG_CODE_SET_BUCKET_REQ, req,
                                       MSG_CODE_SET_BUCKET_RESP)
        return True

    def clear_bucket_props(self, bucket):
        """
        Clear bucket properties, resetting them to their defaults
        """
        if not self.pb_clear_bucket_props():
            return False

        req = riak_pb.RpbResetBucketReq()
        req.bucket = str_to_bytes(bucket.name)
        self._add_bucket_type(req, bucket.bucket_type)
        self._request(MSG_CODE_RESET_BUCKET_REQ, req,
                      MSG_CODE_RESET_BUCKET_RESP)
        return True

    def get_bucket_type_props(self, bucket_type):
        """
        Fetch bucket-type properties
        """
        self._check_bucket_types(bucket_type)

        req = riak_pb.RpbGetBucketTypeReq()
        req.type = str_to_bytes(bucket_type.name)

        msg_code, resp = self._request(MSG_CODE_GET_BUCKET_TYPE_REQ, req,
                                       MSG_CODE_GET_BUCKET_RESP)

        return self._decode_bucket_props(resp.props)

    def set_bucket_type_props(self, bucket_type, props):
        """
        Set bucket-type properties
        """
        self._check_bucket_types(bucket_type)

        req = riak_pb.RpbSetBucketTypeReq()
        req.type = str_to_bytes(bucket_type.name)

        self._encode_bucket_props(props, req)

        msg_code, resp = self._request(MSG_CODE_SET_BUCKET_TYPE_REQ, req,
                                       MSG_CODE_SET_BUCKET_RESP)
        return True

    def mapred(self, inputs, query, timeout=None):
        # dictionary of phase results - each content should be an encoded array
        # which is appended to the result for that phase.
        result = {}
        for phase, content in self.stream_mapred(inputs, query, timeout):
            if phase in result:
                result[phase] += content
            else:
                result[phase] = content

        # If a single result - return the same as the HTTP interface does
        # otherwise return all the phase information
        if not len(result):
            return None
        elif len(result) == 1:
            return result[max(result.keys())]
        else:
            return result

    def stream_mapred(self, inputs, query, timeout=None):
        # Construct the job, optionally set the timeout...
        content = self._construct_mapred_json(inputs, query, timeout)

        req = riak_pb.RpbMapRedReq()
        req.request = str_to_bytes(content)
        req.content_type = str_to_bytes("application/json")

        self._send_msg(MSG_CODE_MAP_RED_REQ, req)

        return RiakPbcMapredStream(self)

    def get_index(self, bucket, index, startkey, endkey=None,
                  return_terms=None, max_results=None, continuation=None,
                  timeout=None, term_regex=None):
        if not self.pb_indexes():
            return self._get_index_mapred_emu(bucket, index, startkey, endkey)

        if term_regex and not self.index_term_regex():
            raise NotImplementedError("Secondary index term_regex is not "
                                      "supported")

        req = self._encode_index_req(bucket, index, startkey, endkey,
                                     return_terms, max_results, continuation,
                                     timeout, term_regex)

        msg_code, resp = self._request(MSG_CODE_INDEX_REQ, req,
                                       MSG_CODE_INDEX_RESP)

        if return_terms and resp.results:
            results = [(decode_index_value(index, pair.key),
                        bytes_to_str(pair.value))
                       for pair in resp.results]
        else:
            results = resp.keys[:]
            if PY3:
                results = [bytes_to_str(key) for key in resp.keys]

        if max_results is not None and resp.HasField('continuation'):
            return (results, bytes_to_str(resp.continuation))
        else:
            return (results, None)

    def stream_index(self, bucket, index, startkey, endkey=None,
                     return_terms=None, max_results=None, continuation=None,
                     timeout=None, term_regex=None):
        if not self.stream_indexes():
            raise NotImplementedError("Secondary index streaming is not "
                                      "supported")

        if term_regex and not self.index_term_regex():
            raise NotImplementedError("Secondary index term_regex is not "
                                      "supported")

        req = self._encode_index_req(bucket, index, startkey, endkey,
                                     return_terms, max_results, continuation,
                                     timeout, term_regex)
        req.stream = True

        self._send_msg(MSG_CODE_INDEX_REQ, req)

        return RiakPbcIndexStream(self, index, return_terms)

    def create_search_index(self, index, schema=None, n_val=None):
        if not self.pb_search_admin():
            raise NotImplementedError("Search 2.0 administration is not "
                                      "supported for this version")
        index = str_to_bytes(index)
        idx = riak_pb.RpbYokozunaIndex(name=index)
        if schema:
            idx.schema = str_to_bytes(schema)
        if n_val:
            idx.n_val = n_val
        req = riak_pb.RpbYokozunaIndexPutReq(index=idx)

        self._request(MSG_CODE_YOKOZUNA_INDEX_PUT_REQ, req,
                      MSG_CODE_PUT_RESP)
        return True

    def get_search_index(self, index):
        if not self.pb_search_admin():
            raise NotImplementedError("Search 2.0 administration is not "
                                      "supported for this version")
        req = riak_pb.RpbYokozunaIndexGetReq(name=str_to_bytes(index))

        msg_code, resp = self._request(MSG_CODE_YOKOZUNA_INDEX_GET_REQ, req,
                                       MSG_CODE_YOKOZUNA_INDEX_GET_RESP)
        if len(resp.index) > 0:
            return self._decode_search_index(resp.index[0])
        else:
            raise RiakError('notfound')

    def list_search_indexes(self):
        if not self.pb_search_admin():
            raise NotImplementedError("Search 2.0 administration is not "
                                      "supported for this version")
        req = riak_pb.RpbYokozunaIndexGetReq()

        msg_code, resp = self._request(MSG_CODE_YOKOZUNA_INDEX_GET_REQ, req,
                                       MSG_CODE_YOKOZUNA_INDEX_GET_RESP)

        return [self._decode_search_index(index) for index in resp.index]

    def delete_search_index(self, index):
        if not self.pb_search_admin():
            raise NotImplementedError("Search 2.0 administration is not "
                                      "supported for this version")
        req = riak_pb.RpbYokozunaIndexDeleteReq(name=str_to_bytes(index))

        self._request(MSG_CODE_YOKOZUNA_INDEX_DELETE_REQ, req,
                      MSG_CODE_DEL_RESP)

        return True

    def create_search_schema(self, schema, content):
        if not self.pb_search_admin():
            raise NotImplementedError("Search 2.0 administration is not "
                                      "supported for this version")
        scma = riak_pb.RpbYokozunaSchema(name=str_to_bytes(schema),
                                         content=str_to_bytes(content))
        req = riak_pb.RpbYokozunaSchemaPutReq(schema=scma)

        self._request(MSG_CODE_YOKOZUNA_SCHEMA_PUT_REQ, req,
                      MSG_CODE_PUT_RESP)
        return True

    def get_search_schema(self, schema):
        if not self.pb_search_admin():
            raise NotImplementedError("Search 2.0 administration is not "
                                      "supported for this version")
        req = riak_pb.RpbYokozunaSchemaGetReq(name=str_to_bytes(schema))

        msg_code, resp = self._request(MSG_CODE_YOKOZUNA_SCHEMA_GET_REQ, req,
                                       MSG_CODE_YOKOZUNA_SCHEMA_GET_RESP)
        result = {}
        result['name'] = bytes_to_str(resp.schema.name)
        result['content'] = bytes_to_str(resp.schema.content)
        return result

    def search(self, index, query, **params):
        if not self.pb_search():
            return self._search_mapred_emu(index, query)

        if PY2 and isinstance(query, unicode):
            query = query.encode('utf8')

        req = riak_pb.RpbSearchQueryReq(index=str_to_bytes(index),
                                        q=str_to_bytes(query))
        self._encode_search_query(req, params)

        msg_code, resp = self._request(MSG_CODE_SEARCH_QUERY_REQ, req,
                                       MSG_CODE_SEARCH_QUERY_RESP)

        result = {}
        if resp.HasField('max_score'):
            result['max_score'] = resp.max_score
        if resp.HasField('num_found'):
            result['num_found'] = resp.num_found
        result['docs'] = [self._decode_search_doc(doc) for doc in resp.docs]
        return result

    def get_counter(self, bucket, key, **params):
        if not bucket.bucket_type.is_default():
            raise NotImplementedError("Counters are not "
                                      "supported with bucket-types, "
                                      "use datatypes instead.")

        if not self.counters():
            raise NotImplementedError("Counters are not supported")

        req = riak_pb.RpbCounterGetReq()
        req.bucket = str_to_bytes(bucket.name)
        req.key = str_to_bytes(key)
        if params.get('r') is not None:
            req.r = self._encode_quorum(params['r'])
        if params.get('pr') is not None:
            req.pr = self._encode_quorum(params['pr'])
        if params.get('basic_quorum') is not None:
            req.basic_quorum = params['basic_quorum']
        if params.get('notfound_ok') is not None:
            req.notfound_ok = params['notfound_ok']

        msg_code, resp = self._request(MSG_CODE_COUNTER_GET_REQ, req,
                                       MSG_CODE_COUNTER_GET_RESP)
        if resp.HasField('value'):
            return resp.value
        else:
            return None

    def update_counter(self, bucket, key, value, **params):
        if not bucket.bucket_type.is_default():
            raise NotImplementedError("Counters are not "
                                      "supported with bucket-types, "
                                      "use datatypes instead.")

        if not self.counters():
            raise NotImplementedError("Counters are not supported")

        req = riak_pb.RpbCounterUpdateReq()
        req.bucket = str_to_bytes(bucket.name)
        req.key = str_to_bytes(key)
        req.amount = value
        if params.get('w') is not None:
            req.w = self._encode_quorum(params['w'])
        if params.get('dw') is not None:
            req.dw = self._encode_quorum(params['dw'])
        if params.get('pw') is not None:
            req.pw = self._encode_quorum(params['pw'])
        if params.get('returnvalue') is not None:
            req.returnvalue = params['returnvalue']

        msg_code, resp = self._request(MSG_CODE_COUNTER_UPDATE_REQ, req,
                                       MSG_CODE_COUNTER_UPDATE_RESP)
        if resp.HasField('value'):
            return resp.value
        else:
            return True

    def fetch_datatype(self, bucket, key, **options):

        if bucket.bucket_type.is_default():
            raise NotImplementedError("Datatypes cannot be used in the default"
                                      " bucket-type.")

        if not self.datatypes():
            raise NotImplementedError("Datatypes are not supported.")

        req = riak_pb.DtFetchReq()
        req.type = str_to_bytes(bucket.bucket_type.name)
        req.bucket = str_to_bytes(bucket.name)
        req.key = str_to_bytes(key)
        self._encode_dt_options(req, options)

        msg_code, resp = self._request(MSG_CODE_DT_FETCH_REQ, req,
                                       MSG_CODE_DT_FETCH_RESP)

        return self._decode_dt_fetch(resp)

    def update_datatype(self, datatype, **options):

        if datatype.bucket.bucket_type.is_default():
            raise NotImplementedError("Datatypes cannot be used in the default"
                                      " bucket-type.")

        if not self.datatypes():
            raise NotImplementedError("Datatypes are not supported.")

        op = datatype.to_op()
        type_name = datatype.type_name
        if not op:
            raise ValueError("No operation to send on datatype {!r}".
                             format(datatype))

        req = riak_pb.DtUpdateReq()
        req.bucket = str_to_bytes(datatype.bucket.name)
        req.type = str_to_bytes(datatype.bucket.bucket_type.name)

        if datatype.key:
            req.key = str_to_bytes(datatype.key)
        if datatype._context:
            req.context = datatype._context

        self._encode_dt_options(req, options)

        self._encode_dt_op(type_name, req, op)

        msg_code, resp = self._request(MSG_CODE_DT_UPDATE_REQ, req,
                                       MSG_CODE_DT_UPDATE_RESP)
        if resp.HasField('key'):
            datatype.key = resp.key[:]
        if resp.HasField('context'):
            datatype._context = resp.context[:]

        if options.get('return_body'):
            datatype._set_value(self._decode_dt_value(type_name, resp))

        return True


text:
package Classes;

import android.os.Parcel;
import android.os.Parcelable;

import java.io.Serializable;
import java.util.Date;

/**
 * Created by luiz on 07/05/2015.
 */
public class Eventos implements Serializable {

    private int _id;
    private String nome;
    private String data_escrita;
    private String faixa_etaria;
    private String local;
    private String hora;
    private String informacoes;
    private String vagas;
    private String valor;
    private String categoria;
    private String data;
    private String imagem;
  //  Date data;

    public Eventos(int id, String nome, String data_escrita, String faixa_etaria, String local, String hora, String informacoes, String vagas, String valor, String categoria, String data, String imagem) {
        this._id = id;
        this.nome = nome;
        this.data_escrita = data_escrita;
        this.faixa_etaria = faixa_etaria;
        this.local = local;
        this.hora = hora;
        this.informacoes = informacoes;
        this.vagas = vagas;
        this.valor = valor;
        this.categoria = categoria;
        this.data = data;
        this.imagem = imagem;
    }

    public Eventos() {

    }

    public int getId() {
        return _id;
    }

    public void setId(int id) {
        this._id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getData_escrita() {
        return data_escrita;
    }

    public void setData_escrita(String data_escrita) {
        this.data_escrita = data_escrita;
    }

    public String getFaixa_etaria() {
        return faixa_etaria;
    }

    public void setFaixa_etaria(String faixa_etaria) {
        this.faixa_etaria = faixa_etaria;
    }

    public String getLocal() {
        return local;
    }

    public void setLocal(String local) {
        this.local = local;
    }

    public String getHora() {
        return hora;
    }

    public void setHora(String hora) {
        this.hora = hora;
    }

    public String getInformacoes() {
        return informacoes;
    }

    public void setInformacoes(String informacoes) {
        this.informacoes = informacoes;
    }

    public String getVagas() {
        return vagas;
    }

    public void setVagas(String vagas) {
        this.vagas = vagas;
    }

    public String getValor() {
        return valor;
    }

    public void setValor(String valor) {
        this.valor = valor;
    }

    public String getCategoria() {
        return categoria;
    }

    public void setCategoria(String categoria) {
        this.categoria = categoria;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public int get_id() {
        return _id;
    }

    public void set_id(int _id) {
        this._id = _id;
    }

    public String getImagem() {
        return imagem;
    }

    public void setImagem(String imagem) {
        this.imagem = imagem;
    }
}


text:
/*
Package cachet provides a client for using the Cachet API (https://cachethq.io/).

Construct a new Cachet client, then use the various services on the client to
access different parts of the Cachet API. For example:

	instance := "https://demo.cachethq.io/"
	client, err := cachet.NewClient(instance, nil)

	// Get all components
	components, resp, err := client.Components.GetAll()

The services of a client divide the API into logical chunks and correspond to
the structure of the Cachet API documentation at https://docs.cachethq.io/docs/.

Authentication

The cachet library supports various methods to support the authentication.
This methods are combined in the AuthenticationService that is available at client.Authentication.

One way is an authentication via HTTP BasicAuth:

	instance := "https://demo.cachethq.io/"
	client, err := cachet.NewClient(instance, nil)

	client.Authentication.SetBasicAuth("test@test.com", "test123")

	component := &cachet.Component{
		Name:        "Beer Fridge",
		Description: "Status of the beer fridge in the kitchen",
		Status:      cachet.ComponentStatusOperational,
	}
	newComponent, resp, err := client.Components.Create(component)

	fmt.Printf("Result: %s\n", newComponent.Name)
	// Result: Beer Fridge

The other way is the API Token by Cachet:

	instance := "https://demo.cachethq.io/"
	client, err := cachet.NewClient(instance, nil)

	client.Authentication.SetTokenAuth("MY-SECRET-TOKEN")

	// ... your action here

Additionally when creating a new client, pass an http.Client that supports further actions for you.
For more information regarding authentication have a look at the Cachet documentation:
https://docs.cachethq.io/docs/api-authentication

*/
package cachet


text:
/**
 * Contains client-side impl of the Raft proxy session manager
 */
package com.hazelcast.client.cp.internal.session;


text:
<component name="libraryTable">
  <library name="SBT: com.esotericsoftware.minlog:minlog:1.2">
    <CLASSES>
      <root url="jar://$USER_HOME$/.ivy2/cache/com.esotericsoftware.minlog/minlog/jars/minlog-1.2.jar!/"/>
    </CLASSES>
    <JAVADOC>
      <root url="jar://$USER_HOME$/.ivy2/cache/com.esotericsoftware.minlog/minlog/docs/minlog-1.2-javadoc.jar!/"/>
    </JAVADOC>
    <SOURCES>
      <root url="jar://$USER_HOME$/.ivy2/cache/com.esotericsoftware.minlog/minlog/srcs/minlog-1.2-sources.jar!/"/>
    </SOURCES>
  </library>
</component>


text:
package org.talend.sdk.component.junit5;

import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;

import javax.json.bind.Jsonb;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.talend.sdk.component.api.service.Service;
import org.talend.sdk.component.api.service.configuration.LocalConfiguration;
import org.talend.sdk.component.junit.ComponentsHandler;
import org.talend.sdk.component.junit.JoinInputFactory;
import org.talend.sdk.component.junit.SimpleComponentRule;
import org.talend.sdk.component.junit.component.BatchTransform;
import org.talend.sdk.component.junit.component.DuplicateEmitTransform;
import org.talend.sdk.component.junit.component.Source;
import org.talend.sdk.component.junit.component.Transform;
import org.talend.sdk.component.runtime.input.Input;
import org.talend.sdk.component.runtime.input.InputImpl;
import org.talend.sdk.component.runtime.input.Mapper;
import org.talend.sdk.component.runtime.input.PartitionMapperImpl;
import org.talend.sdk.component.runtime.output.Processor;

@WithComponents("org.talend.sdk.component.junit.component")
class ComponentExtensionTest {

    @Injected
    private ComponentsHandler handler;

    @Service
    private LocalConfiguration configuration;

    @Service
    private Jsonb jsonb;

    @Test
    void serviceInjection() {
        Stream.of(configuration, jsonb).forEach(Assertions::assertNotNull);
    }

    @Test
    void manualMapper() {
        final Mapper mapper = handler.createMapper(Source.class, new Source.Config() {

            {
                values = asList("a", "b");
            }
        });
        assertFalse(mapper.isStream());
        final Input input = mapper.create();
        assertEquals("a", input.next());
        assertEquals("b", input.next());
        assertNull(input.next());
    }

    @Test
    void sourceCollector() {
        final Mapper mapper = handler.createMapper(Source.class, new Source.Config() {

            {
                values = asList("a", "b");
            }
        });
        assertEquals(asList("a", "b"), handler.collectAsList(String.class, mapper));
    }

    @Test
    void sourceCollectorParallel() {
        final CountDownLatch latch = new CountDownLatch(1);
        final Mapper mapper = new PartitionMapperImpl() {

            @Override
            public long assess() {
                return 2;
            }

            @Override
            public List<Mapper> split(final long desiredSize) {
                assertEquals(1, desiredSize);
                return asList(this, this);
            }

            @Override
            public Input create() {
                return new InputImpl() {

                    private final AtomicBoolean done = new AtomicBoolean();

                    @Override
                    public Object next() {
                        try {
                            latch.await(1, MINUTES);
                        } catch (final InterruptedException e) {
                            Thread.currentThread().interrupt();
                            fail();
                        }
                        return done.compareAndSet(false, true) ? Thread.currentThread().getName() : null;
                    }

                    @Override
                    protected Stream<Method> findMethods(final Class<? extends Annotation> marker) {
                        return Stream.empty();
                    }
                };
            }

            @Override
            protected Stream<Method> findMethods(final Class<? extends Annotation> marker) {
                return Stream.empty();
            }
        };
        latch.countDown();

        final Stream<String> collect = handler.collect(String.class, mapper, 2, 2);
        final List<String> threads = collect.collect(toList());
        assertEquals(threads.toString(), 2, threads.size());
        threads.forEach(n -> assertTrue(n, n.startsWith("ComponentExtension-pool-")));
    }

    @Test
    void processorCollector() {
        final Processor processor = handler.createProcessor(Transform.class, null);
        final SimpleComponentRule.Outputs outputs = handler
                .collect(processor,
                        new JoinInputFactory()
                                .withInput("__default__", asList(new Transform.Record("a"), new Transform.Record("bb")))
                                .withInput("second", asList(new Transform.Record("1"), new Transform.Record("2"))));
        assertEquals(2, outputs.size());
        assertEquals(asList(2, 3), outputs.get(Integer.class, "size"));
        assertEquals(asList("a1", "bb2"), outputs.get(String.class, "value"));
    }

    @Test
    void batchProcessorCollector() {
        final Processor processor = handler.createProcessor(BatchTransform.class, null);
        final SimpleComponentRule.Outputs outputs = handler
                .collect(processor, new JoinInputFactory()
                        .withInput("__default__", asList(new BatchTransform.Record("a"), new Transform.Record("bb")))
                        .withInput("second", asList(new BatchTransform.Record("1"), new Transform.Record("2"))));
        assertEquals(2, outputs.size());
        assertEquals(asList(2, 3), outputs.get(Integer.class, "size"));
        assertEquals(asList("a1", "bb2"), outputs.get(String.class, "value"));
    }

    @Test
    void multipleProcessorCollector() {
        final Processor processor = handler.createProcessor(DuplicateEmitTransform.class, null);
        final SimpleComponentRule.Outputs outputs =
                handler
                        .collect(processor,
                                new JoinInputFactory()
                                        .withInput("__default__",
                                                asList(new DuplicateEmitTransform.Record("a"),
                                                        new Transform.Record("bb")))
                                        .withInput("second", asList(new DuplicateEmitTransform.Record("1"),
                                                new Transform.Record("2"))));
        assertEquals(2, outputs.size());
        assertEquals(asList(2, 3), outputs.get(Integer.class, "size"));
        assertEquals(asList("a1", "a1", "bb2", "bb2"), outputs.get(String.class, "value"));
    }
}


text:
<?php
namespace Common\Behavior;

/**
 * @desc 处理Http响应头行为类
 */
class BuildHeaderBehavior{

    public function run()
    {
        header('Access-Control-Allow-Origin:'.$_SERVER['HTTP_ORIGIN']);
        header('Access-Control-Allow-Credentials:true');
        header('Access-Control-Allow-Methods:POST, GET, OPTIONS');
        header('Access-Control-Allow-Headers:XML-Requested-With');
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Strobilanthes straminea W.W.Sm.

### Remarks
null


text:
using UnityEngine;
using System.Collections;

public class RotateWithInput : MonoBehaviour
{

	public Transform RotateSource;

	public float RotationSpeed = 1;

	public Space space = Space.World;

	public bool X = true;
	public bool Y = true;

	public Collider ControlArea = null;

	Vector3 horizontalAngle;
	Vector3 verticalAngle;

	void Start()
	{
		if(RotateSource == null)
			RotateSource = transform;

		if(space == Space.World)
		{
			horizontalAngle = Vector3.forward;
			verticalAngle = Vector3.right;
		}
		else
		{
			horizontalAngle = transform.forward;
			verticalAngle = transform.right;
		}
	}

	void Update()
	{
		if(X)
			transform.RotateAround(RotateSource.position, horizontalAngle, Input.GetAxis("Horizontal") * -RotationSpeed);
		if(Y)
			transform.RotateAround(RotateSource.position, verticalAngle, Input.GetAxis("Vertical") * RotationSpeed);
	}
}


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

<TITLE>
Message
</TITLE>

<META NAME="date" CONTENT="2013-08-27">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

net.floodlightcontroller.packetstreamer.thrift

Class Message

java.lang.Object
  net.floodlightcontroller.packetstreamer.thrift.Message

All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, java.lang.Comparable<Message>, org.apache.thrift.TBase<Message,Message._Fields>

public class Message
extends java.lang.Object
implements org.apache.thrift.TBase<Message,Message._Fields>, java.io.Serializable, java.lang.Cloneable

See Also:
Serialized Form

Nested Class Summary

static class
Message._Fields

          The set of fields this struct contains, along with convenience methods for finding and manipulating them.

Field Summary

static java.util.Map<Message._Fields,org.apache.thrift.meta_data.FieldMetaData>
metaDataMap

 Packet
packet

private static org.apache.thrift.protocol.TField
PACKET_FIELD_DESC

private static org.apache.thrift.protocol.TField
SESSION_IDS_FIELD_DESC

 java.util.List<java.lang.String>
sessionIDs

private static org.apache.thrift.protocol.TStruct
STRUCT_DESC

Constructor Summary

Message()

Message(java.util.List<java.lang.String> sessionIDs,
        Packet packet)

Message(Message other)

          Performs a deep copy on other.

Method Summary

 void
addToSessionIDs(java.lang.String elem)

 void
clear()

 int
compareTo(Message other)

 Message
deepCopy()

 boolean
equals(Message that)

 boolean
equals(java.lang.Object that)

 Message._Fields
fieldForId(int fieldId)

 java.lang.Object
getFieldValue(Message._Fields field)

 Packet
getPacket()

 java.util.List<java.lang.String>
getSessionIDs()

 java.util.Iterator<java.lang.String>
getSessionIDsIterator()

 int
getSessionIDsSize()

 int
hashCode()

 boolean
isSet(Message._Fields field)

          Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise

 boolean
isSetPacket()

          Returns true if field packet is set (has been assigned a value) and false otherwise

 boolean
isSetSessionIDs()

          Returns true if field sessionIDs is set (has been assigned a value) and false otherwise

 void
read(org.apache.thrift.protocol.TProtocol iprot)

private  void
readObject(java.io.ObjectInputStream in)

 void
setFieldValue(Message._Fields field,
              java.lang.Object value)

 Message
setPacket(Packet packet)

 void
setPacketIsSet(boolean value)

 Message
setSessionIDs(java.util.List<java.lang.String> sessionIDs)

 void
setSessionIDsIsSet(boolean value)

 java.lang.String
toString()

 void
unsetPacket()

 void
unsetSessionIDs()

 void
validate()

 void
write(org.apache.thrift.protocol.TProtocol oprot)

private  void
writeObject(java.io.ObjectOutputStream out)

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

STRUCT_DESC

private static final org.apache.thrift.protocol.TStruct STRUCT_DESC

SESSION_IDS_FIELD_DESC

private static final org.apache.thrift.protocol.TField SESSION_IDS_FIELD_DESC

PACKET_FIELD_DESC

private static final org.apache.thrift.protocol.TField PACKET_FIELD_DESC

sessionIDs

public java.util.List<java.lang.String> sessionIDs

packet

public Packet packet

metaDataMap

public static final java.util.Map<Message._Fields,org.apache.thrift.meta_data.FieldMetaData> metaDataMap

Constructor Detail

Message

public Message()

Message

public Message(java.util.List<java.lang.String> sessionIDs,
               Packet packet)

Message

public Message(Message other)

Performs a deep copy on other.

Method Detail

deepCopy

public Message deepCopy()

Specified by:
deepCopy in interface org.apache.thrift.TBase<Message,Message._Fields>

clear

public void clear()

Specified by:
clear in interface org.apache.thrift.TBase<Message,Message._Fields>

getSessionIDsSize

public int getSessionIDsSize()

getSessionIDsIterator

public java.util.Iterator<java.lang.String> getSessionIDsIterator()

addToSessionIDs

public void addToSessionIDs(java.lang.String elem)

getSessionIDs

public java.util.List<java.lang.String> getSessionIDs()

setSessionIDs

public Message setSessionIDs(java.util.List<java.lang.String> sessionIDs)

unsetSessionIDs

public void unsetSessionIDs()

isSetSessionIDs

public boolean isSetSessionIDs()

Returns true if field sessionIDs is set (has been assigned a value) and false otherwise

setSessionIDsIsSet

public void setSessionIDsIsSet(boolean value)

getPacket

public Packet getPacket()

setPacket

public Message setPacket(Packet packet)

unsetPacket

public void unsetPacket()

isSetPacket

public boolean isSetPacket()

Returns true if field packet is set (has been assigned a value) and false otherwise

setPacketIsSet

public void setPacketIsSet(boolean value)

setFieldValue

public void setFieldValue(Message._Fields field,
                          java.lang.Object value)

Specified by:
setFieldValue in interface org.apache.thrift.TBase<Message,Message._Fields>

getFieldValue

public java.lang.Object getFieldValue(Message._Fields field)

Specified by:
getFieldValue in interface org.apache.thrift.TBase<Message,Message._Fields>

isSet

public boolean isSet(Message._Fields field)

Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise

Specified by:
isSet in interface org.apache.thrift.TBase<Message,Message._Fields>

equals

public boolean equals(java.lang.Object that)

Overrides:
equals in class java.lang.Object

equals

public boolean equals(Message that)

hashCode

public int hashCode()

Overrides:
hashCode in class java.lang.Object

compareTo

public int compareTo(Message other)

Specified by:
compareTo in interface java.lang.Comparable<Message>

fieldForId

public Message._Fields fieldForId(int fieldId)

Specified by:
fieldForId in interface org.apache.thrift.TBase<Message,Message._Fields>

read

public void read(org.apache.thrift.protocol.TProtocol iprot)
          throws org.apache.thrift.TException

Specified by:
read in interface org.apache.thrift.TBase<Message,Message._Fields>

Throws:

org.apache.thrift.TException

write

public void write(org.apache.thrift.protocol.TProtocol oprot)
           throws org.apache.thrift.TException

Specified by:
write in interface org.apache.thrift.TBase<Message,Message._Fields>

Throws:

org.apache.thrift.TException

toString

public java.lang.String toString()

Overrides:
toString in class java.lang.Object

validate

public void validate()
              throws org.apache.thrift.TException

Throws:

org.apache.thrift.TException

writeObject

private void writeObject(java.io.ObjectOutputStream out)
                  throws java.io.IOException

Throws:

java.io.IOException

readObject

private void readObject(java.io.ObjectInputStream in)
                 throws java.io.IOException,
                        java.lang.ClassNotFoundException

Throws:

java.io.IOException

java.lang.ClassNotFoundException

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
'use strict';

var OAuth2Strategy = require('passport-oauth2'),
    util = require('util'),
    request = require('request');

module.exports = TAccountsStrategy;

/**
 * Creates an instance of `TAccountsStrategy`.
 *
 * Applications must supply a `verify` callback, for which the function
 * signature is:
 *
 *     function(accessToken, refreshToken, profile, done) { ... }
 *
 * The verify callback is responsible for finding or creating the user, and
 * invoking `done` with the following arguments:
 *
 *     done(err, user, info);
 *
 * `user` should be set to `false` to indicate an authentication failure.
 * Additional `info` can optionally be passed as a third argument, typically
 * used to display informational messages.  If an exception occured, `err`
 * should be set.
 *
 * Options:
 *
 *   - `authorizationURL`  URL used to obtain an authorization grant
 *   - `tokenURL`          URL used to obtain an access token
 *   - `profileURL`        URL used to obtain a the user profile
 *   - `clientID`          identifies client to service provider
 *   - `clientSecret`      secret used to establish ownership of the client identifer
 *   - `callbackURL`       URL to which the service provider will redirect the user after obtaining authorization
 *   - `passReqToCallback` when `true`, `req` is the first argument to the verify callback (default: `false`)
 *
 * @param {Object} options
 * @param {Function} verify
 * @constructor
 */
function TAccountsStrategy(options, verify) {
  options = options || {};

  options.scope = options.scope || [
        'openid',
        'profile',
        'phone',
        'email'
      ];

  options.customHeaders = {
    Authorization: 'Basic ' + new Buffer(options.clientID + ':' + options.clientSecret).toString('base64')
  };

  options.authorizationURL = options.authorizationURL || 'https://accounts.telefonica.com/telefonica/oauth/authorize';
  options.tokenURL = options.tokenURL || 'https://accounts.telefonica.com/telefonica/oauth/token';
  options.profileURL = options.profileURL || 'https://accounts.telefonica.com/telefonica/openid/userinfo';
  options.logoutURL = options.logoutURL || 'https://accounts.telefonica.com/telefonica/logout';

  OAuth2Strategy.call(this, options, verify);
  this.name = 'taccounts';

  // TODO add support for refresh token

  this.userProfile = getUserProfile;

  this.authorizationParams = getAuthorizationParams;

  this.logout = logout;

  ///////////////////

  function logout() {
    if (!options.logoutCallbackURL) {
      throw new TypeError('TAccountsStrategy requires a logoutCallbackURL option');
    }

    return function logoutMW(req, res) {
      res.redirect(options.logoutURL + '?post_logout_redirect_uri=' + options.logoutCallbackURL);
    };
  }

  function getAuthorizationParams() {
    return options.authorizeParams ? options.authorizeParams : {};
  }

  function getUserProfile(accessToken, callback) {
    var requestOptions = {
      url: options.profileURL,
      headers: {
        'Authorization': 'Bearer ' + accessToken
      },
      json: true
    };

    request.get(requestOptions, function onGetProfile(err, response, body) {
      if (err) {
        return callback(new Error(err.message));
      }
      if (response.statusCode !== 200) {
        return callback(new Error('Invalid response status: ' + response.statusCode));
      }

      // see normalized profile http://passportjs.org/docs/profile
      var normalizedProfile = {
        provider: 'taccounts',
        id: body.sub,
        displayName: body.name
      };

      normalizedProfile.emails = [{value: body.email}];
      // original payload for those who need additional fields from Telefonica Accounts
      normalizedProfile.payload = body;

      return callback(null, normalizedProfile);
    });
  }
}

util.inherits(TAccountsStrategy, OAuth2Strategy);


text:
package SevenZip.Compression.LZ;

import java.io.IOException;

public class OutWindow
{
	byte[] _buffer;
	int _pos;
	int _windowSize = 0;
	int _streamPos;
	java.io.OutputStream _stream;

	public void Create(int windowSize)
	{
		if (_buffer == null || _windowSize != windowSize)
			_buffer = new byte[windowSize];
		_windowSize = windowSize;
		_pos = 0;
		_streamPos = 0;
	}

	public void SetStream(java.io.OutputStream stream) throws IOException
	{
		ReleaseStream();
		_stream = stream;
	}

	public void ReleaseStream() throws IOException
	{
		Flush();
		_stream = null;
	}

	public void Init(boolean solid)
	{
		if (!solid)
		{
			_streamPos = 0;
			_pos = 0;
		}
	}

	public void Flush() throws IOException
	{
		int size = _pos - _streamPos;
		if (size == 0)
			return;
		_stream.write(_buffer, _streamPos, size);
		if (_pos >= _windowSize)
			_pos = 0;
		_streamPos = _pos;
	}

	public void CopyBlock(int distance, int len) throws IOException
	{
		int pos = _pos - distance - 1;
		if (pos < 0)
			pos += _windowSize;
		for (; len != 0; len--)
		{
			if (pos >= _windowSize)
				pos = 0;
			_buffer[_pos++] = _buffer[pos++];
			if (_pos >= _windowSize)
				Flush();
		}
	}

	public void PutByte(byte b) throws IOException
	{
		_buffer[_pos++] = b;
		if (_pos >= _windowSize)
			Flush();
	}

	public byte GetByte(int distance)
	{
		int pos = _pos - distance - 1;
		if (pos < 0)
			pos += _windowSize;
		return _buffer[pos];
	}
}


text:
namespace Apex.AI.Teaching
{
    /// <summary>
    /// Action class for nulling the resource target.
    /// </summary>
    /// <seealso cref="Apex.AI.ActionBase" />
    public sealed class SetResourceTargetToNull : ActionBase
    {
        public override void Execute(IAIContext context)
        {
            ((AIContext)context).resourceTarget = null;
        }
    }
}


text:
import optparse

parser = optparse.OptionParser()
parser.add_option('-i','--input', dest = 'input_file_name', help = 'input_file_name')
parser.add_option('-o','--output', dest = 'output_file_name', help = 'output_file_name')

(options, args) = parser.parse_args()

if options.input_file_name is None:
   options.input_file_name = raw_input('Enter input file name:')

if options.output_file_name is None:
    options.output_file_name = raw_input('Enter output file name:')

input_file_name = options.input_file_name
output_file_name = options.output_file_name

f = open(input_file_name,'rU')
out = open(output_file_name,'w')

lines = f.readlines()

for index in range(len(lines) - 1):

    line = lines[index]

    line = line.split('=')
    #select only entities lines
    #<entity1 rdf:resource="http://data.doremus.org/Self_Contained_Expression/F22/cdf710e4-49d2-411f-b1b9-ccfe2a65e258"/>
    if line[0] == '<entity1 rdf:resource':
        #select only the id cdf710e4-49d2-411f-b1b9-ccfe2a65e258
        id1_whole = line[1].replace('\"/>\n','').strip('\"')
        #id1_whole = id1_whole.split('/')
        #id1 = id1_whole[-2].strip('\"')

        #the following line has the other entity

        next_line = lines[index + 1]

        next_line = next_line.split('=')

        id2_whole = next_line[1].replace('\"/>\n','').strip('\"')
        #id2_whole = id2_whole.split('/')
        #id2 = id2_whole[-2].strip('\"')

        out.write('+,')
        out.write(id1_whole)
        out.write(',')
        out.write(id2_whole)
        out.write(',1.0')
        out.write('\n')

f.close()
out.close()


text:
package com.groupdocs.ui.comparison.dropwizard.common.util;

import com.google.common.collect.Ordering;
import com.groupdocs.ui.comparison.dropwizard.common.entity.web.FileDescriptionEntity;
import com.groupdocs.ui.comparison.dropwizard.common.util.comparator.FileNameComparator;
import com.groupdocs.ui.comparison.dropwizard.common.util.comparator.FileTypeComparator;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Locale;

public class Utils {

    private static final List<String> SUPPORTED_FORMATS = Arrays.asList(
            "doc",
            "docx",
            "htm",
            "html",
            "jpg",
            "jpeg",
            "pdf",
            "png",
            "ppt",
            "pptx",
            "txt",
            "xls",
            "xlsx"
    );

    public static java.util.List<FileDescriptionEntity> orderByTypeAndName(List<FileDescriptionEntity> files) {
        return Ordering.from(FileTypeComparator.instance).compound(FileNameComparator.instance).sortedCopy(files);
    }

    /**
     * Read stream and convert to string
     */
    public static String getStringFromStream(InputStream inputStream) throws IOException {
        byte[] bytes = IOUtils.toByteArray(inputStream);
        // encode ByteArray into String
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * Parse extension of the file's name
     *
     * @param documentGuid path to file
     * @return extension of the file's name
     */
    public static String parseFileExtension(String documentGuid) {
        String extension = FilenameUtils.getExtension(documentGuid);
        return extension == null ? null : extension.toLowerCase(Locale.getDefault());
    }

    /**
     * Check support formats for comparing
     *
     * @param extension file extension
     * @return true - format is supported, false - format is not supported
     */
    public static boolean checkSupportedFiles(String extension) {
        return SUPPORTED_FORMATS.contains(extension);
    }
}


text:
alter table device_profile
    alter column ping_slot_freq type bigint,
    alter column rx_freq_2 type bigint,
    alter column factory_preset_freqs type bigint[];

alter table multicast_group
    alter column frequency type bigint;


text:
<?php

	/**
	 * This page is the central configuration page and common functions for the URMC integrations toolset.
	 */

	include_once("ezsql/shared/ez_sql_core.php");
	include_once("ezsql/oracle8_9/ez_sql_oracle8_9.php");

	$DB   = new ezSQL_oracle8_9('trials_dev',   '', 'cdw1.urmc.rochester.edu:1521/CDWPROD');
	$EXP  = new ezSQL_oracle8_9('i2b2exports',  '', 'i2b2dev.urmc-sh.rochester.edu:1521/i2b2');
	$PM   = new ezSQL_oracle8_9('i2b2pm',       '', 'i2b2dev.urmc-sh.rochester.edu:1521/i2b2');

	$ENVIRONMENT = "T";
	$CHECKPASSWORDS = true;

	/**
	 * Quick field fixup for escaping or simply removing that data from the post fields that are safe to insert.
	 */
	function f( $s ){
		return htmlentities(preg_replace('/[\x7F-\xFF]/','',preg_replace('/[\x00-\x1F]/', '',  str_replace("'","''",$s))),ENT_NOQUOTES,'UTF-8',false);
	}

	/**
	 * this removes things that are nasty from a file name perspective.
	 */
	function filefix( $s ){
		return f(str_replace(array("\\","/","<",">","'",'"','|',':','*','?','%'),"", $s));
	}

	/**
	 * This function encrypts data for secure transmissions between sending and receiving pages. Utilizing
	 * this function applies the destination page in the encryption string, so that a link can't be copied between
	 * pages to apply "copy the hash" hack. Each piece of data is encrypted with an environment and a date key,
	 * so that the data cannot be copied cross implementation, or between test or prod and so that a string has a short
	 * lifespan.
	 *
	 * @param $destination - this is the page or string that both sending and receiving pages agree on.
	 * @param $data - this is the data to encrypt
	 * @returns - $data converted to URLSafe(Base64(AES128($data)))
	 */
	function encryptParameters( $destination, $data ){

		//essentially a once use URL. Also uses wordpress' nonce key to further ensure uniqueness.
		$ENCRYPTION_KEY = strtoupper( $destination . date('ymd') );
		$ciphertext = "";
		$mode = "";
		if( function_exists( "mcrypt_decrypt" ) ){
			$mode = "AES";
			$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
			$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
			$key = pack("H*",md5($ENCRYPTION_KEY));
			$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data.$mode, MCRYPT_MODE_CBC, $iv);
			$ciphertext = $iv . $ciphertext;

		} else {
			//better than nothing I suppose. at least you're comparing codes and are obfuscating.
			$mode = "B64";
			$ciphertext = $ENCRYPTION_KEY . $data .$mode;
		}

		$base64String = base64_encode( $ciphertext );
		//make the string into a usable HTML escaped string.
		$base64String = str_replace( "=", "%3D", $base64String);
		$base64String = str_replace( "+", "%2B", $base64String);
		$base64String = str_replace( "/", "%2F", $base64String);

		//echo( "\nKey : $ENCRYPTION_KEY " );
		//echo( "\nbase64 : $base64String " );

		return $mode.$base64String;

	}

	/**
	 * This is the omega to the encrypt alpha. The decodes the data back to raw format.
 	 * @param $receiver - this is the page or string that both sending and receiving pages agree on.
 	 * @param $base64String - $data converted to URLSafe(Base64(AES128($data))) from encode
 	 * @returns array - an associative array that contains the original data
 	 */
	function decryptParameters( $receiver, $base64String ){

		//reverse the URL crap that might have been added.
		$base64String = str_replace("%3D", "=", $base64String);
		$base64String = str_replace("%2B", "+", $base64String);
		$base64String = str_replace("%2F", "/", $base64String);
		$base64String = str_replace(" ", "+", $base64String);

		$base64String = substr( $base64String, 3 );

		$ciphertext_dec = base64_decode( $base64String );

		//essentially a once use URL. Also uses wordpress' nonce key to further ensure uniqueness.
		$ENCRYPTION_KEY = strtoupper( $receiver . date('ymd') );

		$plaintext_dec = "";
		$mode = "";
		if( function_exists( "mcrypt_decrypt" ) ){
			$mode = "AES";
			$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);

			//initialize the return value to be nothing with no data to be returned if there isn't enough
			//data in the stream to decode.
			$return = array();
			if( strlen($ciphertext_dec) >= $iv_size ){
				$key = pack("H*",md5($ENCRYPTION_KEY));
				$iv_dec = substr($ciphertext_dec, 0, $iv_size);
				$ciphertext_dec = substr($ciphertext_dec, $iv_size);
				$plaintext_dec = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec));

				//detect bad data, the end should be intact.
				if( substr($plaintext_dec, -3) != $mode ){
					$plaintext_dec = "";
				} else {
					$plaintext_dec = substr( $plaintext_dec, 0 , strlen($plaintext_dec)-3 );
				}
			}
		} else {
			$mode = "B64";
			//better than nothing I suppose. at least you're comparing codes and are obfuscating.
			if( strpos($ciphertext_dec,$ENCRYPTION_KEY) == 0 && substr($ciphertext_dec, -3) == $mode ){
				$plaintext_dec = substr( $ciphertext_dec, strlen( $ENCRYPTION_KEY ) );
				$plaintext_dec = substr( $plaintext_dec, 0 , strlen($plaintext_dec)-3 );
			} else {
				$plaintext_dec = "";
			}

		}
		//see if you got an array. if not, don't bother.
		if( strpos($plaintext_dec,'=') > 0 ){
			parse_str($plaintext_dec, $return);
		} else {
			$return = $plaintext_dec;
		}

		return $return;

		return $return;

	}

	/**
	 * Most of the Java Services invocation calls are extremely similar. To that end, this function addresses the
	 * Need to create a separate individualized code to start or stop or get the status of a script.
	 * @returns - an associative array with this job's most current statistics.
	 * @param $DB - connection to database
	 * @param $_ENC - the associative array of data representing the study
	 * @param $javaClassName - this is the instance of the java service you're trying to instantiate.
	 * @param $_REQ - the variables passed in, either $_POST or $_GET
	 * @param $ENV - the enviroment to run this on, note $ENVIRONMENT, in this file cannot be scope referenced, it has to be passed in explicitly.
	 */

	function runJavaService( $DB, $_ENC, $javaClassName, $_REQ , $params, $ENV ){

		if( isset($_ENC["PROJECTID"]) && is_numeric($_ENC["PROJECTID"]) ){

			//look up the last job run.
			$Job_settings = $DB->get_row( "SELECT I2B2_JOBS.*, ".getTime($DB,'LAST_TOUCHED')." AS TIMEOF FROM I2B2_JOBS WHERE PROJECTID=".$_ENC["PROJECTID"]." AND USERNAME='".f($_ENC["USERNAME"])."' AND JOB_TYPE='$javaClassName' ORDER BY JOB_ID DESC"  ,ARRAY_A );

			//if there was some request to start it, then do so.
			if( isset( $_REQ["ACTION"] ) ){
				if( ($Job_settings["STATUS"] == 'Running' || $Job_settings["STATUS"] == 'Queued' || $Job_settings["STATUS"] == 'Created') && $_REQ["ACTION"] == 'Cancel'  ){

					//if the job was running or queued or not yet acknowledged, the cancel it.
					$DB->query( "UPDATE I2B2_JOBS SET STATUS='Cancel' WHERE JOB_ID='".f($Job_settings["JOB_ID"])."'");

				} else {

					//cancel while cancel is silly. So are other statuses. only allow for creation to operate.
					if( $_REQ["ACTION"] == 'Created' ){
						$count = $DB->get_var( "SELECT COUNT(*) AS N FROM I2B2_JOBS WHERE STATUS IN ('Created','Queued','Running') AND JOB_TYPE='$javaClassName' AND PROJECTID=".$_ENC["PROJECTID"]." AND USERNAME='".f($_ENC["USERNAME"])."'");

						if( $count == 0 ){
							$DB->query(
								"INSERT INTO I2B2_JOBS( JOB_ID, STATUS, JOB_TYPE, PROJECTID, PROJECTCODE, PARAMS, USERNAME, ENVIRONMENT ) " .
								"VALUES ( -1, 'Created', '$javaClassName', '".$_ENC["PROJECTID"]."', '".$_ENC["PROJECTCODE"]."', '".f($params)."', '".f($_ENC["USERNAME"])."','".$ENV."' )"
							);
						} else {
							echo( "multiple?" );
						}
					} else {
						echo( "Invalid option selected, current job is ".$Job_settings["STATUS"] );
					}
				}
				$Job_settings = $DB->get_row( "SELECT I2B2_JOBS.*, ".getTime($DB,'LAST_TOUCHED')." AS TIMEOF FROM I2B2_JOBS WHERE PROJECTID=".$_ENC["PROJECTID"]." AND USERNAME='".f($_ENC["USERNAME"])."' AND JOB_TYPE='$javaClassName' ORDER BY JOB_ID DESC"  ,ARRAY_A );
			}
			return $Job_settings;
		} else {
			return array();
		}
	}

	/**
	 * Most of the Java Services invocation calls are extremely similar. To that end, this function addresses the
	 * Need to refresh and to show you the current status as a progress bar.
	 * @returns - a boolean indicating true if done, false if task in progress.
	 * @param $DB - connection to database
	 * @param $_ENC - the associative array of data representing the study
	 * @param $Job_settings - the last known parameters of the job.
	 * @param $taskname - A user friendly name of what this task is accomplishing.
	 * @param $page - what is this job's WS age
	 * @param $_REQ - the variables passed in, either $_POST or $_GET
	 * @param $div - where should the data appear?
	 * @param $supressheader - if the regular progress and boilerplate should be displayed.
	 */

	function showJavaServiceProgressAndRefresh( $DB, $_ENC, $Job_settings, $taskname, $page, $_REQ, $div, $suppressheader ){

		$ans = false;
		if( isset($_ENC["PROJECTID"]) && is_numeric($_ENC["PROJECTID"]) ){
			if( !isset($suppressheader) || !$suppressheader ){
				echo( "
Project # ".htmlspecialchars($_ENC["PROJECTCODE"])."-".htmlspecialchars($_ENC["PROJECTTITLE"])."
" );
				echo( "
Job Started On " . date('m/d/Y', strtotime($Job_settings["ACTUAL_START_TIME"] )) . " With status of ".$Job_settings["STATUS"]. ", last updated " . $Job_settings["TIMEOF"] . "
" );

				$pct = intval($Job_settings["PERCENT_COMPLETE"] );
				echo( "

" );
				echo( "
" . $pct."%
 	" );
				if( $pct < 100 ){
					echo( " 	" );
				}
				echo("

");
			}
			if( !isset($_REQ['NOTNEW']) ){
				$_REQ['NOTNEW'] = 0;
			} else {
				$_REQ['NOTNEW'] = intval($_REQ['NOTNEW']);
			}
			if( trim($Job_settings["STATUS"] ) == "Created" ||
				trim($Job_settings["STATUS"] ) == "Running" ||
				trim($Job_settings["STATUS"] ) == "Queued" ||
				(intval($_REQ['NOTNEW']) < 3 && trim($Job_settings["STATUS"]) == "Cancel" )){

				$DB->query( "UPDATE I2B2_JOBS SET LAST_UI_TOUCHED=SYSDATE WHERE JOB_ID='".f($Job_settings["JOB_ID"])."'");

				if( trim($Job_settings["STATUS"] ) != "Cancel" ){ ?>
					<input type="button" onClick="
						if(confirm('Cancel Export of Databases Now?')){
							jQuery('<?php echo($div);?>').load(
								'<?php echo($page);?>',
								{SESSIONCODE : '<?php echo($_REQ["SESSIONCODE"]);?>', ACTION : 'Cancel', NOTNEW: 'Y' }
							);
					}" value="Cancel <?php echo($taskname);?>"> <?php

				} else {
					echo( "Cancelling $taskname... Please wait..." );
				} ?>

			<?php } else { ?>

				<input type="button" onClick="
					jQuery('<?php echo($div);?>').load(
						'<?php echo($page);?>',
						{SESSIONCODE : '<?php echo($_REQ["SESSIONCODE"]);?>', ACTION : 'Created' }
					);
				" value="Start <?php echo($taskname);?>">

			<?php $ans = true;

			}
		} //if authenticated
		return $ans;
	}

	function showJavaServiceLog( $DB, $jobid ){
		if( isset($jobid) && is_numeric($jobid) ){
			$logs = $DB->get_results( "
				SELECT I2B2_JOBS_LOG.*, ".getTime($DB,'DATEOF')." AS TIMEOF
				FROM I2B2_JOBS_LOG
				WHERE JOB_ID='".$jobid."'
				ORDER BY DATEOF
			"  ,OBJECT );

			echo( "

" );
			$continues = false;
			if( $logs ){
				foreach ( $logs as &$item) {

					if( !$continues ){
						echo( "

".$item->TIMEOF." " );
					}

					if( strpos($item->DESCR,'Exception: ') > 0 ){
						$item->DESCR = substr( $item->DESCR, strpos($item->DESCR,'Exception: ') + 11);
						$item->DESCR = substr( $item->DESCR, 0, strpos($item->DESCR,"\n"));
						$item->DESCR = ( "Error : " . $item->DESCR . "");
					}
					echo (str_replace('<continues/>','',$item->DESCR));
					$continues = strpos($item->DESCR,'<continues/>');

					if( !$continues ){
						echo('

');
					}
				}
			}
			echo( "
" );
		}
	}

	/**
	 * This function will try to figure out your DBMS and spew out a human readable time
	 * @returns SQL coded string representing the time
	 * @param $DB - this is a ezSQL instance, needed to see what DBMS you're using.
	 * @param $var - the variable desired.
	 */
	function getTime( $DB, $var ){
		if( get_class( $DB ) == "ezSQL_oracle8_9"  || get_class( $DB ) == "ezSQL_postgresql" ){
			return "TO_CHAR($var,'HH24:MI:SS')";
		} elseif ( get_class( $DB ) == "ezSQL_mssql" || get_class( $DB ) == "ezSQL_sqlsrv" ){
			return "CONVERT(VARCHAR(8),$var,108)";
		} elseif ( get_class( $DB ) == "ezSQL_mysql" || get_class( $DB ) == "ezSQL_mysqli" ){
			return "DATE_FORMAT($var, '%H:%i:%s')";
		} else {
			return $var;
		}
	}

	/**
	 * This provides a method for checking passwords supplied.
 	 * @param $user - this is the username
	 * @param $pass - password.
	 * @returns Y/N
	 */
	function validatePassword( $user, $pass ){

		$ans = "N";

		// using ldap bind
		$ldappass = $pass;

		if( function_exists( "ldap_connect" ) ){
			// connect to ldap server
			$ldapconn = ldap_connect("ldap.urmc-sh.rochester.edu");
			if ($ldapconn) {

				// Set some ldap options for talking to AD
				ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
				ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);

				// binding to ldap server
				$ldapbind = ldap_bind($ldapconn, "URMC-SH\\".$user, $pass);

				// verify binding
				if ($ldapbind) {
					$ans = "Y";
				}
			}
		}

		//CRI-531 : remove administrative i2b2 locks.
		if( isset( $_SESSION['ADMIN'] ) && $_SESSION['ADMIN'] == 'Y' ){
			$ans = "Y";
		}
		return $ans;
	}

?>