text:
package main

// Here is a quick lookup table for various sorting algorithms.
// In practice, when in doubt go with quicksort, or mergesort.
// For distributed map-reduce-like sifting, prefer a mergesort variant.
//
// Algorithm     | Best Case | Worst Case | Avg. Case | Space Cmplx | Stable? |
// --------------+-----------+------------+-----------+-------------+---------+
// MergeSort     | O(nlg(n)) | O(nlg(n))  | O(nlg(n)) | O(n)        | Yes     |
// --------------+-----------+------------+-----------+-------------+---------+
// InsertionSort | O(n)      | O(n^2)     | O(n^2)    | O(1)        | Yes     |
// --------------+-----------+------------+-----------+-------------+---------+
// QuickSort     | O(nlg(n)) | O(n^2)     | O(nlg(n)) | b:logn av:n | No*     |
// --------------+-----------+------------+-----------+-------------+---------+
// HeapSort      | O(nlg(n)) | O(nlg(n))  | O(nlg(n)) | O(1)        | No      |
// --------------+-----------+------------+-----------+-------------+---------+
// CountingSort  | O(k+n)    | O(k+n)     | O(k+n)    | O(k+n)      | Yes     |
// --------------+-----------+------------+-----------+-------------+---------+
//
// * Usually not: There are stable variants too.
//
// Notes:
// - If you need an in-place sorting, then InsertionSort, or HeapSort can be used.
// - The worst-case is so rare, that QuickSort generally performs the best; you can
//     randomize the pivot to almost eliminate the chance of hitting a worst-case
//     scenario.
// - MergeSort is probably the easiest to implement.
// - InsertionSort is generally *not* efficient.
// - You will only see "BubbleSort" in interviews; it is so bad performance-wise,
//     that is is never used, ever.
// - Unless in an interview, don't reinvent sorting; chances are that your
//     programming language of choice has either a builtin sorting package,
//     or there are reusable libraries that you can link and use.
//     Don't reinvent the wheel; use battle-tested libraries.
// - There are hybrid "clever" algorithms that use (for example) a stable QuickSort
//     for small input sizes; and switches to an unstable QuickSort or MergeSort
//     for larger sizes of input. (v8's (Google Chrome) JavaScript Array.prototype.sort
//     method works this way for example).
func main() {
}


text:
class User < ActiveRecord::Base
  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :pseudo, presence: true, uniqueness: true
  validates :email, presence: true, uniqueness: true, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i }
  validates_confirmation_of :password, :if=>:password_changed?
  validates :password, presence: true

  has_many :posts, dependent: :destroy
  has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
  has_many :following, through: :active_relationships, source: :followed
  has_many :passive_relationships, class_name:  "Relationship", foreign_key: "followed_id", dependent:   :destroy
  has_many :followers, through: :passive_relationships, source: :follower

  has_many :repost_relationships, class_name: "RepostRelationship", foreign_key: "user_id", dependent: :destroy
  has_many :reposts, through: :repost_relationships, source: :post

  has_many :like_relationships, class_name: "LikeRelationship", foreign_key: "user_id", dependent: :destroy
  has_many :likes, through: :like_relationships, source: :post

  before_save :hash_password, :if=>:password_changed?

  def self.find_by_credentials(identifier, password)
    if user = User.find_by(pseudo: identifier) || User.find_by(email: identifier)
      if BCrypt::Password.new(user.password).is_password? password
        return user
      else
        return nil
      end
    end
    return nil
  end

  def self.following?(user1, user2_id)
    user2 = User.find_by(id: user2_id)
    User.find_by(id: user1).following.include?(user2)
  end

  def password_changed?
    !self.password.blank?
  end

  def follow(other_user)
    active_relationships.create(followed_id: other_user)
  end

  def unfollow(other_user)
    active_relationships.find_by(followed_id: other_user).destroy
  end

  private

  def hash_password
    self.password = BCrypt::Password.create(self.password)
  end
end

redpajama_set_name: RedPajamaGithub


text:
import React, {useState} from 'react';
import {useTranslation} from 'react-i18next';
import {useMutation} from 'react-query';

import {useApplication} from '../../../application/ApplicationContext';
import DeleteButton from '../../../controllers/Buttons/DeleteButton';
import ModalConfirmation from '../../../controllers/ModalConfirmation';
import {BlackListEmail} from '../../../types/greylist';

interface DeleteEmailProps {
    onDelete: () => void,
    data: BlackListEmail
}

const DeleteEmail = ({onDelete, data}: DeleteEmailProps) => {
    const {t} = useTranslation();
    const {apiUrl} = useApplication();

    const [show, setShow] = useState(false);

    const deleteRecord = useMutation(
        (data: BlackListEmail) => fetch(`${apiUrl}/opt-in/emails/delete`, {
            method: 'DELETE',
            body: JSON.stringify({
                'email': data.email
            })
        }).then(async response => {
            const data = await response.json();

            // check for error response
            if (!response.ok) {
                // get error message from body or default to response status
                const error = (data && data.message) || response.status;
                return Promise.reject(error);
            }
            onDelete();
        }).catch(error => {
            console.error('There was an error!', error);
        }));

    return (
        <>
            <DeleteButton onClick={() => setShow(true)}/>

            <ModalConfirmation
                show={show}
                onConfirm={() => deleteRecord.mutateAsync(data)}
                onCancel={() => setShow(false)}
                title="blacklist.email.deleteHeader">
                {t('blacklist.email.deleteMessage')}
            </ModalConfirmation>
        </>
    );
};

export default DeleteEmail;


text:
package org.apache.sysml.runtime.matrix.data;

/**
 * SparseBlock implementation that realizes a 'modified compressed sparse row'
 * representation, where each compressed row is stored as a separate SparseRow
 * object which provides flexibility for unsorted row appends without the need
 * for global reshifting of values/indexes but it incurs additional memory
 * overhead per row for object/array headers per row which also slows down
 * memory-bound operations due to higher memory bandwidth requirements.
 *
 */
public class SparseBlockMCSR extends SparseBlock
{
	private static final long serialVersionUID = -4743624499258436199L;

	private SparseRow[] _rows = null;

	/**
	 * Copy constructor sparse block abstraction.
	 */
	public SparseBlockMCSR(SparseBlock sblock)
	{
		//special case SparseBlockMCSR
		if( sblock instanceof SparseBlockMCSR ) {
			SparseRow[] orows = ((SparseBlockMCSR)sblock)._rows;
			_rows = new SparseRow[orows.length];
			for( int i=0; i<_rows.length; i++ )
				_rows[i] = new SparseRow(orows[i]);
		}
		//general case SparseBlock
		else {
			_rows = new SparseRow[sblock.numRows()];
			for( int i=0; i<_rows.length; i++ ) {
				if( !sblock.isEmpty(i) ) {
					int apos = sblock.pos(i);
					int alen = sblock.size(i);
					_rows[i] = new SparseRow(alen);
					_rows[i].setSize(alen);
					System.arraycopy(sblock.indexes(i), apos, _rows[i].indexes(), 0, alen);
					System.arraycopy(sblock.values(i), apos, _rows[i].values(), 0, alen);
				}
			}
		}
	}

	/**
	 * Copy constructor old sparse row representation.
	 */
	public SparseBlockMCSR(SparseRow[] rows, boolean deep) {
		if( deep ) {
			_rows = new SparseRow[rows.length];
			for( int i=0; i<_rows.length; i++ )
				_rows[i] = new SparseRow(rows[i]);
		}
		else {
			_rows = rows;
		}
	}

	public SparseBlockMCSR(int rlen, int clen) {
		_rows = new SparseRow[rlen];
	}

	/**
	 * Get the estimated in-memory size of the sparse block in MCSR
	 * with the given dimensions w/o accounting for overallocation.
	 *
	 * @param nrows
	 * @param ncols
	 * @param sparsity
	 * @return
	 */
	public static long estimateMemory(long nrows, long ncols, double sparsity) {
		double cnnz = Math.max(SparseRow.initialCapacity, Math.ceil(sparsity*ncols));
		double rlen = Math.min(nrows, Math.ceil(sparsity*nrows*ncols));

		//Each sparse row has a fixed overhead of 8B (reference) + 32B (object) +
		//12B (3 int members), 32B (overhead int array), 32B (overhead double array),
		//Each non-zero value requires 12B for the column-index/value pair.
		//Overheads for arrays, objects, and references refer to 64bit JVMs
		//If nnz < than rows we have only also empty rows.
		double size = 16;                 //object
		size += rlen * (116 + cnnz * 12); //sparse rows
		size += 32 + nrows * 8d;          //references

		// robustness for long overflows
		return (long) Math.min(size, Long.MAX_VALUE);
	}

	///////////////////
	//SparseBlock implementation

	@Override
	public void allocate(int r) {
		if( _rows[r] == null )
			_rows[r] = new SparseRow();
	}

	@Override
	public void allocate(int r, int nnz) {
		if( _rows[r] == null )
			_rows[r] = new SparseRow(nnz);
	}

	@Override
	public void allocate(int r, int ennz, int maxnnz) {
		if( _rows[r] == null )
			_rows[r] = new SparseRow(ennz, maxnnz);
	}

	@Override
	public int numRows() {
		return _rows.length;
	}

	@Override
	public boolean isThreadSafe() {
		return true;
	}

	@Override
	public boolean isContiguous() {
		return false;
	}

	@Override
	public void reset() {
		for( SparseRow row : _rows )
			if( row != null )
				row.reset(row.size(), Integer.MAX_VALUE);
	}

	@Override
	public void reset(int ennz, int maxnnz) {
		for( SparseRow row : _rows )
			if( row != null )
				row.reset(ennz, maxnnz);
	}

	@Override
	public void reset(int r, int ennz, int maxnnz) {
		if( _rows[r] != null )
			_rows[r].reset(ennz, maxnnz);
	}

	@Override
	public long size() {
		//recompute non-zeros to avoid redundant maintenance
		long nnz = 0;
		for( SparseRow row : _rows )
			if( row != null )
				nnz += row.size();
		return nnz;
	}

	@Override
	public int size(int r) {
		//prior check with isEmpty(r) expected
		//TODO perf sparse block
		return (_rows[r]!=null) ? _rows[r].size() : 0;
	}

	@Override
	public long size(int rl, int ru) {
		int ret = 0;
		for( int i=rl; i<ru; i++ )
			ret += (_rows[i]!=null) ? _rows[i].size() : 0;
		return ret;
	}

	@Override
	public long size(int rl, int ru, int cl, int cu) {
		long nnz = 0;
		for(int i=rl; i<ru; i++)
			if( !isEmpty(i) ) {
				int start = posFIndexGTE(i, cl);
				int end = posFIndexGTE(i, cu);
				nnz += (start!=-1) ? (end-start) : 0;
			}
		return nnz;
	}

	@Override
	public boolean isEmpty(int r) {
		return (_rows[r]==null || _rows[r].isEmpty());
	}

	@Override
	public int[] indexes(int r) {
		//prior check with isEmpty(r) expected
		return _rows[r].indexes();
	}

	@Override
	public double[] values(int r) {
		//prior check with isEmpty(r) expected
		return _rows[r].values();
	}

	@Override
	public int pos(int r) {
		//arrays per row (always start 0)
		return 0;
	}

	@Override
	public boolean set(int r, int c, double v) {
		if( _rows[r] == null )
			_rows[r] = new SparseRow();
		return _rows[r].set(c, v);
	}

	@Override
	public void set(int r, SparseRow row, boolean deep) {
		_rows[r] = (deep && row != null) ?
				new SparseRow(row) : row;
	}

	@Override
	public void append(int r, int c, double v) {
		if( _rows[r] == null )
			_rows[r] = new SparseRow();
		_rows[r].append(c, v);
	}

	@Override
	public void setIndexRange(int r, int cl, int cu, double[] v, int vix, int len) {
		if( _rows[r] == null )
			_rows[r] = new SparseRow();
		//different sparse row semantics: upper bound inclusive
		_rows[r].setIndexRange(cl, cu-1, v, vix, len);
	}

	@Override
	public void deleteIndexRange(int r, int cl, int cu) {
		//prior check with isEmpty(r) expected
		//different sparse row semantics: upper bound inclusive
		_rows[r].deleteIndexRange(cl, cu-1);
	}

	@Override
	public void sort() {
		for( SparseRow row : _rows )
			if( row != null && !row.isEmpty() )
				row.sort();
	}

	@Override
	public void sort(int r) {
		//prior check with isEmpty(r) expected
		_rows[r].sort();
	}

	@Override
	public double get(int r, int c) {
		if( _rows[r] == null )
			return 0;
		return _rows[r].get(c);
	}

	@Override
	public SparseRow get(int r) {
		return _rows[r];
	}

	@Override
	public int posFIndexLTE(int r, int c) {
		//prior check with isEmpty(r) expected
		return _rows[r].searchIndexesFirstLTE(c);
	}

	@Override
	public int posFIndexGTE(int r, int c) {
		//prior check with isEmpty(r) expected
		return _rows[r].searchIndexesFirstGTE(c);
	}

	@Override
	public int posFIndexGT(int r, int c) {
		//prior check with isEmpty(r) expected
		return _rows[r].searchIndexesFirstGT(c);
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("SparseBlockMCSR: rlen=");
		sb.append(numRows());
		sb.append(", nnz=");
		sb.append(size());
		sb.append("\n");
		for( int i=0; i<numRows(); i++ ) {
			sb.append("row +");
			sb.append(i);
			sb.append(": ");
			sb.append(_rows[i]);
			sb.append("\n");
		}

		return sb.toString();
	}
}


text:
{% extends 'base.html' %}
{% load static %}

{% block head_title_separator %}{% endblock %}

{% block content %}

        Hello.
        I'm a software developer
        from Perth, Western Australia.
        I'm interested in
        free and
        open source software (although I do use a Mac…)
        and I've spent most of
        my life working on the web.

I'm a full-stack kind of guy, but my interest is mostly in
        Python,
        mainly working with Django.

        This site's code is under a
        BSD 2-Clause license,
        in case you'd like to
        see how it's built
        or reuse any of my work.

      {% for activity in activities %}
        {% if forloop.counter <= SITE_MAX_RECENT_ACTIVITY_ITEMS %}
          {% include 'rows/activity-item.html' %}
        {% endif %}
      {% endfor %}

GitHub

Twitter

Dev Twitter

Last.fm

Delicious

Foursquare

Facebook

Google+

App.net

Kindle

Django People

Django Gigs

Coderwall

Stack Overflow

LinkedIn

or, like… adam@hipikat.org

{% endblock content %}

{% block footer_cols_class %} large-7 push-4 columns{% endblock %}


text:
"""
    transitions.extensions.states
    -----------------------------

    This module contains mix ins which can be used to extend state functionality.
"""

from collections import Counter
from threading import Timer
import logging
import inspect

from ..core import MachineError, listify, State

_LOGGER = logging.getLogger(__name__)
_LOGGER.addHandler(logging.NullHandler())

class Tags(State):
    """ Allows states to be tagged.
        Attributes:
            tags (list): A list of tag strings. `State.is_<tag>` may be used
                to check if <tag> is in the list.
    """
    def __init__(self, *args, **kwargs):
        """
        Args:
            **kwargs: If kwargs contains `tags`, assign them to the attribute.
        """
        self.tags = kwargs.pop('tags', [])
        super(Tags, self).__init__(*args, **kwargs)

    def __getattr__(self, item):
        if item.startswith('is_'):
            return item[3:] in self.tags
        return super(Tags, self).__getattribute__(item)

class Error(Tags):
    """ This mix in builds upon tag and should be used INSTEAD of Tags if final states that have
        not been tagged with 'accepted' should throw an `MachineError`.
    """

    def __init__(self, *args, **kwargs):
        """
        Args:
            **kwargs: If kwargs contains the keyword `accepted` add the 'accepted' tag to a tag list
                which will be forwarded to the Tags constructor.
        """
        tags = kwargs.get('tags', [])
        accepted = kwargs.pop('accepted', False)
        if accepted:
            tags.append('accepted')
            kwargs['tags'] = tags
        super(Error, self).__init__(*args, **kwargs)

    def enter(self, event_data):
        """ Extends transitions.core.State.enter. Throws a `MachineError` if there is
            no leaving transition from this state and 'accepted' is not in self.tags.
        """
        if not event_data.machine.get_triggers(self.name) and not self.is_accepted:
            raise MachineError("Error state '{0}' reached!".format(self.name))
        super(Error, self).enter(event_data)

class Timeout(State):
    """ Adds timeout functionality to a state. Timeouts are handled model-specific.
    Attributes:
        timeout (float): Seconds after which a timeout function should be called.
        on_timeout (list): Functions to call when a timeout is triggered.
    """

    dynamic_methods = ['on_timeout']

    def __init__(self, *args, **kwargs):
        """
        Args:
            **kwargs: If kwargs contain 'timeout', assign the float value to self.timeout. If timeout
                is set, 'on_timeout' needs to be passed with kwargs as well or an AttributeError will
                be thrown. If timeout is not passed or equal 0.
        """
        self.timeout = kwargs.pop('timeout', 0)
        self._on_timeout = None
        if self.timeout > 0:
            try:
                self.on_timeout = kwargs.pop('on_timeout')
            except KeyError:
                raise AttributeError("Timeout state requires 'on_timeout' when timeout is set.")  # from KeyError
        else:
            self._on_timeout = kwargs.pop('on_timeout', [])
        self.runner = {}
        super(Timeout, self).__init__(*args, **kwargs)

    def enter(self, event_data):
        """ Extends `transitions.core.State.enter` by starting a timeout timer for the current model
            when the state is entered and self.timeout is larger than 0.
        """
        if self.timeout > 0:
            timer = Timer(self.timeout, self._process_timeout, args=(event_data,))
            timer.daemon = True
            timer.start()
            self.runner[id(event_data.model)] = timer
        return super(Timeout, self).enter(event_data)

    def exit(self, event_data):
        """ Extends `transitions.core.State.exit` by canceling a timer for the current model. """
        timer = self.runner.get(id(event_data.model), None)
        if timer is not None and timer.is_alive():
            timer.cancel()
        return super(Timeout, self).exit(event_data)

    def _process_timeout(self, event_data):
        _LOGGER.debug("%sTimeout state %s. Processing callbacks...", event_data.machine.name, self.name)
        for callback in self.on_timeout:
            event_data.machine.callback(callback, event_data)
        _LOGGER.info("%sTimeout state %s processed.", event_data.machine.name, self.name)

    @property
    def on_timeout(self):
        """ List of strings and callables to be called when the state timeouts. """
        return self._on_timeout

    @on_timeout.setter
    def on_timeout(self, value):
        """ Listifies passed values and assigns them to on_timeout."""
        self._on_timeout = listify(value)

class Volatile(State):
    """ Adds scopes/temporal variables to the otherwise persistent state objects.
    Attributes:
        volatile_cls (cls): Class of the temporal object to be initiated.
        volatile_hook (str): Model attribute name which will contain the volatile instance.
    """

    def __init__(self, *args, **kwargs):
        """
        Args:
            **kwargs: If kwargs contains `volatile`, always create an instance of the passed class
                whenever the state is entered. The instance is assigned to a model attribute which
                can be passed with the kwargs keyword `hook`. If hook is not passed, the instance will
                be assigned to the 'attribute' scope. If `volatile` is not passed, an empty object will
                be assigned to the model's hook.
        """
        self.volatile_cls = kwargs.pop('volatile', VolatileObject)
        self.volatile_hook = kwargs.pop('hook', 'scope')
        super(Volatile, self).__init__(*args, **kwargs)
        self.initialized = True

    def enter(self, event_data):
        """ Extends `transitions.core.State.enter` by creating a volatile object and assign it to
            the current model's hook. """
        setattr(event_data.model, self.volatile_hook, self.volatile_cls())
        super(Volatile, self).enter(event_data)

    def exit(self, event_data):
        """ Extends `transitions.core.State.exit` by deleting the temporal object from the model. """
        super(Volatile, self).exit(event_data)
        try:
            delattr(event_data.model, self.volatile_hook)
        except AttributeError:
            pass

class Retry(State):
    """ The Retry mix-in sets a limit on the number of times a state may be
        re-entered from itself.

        The first time a state is entered it does not count as a retry. Thus with
        `retries=3` the state can be entered four times before it fails.

        When the retry limit is exceeded, the state is not entered and instead the
        `on_failure` callback is invoked on the model. For example,

            Retry(retries=3, on_failure='to_failed')

        transitions the model directly to the 'failed' state, if the machine has
        automatic transitions enabled (the default).

        Attributes:
            retries (int): Number of retries to allow before failing.
            on_failure (str): Function to invoke on the model when the retry limit
                is exceeded.
    """
    def __init__(self, *args, **kwargs):
        """
        Args:
            **kwargs: If kwargs contains `retries`, then limit the number of times
                the state may be re-entered from itself. The argument `on_failure`,
                which is the function to invoke on the model when the retry limit
                is exceeded, must also be provided.
        """
        self.retries = kwargs.pop('retries', 0)
        self.on_failure = kwargs.pop('on_failure', None)
        self.retry_counts = Counter()
        if self.retries > 0 and self.on_failure is None:
            raise AttributeError("Retry state requires 'on_failure' when "
                                 "'retries' is set.")
        super(Retry, self).__init__(*args, **kwargs)

    def enter(self, event_data):
        k = id(event_data.model)

        # If we are entering from a different state, then this is our first try;
        # reset the retry counter.
        if event_data.transition.source != self.name:
            _LOGGER.debug('%sRetry limit for state %s reset (came from %s)',
                          event_data.machine.name, self.name,
                          event_data.transition.source)
            self.retry_counts[k] = 0

        # If we have tried too many times, invoke our failure callback instead
        if self.retry_counts[k] > self.retries > 0:
            _LOGGER.info('%sRetry count for state %s exceeded limit (%i)',
                         event_data.machine.name, self.name, self.retries)
            event_data.machine.callback(self.on_failure, event_data)
            return

        # Otherwise, increment the retry count and continue per normal
        _LOGGER.debug('%sRetry count for state %s is now %i',
                      event_data.machine.name, self.name, self.retry_counts[k])
        self.retry_counts.update((k,))
        super(Retry, self).enter(event_data)

def add_state_features(*args):
    """ State feature decorator. Should be used in conjunction with a custom Machine class. """
    def _class_decorator(cls):

        class CustomState(type('CustomState', args, {}), cls.state_cls):
            """ The decorated State. It is based on the State class used by the decorated Machine. """

        method_list = sum([c.dynamic_methods for c in inspect.getmro(CustomState) if hasattr(c, 'dynamic_methods')], [])
        CustomState.dynamic_methods = list(set(method_list))
        cls.state_cls = CustomState
        return cls
    return _class_decorator

class VolatileObject(object):
    """ Empty Python object which can be used to assign attributes to."""


text:
//******************************************************************************************************
//  HomeUserControl.xaml.cs - Gbtc
//
//  Copyright © 2010, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  07/27/2011 - Mehulbhai P Thakkar
//       Generated original version of source code.
//
//******************************************************************************************************

using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using System.Xml.Serialization;
using GSF.IO;

namespace GSF.TimeSeries.UI.UserControls
{
    /// <summary>
    /// Interaction logic for HomeUserControl.xaml
    /// </summary>
    public partial class HomeUserControl : UserControl
    {
        #region [ Members ]

        // Fields
        private readonly ObservableCollection<MenuDataItem> m_menuDataItems;

        #endregion

        #region [ Constructors ]

        /// <summary>
        /// Creates an instance of <see cref="HomeUserControl"/>.
        /// </summary>
        public HomeUserControl()
        {
            InitializeComponent();
            // Load Menu
            XmlRootAttribute xmlRootAttribute = new XmlRootAttribute("MenuDataItems");
            XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<MenuDataItem>), xmlRootAttribute);

            using (XmlReader reader = XmlReader.Create(FilePath.GetAbsolutePath("Menu.xml")))
            {
                m_menuDataItems = (ObservableCollection<MenuDataItem>)serializer.Deserialize(reader);
            }
        }

        #endregion

        #region [ Methods ]

        /// <summary>
        /// Recursively finds menu item to navigate to when a button is clicked on the UI.
        /// </summary>
        /// <param name="items">Collection of menu items.</param>
        /// <param name="stringToMatch">Item to search for in menu items collection.</param>
        /// <param name="item">Returns a menu item.</param>
        private void GetMenuDataItem(ObservableCollection<MenuDataItem> items, string stringToMatch, ref MenuDataItem item)
        {
            for (int i = 0; i < items.Count; i++)
            {
                if (items[i].MenuText.Contains(stringToMatch))
                {
                    item = items[i];
                    break;
                }
                else
                {
                    if (items[i].SubMenuItems.Count > 0)
                    {
                        GetMenuDataItem(items[i].SubMenuItems, stringToMatch, ref item);
                    }
                }
            }
        }

        /// <summary>
        /// Handles click event of the buttons on the screen.
        /// </summary>
        /// <param name="sender">Source of the event.</param>
        /// <param name="e">Event arguments.</param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MenuDataItem item = new MenuDataItem();
            FrameworkElement source = e.Source as FrameworkElement;

            switch (source.Name)
            {
                case "ButtonSecurity": GetMenuDataItem(m_menuDataItems, "Security", ref item);
                    break;
                default: break;
            }

            if (item.MenuText != null)
            {
                item.Command.Execute(null);
            }
        }

        #endregion

    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.run.v1.model;

/**
 * Task represents a single run of a container to completion.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Run Admin API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Task extends com.google.api.client.json.GenericJson {

  /**
   * Optional. APIVersion defines the versioned schema of this representation of an object. Servers
   * should convert recognized schemas to the latest internal value, and may reject unrecognized
   * values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-
   * conventions.md#resources +optional
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String apiVersion;

  /**
   * Optional. Kind is a string value representing the REST resource this object represents. Servers
   * may infer this from the endpoint the client submits requests to. Cannot be updated. In
   * CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-
   * conventions.md#types-kinds +optional
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String kind;

  /**
   * Optional. Standard object's metadata. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata +optional
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private ObjectMeta metadata;

  /**
   * Optional. Specification of the desired behavior of an execution. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status +optional
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private TaskSpec spec;

  /**
   * Output only. Current status of an execution. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status +optional
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private TaskStatus status;

  /**
   * Optional. APIVersion defines the versioned schema of this representation of an object. Servers
   * should convert recognized schemas to the latest internal value, and may reject unrecognized
   * values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-
   * conventions.md#resources +optional
   * @return value or {@code null} for none
   */
  public java.lang.String getApiVersion() {
    return apiVersion;
  }

  /**
   * Optional. APIVersion defines the versioned schema of this representation of an object. Servers
   * should convert recognized schemas to the latest internal value, and may reject unrecognized
   * values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-
   * conventions.md#resources +optional
   * @param apiVersion apiVersion or {@code null} for none
   */
  public Task setApiVersion(java.lang.String apiVersion) {
    this.apiVersion = apiVersion;
    return this;
  }

  /**
   * Optional. Kind is a string value representing the REST resource this object represents. Servers
   * may infer this from the endpoint the client submits requests to. Cannot be updated. In
   * CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-
   * conventions.md#types-kinds +optional
   * @return value or {@code null} for none
   */
  public java.lang.String getKind() {
    return kind;
  }

  /**
   * Optional. Kind is a string value representing the REST resource this object represents. Servers
   * may infer this from the endpoint the client submits requests to. Cannot be updated. In
   * CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-
   * conventions.md#types-kinds +optional
   * @param kind kind or {@code null} for none
   */
  public Task setKind(java.lang.String kind) {
    this.kind = kind;
    return this;
  }

  /**
   * Optional. Standard object's metadata. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata +optional
   * @return value or {@code null} for none
   */
  public ObjectMeta getMetadata() {
    return metadata;
  }

  /**
   * Optional. Standard object's metadata. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata +optional
   * @param metadata metadata or {@code null} for none
   */
  public Task setMetadata(ObjectMeta metadata) {
    this.metadata = metadata;
    return this;
  }

  /**
   * Optional. Specification of the desired behavior of an execution. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status +optional
   * @return value or {@code null} for none
   */
  public TaskSpec getSpec() {
    return spec;
  }

  /**
   * Optional. Specification of the desired behavior of an execution. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status +optional
   * @param spec spec or {@code null} for none
   */
  public Task setSpec(TaskSpec spec) {
    this.spec = spec;
    return this;
  }

  /**
   * Output only. Current status of an execution. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status +optional
   * @return value or {@code null} for none
   */
  public TaskStatus getStatus() {
    return status;
  }

  /**
   * Output only. Current status of an execution. More info:
   * https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status +optional
   * @param status status or {@code null} for none
   */
  public Task setStatus(TaskStatus status) {
    this.status = status;
    return this;
  }

  @Override
  public Task set(String fieldName, Object value) {
    return (Task) super.set(fieldName, value);
  }

  @Override
  public Task clone() {
    return (Task) super.clone();
  }

}


text:
/**
 * @author Aslak Hellesøy
 * @version $Revision$
 */
package org.nanocontainer.deployer;

import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSelectInfo;
import org.apache.commons.vfs.FileSelector;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.impl.VFSClassLoader;
import org.apache.commons.vfs.VFS;
import org.nanocontainer.integrationkit.ContainerBuilder;
import org.nanocontainer.script.ScriptedContainerBuilderFactory;
import org.picocontainer.defaults.ObjectReference;
import org.picocontainer.defaults.SimpleReference;
import org.nanocontainer.script.UnsupportedScriptTypeException;
import org.nanocontainer.script.ScriptBuilderResolver;

/**
 * This class is capable of deploying an application from any kind of file system
 * supported by Jakarta VFS.
 * (Like local files, zip files etc.) - following the ScriptedContainerBuilderFactory scripting model.
 *
 * The root folder to deploy must have the following file structure:
 *

 * +-someapp/
 *   +-META-INF/
 *   | +-nanocontainer.[py|js|xml|bsh]
 *   +-com/
 *     +-blablah/
 *       +-Hip.class
 *       +-Hop.class
 *

 *
 * For those familiar with J2EE containers (or other containers for that matter), the
 * META-INF/picocontainer script is the ScriptedContainerBuilderFactory composition script. It plays the same
 * role as more classical "deployment descriptors", except that deploying via a full blown
 * scripting language is a lot more powerful!
 *
 * A new class loader (which will be a child of parentClassLoader) will be created. This classloader will make
 * the classes under the root folder available to the deployment script.
 *
 * IMPORTANT NOTE:
 * The scripting engine (rhino, jython, groovy etc.) should be loaded by the same classLoader as
 * the appliacation classes, i.e. the VFSClassLoader pointing to the app directory.
 *
 *

 *    +-------------------+
 *    | xxx               |  <-- parent app loader (must not contain classes from app builder classloader)
 *    +-------------------+
 *              |
 *    +-------------------+
 *    | someapp           | <-- app classloader (must not contain classes from app builder classloader)
 *    +-------------------+
 *              |
 *    +-------------------+
 *    | picocontainer     |
 *    | nanocontainer     |  <-- app builder classloader
 *    | rhino             |
 *    | jython            |
 *    | groovy            |
 *    +-------------------+
 *

 *
 * This means that these scripting engines should *not* be accessible by any of the app classloader, since this
 * may prevent the scripting engine from seeing the classes loaded by the VFSClassLoader. In other words,
 * the scripting engine classed may be loaded several times by different class loaders - once for each
 * deployed application.
 *
 * @author Aslak Hellesøy
 */
public class NanoContainerDeployer implements Deployer {

    /**
     * VFS file system manager.
     */
    private final FileSystemManager fileSystemManager;

    /**
     * File system basename.  Defaults to 'nanocontainer'.  May be set differently
     * for other applications.
     */
    private final String fileBasename;

    /**
     * File Name to builder class name resolver.
     */
    private ScriptBuilderResolver resolver;

    /**
     * Default constructor that makes sensible defaults.
     * @throws FileSystemException
     */
    public NanoContainerDeployer() throws FileSystemException {
        this(VFS.getManager(), new ScriptBuilderResolver());
    }

    /**
     * Constructs a nanocontainer deployer with the specified file system manager.
     * @param fileSystemManager A VFS FileSystemManager.
     */
    public NanoContainerDeployer(final FileSystemManager fileSystemManager) {
        this(fileSystemManager,"nanocontainer");
    }

    /**
     * Constructs this object with both a VFS file system manager, and
     * @param fileSystemManager FileSystemManager
     * @param builderResolver ScriptBuilderResolver
     */
    public NanoContainerDeployer(final FileSystemManager fileSystemManager, ScriptBuilderResolver builderResolver) {
        this(fileSystemManager);
        resolver = builderResolver;
    }

    /**
     * Constructs a nanocontainer deployer with the specified file system manager
     * and specifies a 'base name' for the configuration file that will be loaded.
     * @param fileSystemManager A VFS FileSystemManager.
     * @todo Deprecate this and replace 'base file name' with the concept
     * of a ArchiveLayout that defines where jars are stored, where the composition
     * script is stored, etc.
     */
    public NanoContainerDeployer(final FileSystemManager fileSystemManager, String baseFileName) {
        this.fileSystemManager = fileSystemManager;
        fileBasename = baseFileName;
        resolver = new ScriptBuilderResolver();
    }

    /**
     * Deploys an application.
     *
     * @param applicationFolder the root applicationFolder of the application.
     * @param parentClassLoader the classloader that loads the application classes.
     * @param parentContainerRef reference to the parent container (can be used to lookup components form a parent container).
     * @return an ObjectReference holding a PicoContainer with the deployed components
     * @throws org.apache.commons.vfs.FileSystemException if the file structure was bad.
     * @throws org.nanocontainer.integrationkit.PicoCompositionException if the deployment failed for some reason.
     */
    public ObjectReference deploy(FileObject applicationFolder, ClassLoader parentClassLoader, ObjectReference parentContainerRef) throws FileSystemException, ClassNotFoundException {
        return deploy(applicationFolder, parentClassLoader, parentContainerRef, null);
    }

    public ObjectReference deploy(FileObject applicationFolder, ClassLoader parentClassLoader, ObjectReference parentContainerRef, Object assemblyScope) throws FileSystemException, ClassNotFoundException {
        ClassLoader applicationClassLoader = new VFSClassLoader(applicationFolder, fileSystemManager, parentClassLoader);

        FileObject deploymentScript = getDeploymentScript(applicationFolder);

        ObjectReference result = new SimpleReference();

        String extension = "." + deploymentScript.getName().getExtension();
        Reader scriptReader = new InputStreamReader(deploymentScript.getContent().getInputStream());
        String builderClassName = null;
        try {
            builderClassName = resolver.getBuilderClassName(extension);
        } catch (UnsupportedScriptTypeException ex) {
            throw new FileSystemException("Could not find a suitable builder for: " + deploymentScript.getName()
                + ".  Known extensions are: [groovy|bsh|js|py|xml]", ex);
        }

        ScriptedContainerBuilderFactory scriptedContainerBuilderFactory = new ScriptedContainerBuilderFactory(scriptReader, builderClassName, applicationClassLoader);
        ContainerBuilder builder = scriptedContainerBuilderFactory.getContainerBuilder();
        builder.buildContainer(result, parentContainerRef, assemblyScope, true);

        return result;

    }

    /**
     * Given the base application folder, return a file object that represents the
     * nanocontainer configuration script.
     * @param applicationFolder FileObject
     * @return FileObject
     * @throws FileSystemException
     */
    protected FileObject getDeploymentScript(FileObject applicationFolder) throws FileSystemException {
        final FileObject metaInf = applicationFolder.getChild("META-INF");
        if(metaInf == null) {
            throw new FileSystemException("Missing META-INF folder in " + applicationFolder.getName().getPath());
        }
        final FileObject[] nanocontainerScripts = metaInf.findFiles(new FileSelector(){

            public boolean includeFile(FileSelectInfo fileSelectInfo) throws Exception {
                return fileSelectInfo.getFile().getName().getBaseName().startsWith(getFileBasename());
            }

            public boolean traverseDescendents(FileSelectInfo fileSelectInfo) throws Exception {
              //
              //nanocontainer.* can easily be deep inside a directory tree and
              //we end up not picking up our desired script.
              //
              if (fileSelectInfo.getDepth() > 1) {
                return false;
              } else {
                return true;
              }
            }
        });

        if(nanocontainerScripts == null || nanocontainerScripts.length < 1) {
            throw new FileSystemException("No deployment script ("+ getFileBasename() +".[groovy|bsh|js|py|xml]) in " + applicationFolder.getName().getPath() + "/META-INF");
        }

        if (nanocontainerScripts.length == 1) {
          return nanocontainerScripts[0];
        } else {
          throw new FileSystemException("Found more than one candidate config script in : " + applicationFolder.getName().getPath() + "/META-INF."
              + "Please only have one " + getFileBasename() + ".[groovy|bsh|js|py|xml] this directory.");
        }

    }

    /**
     * Retrieve the file base name.
     * @return String
     */
    public String getFileBasename() {
        return fileBasename;
    }
}


text:
using System;

using Android.Content;
using Android.Util;
using Android.Views;
using Android.Graphics;
using Android.Animation;
using Android.Graphics.Drawables;

namespace EvolveQuest.Droid
{
    public enum MapPinPosition
    {
        Left,
        Center,
        Right
    };

    public class QuestMapView : View
    {
        const int BaseRadius = 5;

        Paint mainPaint;
        Paint linePaint;
        Drawable ripple;

        int radius;
        int textMargin;

        MapPinPosition[] pins;

        int[] shiverOffsets;
        ValueAnimator shiverAnimator;
        int shiverIndex;
        float currentShiverInterpolation;

        int[] heightVariants;

        public QuestMapView(Context context)
            : base(context)
        {
            Initialize();
        }

        public QuestMapView(Context context, IAttributeSet attrs)
            : base(context, attrs)
        {
            Initialize();
        }

        public QuestMapView(Context context, IAttributeSet attrs, int defStyle)
            : base(context, attrs, defStyle)
        {
            Initialize();
        }

        public int CurrentPin { get; set; }

        void Initialize()
        {
            var display = Resources.DisplayMetrics;
            // Numbers and dots
            mainPaint = new Paint
            {
                AntiAlias = true,
                Color = Color.White,
                TextSize = TypedValue.ApplyDimension(ComplexUnitType.Sp, 12, display),
            };
            linePaint = new Paint
            {
                AntiAlias = true,
                Color = Color.Argb(0xaa, 0xff, 0xff, 0xff),
            };
            linePaint.SetStyle(Paint.Style.Stroke);
            ripple = Context.Resources.GetDrawable(Resource.Drawable.ripple_background);

            radius = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, BaseRadius, display);
            textMargin = (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 10, display);

            heightVariants = new []
            {
                0,
                (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 16, display),
                -(int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 14, display),
                (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 9, display),
            };

            shiverOffsets = new []
            {
                (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 9, display),
                (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 3, display),
                -(int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 8, display),
                (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 4, display),
                -(int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 7, display),
                (int)TypedValue.ApplyDimension(ComplexUnitType.Dip, 6, display),
            };
            shiverAnimator = ObjectAnimator.OfFloat(this, "scaleX", 0, 1);
            shiverAnimator.SetInterpolator(new TriangleWave());
            shiverAnimator.SetDuration(8000);
            shiverAnimator.RepeatCount = ValueAnimator.Infinite;
            shiverAnimator.AnimationRepeat += (sender, e) => shiverIndex++;
        }

        public void SetPins(MapPinPosition[] pins)
        {
            this.pins = pins;
            Invalidate();
            if (!shiverAnimator.IsStarted)
                shiverAnimator.Start();
        }

        protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            var height = PaddingTop + PaddingBottom;
            var vspace = Resources.DisplayMetrics.HeightPixels / 5;
            heightMeasureSpec = MeasureSpec.MakeMeasureSpec(height + vspace * (pins.Length - 1), MeasureSpecMode.Exactly);

            base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
        }

        public override void Draw(Canvas canvas)
        {
            if (pins == null)
                return;

            var xcoords = new int []
            {
                PaddingLeft,   // Left
                Width / 2,    // Center
                Width - PaddingRight // Right
            };

            var vspace = (Height - PaddingTop - PaddingBottom) / (pins.Length - 1);
            var currY = PaddingTop;

            for (int i = 0; i < pins.Length; i++)
            {
                var pin = pins[i];
                var x = xcoords[(int)pin];
                var y = currY + heightVariants[i % heightVariants.Length];

                // Apply shivering
                x = ApplyShivering(i, x);
                y = ApplyShivering(i + 1, y);

                // First draw joint line if needed
                if (i < pins.Length - 1)
                {
                    var x1 = xcoords[(int)pins[i + 1]];
                    var y1 = currY + vspace + heightVariants[(i + 1) % heightVariants.Length];
                    x1 = ApplyShivering(i + 1, x1);
                    y1 = ApplyShivering(i + 2, y1);
                    canvas.DrawLine(x, y, x1, y1, linePaint);
                }

                // If the point is currently the selected one, draw the ripple current state
                if (CurrentPin == i)
                {
                    var dur = shiverAnimator.Duration / 4;
                    var fraction = (float)(shiverAnimator.CurrentPlayTime % dur) / dur;
                    // Cheap interpolation
                    fraction *= fraction;
                    var rippleRadius = (int)(radius * (5 * fraction + 1)) - 8;
                    var color = Color.Argb((int)Math.Round(0x99 * (1 - fraction)),
                                    0xFF, 0xFF, 0xFF);
                    ((GradientDrawable)ripple).SetColor(color.ToArgb());
                    ripple.SetBounds(x - rippleRadius, y - rippleRadius, x + rippleRadius, y + rippleRadius);
                    ripple.Draw(canvas);
                }

                // Then draw our point
                canvas.DrawCircle(x, y, radius, mainPaint);

                // Finally draw the step number
                var ty = y;
                var tx = x;

                if (pin == MapPinPosition.Right)
                    tx += textMargin;
                else if (pin == MapPinPosition.Left)
                    tx -= textMargin * 2;
                else
                {
                    if (i == 0 || i == pins.Length - 1)
                        ty += (i == 0) ? -textMargin : 2 * textMargin;
                    else
                    {
                        var prev = pins[i - 1];
                        var next = pins[i + 1];

                        if (prev != next)
                            ty -= textMargin;
                        tx += prev == MapPinPosition.Left ? textMargin : -textMargin;
                    }
                }
                canvas.DrawText((i + 1).ToString(), tx, ty, mainPaint);

                currY += vspace;
            }
        }

        int ApplyShivering(int i, int value)
        {
            value += (int)Math.Round(shiverOffsets[(i + shiverIndex) % shiverOffsets.Length] * currentShiverInterpolation);
            return value;
        }

        public override float ScaleX
        {
            get
            {
                return currentShiverInterpolation;
            }
            set
            {
                currentShiverInterpolation = value;
                Invalidate();
            }
        }
    }

    class TriangleWave : Java.Lang.Object, ITimeInterpolator
    {
        public float GetInterpolation(float input)
        {
            var t = input * 2;
            return (float)(2 * Math.Abs(t - Math.Floor(t + 0.5)) * (1 - 2 * Math.Floor(t)));
        }
    }
}


text:
package io.taig.android.widget.operation

import android.view.View
import io.taig.android.graphic.Direction._
import io.taig.android.graphic.Distance
import io.taig.android.widget.syntax.view._

final class view(view: View) {
  def getPadding =
    Distance(view.getPaddingLeft,
             view.getPaddingTop,
             view.getPaddingRight,
             view.getPaddingBottom)

  /**
    * Apply same padding to all Directions
    */
  def setPadding(padding: Int) =
    view.setPadding(padding, padding, padding, padding)

  /**
    * Apply vertical and horizontal padding
    */
  def setPadding(vertical: Int, horizontal: Int) =
    view.setPadding(horizontal, vertical, horizontal, vertical)

  def setPadding(padding: Distance[Int]) =
    view.setPadding(padding.left, padding.top, padding.right, padding.bottom)

  def setPadding(direction: Direction, padding: Int) = direction match {
    case Left ⇒
      view.setPadding(padding,
                      view.getPaddingTop,
                      view.getPaddingRight,
                      view.getPaddingBottom)
    case Top ⇒
      view.setPadding(view.getPaddingLeft,
                      padding,
                      view.getPaddingRight,
                      view.getPaddingBottom)
    case Right ⇒
      view.setPadding(view.getPaddingLeft,
                      view.getPaddingTop,
                      padding,
                      view.getPaddingBottom)
    case Bottom ⇒
      view.setPadding(view.getPaddingLeft,
                      view.getPaddingTop,
                      view.getPaddingRight,
                      padding)
  }

  def getBottomTo(parent: View): Int = view.getParent match {
    case `parent` ⇒ view.getBottom
    case intermediate: View ⇒ view.getBottom + intermediate.getBottomTo(parent)
    case _ ⇒ sys.error("Can't resolve relative bottom")
  }

  def getLeftTo(parent: View): Int = view.getParent match {
    case `parent` ⇒ view.getLeft
    case intermediate: View ⇒ view.getLeft + intermediate.getLeftTo(parent)
    case _ ⇒ sys.error("Can't resolve relative left")
  }

  def getRightTo(parent: View): Int = view.getParent match {
    case `parent` ⇒ view.getRight
    case intermediate: View ⇒ view.getRight + intermediate.getRightTo(parent)
    case _ ⇒ sys.error("Can't resolve relative right")
  }

  def getTopTo(parent: View): Int = view.getParent match {
    case `parent` ⇒ view.getTop
    case intermediate: View ⇒ view.getTop + intermediate.getTopTo(parent)
    case _ ⇒ sys.error("Can't resolve relative top")
  }

  def next: Option[View] = view match {
    case viewGroup: android.view.ViewGroup if viewGroup.getChildCount > 0 ⇒
      Some(viewGroup.getChildAt(0))
    case view ⇒
      view.getParent match {
        case viewGroup: android.view.ViewGroup ⇒
          Option(viewGroup.getChildAt(viewGroup.indexOfChild(view) + 1))
        case _ ⇒ None
      }
  }

  /**
    * Wrap this view with the given view, and also rewire the parent (if present)
    */
  def wrap[V <: android.view.ViewGroup](viewGroup: V): V = {
    view.getParent match {
      case parent: android.view.ViewGroup ⇒
        parent.removeView(view)
        parent.addView(viewGroup, view.getLayoutParams)
      case _ ⇒ //
    }

    viewGroup.addView(view)
    viewGroup
  }
}


text:
// Type definitions for Couchbase Node.js SDK 2.1.2
// Project: https://github.com/couchbase/couchnode
// Definitions by: Marwan Aouida <https://github.com/maouida>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/// <reference path="../node/node.d.ts"/>

declare module 'couchbase' {

    import events = require('events');

    /**
     * Enumeration of all error codes. See libcouchbase documentation for more details on what these errors represent.
     */
    enum errors {
        /** Operation was successful. **/
        success,

        /** Authentication should continue. **/
        authContinue,

        /** Error authenticating. **/
        authError,

        /** The passed incr/decr delta was invalid. **/
        deltaBadVal,

        /** Object is too large to be stored on the cluster. **/
        objectTooBig,

        /** Operation was successful. **/
        serverBusy,

        /** Server is too busy to handle your request right now. **/
        cLibInternal,

        /** An invalid arguement was passed. **/
        cLinInvalidArgument,

        /** The server is out of memory. **/
        cLibOutOfMemory,

        /** An invalid range was specified. **/
        invalidRange,

        /** An unknown error occured within libcouchbase. **/
        cLibGenericError,

        /** A temporary error occured. Try again. **/
        temporaryError,

        /** The key already exists on the server. **/
        keyAlreadyExists,

        /** The key does not exist on the server. **/
        keyNotFound,

        /** Failed to open library. **/
        failedToOpenLibrary,

        /** Failed to find expected symbol in library. **/
        failedToFindSymbol,

        /** A network error occured. **/
        networkError,

        /** Operations were performed on the incorrect server. **/
        wrongServer,

        /** Operations were performed on the incorrect server. **/
        notMyVBucket,

        /** The document was not stored. **/
        notSorted,

        /** An unsupported operation was sent to the server. **/
        notSupported,

        /** An unknown command was sent to the server. **/
        unknownCommand,

        /** An unknown host was specified. **/
        unknownHost,

        /** A protocol error occured. **/
        protocolError,

        /** The operation timed out. **/
        timedOut,

        /** Error connecting to the server. **/
        connectError,

        /** The bucket you request was not found. **/
        bukcketNotFound,

        /** libcouchbase is out of memory. **/
        clientOutOfMemory,

        /** A temporary error occured in libcouchbase. Try again. **/
        clientTemporaryError,

        /** A bad handle was passed. **/
        badHandle,

        /** A server bug caused the operation to fail. **/
        serverBug,

        /** The host format specified is invalid. **/
        invalidHostFormat,

        /**  Not enough nodes to meet the operations durability requirements. **/
        notEnoughNodes,

        /** Duplicate items. **/
        duplicateItems,

        /** Key mapping failed and could not match a server. **/
        noMatchingServerForKey,

        /** A bad environment variable was specified. **/
        badEnvironmentVariable,

        /** Couchnode is out of memory. **/
        outOfMemory,

        /** Invalid arguements were passed. **/
        invalidArguments,

        /** An error occured while trying to schedule the operation. **/
        schedulingError,

        /** Not all operations completed successfully. **/
        checkResults,

        /** A generic error occured in Couchnode. **/
        genericError,

        /** The specified durability requirements could not be satisfied. **/
        durabilityFailed,

        /** An error occured during a RESTful operation. **/
        restError
    }

    /**
     * Represents a singular cluster containing your buckets.
     */
    class Cluster {
        /**
         * Create a new instance of the Cluster class.
         * @param cnstr The connection string for your cluster.
         * @param options The options object.
         */
        constructor(cnstr?: string, options?: ClusterConstructorOptions);

        /**
         * Creates a manager allowing the management of a Couchbase cluster.
         */
        manager(): ClusterManager;

        /**
         * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this.
         * @param name The name of the bucket to open.
         */
        openBucket(name?: string): Bucket;

        /**
         * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this.
         * @param name The name of the bucket to open.
         * @param password Password for the bucket.
         */
        openBucket(name?: string, password?: string): Bucket;

        /**
         * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this.
         * @param name The name of the bucket to open.
         * @param callback Callback to invoke on connection success or failure.
         */
        openBucket(name?: string, callback?: Function): Bucket;

        /**
         * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this.
         * @param name The name of the bucket to open.
         * @param password Password for the bucket.
         * @param callback Callback to invoke on connection success or failure.
         */
        openBucket(name?: string, password?: string, callback?: Function): Bucket;
    }

    interface ClusterConstructorOptions {
        /**
         * The path to the certificate to use for SSL connections
         */
        certpath: string;
    }

    interface CreateBucketOptions {
        /**
         * The bucket name
         */
        name?: string;
        authType?: string,
        bucketType?: string;
        ramQuotaMB?: number;
        replicaNumber?: number;
    }

    /**
     * Class for performing management operations against a cluster.
     */
    interface ClusterManager {
        /**
         *
         * @param name
         * @param callback
         */
        createBucket(name: string, callback: Function): void;

        /**
         *
         * @param name
         * @param opts
         * @param callback
         */
        createBucket(name: string, opts: any, callback: Function): void;

        /**
         *
         * @param callback
         */
        listBuckets(callback: Function): void;

        /**
         *
         * @param name
         * @param callback
         */
        removeBucket(name: string, callback: Function): void;
    }

    /**
     * The virtual class thrown for all Couchnode errors.
     */
    interface CouchbaseError extends Error {
        /**
         * The error code for this error.
         */
        code: errors;
    }

    interface AppendOptions {
        /**
         * The CAS value to check. If the item on the server contains a different CAS value, the operation will fail. Note that if this option is undefined, no comparison will be performed.
         */
        cas?: Bucket.CAS;

        /**
         * Ensures this operation is persisted to this many nodes.
         */
        persist_to?: number;

        /**
         * 	Ensures this operation is replicated to this many nodes.
         */
        replicate_to?: number;
    }

    interface PrependOptions extends AppendOptions { }

    interface RemoveOptions extends AppendOptions { }

    interface ReplaceOptions extends AppendOptions {
        /**
         * Set the initial expiration time for the document. A value of 0 represents never expiring.
         */
        expiry?: number;
    }

    interface UpsertOptions extends ReplaceOptions { }

    interface TouchOptions {
        /**
         * 	Ensures this operation is persisted to this many nodes.
         */
        persist_to?: number;

        /**
         * Ensures this operation is replicated to this many nodes.
         */
        replicate_to?: number;
    }

    interface CounterOptions {
        /**
         * Sets the initial value for the document if it does not exist. Specifying a value of undefined will cause the operation to fail if the document does not exist, otherwise this value must be equal to or greater than 0.
         */
        initial?: number;

        /**
         * Set the initial expiration time for the document. A value of 0 represents never expiring.
         */
        expiry?: number;

        /**
         * Ensures this operation is persisted to this many nodes
         */
        persist_to?: number;

        /**
         * Ensures this operation is replicated to this many nodes
         */
        replicate_to?: number;
    }

    interface GetAndLockOptions {
        lockTime?: number;
    }

    interface GetReplicaOptions {

        /**
         * The index for which replica you wish to retrieve this value from, or if undefined, use the value from the first server that replies.
         */
        index?: number;
    }

    interface InsertOptions {

        /**
         * Set the initial expiration time for the document. A value of 0 represents never expiring.
         */
        expiry?: number;

        /**
         * Ensures this operation is persisted to this many nodes.
         */
        persist_to?: number;

        /**
         * 	Ensures this operation is replicated to this many nodes.
         */
        replicate_to?: number;
    }

    /**
     * A class for performing management operations against a bucket. This class should not be instantiated directly, but instead through the use of the Bucket#manager method instead.
     */
    interface BucketManager {

        /**
         * Flushes the cluster, deleting all data stored within this bucket. Note that this method requires the Flush permission to be enabled on the bucket from the management console before it will work.
         * @param callback The callback function.
         */
        flush(callback: Function): void;

        /**
         * Retrieves a specific design document from this bucket.
         * @param name
         * @param callback The callback function.
         */
        getDesignDocument(name: string, callback: Function): void;

        /**
         * Retrieves a list of all design documents registered to a bucket.
         * @param callback The callback function.
         */
        getDesignDocuments(callback: Function): void;

        /**
         * Registers a design document to this bucket, failing if it already exists.
         * @param name
         * @param data
         * @param callback The callback function.
         * @returns {}
         */
        insertDesignDocument(name: string, data: any, callback: Function): void;

        /**
         * Unregisters a design document from this bucket.
         * @param name
         * @param callback The callback function.
         * @returns {}
         */
        removeDesignDocument(name: string, callback: Function): void;

        /**
         * Registers a design document to this bucket, overwriting any existing design document that was previously registered.
         * @param name
         * @param data
         * @param callback The callback function.
         * @returns {}
         */
        upsertDesignDocument(name: string, data: any, callback: Function): void;
    }

    /**
     * Class for dynamically construction of view queries. This class should never be constructed directly, instead you should use ViewQuery.from to construct this object.
     */
    class ViewQuery {
        /**
         * Instantiates a ViewQuery object for the specified design document and view name.
         * @param ddoc The design document to use.
         * @param name The view to use.
         */
        static from(ddoc: string, name: string): ViewQuery;

        /**
         * Specifies the design document and view name to use for this query.
         * @param ddoc The design document to use.
         * @param name The view to use.
         */
        from(ddoc: string, name: string): ViewQuery;

        /**
         * Allows you to specify custom view options that may not be available though the fluent interface defined by this class.
         * @param opts
         */
        custom(opts: any): ViewQuery;

        /**
         * Flag to request a view request accross all nodes in the case of a development view.
         * @param full_set
         */
        full_set(full_set: boolean): ViewQuery;

        /**
         * Specifies whether to preform grouping during view execution.
         * @param group
         */
        group(group: boolean): ViewQuery;

        /**
         * Specifies the level at which to perform view grouping.
         * @param group_level
         */
        group_level(group_level: number): ViewQuery;

        /**
         * Specifies a range of document id's to retrieve from the index.
         * @param start
         * @param end
         */
        id_range(start: any, end: any): ViewQuery;

        /**
         * Flag to request a view request include the full document value.
         * @param include_docs
         */
        include_docs(include_docs: boolean): ViewQuery;

        /**
         * Specifies a specified key to retrieve from the index.
         * @param key
         */
        key(key: any): ViewQuery;

        /**
         * Specifies a list of keys you wish to retrieve from the index.
         * @param keys
         */
        keys(key: any[]): ViewQuery;

        /**
         * Specifies the maximum number of results to return.
         * @param limit
         */
        limit(limit: number): ViewQuery;

        /**
         * Sets the error handling mode for this query.
         * @param mode
         */
        on_error(mode: ViewQuery.ErrorMode): ViewQuery;

        /**
         * Specifies the desired ordering for the results.
         * @param order
         */
        order(order: ViewQuery.Order): ViewQuery;

        /**
         * Specifies a range of keys to retrieve from the index. You may specify both a start and an end point and additionally specify whether or not the end value is inclusive or exclusive.
         * @param start
         * @param end
         * @param inclusive_end
         */
        range(start: any | any[], end: any | any[], inclusive_end?: boolean): ViewQuery;

        /**
         * Specifies whether to execute the map-reduce reduce step.
         * @param reduce
         */
        reduce(reduce: boolean): ViewQuery;

        /**
         * Specifies how many results to skip from the beginning of the result set.
         * @param skip
         */
        skip(skip: number): ViewQuery;

        /**
         * Specifies how this query will affect view indexing, both before and after the query is executed.
         * @param stale
         */
        stale(stale: ViewQuery.Update): ViewQuery;
    }

    namespace ViewQuery {
        /**
         * Enumeration for specifying on_error behaviour.
         */
        enum ErrorMode {
            /**
             * Continues querying when an error occurs.
             */
            CONTINUE,

            /**
             * Stops and errors query when an error occurs.
             */
            STOP
        }

        /**
         * Enumeration for specifying view result ordering.
         */
        enum Order {
            /**
             * Orders with lower values first and higher values last.
             */
            ASCENDING,

            /**
             * Orders with higher values first and lower values last.
             */
            DESCENDING
        }

        /**
         * Enumeration for specifying view update semantics.
         */
        enum Update {
            /**
             * Causes the view to be fully indexed before results are retrieved.
             */
            BEFORE,

            /**
             * Allows the index to stay in whatever state it is already in prior retrieval of the query results.
             */
            NONE,

            /**
             * Forces the view to be indexed after the results of this query has been fetched.
             */
            AFTER
        }
    }

    /**
     * Class for dynamically construction of N1QL queries. This class should never be constructed directly, instead you should use the N1qlQuery.fromString static method to instantiate a N1qlStringQuery.
     */
    class N1qlQuery {
        /**
         * Creates a query object directly from the passed query string.
         * @param str
         */
        static fromString(str: string): N1qlStringQuery;

        /**
         * Returns the fully prepared string representation of this query.
         */
        toString(): string;
    }

    namespace N1qlQuery {
        /**
         * Enumeration for specifying N1QL consistency semantics.
         */
        enum Consistency {
            /**
             * 	This is the default (for single-statement requests).
             */
            NOT_BOUND,

            /**
             * This implements strong consistency per request.
             */
            REQUEST_PLUS,

            /**
             * This implements strong consistency per statement.
             */
            STATEMENT_PLUS
        }
    }

    /**
     * Class for holding a explicitly defined N1QL query string.
     */
    class N1qlStringQuery extends N1qlQuery {
        /**
         * Specifies whether this query is adhoc or should be prepared.
         * @param adhoc
         */
        adhoc(adhoc: boolean): N1qlStringQuery;

        /**
         * Specify the consistency level for this query.
         * @param val
         */
        consistency(val: N1qlQuery.Consistency): N1qlStringQuery;

        /**
         * Returns the fully prepared object representation of this query.
         */
        toObject(): any;

        /**
         * Returns the fully prepared string representation of this query.
         */
        toString(): string;
    }

    /**
     * Class for dynamically construction of spatial queries. This class should never be constructed directly, instead you should use SpatialQuery.from to construct this object.
     */
    class SpatialQuery {
        /**
         * Instantiates a SpatialQuery object for the specified design document and view name.
         * @param ddoc The design document to use.
         * @param name 	The view to use.
         */
        static from(ddoc: string, name: string): SpatialQuery;

        /**
         * Specifies the design document and view name to use for this query.
         * @param ddoc
         * @param name
         */
        from(ddoc: string, name: string): SpatialQuery;

        /**
         * Specifies a bounding box to query the index for. This value must be an array of exactly 4 numbers which represents the left, top, right and bottom edges of the bounding box (in that order).
         * @param bbox
         */
        bbox(bbox: number[]): SpatialQuery;

        /**
         * Allows you to specify custom view options that may not be available though the fluent interface defined by this class.
         * @param opts
         */
        custom(opts: any): SpatialQuery;

        /**
         * Specifies the maximum number of results to return.
         * @param limit
         */
        limit(limit: number): SpatialQuery;

        /**
         * Specifies how many results to skip from the beginning of the result set.
         * @param skip
         */
        skip(skip: number): SpatialQuery;

        /**
         * Specifies how this query will affect view indexing, both before and after the query is executed.
         * @param stale
         */
        stale(stale: SpatialQuery.Update): SpatialQuery;
    }

    namespace SpatialQuery {
        /**
         * Enumeration for specifying view update semantics.
         */
        enum Update {
            /**
             * Causes the view to be fully indexed before results are retrieved.
             */
            BEFORE,

            /**
             * Allows the index to stay in whatever state it is already in prior retrieval of the query results.
             */
            NONE,

            /**
             * 	Forces the view to be indexed after the results of this query has been fetched.
             */
            AFTER
        }
    }

    /**
     * The Bucket class represents a connection to a Couchbase bucket. Never instantiate this class directly. Instead use the Cluster#openBucket method instead.
     */
    interface Bucket {
        /**
         * Returns the version of the Node.js library as a string.
         */
        clientVersion: string;

        /**
         * Gets or sets the config throttling in milliseconds. The config throttling is the time that Bucket will wait before forcing a configuration refresh. If no refresh occurs before this period while a configuration is marked invalid, an update will be triggered.
         */
        configThrottle: number;

        /**
         * Sets or gets the connection timeout in milliseconds. This is the timeout value used when connecting to the configuration port during the initial connection (in this case, use this as a key in the 'options' parameter in the constructor) and/or when Bucket attempts to reconnect in-situ (if the current connection has failed).
         */
        connectionTimeout: number;

        /**
         * Gets or sets the durability interval in milliseconds. The durability interval is the time that Bucket will wait between requesting new durability information during a durability poll.
         */
        durabilityInterval: number;

        /**
         * Gets or sets the durability timeout in milliseconds. The durability timeout is the time that Bucket will wait for a response from the server in regards to a durability request. If there are no responses received within this time frame, the request fails with an error.
         */
        durabilityTimeout: number;

        /**
         * Returns the libcouchbase version as a string. This information will usually be in the format of 2.4.0-fffffff representing the major, minor, patch and git-commit that the built libcouchbase is based upon.
         */
        lcbVersion: string;

        /**
         * Gets or sets the management timeout in milliseconds. The management timeout is the time that Bucket will wait for a response from the server for a management request. If the response is not received within this time frame, the request is failed out with an error.
         */
        managementTimeout: number;

        /**
         * Sets or gets the node connection timeout in msecs. This value is similar to Bucket#connectionTimeout, but defines the time to wait for a particular node to respond before trying the next one.
         */
        nodeConnectionTimeout: number;

        /**
         * Gets or sets the operation timeout in milliseconds. The operation timeout is the time that Bucket will wait for a response from the server for a CRUD operation. If the response is not received within this time frame, the operation is failed with an error.
         */
        operationTimeout: number;

        /**
         * Gets or sets the view timeout in milliseconds. The view timeout is the time that Bucket will wait for a response from the server for a view request. If the response is not received within this time frame, the request fails with an error.
         */
        viewTimeout: number;

        /**
         * Similar to Bucket#upsert, but instead of setting a new key, it appends data to the existing key. Note that this function only makes sense when the stored data is a string; 'appending' to a JSON document may result in parse errors when the document is later retrieved.
         * @param key The target document key.
         * @param fragment The document's contents to append.
         * @param callback The callback function.
         */
        append(key: any | Buffer, fragment: any, callback: Bucket.OpCallback): void;

        /**
         *
         * @param key The target document key.
         * @param fragment The document's contents to append.
         * @param options The options object.
         * @param callback The callback function.
         */
        append(key: any | Buffer, fragment: any, options: AppendOptions, callback: Bucket.OpCallback): void;

        /**
         * Increments or decrements a key's numeric value.
         * Note that JavaScript does not support 64-bit integers (while libcouchbase and the server do). You might receive an inaccurate value if the number is greater than 53-bits (JavaScript's maximum integer precision).
         * @param key The target document key.
         * @param delta The amount to add or subtract from the counter value. This value may be any non-zero integer.
         * @param callback The callback function.
         */
        counter(key: any | Buffer, delta: number, callback: Bucket.OpCallback): void;

        /**
         *
         * @param key The target document key.
         * @param delta The amount to add or subtract from the counter value. This value may be any non-zero integer.
         * @param options The options object.
         * @param callback The callback function.
         */
        counter(key: any | Buffer, delta: number, options: CounterOptions, callback: Bucket.OpCallback): void;

        /**
         * Shuts down this connection.
         */
        disconnect(): void;

        /**
         * Enables N1QL support on the client. A cbq-server URI must be passed. This method will be deprecated in the future in favor of automatic configuration through the connected cluster.
         * @param hosts An array of host/port combinations which are N1QL servers attached to this cluster.
         */
        enableN1ql(hosts: string | string[]): void;

        /**
         * Retrieves a document.
         * @param key The target document key.
         * @param callback The callback function.
         */
        get(key: any | Buffer, callback: Bucket.OpCallback): void;

        /**
         * @param key The target document key.
         * @param options The options object.
         * @param callback The callback function.
         */
        get(key: any | Buffer, options: any, callback: Bucket.OpCallback): void;

        /**
         * Lock the document on the server and retrieve it. When an document is locked, its CAS changes and subsequent operations on the document (without providing the current CAS) will fail until the lock is no longer held.
         * This function behaves identically to Bucket#get in that it will return the value. It differs in that the document is also locked. This ensures that attempts by other client instances to access this document while the lock is held will fail.
         * Once locked, a document can be unlocked either by explicitly calling Bucket#unlock or by performing a storage operation (e.g. Bucket#upsert, Bucket#replace, Bucket::append) with the current CAS value. Note that any other lock operations on this key will fail while a document is locked.
         * @param key The target document key.
         * @param callback The callback function.
         */
        getAndLock(key: any, callback: Bucket.OpCallback): void;

        /**
         * Lock the document on the server and retrieve it. When an document is locked, its CAS changes and subsequent operations on the document (without providing the current CAS) will fail until the lock is no longer held.
         * This function behaves identically to Bucket#get in that it will return the value. It differs in that the document is also locked. This ensures that attempts by other client instances to access this document while the lock is held will fail.
         * Once locked, a document can be unlocked either by explicitly calling Bucket#unlock or by performing a storage operation (e.g. Bucket#upsert, Bucket#replace, Bucket::append) with the current CAS value. Note that any other lock operations on this key will fail while a document is locked.
         * @param key The target document key.
         * @param options The options object.
         * @param callback The callback function.
         * @returns {}
         */
        getAndLock(key: any, options: GetAndLockOptions, callback: Bucket.OpCallback): void;

        /**
         * Retrieves a document and updates the expiry of the item at the same time.
         * @param key The target document key.
         * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds).
         * @param options The options object.
         * @param callback The callback function.
         */
        getAndTouch(key: any | Buffer, expiry: number, options: any, callback: Bucket.OpCallback): void;

        /**
         * Retrieves a document and updates the expiry of the item at the same time.
         * @param key The target document key.
         * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds).
         * @param callback The callback function.
         */
        getAndTouch(key: any | Buffer, expiry: number, callback: Bucket.OpCallback): void;

        /**
         * Retrieves a list of keys
         * @param keys The target document keys.
         * @param callback The callback function.
         */
        getMulti(key: any[] | Buffer[], callback: Bucket.MultiGetCallback): void;

        /**
         * Get a document from a replica server in your cluster.
         * @param key The target document key.
         * @param callback The callback function.
         */
        getReplica(key: any | Buffer, callback: Bucket.OpCallback): void;

        /**
        * Get a document from a replica server in your cluster.
        * @param key The target document key.
        * @param options The options object.
        * @param callback The callback function.
        */
        getReplica(key: any | Buffer, options: GetReplicaOptions, callback: Bucket.OpCallback): void;

        /**
         * Identical to Bucket#upsert but will fail if the document already exists.
         * @param key The target document key.
         * @param value The document's contents.
         * @param callback The callback function.
         */
        insert(key: any | Buffer, value: any, callback: Bucket.OpCallback): void;

        /**
         * Identical to Bucket#upsert but will fail if the document already exists.
         * @param key The target document key.
         * @param value The document's contents.
         * @param options The options object.
         * @param callback The callback function.
         */
        insert(key: any | Buffer, value: any, options: InsertOptions, callback: Bucket.OpCallback): void;

        /**
         * Returns an instance of a BuckerManager for performing management operations against a bucket.
         */
        manager(): BucketManager;

        /**
         * Like Bucket#append, but prepends data to the existing value.
         * @param key The target document key.
         * @param fragment The document's contents to prepend.
         * @param callback The callback function.
         */
        prepend(key: any, fragment: any, callback: Bucket.OpCallback): void;

        /**
         * Like Bucket#append, but prepends data to the existing value.
         * @param key The target document key.
         * @param fragment The document's contents to prepend.
         * @param options The options object.
         * @param callback The callback function.
         */
        prepend(key: any, fragment: any, options: PrependOptions, callback: Bucket.OpCallback): void;

        /**
         * Executes a previously prepared query object. This could be a ViewQuery or a N1qlQuery.
         * Note: N1qlQuery queries are currently an uncommitted interface and may be subject to change in 2.0.0's final release.
         * @param query The query to execute.
         * @param callback The callback function.
         */
        query(query: ViewQuery | N1qlQuery, callback: Bucket.QueryCallback): Bucket.ViewQueryResponse | Bucket.N1qlQueryResponse;

        /**
         * Executes a previously prepared query object. This could be a ViewQuery or a N1qlQuery.
         * Note: N1qlQuery queries are currently an uncommitted interface and may be subject to change in 2.0.0's final release.
         * @param query The query to execute.
         * @param params A list or map to do replacements on a N1QL query.
         * @param callback The callback function.
         */
        query(query: ViewQuery | N1qlQuery, params: Object | Array<any>, callback: Bucket.QueryCallback): Bucket.ViewQueryResponse | Bucket.N1qlQueryResponse;

        /**
         * Deletes a document on the server.
         * @param key The target document key.
         * @param callback The callback function.
         */
        remove(key: any | Buffer, callback: Bucket.OpCallback): void;

        /**
         * Deletes a document on the server.
         * @param key The target document key.
         * @param options The options object.
         * @param callback The callback function.
         */
        remove(key: any | Buffer, options: RemoveOptions, callback: Bucket.OpCallback): void;

        /**
         * Identical to Bucket#upsert, but will only succeed if the document exists already (i.e. the inverse of Bucket#insert).
         * @param key The target document key.
         * @param value The document's contents.
         * @param callback The callback function.
         */
        replace(key: any | Buffer, value: any, callback: Bucket.OpCallback): void;

        /**
         * Identical to Bucket#upsert, but will only succeed if the document exists already (i.e. the inverse of Bucket#insert).
         * @param key The target document key.
         * @param value The document's contents.
         * @param options The options object.
         * @param callback The callback function.
         */
        replace(key: any | Buffer, value: any, options: ReplaceOptions, callback: Bucket.OpCallback): void;

        /**
         * Configures a custom set of transcoder functions for encoding and decoding values that are being stored or retreived from the server.
         * @param encoder The function for encoding.
         * @param decoder The function for decoding.
         */
        setTranscoder(encoder: Bucket.EncoderFunction, decoder: Bucket.DecoderFunction): void;

        /**
         * Update the document expiration time.
         * @param key The target document key.
         * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds). Values larger than 302460*60 seconds (30 days) are interpreted as absolute times (from the epoch).
         * @param options The options object.
         * @param callback The callback function.
         */
        touch(key: any | Buffer, expiry: number, options: TouchOptions, callback: Bucket.OpCallback): void;

        /**
         * Unlock a previously locked document on the server. See the Bucket#lock method for more details on locking.
         * @param key The target document key.
         * @param cas The CAS value returned when the key was locked. This operation will fail if the CAS value provided does not match that which was the result of the original lock operation.
         * @param callback The callback function.
         */
        unlock(key: any | Buffer, cas: Bucket.CAS, callback: Bucket.OpCallback): void;

        /**
         * Unlock a previously locked document on the server. See the Bucket#lock method for more details on locking.
         * @param key The target document key.
         * @param cas The CAS value returned when the key was locked. This operation will fail if the CAS value provided does not match that which was the result of the original lock operation.
         * @param options The options object.
         * @param callback The callback function.
         */
        unlock(key: any | Buffer, cas: Bucket.CAS, options: any, callback: Bucket.OpCallback): void;

        /**
         * Stores a document to the bucket.
         * @param key The target document key.
         * @param value The document's contents.
         * @param callback The callback function.
         */
        upsert(key: any | Buffer, value: any, callback: Bucket.OpCallback): void;

        /**
         * Stores a document to the bucket.
         * @param key The target document key.
         * @param value The document's contents.
         * @param options The options object.
         * @param callback The callback function.
         */
        upsert(key: any | Buffer, value: any, options: UpsertOptions, callback: Bucket.OpCallback): void;
    }

    namespace Bucket {

        /**
         * his is used as a callback from executed queries. It is a shortcut method that automatically subscribes to the rows and error events of the Bucket.ViewQueryResponse.
         */
        interface QueryCallback {
            /**
             * @param error The error for the operation. This can either be an Error object or a falsy value.
             * @param rows The rows returned from the query.
             * @param meta The metadata returned by the query.
             */
            (error: CouchbaseError, rows: any[], meta: Bucket.ViewQueryResponse.Meta): void;
        }

        /**
         * Single-Key callbacks.
         * This callback is passed to all of the single key functions.
         * It returns a result objcet containing a combination of a CAS and a value, depending on which operation was invoked.
         */
        interface OpCallback {
            /**
             * @param error The error for the operation. This can either be an Error object or a value which evaluates to false (null, undefined, 0 or false).
             * @param result The result of the operation that was executed. This usually contains at least a cas property, and on some operations will contain a value property as well.
             */
            (error: CouchbaseError | number, result: any): void;
        }

        /**
         * Multi-Get Callback.
         * This callback is used to return results from a getMulti operation.
         */
        interface MultiGetCallback {
            /**
             * @param error The number of keys that failed to be retrieved. The precise errors are available by checking the error property of the individual documents.
             * @param results This is a map of keys to results. The result for each key will optionally contain an error if one occured, or if no error occured will contain the CAS and value of the document.
             */
            (error: number, results: any[]): void;
        }

        /**
         * Transcoder Encoding Function.
         * This function will receive a value when a storage operation is invoked that needs to encode user-provided data for storage into Couchbase. It expects to be returned a Buffer object to store along with an integer representing any flag metadata relating to how to decode the key later using the matching DecoderFunction.
         */
        interface EncoderFunction {
            /**
             * Transcoder Encoding Function.
             * This function will receive a value when a storage operation is invoked that needs to encode user-provided data for storage into Couchbase. It expects to be returned a Buffer object to store along with an integer representing any flag metadata relating to how to decode the key later using the matching DecoderFunction.
             * @param value The value needing encoding.
             */
            (value: any): Bucket.TranscoderDoc;
        }

        /**
         * Transcoder Decoding Function.
         * This function will receive an object containing a Buffer value and an integer value representing any flags metadata whenever a retrieval operation is executed. It is expected that this function will return a value representing the original value stored and encoded with its matching EncoderFunction.
         */
        interface DecoderFunction {
            /**
             *
             * @param doc The data from Couchbase to decode.
             */
            (doc: Bucket.TranscoderDoc): any
        }

        /**
         * The CAS value is a special object that indicates the current state of the item on the server. Each time an object is mutated on the server, the value is changed. CAS objects can be used in conjunction with mutation operations to ensure that the value on the server matches the local value retrieved by the client. This is useful when doing document updates on the server as you can ensure no changes were applied by other clients while you were in the process of mutating the document locally.
         * In the Node.js SDK, the CAS is represented as an opaque value. As such,y ou cannot generate CAS objects, but should rather use the values returned from a Bucket.OpCallback.
         */
        interface CAS {

        }

        /**
         * An event emitter allowing you to bind to various query result set events.
         */
        interface N1qlQueryResponse extends events.EventEmitter {

        }

        namespace N1qlQueryResponse {
            /**
             * The meta-information available from a view query response.
             */
            interface Meta {
                /**
                 * The identifier for this query request.
                 */
                requestID: number;
            }
        }

        /**
         * A class used in relation to transcoders.
         */
        class TranscoderDoc {
            value: Buffer;
            flags: number;
        }

        /**
         * An event emitter allowing you to bind to various query result set events.
         */
        interface ViewQueryResponse extends events.EventEmitter {

        }

        namespace ViewQueryResponse {
            /**
             * The meta-information available from a view query response.
             */
            interface Meta {
                /**
                 * The total number of rows available in the index of the view that was queried.
                 */
                total_rows: number;
            }
        }
    }
}


text:
/* jquery.sparkline 2.1.2 - http://omnipotent.net/jquery.sparkline/
** Licensed under the New BSD License - see above site for details */