text:
#ifndef BERRYABSTRACTHANDLER_H_
#define BERRYABSTRACTHANDLER_H_

#include "berryIHandler.h"
#include "berryIHandlerListener.h"

#include <org_blueberry_core_commands_Export.h>

namespace berry {

/**
 *

 * This class is a partial implementation of IHandler. This
 * abstract implementation provides support for handler listeners. You should
 * subclass from this class unless you want to implement your own listener
 * support. Subclasses should call
 * {@link AbstractHandler#fireHandlerChanged(HandlerEvent)}when the handler
 * changes. Subclasses can also override {@link AbstractHandler#isEnabled()} and
 * {@link AbstractHandler#isHandled()}.
 *

 */
class BERRY_COMMANDS AbstractHandler : public QObject, public IHandler { // ,public EventManager {

  Q_OBJECT
  Q_INTERFACES(berry::IHandler)

public:
  berryObjectMacro(AbstractHandler)

private:

  /**
   * Track this base class enabled state.
   */
  bool baseEnabled;

  IHandlerListener::Events handlerListeners;

public:

  AbstractHandler();

  /**
   * @see IHandler#addHandlerListener(IHandlerListener)
   */
  void AddHandlerListener(IHandlerListener* handlerListener) override;

  /**
   * The default implementation does nothing. Subclasses who attach listeners
   * to other objects are encouraged to detach them in this method.
   *
   * @see IHandler#Dispose()
   */
  void Dispose() override;

  /**
   * Whether this handler is capable of executing at this time. Subclasses may
   * override this method. If clients override this method they should also
   * consider overriding {@link #setEnabled(Object)} so they can be notified
   * about framework execution contexts.
   *
   * @return true
   * @see #setEnabled(Object)
   * @see #setBaseEnabled(boolean)
   */
  bool IsEnabled() const override;

  /**
   * Called by the framework to allow the handler to update its enabled state
   * by extracting the same information available at execution time. Clients
   * may override if they need to extract information from the application
   * context.
   *
   * @param evaluationContext
   *            the application context. May be null
   * @see #SetBaseEnabled(bool)
   */
  void SetEnabled(const Object::Pointer& evaluationContext) override;

  /**
   * Whether this handler is capable of handling delegated responsibilities at
   * this time. Subclasses may override this method.
   *
   * @return true
   */
  bool IsHandled() const override;

  /**
   * @see IHandler#removeHandlerListener(IHandlerListener)
   */
  void RemoveHandlerListener(IHandlerListener* handlerListener) override;

protected:

  /**
   * Fires an event to all registered listeners describing changes to this
   * instance.
   *

   * Subclasses may extend the definition of this method (i.e., if a different
   * type of listener can be attached to a subclass). This is used primarily
   * for support of AbstractHandler in
   * org.blueberry.ui.workbench, and clients should be wary of
   * overriding this behaviour. If this method is overridden, then the first
   * line of the method should be "super.fireHandlerChanged(handlerEvent);".
   *

   *
   * @param handlerEvent
   *            the event describing changes to this instance. Must not be
   *            null.
   */
  void FireHandlerChanged(const SmartPointer<HandlerEvent>& handlerEvent);

  /**
   * Allow the default {@link #isEnabled()} to answer our enabled state. It
   * will fire a HandlerEvent if necessary. If clients use this method they
   * should also consider overriding {@link #setEnabled(Object)} so they can
   * be notified about framework execution contexts.
   *
   * @param state
   *            the enabled state
   */
  void SetBaseEnabled(bool state);

  /**
   *

   * Returns true iff there is one or more IHandlerListeners attached to this
   * AbstractHandler.
   *

   *

   * Subclasses may extend the definition of this method (i.e., if a different
   * type of listener can be attached to a subclass). This is used primarily
   * for support of AbstractHandler in
   * org.blueberry.ui.qt, and clients should be wary of
   * overriding this behaviour. If this method is overridden, then the return
   * value should include "super.hasListeners() ||".
   *

   *
   * @return true iff there is one or more IHandlerListeners attached to this
   *         AbstractHandler
   */
  virtual bool HasListeners() const;

};

}

#endif /*BERRYABSTRACTHANDLER_H_*/


text:
/*
* File:   spell.hh
* Author: NeveHanter
*
* Created on 20 march 2014, 17:29
*/

#ifndef SPELL_HH
#define	SPELL_HH

class CSpellDatabase;

#include <string>
#include <vector>
#include "datatypes.hh"
#include "effect.hh"

struct Spell {
	std::string id;
	std::string name;
	std::string desc;

	int castCost;

	CSpellTargetType targetType;
	CSpellCastStyle castStyle;

	std::vector<Effect> effects;
};

class CSpellDatabase {
    private:
		std::vector<Spell> m_spells;

	public:
		void addSpell(Spell spell) {
			m_spells.push_back(spell);
		}

		Spell getSpell(size_t index) {
			if(index < m_spells.size())
				return m_spells.at(index);
			else
				throw Exception("Trying to get unexisting spell by index: " + std::to_string(index), 1000);
		}

		Spell getSpell_byName(std::string name) {
			for(std::vector<Spell>::iterator spell = m_spells.begin(); spell != m_spells.end(); ++spell) {
				if(spell->name.compare(name) == 0) {
					return *spell;
				}
			}

			throw Exception("Trying to get unexisting spell by name: \"" + name + "\".", 1000);
		}

		Spell getSpell_byId(std::string id) {
			for(std::vector<Spell>::iterator spell = m_spells.begin(); spell != m_spells.end(); ++spell) {
				if(spell->id.compare(id) == 0) {
					return *spell;
				}
			}

			throw Exception("Trying to get unexisting spell by id: \"" + id + "\".", 1000);
		}
};

#endif /* SPELL_HH */

redpajama_set_name: RedPajamaGithub


text:
package com.bzh.dytt.data.db;

import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;

import com.bzh.dytt.data.entity.CategoryMap;
import com.bzh.dytt.data.entity.MovieCategory;

import java.util.List;

import static android.arch.persistence.room.OnConflictStrategy.IGNORE;

@Dao
public interface CategoryMapDAO {

    @Insert(onConflict = IGNORE)
    void insertCategoryMapList(List<CategoryMap> categoryMapList);

    @Query("SELECT * FROM category_map WHERE category = :category ORDER BY serial_number DESC")
    LiveData<List<CategoryMap>> getMovieLinksByCategory(MovieCategory category);

    @Query("SELECT * FROM category_map WHERE category = :category AND `query`=:query ORDER BY serial_number DESC")
    LiveData<List<CategoryMap>> getMovieLinksByCategoryAndQuery(MovieCategory category, String query);

    @Update
    void updateCategory(CategoryMap categoryMap);

}


text:
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/radix-tree.h>
#include <linux/percpu.h>
#include <linux/slab.h>
#include <linux/notifier.h>
#include <linux/cpu.h>
#include <linux/gfp.h>
#include <linux/string.h>
#include <linux/bitops.h>
#include <linux/rcupdate.h>

#ifdef __KERNEL__
#define RADIX_TREE_MAP_SHIFT	(CONFIG_BASE_SMALL ? 4 : 6)
#else
#define RADIX_TREE_MAP_SHIFT	3	/* For more stressful testing */
#endif

#define RADIX_TREE_MAP_SIZE	(1UL << RADIX_TREE_MAP_SHIFT)
#define RADIX_TREE_MAP_MASK	(RADIX_TREE_MAP_SIZE-1)

#define RADIX_TREE_TAG_LONGS	\
	((RADIX_TREE_MAP_SIZE + BITS_PER_LONG - 1) / BITS_PER_LONG)

struct radix_tree_node {
	unsigned int	height;		/* Height from the bottom */
	unsigned int	count;
	struct rcu_head	rcu_head;
	void		*slots[RADIX_TREE_MAP_SIZE];
	unsigned long	tags[RADIX_TREE_MAX_TAGS][RADIX_TREE_TAG_LONGS];
};

struct radix_tree_path {
	struct radix_tree_node *node;
	int offset;
};

#define RADIX_TREE_INDEX_BITS  (8 /* CHAR_BIT */ * sizeof(unsigned long))
#define RADIX_TREE_MAX_PATH (DIV_ROUND_UP(RADIX_TREE_INDEX_BITS, \
					  RADIX_TREE_MAP_SHIFT))

/*
 * The height_to_maxindex array needs to be one deeper than the maximum
 * path as height 0 holds only 1 entry.
 */
static unsigned long height_to_maxindex[RADIX_TREE_MAX_PATH + 1] __read_mostly;

/*
 * Radix tree node cache.
 */
static struct kmem_cache *radix_tree_node_cachep;

/*
 * Per-cpu pool of preloaded nodes
 */
struct radix_tree_preload {
	int nr;
	struct radix_tree_node *nodes[RADIX_TREE_MAX_PATH];
};
static DEFINE_PER_CPU(struct radix_tree_preload, radix_tree_preloads) = { 0, };

static inline gfp_t root_gfp_mask(struct radix_tree_root *root)
{
	return root->gfp_mask & __GFP_BITS_MASK;
}

static inline void tag_set(struct radix_tree_node *node, unsigned int tag,
		int offset)
{
	__set_bit(offset, node->tags[tag]);
}

static inline void tag_clear(struct radix_tree_node *node, unsigned int tag,
		int offset)
{
	__clear_bit(offset, node->tags[tag]);
}

static inline int tag_get(struct radix_tree_node *node, unsigned int tag,
		int offset)
{
	return test_bit(offset, node->tags[tag]);
}

static inline void root_tag_set(struct radix_tree_root *root, unsigned int tag)
{
	root->gfp_mask |= (__force gfp_t)(1 << (tag + __GFP_BITS_SHIFT));
}

static inline void root_tag_clear(struct radix_tree_root *root, unsigned int tag)
{
	root->gfp_mask &= (__force gfp_t)~(1 << (tag + __GFP_BITS_SHIFT));
}

static inline void root_tag_clear_all(struct radix_tree_root *root)
{
	root->gfp_mask &= __GFP_BITS_MASK;
}

static inline int root_tag_get(struct radix_tree_root *root, unsigned int tag)
{
	return (__force unsigned)root->gfp_mask & (1 << (tag + __GFP_BITS_SHIFT));
}

/*
 * Returns 1 if any slot in the node has this tag set.
 * Otherwise returns 0.
 */
static inline int any_tag_set(struct radix_tree_node *node, unsigned int tag)
{
	int idx;
	for (idx = 0; idx < RADIX_TREE_TAG_LONGS; idx++) {
		if (node->tags[tag][idx])
			return 1;
	}
	return 0;
}
/*
 * This assumes that the caller has performed appropriate preallocation, and
 * that the caller has pinned this thread of control to the current CPU.
 */
static struct radix_tree_node *
radix_tree_node_alloc(struct radix_tree_root *root)
{
	struct radix_tree_node *ret = NULL;
	gfp_t gfp_mask = root_gfp_mask(root);

	if (!(gfp_mask & __GFP_WAIT)) {
		struct radix_tree_preload *rtp;

		/*
		 * Provided the caller has preloaded here, we will always
		 * succeed in getting a node here (and never reach
		 * kmem_cache_alloc)
		 */
		rtp = &__get_cpu_var(radix_tree_preloads);
		if (rtp->nr) {
			ret = rtp->nodes[rtp->nr - 1];
			rtp->nodes[rtp->nr - 1] = NULL;
			rtp->nr--;
		}
	}
	if (ret == NULL)
		ret = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);

	BUG_ON(radix_tree_is_indirect_ptr(ret));
	return ret;
}

static void radix_tree_node_rcu_free(struct rcu_head *head)
{
	struct radix_tree_node *node =
			container_of(head, struct radix_tree_node, rcu_head);

	/*
	 * must only free zeroed nodes into the slab. radix_tree_shrink
	 * can leave us with a non-NULL entry in the first slot, so clear
	 * that here to make sure.
	 */
	tag_clear(node, 0, 0);
	tag_clear(node, 1, 0);
	node->slots[0] = NULL;
	node->count = 0;

	kmem_cache_free(radix_tree_node_cachep, node);
}

static inline void
radix_tree_node_free(struct radix_tree_node *node)
{
	call_rcu(&node->rcu_head, radix_tree_node_rcu_free);
}

/*
 * Load up this CPU's radix_tree_node buffer with sufficient objects to
 * ensure that the addition of a single element in the tree cannot fail.  On
 * success, return zero, with preemption disabled.  On error, return -ENOMEM
 * with preemption not disabled.
 *
 * To make use of this facility, the radix tree must be initialised without
 * __GFP_WAIT being passed to INIT_RADIX_TREE().
 */
int radix_tree_preload(gfp_t gfp_mask)
{
	struct radix_tree_preload *rtp;
	struct radix_tree_node *node;
	int ret = -ENOMEM;

	preempt_disable();
	rtp = &__get_cpu_var(radix_tree_preloads);
	while (rtp->nr < ARRAY_SIZE(rtp->nodes)) {
		preempt_enable();
		node = kmem_cache_alloc(radix_tree_node_cachep, gfp_mask);
		if (node == NULL)
			goto out;
		preempt_disable();
		rtp = &__get_cpu_var(radix_tree_preloads);
		if (rtp->nr < ARRAY_SIZE(rtp->nodes))
			rtp->nodes[rtp->nr++] = node;
		else
			kmem_cache_free(radix_tree_node_cachep, node);
	}
	ret = 0;
out:
	return ret;
}
EXPORT_SYMBOL(radix_tree_preload);

/*
 *	Return the maximum key which can be store into a
 *	radix tree with height HEIGHT.
 */
static inline unsigned long radix_tree_maxindex(unsigned int height)
{
	return height_to_maxindex[height];
}

/*
 *	Extend a radix tree so it can store key @index.
 */
static int radix_tree_extend(struct radix_tree_root *root, unsigned long index)
{
	struct radix_tree_node *node;
	unsigned int height;
	int tag;

	/* Figure out what the height should be.  */
	height = root->height + 1;
	while (index > radix_tree_maxindex(height))
		height++;

	if (root->rnode == NULL) {
		root->height = height;
		goto out;
	}

	do {
		unsigned int newheight;
		if (!(node = radix_tree_node_alloc(root)))
			return -ENOMEM;

		/* Increase the height.  */
		node->slots[0] = radix_tree_indirect_to_ptr(root->rnode);

		/* Propagate the aggregated tag info into the new root */
		for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
			if (root_tag_get(root, tag))
				tag_set(node, tag, 0);
		}

		newheight = root->height+1;
		node->height = newheight;
		node->count = 1;
		node = radix_tree_ptr_to_indirect(node);
		rcu_assign_pointer(root->rnode, node);
		root->height = newheight;
	} while (height > root->height);
out:
	return 0;
}

/**
 *	radix_tree_insert    -    insert into a radix tree
 *	@root:		radix tree root
 *	@index:		index key
 *	@item:		item to insert
 *
 *	Insert an item into the radix tree at position @index.
 */
int radix_tree_insert(struct radix_tree_root *root,
			unsigned long index, void *item)
{
	struct radix_tree_node *node = NULL, *slot;
	unsigned int height, shift;
	int offset;
	int error;

	BUG_ON(radix_tree_is_indirect_ptr(item));

	/* Make sure the tree is high enough.  */
	if (index > radix_tree_maxindex(root->height)) {
		error = radix_tree_extend(root, index);
		if (error)
			return error;
	}

	slot = radix_tree_indirect_to_ptr(root->rnode);

	height = root->height;
	shift = (height-1) * RADIX_TREE_MAP_SHIFT;

	offset = 0;			/* uninitialised var warning */
	while (height > 0) {
		if (slot == NULL) {
			/* Have to add a child node.  */
			if (!(slot = radix_tree_node_alloc(root)))
				return -ENOMEM;
			slot->height = height;
			if (node) {
				rcu_assign_pointer(node->slots[offset], slot);
				node->count++;
			} else
				rcu_assign_pointer(root->rnode,
					radix_tree_ptr_to_indirect(slot));
		}

		/* Go a level down */
		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
		node = slot;
		slot = node->slots[offset];
		shift -= RADIX_TREE_MAP_SHIFT;
		height--;
	}

	if (slot != NULL)
		return -EEXIST;

	if (node) {
		node->count++;
		rcu_assign_pointer(node->slots[offset], item);
		BUG_ON(tag_get(node, 0, offset));
		BUG_ON(tag_get(node, 1, offset));
	} else {
		rcu_assign_pointer(root->rnode, item);
		BUG_ON(root_tag_get(root, 0));
		BUG_ON(root_tag_get(root, 1));
	}

	return 0;
}
EXPORT_SYMBOL(radix_tree_insert);

/*
 * is_slot == 1 : search for the slot.
 * is_slot == 0 : search for the node.
 */
static void *radix_tree_lookup_element(struct radix_tree_root *root,
				unsigned long index, int is_slot)
{
	unsigned int height, shift;
	struct radix_tree_node *node, **slot;

	node = rcu_dereference(root->rnode);
	if (node == NULL)
		return NULL;

	if (!radix_tree_is_indirect_ptr(node)) {
		if (index > 0)
			return NULL;
		return is_slot ? (void *)&root->rnode : node;
	}
	node = radix_tree_indirect_to_ptr(node);

	height = node->height;
	if (index > radix_tree_maxindex(height))
		return NULL;

	shift = (height-1) * RADIX_TREE_MAP_SHIFT;

	do {
		slot = (struct radix_tree_node **)
			(node->slots + ((index>>shift) & RADIX_TREE_MAP_MASK));
		node = rcu_dereference(*slot);
		if (node == NULL)
			return NULL;

		shift -= RADIX_TREE_MAP_SHIFT;
		height--;
	} while (height > 0);

	return is_slot ? (void *)slot:node;
}

/**
 *	radix_tree_lookup_slot    -    lookup a slot in a radix tree
 *	@root:		radix tree root
 *	@index:		index key
 *
 *	Returns:  the slot corresponding to the position @index in the
 *	radix tree @root. This is useful for update-if-exists operations.
 *
 *	This function can be called under rcu_read_lock iff the slot is not
 *	modified by radix_tree_replace_slot, otherwise it must be called
 *	exclusive from other writers. Any dereference of the slot must be done
 *	using radix_tree_deref_slot.
 */
void **radix_tree_lookup_slot(struct radix_tree_root *root, unsigned long index)
{
	return (void **)radix_tree_lookup_element(root, index, 1);
}
EXPORT_SYMBOL(radix_tree_lookup_slot);

/**
 *	radix_tree_lookup    -    perform lookup operation on a radix tree
 *	@root:		radix tree root
 *	@index:		index key
 *
 *	Lookup the item at the position @index in the radix tree @root.
 *
 *	This function can be called under rcu_read_lock, however the caller
 *	must manage lifetimes of leaf nodes (eg. RCU may also be used to free
 *	them safely). No RCU barriers are required to access or modify the
 *	returned item, however.
 */
void *radix_tree_lookup(struct radix_tree_root *root, unsigned long index)
{
	return radix_tree_lookup_element(root, index, 0);
}
EXPORT_SYMBOL(radix_tree_lookup);

/**
 *	radix_tree_tag_set - set a tag on a radix tree node
 *	@root:		radix tree root
 *	@index:		index key
 *	@tag: 		tag index
 *
 *	Set the search tag (which must be < RADIX_TREE_MAX_TAGS)
 *	corresponding to @index in the radix tree.  From
 *	the root all the way down to the leaf node.
 *
 *	Returns the address of the tagged item.   Setting a tag on a not-present
 *	item is a bug.
 */
void *radix_tree_tag_set(struct radix_tree_root *root,
			unsigned long index, unsigned int tag)
{
	unsigned int height, shift;
	struct radix_tree_node *slot;

	height = root->height;
	BUG_ON(index > radix_tree_maxindex(height));

	slot = radix_tree_indirect_to_ptr(root->rnode);
	shift = (height - 1) * RADIX_TREE_MAP_SHIFT;

	while (height > 0) {
		int offset;

		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
		if (!tag_get(slot, tag, offset))
			tag_set(slot, tag, offset);
		slot = slot->slots[offset];
		BUG_ON(slot == NULL);
		shift -= RADIX_TREE_MAP_SHIFT;
		height--;
	}

	/* set the root's tag bit */
	if (slot && !root_tag_get(root, tag))
		root_tag_set(root, tag);

	return slot;
}
EXPORT_SYMBOL(radix_tree_tag_set);

/**
 *	radix_tree_tag_clear - clear a tag on a radix tree node
 *	@root:		radix tree root
 *	@index:		index key
 *	@tag: 		tag index
 *
 *	Clear the search tag (which must be < RADIX_TREE_MAX_TAGS)
 *	corresponding to @index in the radix tree.  If
 *	this causes the leaf node to have no tags set then clear the tag in the
 *	next-to-leaf node, etc.
 *
 *	Returns the address of the tagged item on success, else NULL.  ie:
 *	has the same return value and semantics as radix_tree_lookup().
 */
void *radix_tree_tag_clear(struct radix_tree_root *root,
			unsigned long index, unsigned int tag)
{
	/*
	 * The radix tree path needs to be one longer than the maximum path
	 * since the "list" is null terminated.
	 */
	struct radix_tree_path path[RADIX_TREE_MAX_PATH + 1], *pathp = path;
	struct radix_tree_node *slot = NULL;
	unsigned int height, shift;

	height = root->height;
	if (index > radix_tree_maxindex(height))
		goto out;

	shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
	pathp->node = NULL;
	slot = radix_tree_indirect_to_ptr(root->rnode);

	while (height > 0) {
		int offset;

		if (slot == NULL)
			goto out;

		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
		pathp[1].offset = offset;
		pathp[1].node = slot;
		slot = slot->slots[offset];
		pathp++;
		shift -= RADIX_TREE_MAP_SHIFT;
		height--;
	}

	if (slot == NULL)
		goto out;

	while (pathp->node) {
		if (!tag_get(pathp->node, tag, pathp->offset))
			goto out;
		tag_clear(pathp->node, tag, pathp->offset);
		if (any_tag_set(pathp->node, tag))
			goto out;
		pathp--;
	}

	/* clear the root's tag bit */
	if (root_tag_get(root, tag))
		root_tag_clear(root, tag);

out:
	return slot;
}
EXPORT_SYMBOL(radix_tree_tag_clear);

/**
 * radix_tree_tag_get - get a tag on a radix tree node
 * @root:		radix tree root
 * @index:		index key
 * @tag: 		tag index (< RADIX_TREE_MAX_TAGS)
 *
 * Return values:
 *
 *  0: tag not present or not set
 *  1: tag set
 */
int radix_tree_tag_get(struct radix_tree_root *root,
			unsigned long index, unsigned int tag)
{
	unsigned int height, shift;
	struct radix_tree_node *node;
	int saw_unset_tag = 0;

	/* check the root's tag bit */
	if (!root_tag_get(root, tag))
		return 0;

	node = rcu_dereference(root->rnode);
	if (node == NULL)
		return 0;

	if (!radix_tree_is_indirect_ptr(node))
		return (index == 0);
	node = radix_tree_indirect_to_ptr(node);

	height = node->height;
	if (index > radix_tree_maxindex(height))
		return 0;

	shift = (height - 1) * RADIX_TREE_MAP_SHIFT;

	for ( ; ; ) {
		int offset;

		if (node == NULL)
			return 0;

		offset = (index >> shift) & RADIX_TREE_MAP_MASK;

		/*
		 * This is just a debug check.  Later, we can bale as soon as
		 * we see an unset tag.
		 */
		if (!tag_get(node, tag, offset))
			saw_unset_tag = 1;
		if (height == 1) {
			int ret = tag_get(node, tag, offset);

			BUG_ON(ret && saw_unset_tag);
			return !!ret;
		}
		node = rcu_dereference(node->slots[offset]);
		shift -= RADIX_TREE_MAP_SHIFT;
		height--;
	}
}
EXPORT_SYMBOL(radix_tree_tag_get);

/**
 *	radix_tree_next_hole    -    find the next hole (not-present entry)
 *	@root:		tree root
 *	@index:		index key
 *	@max_scan:	maximum range to search
 *
 *	Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the lowest
 *	indexed hole.
 *
 *	Returns: the index of the hole if found, otherwise returns an index
 *	outside of the set specified (in which case 'return - index >= max_scan'
 *	will be true). In rare cases of index wrap-around, 0 will be returned.
 *
 *	radix_tree_next_hole may be called under rcu_read_lock. However, like
 *	radix_tree_gang_lookup, this will not atomically search a snapshot of
 *	the tree at a single point in time. For example, if a hole is created
 *	at index 5, then subsequently a hole is created at index 10,
 *	radix_tree_next_hole covering both indexes may return 10 if called
 *	under rcu_read_lock.
 */
unsigned long radix_tree_next_hole(struct radix_tree_root *root,
				unsigned long index, unsigned long max_scan)
{
	unsigned long i;

	for (i = 0; i < max_scan; i++) {
		if (!radix_tree_lookup(root, index))
			break;
		index++;
		if (index == 0)
			break;
	}

	return index;
}
EXPORT_SYMBOL(radix_tree_next_hole);

/**
 *	radix_tree_prev_hole    -    find the prev hole (not-present entry)
 *	@root:		tree root
 *	@index:		index key
 *	@max_scan:	maximum range to search
 *
 *	Search backwards in the range [max(index-max_scan+1, 0), index]
 *	for the first hole.
 *
 *	Returns: the index of the hole if found, otherwise returns an index
 *	outside of the set specified (in which case 'index - return >= max_scan'
 *	will be true). In rare cases of wrap-around, LONG_MAX will be returned.
 *
 *	radix_tree_next_hole may be called under rcu_read_lock. However, like
 *	radix_tree_gang_lookup, this will not atomically search a snapshot of
 *	the tree at a single point in time. For example, if a hole is created
 *	at index 10, then subsequently a hole is created at index 5,
 *	radix_tree_prev_hole covering both indexes may return 5 if called under
 *	rcu_read_lock.
 */
unsigned long radix_tree_prev_hole(struct radix_tree_root *root,
				   unsigned long index, unsigned long max_scan)
{
	unsigned long i;

	for (i = 0; i < max_scan; i++) {
		if (!radix_tree_lookup(root, index))
			break;
		index--;
		if (index == LONG_MAX)
			break;
	}

	return index;
}
EXPORT_SYMBOL(radix_tree_prev_hole);

static unsigned int
__lookup(struct radix_tree_node *slot, void ***results, unsigned long index,
	unsigned int max_items, unsigned long *next_index)
{
	unsigned int nr_found = 0;
	unsigned int shift, height;
	unsigned long i;

	height = slot->height;
	if (height == 0)
		goto out;
	shift = (height-1) * RADIX_TREE_MAP_SHIFT;

	for ( ; height > 1; height--) {
		i = (index >> shift) & RADIX_TREE_MAP_MASK;
		for (;;) {
			if (slot->slots[i] != NULL)
				break;
			index &= ~((1UL << shift) - 1);
			index += 1UL << shift;
			if (index == 0)
				goto out;	/* 32-bit wraparound */
			i++;
			if (i == RADIX_TREE_MAP_SIZE)
				goto out;
		}

		shift -= RADIX_TREE_MAP_SHIFT;
		slot = rcu_dereference(slot->slots[i]);
		if (slot == NULL)
			goto out;
	}

	/* Bottom level: grab some items */
	for (i = index & RADIX_TREE_MAP_MASK; i < RADIX_TREE_MAP_SIZE; i++) {
		index++;
		if (slot->slots[i]) {
			results[nr_found++] = &(slot->slots[i]);
			if (nr_found == max_items)
				goto out;
		}
	}
out:
	*next_index = index;
	return nr_found;
}

/**
 *	radix_tree_gang_lookup - perform multiple lookup on a radix tree
 *	@root:		radix tree root
 *	@results:	where the results of the lookup are placed
 *	@first_index:	start the lookup from this key
 *	@max_items:	place up to this many items at *results
 *
 *	Performs an index-ascending scan of the tree for present items.  Places
 *	them at *@results and returns the number of items which were placed at
 *	*@results.
 *
 *	The implementation is naive.
 *
 *	Like radix_tree_lookup, radix_tree_gang_lookup may be called under
 *	rcu_read_lock. In this case, rather than the returned results being
 *	an atomic snapshot of the tree at a single point in time, the semantics
 *	of an RCU protected gang lookup are as though multiple radix_tree_lookups
 *	have been issued in individual locks, and results stored in 'results'.
 */
unsigned int
radix_tree_gang_lookup(struct radix_tree_root *root, void **results,
			unsigned long first_index, unsigned int max_items)
{
	unsigned long max_index;
	struct radix_tree_node *node;
	unsigned long cur_index = first_index;
	unsigned int ret;

	node = rcu_dereference(root->rnode);
	if (!node)
		return 0;

	if (!radix_tree_is_indirect_ptr(node)) {
		if (first_index > 0)
			return 0;
		results[0] = node;
		return 1;
	}
	node = radix_tree_indirect_to_ptr(node);

	max_index = radix_tree_maxindex(node->height);

	ret = 0;
	while (ret < max_items) {
		unsigned int nr_found, slots_found, i;
		unsigned long next_index;	/* Index of next search */

		if (cur_index > max_index)
			break;
		slots_found = __lookup(node, (void ***)results + ret, cur_index,
					max_items - ret, &next_index);
		nr_found = 0;
		for (i = 0; i < slots_found; i++) {
			struct radix_tree_node *slot;
			slot = *(((void ***)results)[ret + i]);
			if (!slot)
				continue;
			results[ret + nr_found] = rcu_dereference(slot);
			nr_found++;
		}
		ret += nr_found;
		if (next_index == 0)
			break;
		cur_index = next_index;
	}

	return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup);

/**
 *	radix_tree_gang_lookup_slot - perform multiple slot lookup on radix tree
 *	@root:		radix tree root
 *	@results:	where the results of the lookup are placed
 *	@first_index:	start the lookup from this key
 *	@max_items:	place up to this many items at *results
 *
 *	Performs an index-ascending scan of the tree for present items.  Places
 *	their slots at *@results and returns the number of items which were
 *	placed at *@results.
 *
 *	The implementation is naive.
 *
 *	Like radix_tree_gang_lookup as far as RCU and locking goes. Slots must
 *	be dereferenced with radix_tree_deref_slot, and if using only RCU
 *	protection, radix_tree_deref_slot may fail requiring a retry.
 */
unsigned int
radix_tree_gang_lookup_slot(struct radix_tree_root *root, void ***results,
			unsigned long first_index, unsigned int max_items)
{
	unsigned long max_index;
	struct radix_tree_node *node;
	unsigned long cur_index = first_index;
	unsigned int ret;

	node = rcu_dereference(root->rnode);
	if (!node)
		return 0;

	if (!radix_tree_is_indirect_ptr(node)) {
		if (first_index > 0)
			return 0;
		results[0] = (void **)&root->rnode;
		return 1;
	}
	node = radix_tree_indirect_to_ptr(node);

	max_index = radix_tree_maxindex(node->height);

	ret = 0;
	while (ret < max_items) {
		unsigned int slots_found;
		unsigned long next_index;	/* Index of next search */

		if (cur_index > max_index)
			break;
		slots_found = __lookup(node, results + ret, cur_index,
					max_items - ret, &next_index);
		ret += slots_found;
		if (next_index == 0)
			break;
		cur_index = next_index;
	}

	return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup_slot);

/*
 * FIXME: the two tag_get()s here should use find_next_bit() instead of
 * open-coding the search.
 */
static unsigned int
__lookup_tag(struct radix_tree_node *slot, void ***results, unsigned long index,
	unsigned int max_items, unsigned long *next_index, unsigned int tag)
{
	unsigned int nr_found = 0;
	unsigned int shift, height;

	height = slot->height;
	if (height == 0)
		goto out;
	shift = (height-1) * RADIX_TREE_MAP_SHIFT;

	while (height > 0) {
		unsigned long i = (index >> shift) & RADIX_TREE_MAP_MASK ;

		for (;;) {
			if (tag_get(slot, tag, i))
				break;
			index &= ~((1UL << shift) - 1);
			index += 1UL << shift;
			if (index == 0)
				goto out;	/* 32-bit wraparound */
			i++;
			if (i == RADIX_TREE_MAP_SIZE)
				goto out;
		}
		height--;
		if (height == 0) {	/* Bottom level: grab some items */
			unsigned long j = index & RADIX_TREE_MAP_MASK;

			for ( ; j < RADIX_TREE_MAP_SIZE; j++) {
				index++;
				if (!tag_get(slot, tag, j))
					continue;
				/*
				 * Even though the tag was found set, we need to
				 * recheck that we have a non-NULL node, because
				 * if this lookup is lockless, it may have been
				 * subsequently deleted.
				 *
				 * Similar care must be taken in any place that
				 * lookup ->slots[x] without a lock (ie. can't
				 * rely on its value remaining the same).
				 */
				if (slot->slots[j]) {
					results[nr_found++] = &(slot->slots[j]);
					if (nr_found == max_items)
						goto out;
				}
			}
		}
		shift -= RADIX_TREE_MAP_SHIFT;
		slot = rcu_dereference(slot->slots[i]);
		if (slot == NULL)
			break;
	}
out:
	*next_index = index;
	return nr_found;
}

/**
 *	radix_tree_gang_lookup_tag - perform multiple lookup on a radix tree
 *	                             based on a tag
 *	@root:		radix tree root
 *	@results:	where the results of the lookup are placed
 *	@first_index:	start the lookup from this key
 *	@max_items:	place up to this many items at *results
 *	@tag:		the tag index (< RADIX_TREE_MAX_TAGS)
 *
 *	Performs an index-ascending scan of the tree for present items which
 *	have the tag indexed by @tag set.  Places the items at *@results and
 *	returns the number of items which were placed at *@results.
 */
unsigned int
radix_tree_gang_lookup_tag(struct radix_tree_root *root, void **results,
		unsigned long first_index, unsigned int max_items,
		unsigned int tag)
{
	struct radix_tree_node *node;
	unsigned long max_index;
	unsigned long cur_index = first_index;
	unsigned int ret;

	/* check the root's tag bit */
	if (!root_tag_get(root, tag))
		return 0;

	node = rcu_dereference(root->rnode);
	if (!node)
		return 0;

	if (!radix_tree_is_indirect_ptr(node)) {
		if (first_index > 0)
			return 0;
		results[0] = node;
		return 1;
	}
	node = radix_tree_indirect_to_ptr(node);

	max_index = radix_tree_maxindex(node->height);

	ret = 0;
	while (ret < max_items) {
		unsigned int nr_found, slots_found, i;
		unsigned long next_index;	/* Index of next search */

		if (cur_index > max_index)
			break;
		slots_found = __lookup_tag(node, (void ***)results + ret,
				cur_index, max_items - ret, &next_index, tag);
		nr_found = 0;
		for (i = 0; i < slots_found; i++) {
			struct radix_tree_node *slot;
			slot = *(((void ***)results)[ret + i]);
			if (!slot)
				continue;
			results[ret + nr_found] = rcu_dereference(slot);
			nr_found++;
		}
		ret += nr_found;
		if (next_index == 0)
			break;
		cur_index = next_index;
	}

	return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup_tag);

/**
 *	radix_tree_gang_lookup_tag_slot - perform multiple slot lookup on a
 *					  radix tree based on a tag
 *	@root:		radix tree root
 *	@results:	where the results of the lookup are placed
 *	@first_index:	start the lookup from this key
 *	@max_items:	place up to this many items at *results
 *	@tag:		the tag index (< RADIX_TREE_MAX_TAGS)
 *
 *	Performs an index-ascending scan of the tree for present items which
 *	have the tag indexed by @tag set.  Places the slots at *@results and
 *	returns the number of slots which were placed at *@results.
 */
unsigned int
radix_tree_gang_lookup_tag_slot(struct radix_tree_root *root, void ***results,
		unsigned long first_index, unsigned int max_items,
		unsigned int tag)
{
	struct radix_tree_node *node;
	unsigned long max_index;
	unsigned long cur_index = first_index;
	unsigned int ret;

	/* check the root's tag bit */
	if (!root_tag_get(root, tag))
		return 0;

	node = rcu_dereference(root->rnode);
	if (!node)
		return 0;

	if (!radix_tree_is_indirect_ptr(node)) {
		if (first_index > 0)
			return 0;
		results[0] = (void **)&root->rnode;
		return 1;
	}
	node = radix_tree_indirect_to_ptr(node);

	max_index = radix_tree_maxindex(node->height);

	ret = 0;
	while (ret < max_items) {
		unsigned int slots_found;
		unsigned long next_index;	/* Index of next search */

		if (cur_index > max_index)
			break;
		slots_found = __lookup_tag(node, results + ret,
				cur_index, max_items - ret, &next_index, tag);
		ret += slots_found;
		if (next_index == 0)
			break;
		cur_index = next_index;
	}

	return ret;
}
EXPORT_SYMBOL(radix_tree_gang_lookup_tag_slot);

/**
 *	radix_tree_shrink    -    shrink height of a radix tree to minimal
 *	@root		radix tree root
 */
static inline void radix_tree_shrink(struct radix_tree_root *root)
{
	/* try to shrink tree height */
	while (root->height > 0) {
		struct radix_tree_node *to_free = root->rnode;
		void *newptr;

		BUG_ON(!radix_tree_is_indirect_ptr(to_free));
		to_free = radix_tree_indirect_to_ptr(to_free);

		/*
		 * The candidate node has more than one child, or its child
		 * is not at the leftmost slot, we cannot shrink.
		 */
		if (to_free->count != 1)
			break;
		if (!to_free->slots[0])
			break;

		/*
		 * We don't need rcu_assign_pointer(), since we are simply
		 * moving the node from one part of the tree to another. If
		 * it was safe to dereference the old pointer to it
		 * (to_free->slots[0]), it will be safe to dereference the new
		 * one (root->rnode).
		 */
		newptr = to_free->slots[0];
		if (root->height > 1)
			newptr = radix_tree_ptr_to_indirect(newptr);
		root->rnode = newptr;
		root->height--;
		radix_tree_node_free(to_free);
	}
}

/**
 *	radix_tree_delete    -    delete an item from a radix tree
 *	@root:		radix tree root
 *	@index:		index key
 *
 *	Remove the item at @index from the radix tree rooted at @root.
 *
 *	Returns the address of the deleted item, or NULL if it was not present.
 */
void *radix_tree_delete(struct radix_tree_root *root, unsigned long index)
{
	/*
	 * The radix tree path needs to be one longer than the maximum path
	 * since the "list" is null terminated.
	 */
	struct radix_tree_path path[RADIX_TREE_MAX_PATH + 1], *pathp = path;
	struct radix_tree_node *slot = NULL;
	struct radix_tree_node *to_free;
	unsigned int height, shift;
	int tag;
	int offset;

	height = root->height;
	if (index > radix_tree_maxindex(height))
		goto out;

	slot = root->rnode;
	if (height == 0) {
		root_tag_clear_all(root);
		root->rnode = NULL;
		goto out;
	}
	slot = radix_tree_indirect_to_ptr(slot);

	shift = (height - 1) * RADIX_TREE_MAP_SHIFT;
	pathp->node = NULL;

	do {
		if (slot == NULL)
			goto out;

		pathp++;
		offset = (index >> shift) & RADIX_TREE_MAP_MASK;
		pathp->offset = offset;
		pathp->node = slot;
		slot = slot->slots[offset];
		shift -= RADIX_TREE_MAP_SHIFT;
		height--;
	} while (height > 0);

	if (slot == NULL)
		goto out;

	/*
	 * Clear all tags associated with the just-deleted item
	 */
	for (tag = 0; tag < RADIX_TREE_MAX_TAGS; tag++) {
		if (tag_get(pathp->node, tag, pathp->offset))
			radix_tree_tag_clear(root, index, tag);
	}

	to_free = NULL;
	/* Now free the nodes we do not need anymore */
	while (pathp->node) {
		pathp->node->slots[pathp->offset] = NULL;
		pathp->node->count--;
		/*
		 * Queue the node for deferred freeing after the
		 * last reference to it disappears (set NULL, above).
		 */
		if (to_free)
			radix_tree_node_free(to_free);

		if (pathp->node->count) {
			if (pathp->node ==
					radix_tree_indirect_to_ptr(root->rnode))
				radix_tree_shrink(root);
			goto out;
		}

		/* Node with zero slots in use so free it */
		to_free = pathp->node;
		pathp--;

	}
	root_tag_clear_all(root);
	root->height = 0;
	root->rnode = NULL;
	if (to_free)
		radix_tree_node_free(to_free);

out:
	return slot;
}
EXPORT_SYMBOL(radix_tree_delete);

/**
 *	radix_tree_tagged - test whether any items in the tree are tagged
 *	@root:		radix tree root
 *	@tag:		tag to test
 */
int radix_tree_tagged(struct radix_tree_root *root, unsigned int tag)
{
	return root_tag_get(root, tag);
}
EXPORT_SYMBOL(radix_tree_tagged);

static void
radix_tree_node_ctor(void *node)
{
	memset(node, 0, sizeof(struct radix_tree_node));
}

static __init unsigned long __maxindex(unsigned int height)
{
	unsigned int width = height * RADIX_TREE_MAP_SHIFT;
	int shift = RADIX_TREE_INDEX_BITS - width;

	if (shift < 0)
		return ~0UL;
	if (shift >= BITS_PER_LONG)
		return 0UL;
	return ~0UL >> shift;
}

static __init void radix_tree_init_maxindex(void)
{
	unsigned int i;

	for (i = 0; i < ARRAY_SIZE(height_to_maxindex); i++)
		height_to_maxindex[i] = __maxindex(i);
}

static int radix_tree_callback(struct notifier_block *nfb,
                            unsigned long action,
                            void *hcpu)
{
       int cpu = (long)hcpu;
       struct radix_tree_preload *rtp;

       /* Free per-cpu pool of perloaded nodes */
       if (action == CPU_DEAD || action == CPU_DEAD_FROZEN) {
               rtp = &per_cpu(radix_tree_preloads, cpu);
               while (rtp->nr) {
                       kmem_cache_free(radix_tree_node_cachep,
                                       rtp->nodes[rtp->nr-1]);
                       rtp->nodes[rtp->nr-1] = NULL;
                       rtp->nr--;
               }
       }
       return NOTIFY_OK;
}

void __init radix_tree_init(void)
{
	radix_tree_node_cachep = kmem_cache_create("radix_tree_node",
			sizeof(struct radix_tree_node), 0,
			SLAB_PANIC | SLAB_RECLAIM_ACCOUNT,
			radix_tree_node_ctor);
	radix_tree_init_maxindex();
	hotcpu_notifier(radix_tree_callback, 0);
}


text:
/**
 * PatientKeyPerformanceIndicatorService.java
 *
 * Project: projecth
 *
 * @author mobileman
 * @date 14.1.2011
 * @version 1.0
 *
 * (c) 2010 MobileMan GmbH
 */

package com.mobileman.projecth.business.patient;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.mobileman.projecth.business.SearchService;
import com.mobileman.projecth.domain.dto.patient.kpi.KeyPerformanceIndicatorStatistics;
import com.mobileman.projecth.domain.index.kpi.KeyPerformanceIndicatorType;
import com.mobileman.projecth.domain.patient.kpi.PatientKeyPerformanceIndicator;

/**
 * Service performing various KPI computations for a patient
 *
 * @author mobileman
 *
 */
public interface PatientKPIService extends SearchService<PatientKeyPerformanceIndicator> {

	/**
	 * @param patientId
	 * @param kpiTypeId
	 * @param startDate
	 * @param endDate
	 * @return computed KPI value based on given type of
	 *         {@link KeyPerformanceIndicatorType} in given time window for a
	 *         patient
	 * @throws IllegalArgumentException
	 *             if
patientId == null

kpiTypeId == null

	 *             startDate == null

endDate == null

	 */
	BigDecimal computeKPI(Long patientId, Long kpiTypeId, Date startDate, Date endDate) throws IllegalArgumentException;

	/**
	 * Computes KPI values for giben type of {@link KeyPerformanceIndicatorType} in given time window for a
	 * patient
	 * @param patientId
	 * @param kpiTypeId
	 * @param startDate
	 * @param endDate
	 * @return computed list of computed KPI values for giben type of
	 *         {@link KeyPerformanceIndicatorType} in given time window for a
	 *         patient
	 * @throws IllegalArgumentException if
	 *
patientId == null

	 *
kpiTypeId == null

	 *
startDate == null

	 *
endDate == null

	 */
	List<KeyPerformanceIndicatorStatistics> computeKPITimeline(Long patientId, Long kpiTypeId, Date startDate,
			Date endDate) throws IllegalArgumentException;

	/**
	 * Computes KPI average values for giben type of {@link KeyPerformanceIndicatorType} in given time window
	 * @param kpiTypeId
	 * @param startDate
	 * @param endDate
	 * @return computed list of computed KPI average values for giben type of
	 *         {@link KeyPerformanceIndicatorType} in given time window
	 * @throws IllegalArgumentException if
	 *
kpiTypeId == null

	 *
startDate == null

	 *
endDate == null

	 */
	List<KeyPerformanceIndicatorStatistics> computeKPIAverageTimeline(Long kpiTypeId, Date startDate,
			Date endDate) throws IllegalArgumentException;
}


text:
from __future__ import print_function

from math import sin, cos, atan2, sqrt, pi, radians

import numpy as np
import pandas as pd
import scipy.ndimage as im

from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.resources import INLINE
from bokeh.browserlib import view

from bokeh.glyphs import Line, Patches
from bokeh.widgets import VBox
from bokeh.objects import (
    Plot, GMapPlot, MapOptions,
    Range1d, DataRange1d,
    ColumnDataSource,
    LinearAxis, Grid,
    PanTool, WheelZoomTool, ResetTool, BoxSelectTool, HoverTool)

from bokeh.sampledata.mtb import obiszow_mtb_xcm

def haversin(theta):
    return sin(0.5*theta)**2

def distance(p1, p2):
    """Distance between (lat1, lon1) and (lat2, lon2). """
    R = 6371

    lat1, lon1 = p1
    lat2, lon2 = p2

    phi1 = radians(lat1)
    phi2 = radians(lat2)
    delta_lat = radians(lat2 - lat1)
    delta_lon = radians(lon2 - lon1)

    a = haversin(delta_lat) + cos(phi1)*cos(phi2)*haversin(delta_lon)
    return 2*R*atan2(sqrt(a), sqrt(1-a))

def prep_data(dataset):
    df = dataset.copy()

    latlon = list(zip(df.lat, df.lon))
    dist = np.array([ distance(latlon[i+1], latlon[i]) for i in range(len((latlon[:-1]))) ])

    df["dist"] = np.concatenate(([0], np.cumsum(dist)))

    slope = np.abs(100*np.diff(df.alt)/(1000*dist))
    slope[np.where(                 slope <  4) ] = 0 # "green"
    slope[np.where((slope >=  4) & (slope <  6))] = 1 # "yellow"
    slope[np.where((slope >=  6) & (slope < 10))] = 2 # "pink"
    slope[np.where((slope >= 10) & (slope < 15))] = 3 # "orange"
    slope[np.where( slope >= 15                )] = 4 # "red"
    slope = im.median_filter(slope, 6)

    colors = np.empty_like(slope, dtype=object)
    colors[np.where(slope == 0)] = "green"
    colors[np.where(slope == 1)] = "yellow"
    colors[np.where(slope == 2)] = "pink"
    colors[np.where(slope == 3)] = "orange"
    colors[np.where(slope == 4)] = "red"
    df["colors"] = list(colors) + [None]              # NOTE: add [None] just make pandas happy

    return df

title = "Obiszów MTB XCM"

def trail_map(data):
    lon = (min(data.lon) + max(data.lon))/2
    lat = (min(data.lat) + max(data.lat))/2

    map_options = MapOptions(lng=lon, lat=lat, zoom=13)
    plot = GMapPlot(title="%s - Trail Map" % title, map_options=map_options, plot_width=800, plot_height=800)

    xaxis = LinearAxis()
    plot.add_layout(xaxis, 'below')

    yaxis = LinearAxis()
    plot.add_layout(yaxis, 'left')

    xgrid = Grid(plot=plot, dimension=0, ticker=xaxis.ticker, grid_line_dash="dashed", grid_line_color="gray")
    ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker, grid_line_dash="dashed", grid_line_color="gray")
    plot.renderers.extend([xgrid, ygrid])

    hover = HoverTool(tooltips=dict(distance="@dist"))
    plot.add_tools(hover, PanTool(), WheelZoomTool(), ResetTool(), BoxSelectTool())

    line_source = ColumnDataSource(dict(x=data.lon, y=data.lat, dist=data.dist))

    line = Line(x="x", y="y", line_color="blue", line_width=2)
    plot.add_glyph(line_source, line)

    plot.x_range = DataRange1d(sources=[line_source.columns("x")])
    plot.y_range = DataRange1d(sources=[line_source.columns("y")])

    return plot

def altitude_profile(data):
    plot = Plot(title="%s - Altitude Profile" % title, plot_width=800, plot_height=400)

    xaxis = LinearAxis(axis_label="Distance (km)")
    plot.add_layout(xaxis, 'below')

    yaxis = LinearAxis(axis_label="Altitude (m)")
    plot.add_layout(yaxis, 'left')

    xgrid = Grid(plot=plot, dimension=0, ticker=xaxis.ticker)
    ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker)
    plot.renderers.extend([xgrid, ygrid])

    plot.add_tools(PanTool(), WheelZoomTool(), ResetTool(), BoxSelectTool())

    X, Y = data.dist, data.alt
    y0 = min(Y)

    patches_source = ColumnDataSource(dict(
        xs = [ [X[i], X[i+1], X[i+1], X[i]] for i in range(len(X[:-1])) ],
        ys = [ [y0,   y0,     Y[i+1], Y[i]] for i in range(len(Y[:-1])) ],
        color = data.colors[:-1]
    ))

    patches = Patches(xs="xs", ys="ys", fill_color="color", line_color="color")
    plot.add_glyph(patches_source, patches)

    line_source = ColumnDataSource(dict(
        x = data.dist,
        y = data.alt,
    ))

    line = Line(x='x', y='y', line_color="black", line_width=1)
    plot.add_glyph(line_source, line)

    plot.x_range = DataRange1d(sources=[line_source.columns("x")])
    plot.y_range = DataRange1d(sources=[line_source.columns("y")])

    return plot

data = prep_data(obiszow_mtb_xcm)

trail = trail_map(data)
altitude = altitude_profile(data)

layout = VBox(children=[altitude, trail])

doc = Document()
doc.add(layout)

if __name__ == "__main__":
    filename = "trail.html"
    with open(filename, "w") as f:
        f.write(file_html(doc, INLINE, "Trail map and altitude profile"))
    print("Wrote %s" % filename)
    view(filename)


text:
Implementation of TSDB storage plugin. Plugin uses REST API to work with TSDB.

For more information about openTSDB follow this link <http://opentsdb.net>

There is list of required params:

* metric     - The name of a metric stored in the db.

* start      - The start time for the query. This can be a relative or absolute timestamp.

* aggregator - The name of an aggregation function to use.

optional param is:

* downsample - An optional downsampling function to reduce the amount of data returned.

* end - An end time for the query. If not supplied, the TSD will assume the local system time on the server.
This may be a relative or absolute timestamp. This param is optional, and if it isn't specified we will send null
to the db in this field, but in this case db will assume the local system time on the server.

List of supported aggregators

<http://opentsdb.net/docs/build/html/user_guide/query/aggregators.html>

List of supported time

<http://opentsdb.net/docs/build/html/user_guide/query/dates.html>

Params must be specified in FROM clause of the query separated by commas. For example

`opentsdb.(metric=metric_name, start=4d-ago, aggregator=sum)`

Supported queries for now are listed below:

```
USE opentsdb
```

```
SHOW tables
```
Will print available metrics. Max number of the printed results is a Integer.MAX value

```
SELECT * FROM opentsdb. `(metric=warp.speed.test, start=47y-ago, aggregator=sum)`
```
Return aggregated elements from `warp.speed.test` table since 47y-ago

```
SELECT * FROM opentsdb.`(metric=warp.speed.test, aggregator=avg, start=47y-ago)`
```
Return aggregated elements from `warp.speed.test` table

```
SELECT `timestamp`, sum(`aggregated value`) FROM opentsdb.`(metric=warp.speed.test, aggregator=avg, start=47y-ago)` GROUP BY `timestamp`
```
Return aggregated and grouped value by standard drill functions from `warp.speed.test table`, but with the custom aggregator

```
SELECT * FROM opentsdb.`(metric=warp.speed.test, aggregator=avg, start=47y-ago, downsample=5m-avg)`
```
Return aggregated data limited by downsample

```
SELECT * FROM opentsdb.`(metric=warp.speed.test, aggregator=avg, start=47y-ago, end=1407165403000)`
```
Return aggregated data limited by end time


text:
<?php

  namespace osCommerce\OM\Core\Site\Admin\Application\CoreUpdate\Model;

  use osCommerce\OM\Core\Site\Admin\Application\CoreUpdate\CoreUpdate;

  class findPackageContents {
    public static function execute($search) {
      $result = CoreUpdate::getPackageContents();

      foreach ( $result['entries'] as $k => $v ) {
        if ( stripos($v['name'], $search) === false ) {
          unset($result['entries'][$k]);
        }
      }

      $result['total'] = count($result['entries']);

      return $result;
    }
  }
?>


text:
/*
 * vtkIGTLIODeviceFactory.h
 *
 *  Created on: 21. jan. 2016
 *      Author: cas
 */

#ifndef IGTLIODEVICEFACTORY_H_
#define IGTLIODEVICEFACTORY_H_

#include <map>
#include <string>

// VTK includes
#include <vtkObject.h>
#include <vtkSmartPointer.h>

// IGTLIO includes
#include "igtlioLogicExport.h"
#include "igtlioDevice.h"

typedef vtkSmartPointer<class igtlioDeviceCreator> igtlioDeviceCreatorPointer;
typedef vtkSmartPointer<class igtlioDeviceFactory> igtlioDeviceFactoryPointer;

class OPENIGTLINKIO_LOGIC_EXPORT igtlioDeviceFactory : public vtkObject
{
 public:
  static igtlioDeviceFactory *New();
  vtkTypeMacro(igtlioDeviceFactory,vtkObject);

  void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE;

  igtlioDeviceCreatorPointer GetCreator(std::string device_type) const;
  std::vector<std::string> GetAvailableDeviceTypes() const;

  // Create a Device object based on an input device_type
  // TODO: Should we accept prefixed message types as well?
  igtlioDevicePointer create(std::string device_type, std::string device_name) const;

protected:
  igtlioDeviceFactory();
  virtual ~igtlioDeviceFactory();

  // Register a factory for a specific Device Type.
  template<class CREATOR_TYPE>
  void registerCreator();

  std::map<std::string, igtlioDeviceCreatorPointer> Creators;
};

#endif /* IGTLIODEVICEFACTORY_H_ */


text:
//
//  MediaTableViewCell.m
//  instagram-clone
//
//  Created by Jordan Carlson on 6/2/16.
//  Copyright © 2016 savagej. All rights reserved.
//

#import "MediaTableViewCell.h"
#import "Media.h"
#import "Comment.h"
#import "User.h"
#import "LikeButton.h"
#import "ComposeCommentView.h"

@interface MediaTableViewCell () <UIGestureRecognizerDelegate, ComposeCommentViewDelegate>

@property (nonatomic, strong) UIImageView *mediaImageView;
@property (nonatomic, strong) UILabel *usernameAndCaptionLabel;
@property (nonatomic, strong) UILabel *commentLabel;
@property (nonatomic, strong) NSLayoutConstraint *imageHeightConstraint;
@property (nonatomic, strong) NSLayoutConstraint *usernameAndCaptionLabelHeightConstraint;
@property (nonatomic, strong) NSLayoutConstraint *commentLabelHeightConstraint;
@property (nonatomic, strong) UITapGestureRecognizer *tapGestureRecognizer;
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGestureRecognizer;
@property (nonatomic, strong) LikeButton *likeButton;
@property (nonatomic, strong) ComposeCommentView *commentView;
@property (nonatomic, strong) NSArray *horizontallyRegularConstraints;
@property (nonatomic, strong) NSArray *horizontallyCompactConstraints;

@end

static UIFont *lightFont;
static UIFont *boldFont;
static UIColor *usernameLabelGray;
static UIColor *commentLabelGray;
static UIColor *linkColor;
static NSParagraphStyle *paragraphStyle;

@implementation MediaTableViewCell

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:NO animated:animated];

}

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    [super setHighlighted:NO animated:animated];
}

+ (void)load {
    lightFont = [UIFont fontWithName:@"HelveticaNeue-Thin" size:11];
    boldFont = [UIFont fontWithName:@"HelveticaNeue-Bold" size:11];
    usernameLabelGray = [UIColor colorWithRed:0.933 green:0.933 blue:0.933 alpha:1]; /*#eeeeee*/
    commentLabelGray = [UIColor colorWithRed:0.898 green:0.898 blue:0.898 alpha:1]; /*#e5e5e5*/
    linkColor = [UIColor colorWithRed:0.345 green:0.314 blue:0.427 alpha:1]; /*#58506d*/

    NSMutableParagraphStyle *mutableParagraphStyle = [[NSMutableParagraphStyle alloc] init];
    mutableParagraphStyle.headIndent = 20.0;
    mutableParagraphStyle.firstLineHeadIndent = 20.0;
    mutableParagraphStyle.tailIndent = -20.0;
    mutableParagraphStyle.paragraphSpacingBefore = 5;

    paragraphStyle = mutableParagraphStyle;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        self.mediaImageView = [[UIImageView alloc] init];
        self.mediaImageView.userInteractionEnabled = YES;

        self.tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapFired:)];
        self.tapGestureRecognizer.delegate = self;
        [self.mediaImageView addGestureRecognizer:self.tapGestureRecognizer];

        self.longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressFired:)];
        self.longPressGestureRecognizer.delegate = self;
        [self.mediaImageView addGestureRecognizer:self.longPressGestureRecognizer];

        self.usernameAndCaptionLabel = [[UILabel alloc] init];
        self.usernameAndCaptionLabel.numberOfLines = 0;
        self.usernameAndCaptionLabel.backgroundColor = usernameLabelGray;

        self.commentLabel = [[UILabel alloc] init];
        self.commentLabel.numberOfLines = 0;
        self.commentLabel.backgroundColor = commentLabelGray;

        self.likeButton = [[LikeButton alloc] init];
        [self.likeButton addTarget:self action:@selector(likePressed:) forControlEvents:UIControlEventTouchUpInside];
        self.likeButton.backgroundColor = usernameLabelGray;

        self.commentView = [[ComposeCommentView alloc] init];
        self.commentView.delegate = self;

        for (UIView *view in @[self.mediaImageView, self.usernameAndCaptionLabel, self.commentLabel, self.likeButton, self.commentView]) {
            [self.contentView addSubview:view];
            view.translatesAutoresizingMaskIntoConstraints = NO;

        }

        NSDictionary *viewDictionary = NSDictionaryOfVariableBindings(_mediaImageView, _usernameAndCaptionLabel, _commentLabel, _likeButton, _commentView);

        self.horizontallyCompactConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_mediaImageView]|" options:kNilOptions metrics:nil views:viewDictionary];

        NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:_mediaImageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:320];
        NSLayoutConstraint *centerConstraint = [NSLayoutConstraint constraintWithItem:self.contentView
                                                                            attribute:NSLayoutAttributeCenterX
                                                                            relatedBy:0
                                                                               toItem:_mediaImageView
                                                                            attribute:NSLayoutAttributeCenterX
                                                                           multiplier:1
                                                                             constant:0];

        self.horizontallyRegularConstraints = @[widthConstraint, centerConstraint];

        if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
            /* It's compact! */
            [self.contentView addConstraints:self.horizontallyCompactConstraints];
        } else if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassRegular) {
            /* It's regular! */
            [self.contentView addConstraints:self.horizontallyRegularConstraints];
        }

        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_usernameAndCaptionLabel][_likeButton(==38)]|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:nil views:viewDictionary]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_commentLabel]|" options:kNilOptions metrics:nil views:viewDictionary]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_commentView]|" options:kNilOptions metrics:nil views:viewDictionary]];

        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_mediaImageView][_usernameAndCaptionLabel][_commentLabel][_commentView(==100)]"
                                                                                options:kNilOptions
                                                                                metrics:nil
                                                                                views:viewDictionary]];

        self.imageHeightConstraint = [NSLayoutConstraint constraintWithItem:_mediaImageView
                                                                  attribute:NSLayoutAttributeHeight
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:nil
                                                                  attribute:NSLayoutAttributeNotAnAttribute
                                                                 multiplier:1
                                                                   constant:100];
        self.imageHeightConstraint.identifier = @"Image height constraint";

        self.usernameAndCaptionLabelHeightConstraint = [NSLayoutConstraint constraintWithItem:_usernameAndCaptionLabel
                                                                                attribute:NSLayoutAttributeHeight
                                                                                relatedBy:NSLayoutRelationEqual
                                                                                toItem:nil
                                                                                attribute:NSLayoutAttributeNotAnAttribute
                                                                                multiplier:1
                                                                                constant:100];
        self.usernameAndCaptionLabelHeightConstraint.identifier = @"Username and caption label height constraint";

        self.commentLabelHeightConstraint = [NSLayoutConstraint constraintWithItem:_commentLabel
                                                                         attribute:NSLayoutAttributeHeight
                                                                         relatedBy:NSLayoutRelationEqual
                                                                            toItem:nil
                                                                         attribute:NSLayoutAttributeNotAnAttribute
                                                                        multiplier:1
                                                                          constant:100];
        self.commentLabelHeightConstraint.identifier = @"Comment label height constraint";

        [self.contentView addConstraints:@[self.imageHeightConstraint, self.usernameAndCaptionLabelHeightConstraint, self.commentLabelHeightConstraint]];
    }
    return self;
}

- (NSAttributedString *) usernameAndCaptionString {
    // #1
    CGFloat usernameFontSize = 15;

    // #2 - Make a string that says "username caption"
    NSString *baseString = [NSString stringWithFormat:@"%@ %@", self.mediaItem.user.userName, self.mediaItem.caption];

    // #3 - Make an attributed string, with the "username" bold
    NSMutableAttributedString *mutableUsernameAndCaptionString = [[NSMutableAttributedString alloc] initWithString:baseString attributes:@{NSFontAttributeName : [lightFont fontWithSize:usernameFontSize], NSParagraphStyleAttributeName : paragraphStyle}];

    // #4
    NSRange usernameRange = [baseString rangeOfString:self.mediaItem.user.userName];
    [mutableUsernameAndCaptionString addAttribute:NSFontAttributeName value:[boldFont fontWithSize:usernameFontSize] range:usernameRange];
    [mutableUsernameAndCaptionString addAttribute:NSForegroundColorAttributeName value:linkColor range:usernameRange];

    return mutableUsernameAndCaptionString;
}

- (NSAttributedString *) commentString {
    NSMutableAttributedString *commentString = [[NSMutableAttributedString alloc] init];

    for (Comment *comment in self.mediaItem.comments) {
        // Make a string that says "username comment" followed by a line break
        NSString *baseString = [NSString stringWithFormat:@"%@ %@\n", comment.from.userName, comment.text];

        // Make an attributed string, with the "username" bold

        NSMutableAttributedString *oneCommentString = [[NSMutableAttributedString alloc] initWithString:baseString attributes:@{NSFontAttributeName : lightFont, NSParagraphStyleAttributeName : paragraphStyle}];

        NSRange usernameRange = [baseString rangeOfString:comment.from.userName];
        [oneCommentString addAttribute:NSFontAttributeName value:boldFont range:usernameRange];
        [oneCommentString addAttribute:NSForegroundColorAttributeName value:linkColor range:usernameRange];

        [commentString appendAttributedString:oneCommentString];
    }

    return commentString;
}

- (void) layoutSubviews {
    [super layoutSubviews];

    if (!self.mediaItem) {
        return;
    }
    // Before layout, calculate the intrinsic size of the labels (the size they "want" to be), and add 20 to the height for some vertical padding.
    CGSize maxSize = CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX);
    CGSize usernameLabelSize = [self.usernameAndCaptionLabel sizeThatFits:maxSize];
    CGSize commentLabelSize = [self.commentLabel sizeThatFits:maxSize];

    self.usernameAndCaptionLabelHeightConstraint.constant = usernameLabelSize.height == 0 ? 0 : usernameLabelSize.height + 20;
    self.commentLabelHeightConstraint.constant = commentLabelSize.height == 0 ? 0 : commentLabelSize.height + 20;

    if (self.mediaItem.image.size.width > 0 && CGRectGetWidth(self.contentView.bounds) > 0) {
        if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
            /* It's compact! */
            self.imageHeightConstraint.constant = self.mediaItem.image.size.height / self.mediaItem.image.size.width * CGRectGetWidth(self.contentView.bounds);
        } else if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassRegular) {
            /* It's regular! */
            self.imageHeightConstraint.constant = 320;
        }
    } else {
        self.imageHeightConstraint.constant = 0;
    }
    // Hide the line between cells
    self.separatorInset = UIEdgeInsetsMake(0, CGRectGetWidth(self.bounds)/2.0, 0, CGRectGetWidth(self.bounds)/2.0);
}

- (void) setMediaItem:(Media *)mediaItem {
    _mediaItem = mediaItem;
    self.mediaImageView.image = _mediaItem.image;
    self.usernameAndCaptionLabel.attributedText = [self usernameAndCaptionString];
    self.commentLabel.attributedText = [self commentString];
    self.likeButton.likeButtonState = mediaItem.likeState;
    self.commentView.text = mediaItem.temporaryComment;

}

+ (CGFloat) heightForMediaItem:(Media *)mediaItem width:(CGFloat)width traitCollection:(UITraitCollection *) traitCollection {
    // Make a cell
    MediaTableViewCell *layoutCell = [[MediaTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"layoutCell"];

    layoutCell.mediaItem = mediaItem;

    layoutCell.frame = CGRectMake(0, 0, width, CGRectGetHeight(layoutCell.frame));

    layoutCell.overrideTraitCollection = traitCollection;

    [layoutCell setNeedsLayout];
    [layoutCell layoutIfNeeded];

    return CGRectGetMaxY(layoutCell.commentView.frame);

}

- (void) traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact) {
        /* It's compact! */
        [self.contentView removeConstraints:self.horizontallyRegularConstraints];
        [self.contentView addConstraints:self.horizontallyCompactConstraints];
    } else if (self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassRegular) {
        /* It's regular */
        [self.contentView removeConstraints:self.horizontallyCompactConstraints];
        [self.contentView addConstraints:self.horizontallyRegularConstraints];
    }
}
- (UITraitCollection *) traitCollection {
    if (self.overrideTraitCollection) {
        return self.overrideTraitCollection;
    }

    return [super traitCollection];
}
#pragma mark - Image View

- (void) tapFired:(UITapGestureRecognizer *)sender {
    [self.delegate cell:self didTapImageView:self.mediaImageView];
}

- (void) longPressFired:(UILongPressGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateBegan) {
        [self.delegate cell:self didLongPressImageView:self.mediaImageView];
    }
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return self.isEditing == NO;
}

#pragma mark - Liking

- (void) likePressed:(UIButton *)sender {
    [self.delegate cellDidPressLikeButton:self];
}

#pragma mark - ComposeCommentViewDelegate

- (void) commentViewDidPressCommentButton:(ComposeCommentView *)sender {
    [self.delegate cell:self didComposeComment:self.mediaItem.temporaryComment];
}

- (void) commentView:(ComposeCommentView *)sender textDidChange:(NSString *)text {
    self.mediaItem.temporaryComment = text;
}

- (void) commentViewWillStartEditing:(ComposeCommentView *)sender {
    [self.delegate cellWillStartComposingComment:self];
}

- (void) stopComposingComment {
    [self.commentView stopComposingComment];
}

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BACnet.Types;

namespace BACnet.Ashrae.Objects
{
    public interface IAnalogInput
    {
        [PropertyId(PropertyIdentifier.ObjectIdentifier)]
        ObjectId ObjectIdentifier { get; }

        [PropertyId(PropertyIdentifier.ObjectName)]
        string ObjectName { get; }

        [PropertyId(PropertyIdentifier.ObjectType)]
        ObjectType ObjectType { get; }

        [PropertyId(PropertyIdentifier.PresentValue)]
        float PresentValue { get; }

        [PropertyId(PropertyIdentifier.Description)]
        Option<string> Description { get; }

        [PropertyId(PropertyIdentifier.DeviceType)]
        Option<string> DeviceType { get; }

        [PropertyId(PropertyIdentifier.StatusFlags)]
        StatusFlags StatusFlags { get; }

        [PropertyId(PropertyIdentifier.EventState)]
        EventState EventState { get; }

        [PropertyId(PropertyIdentifier.Reliability)]
        Option<Reliability> Reliability { get; }

        [PropertyId(PropertyIdentifier.OutOfService)]
        bool OutOfService { get; }

        [PropertyId(PropertyIdentifier.UpdateInterval)]
        Option<uint> UpdateInterval { get; }

        [PropertyId(PropertyIdentifier.Units)]
        EngineeringUnits Units { get; }

        [PropertyId(PropertyIdentifier.MinPresValue)]
        Option<float> MinPresValue { get; }

        [PropertyId(PropertyIdentifier.MaxPresValue)]
        Option<float> MaxPresValue { get; }

        [PropertyId(PropertyIdentifier.Resolution)]
        Option<float> Resolution { get; }

        [PropertyId(PropertyIdentifier.CovIncrement)]
        Option<float> CovIncrement { get; }

        [PropertyId(PropertyIdentifier.TimeDelay)]
        Option<uint> TimeDelay { get; }

        [PropertyId(PropertyIdentifier.NotificationClass)]
        Option<uint> NotificationClass { get; }

        [PropertyId(PropertyIdentifier.HighLimit)]
        Option<float> HighLimit { get; }

        [PropertyId(PropertyIdentifier.LowLimit)]
        Option<float> LowLimit { get; }

        [PropertyId(PropertyIdentifier.Deadband)]
        Option<float> Deadband { get; }

        [PropertyId(PropertyIdentifier.LimitEnable)]
        Option<LimitEnable> LimitEnable { get; }

        [PropertyId(PropertyIdentifier.EventEnable)]
        Option<EventTransitionBits> EventEnable { get; }

        [PropertyId(PropertyIdentifier.AckedTransitions)]
        Option<EventTransitionBits> AckedTransitions { get; }

        [PropertyId(PropertyIdentifier.NotifyType)]
        Option<NotifyType> NotifyType { get; }

        [PropertyId(PropertyIdentifier.EventTimeStamps)]
        Option<ReadOnlyArray<TimeStamp>> EventTimeStamps { get; }

        [PropertyId(PropertyIdentifier.ProfileName)]
        Option<string> ProfileName { get; }
    }
}


text:
package uk.co.senab.photup.base;

import com.actionbarsherlock.app.SherlockActivity;

import uk.co.senab.photup.util.Analytics;

public class PhotupActivity extends SherlockActivity {

    @Override
    protected void onStart() {
        super.onStart();
        Analytics.onStartSession(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Analytics.onEndSession(this);
    }

}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_ValueType3507792607.h"

// System.Collections.Generic.List`1<System.Single>
struct List_1_t1445631064;

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// System.Collections.Generic.List`1/Enumerator<System.Single>
struct  Enumerator_t980360738
{
public:
	// System.Collections.Generic.List`1<T> System.Collections.Generic.List`1/Enumerator::l
	List_1_t1445631064 * ___l_0;
	// System.Int32 System.Collections.Generic.List`1/Enumerator::next
	int32_t ___next_1;
	// System.Int32 System.Collections.Generic.List`1/Enumerator::ver
	int32_t ___ver_2;
	// T System.Collections.Generic.List`1/Enumerator::current
	float ___current_3;

public:
	inline static int32_t get_offset_of_l_0() { return static_cast<int32_t>(offsetof(Enumerator_t980360738, ___l_0)); }
	inline List_1_t1445631064 * get_l_0() const { return ___l_0; }
	inline List_1_t1445631064 ** get_address_of_l_0() { return &___l_0; }
	inline void set_l_0(List_1_t1445631064 * value)
	{
		___l_0 = value;
		Il2CppCodeGenWriteBarrier(&___l_0, value);
	}

	inline static int32_t get_offset_of_next_1() { return static_cast<int32_t>(offsetof(Enumerator_t980360738, ___next_1)); }
	inline int32_t get_next_1() const { return ___next_1; }
	inline int32_t* get_address_of_next_1() { return &___next_1; }
	inline void set_next_1(int32_t value)
	{
		___next_1 = value;
	}

	inline static int32_t get_offset_of_ver_2() { return static_cast<int32_t>(offsetof(Enumerator_t980360738, ___ver_2)); }
	inline int32_t get_ver_2() const { return ___ver_2; }
	inline int32_t* get_address_of_ver_2() { return &___ver_2; }
	inline void set_ver_2(int32_t value)
	{
		___ver_2 = value;
	}

	inline static int32_t get_offset_of_current_3() { return static_cast<int32_t>(offsetof(Enumerator_t980360738, ___current_3)); }
	inline float get_current_3() const { return ___current_3; }
	inline float* get_address_of_current_3() { return &___current_3; }
	inline void set_current_3(float value)
	{
		___current_3 = value;
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
namespace athena {

class DragHandleDelegateTest : public DragHandleScrollDelegate {
 public:
  explicit DragHandleDelegateTest()
      : begin_delta_(0),
        got_scroll_end_(false),
        update_delta_(0) {}

  virtual ~DragHandleDelegateTest() {}

  void Reset() {
    begin_delta_ = 0;
    got_scroll_end_ = false;
    update_delta_ = 0;
  }

  float begin_delta() { return begin_delta_; }
  bool got_scroll_end() { return got_scroll_end_; }
  float update_delta() { return update_delta_; }

 private:
  // DragHandleScrollDelegate:
  virtual void HandleScrollBegin(float delta) OVERRIDE {
    begin_delta_ = delta;
  }

  virtual void HandleScrollEnd() OVERRIDE {
    got_scroll_end_ = true;
  }

  virtual void HandleScrollUpdate(float delta) OVERRIDE {
    update_delta_ = delta;
  }

  float begin_delta_;
  bool got_scroll_end_;
  float update_delta_;

  DISALLOW_COPY_AND_ASSIGN(DragHandleDelegateTest);
};

typedef aura::test::AuraTestBase DragHandleTest;

const int kDragHandleWidth = 10;
const int kDragHandleHeight = 100;

ui::GestureEvent CreateGestureEvent(ui::EventType type,
                                    float x,
                                    float delta_x) {
  ui::GestureEvent event(
      x,
      1,
      0,
      base::TimeDelta::FromInternalValue(base::Time::Now().ToInternalValue()),
      type == ui::ET_GESTURE_SCROLL_END
          ? ui::GestureEventDetails(type)
          : ui::GestureEventDetails(type, delta_x, 0));
  event.set_root_location(gfx::PointF(x, 1));
  return event;
}

TEST_F(DragHandleTest, ScrollTest) {
  DragHandleDelegateTest delegate;
  scoped_ptr<views::View> drag_handle(
      CreateDragHandleView(DragHandleScrollDirection::DRAG_HANDLE_HORIZONTAL,
                           &delegate,
                           kDragHandleWidth,
                           kDragHandleHeight));

  views::Widget widget;
  views::Widget::InitParams params(
      views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  params.parent = root_window();
  params.accept_events = true;
  params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  widget.Init(params);
  widget.SetContentsView(drag_handle.get());
  const gfx::Size& size = gfx::Size(kDragHandleWidth, kDragHandleHeight);
  widget.SetSize(size);
  widget.SetBounds(gfx::Rect(0, 0, size.width(), size.height()));

  const float begin_x = 4.0;
  const float begin_delta = 10.0;
  const float update_delta = 15.0;

  ui::GestureEvent scroll_begin_model =
      CreateGestureEvent(ui::ET_GESTURE_SCROLL_BEGIN, begin_x, begin_delta);
  ui::GestureEvent scroll_update_model =
      CreateGestureEvent(ui::ET_GESTURE_SCROLL_UPDATE,
                         begin_x + update_delta,
                         update_delta - begin_delta);
  ui::GestureEvent scroll_end_model =
      CreateGestureEvent(ui::ET_GESTURE_SCROLL_END, begin_x + update_delta, 0);
  ui::GestureEvent fling_start_model =
      CreateGestureEvent(ui::ET_SCROLL_FLING_START, begin_x + update_delta, 0);

  // Normal scroll
  ui::GestureEvent e(scroll_begin_model);
  widget.OnGestureEvent(&e);
  EXPECT_EQ(begin_delta, delegate.begin_delta());
  EXPECT_EQ(0, delegate.update_delta());
  EXPECT_FALSE(delegate.got_scroll_end());
  e = ui::GestureEvent(scroll_update_model);
  widget.OnGestureEvent(&e);
  EXPECT_EQ(update_delta, delegate.update_delta());
  EXPECT_FALSE(delegate.got_scroll_end());
  e = ui::GestureEvent(scroll_end_model);
  widget.OnGestureEvent(&e);
  EXPECT_EQ(update_delta, delegate.update_delta());
  EXPECT_TRUE(delegate.got_scroll_end());

  delegate.Reset();

  // Scroll ending with a fling
  e = ui::GestureEvent(scroll_begin_model);
  widget.OnGestureEvent(&e);
  e = ui::GestureEvent(scroll_update_model);
  widget.OnGestureEvent(&e);
  e = ui::GestureEvent(fling_start_model);
  widget.OnGestureEvent(&e);
  EXPECT_TRUE(delegate.got_scroll_end());

  delegate.Reset();

  drag_handle.reset();
}

}  // namespace athena


text:
package cz.muni.ics.phil.bis.server.views;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

/**
 *
 * @author Dominik Szalai - emptulik at gmail.com
 */
public class ExcelReportView extends AbstractExcelView
{

    @Override
    protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
//    private static final Logger log = Logger.getLogger(AbstractExcelView.class);
//    private ExcelService excelService;
//
//    @Override
//    protected void buildExcelDocument(Map<String, Object> map, org.apache.poi.hssf.usermodel.HSSFWorkbook hssfw, HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception
//    {
//        Long departmentID = (Long) map.get("id");
//        excelService.generateDepartmentReport(hssfw, departmentID, 0, 0);
//    }
//
//    public void setExcelService(ExcelService excelService)
//    {
//        this.excelService = excelService;
//    }
}


text:
<?php
namespace Rails\ActiveRecord\Persistence;

use Zend\Db\Sql as ZfSql;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\Exception as AdapterException;
use Rails\ActiveRecord\Base;

class Sql
{
    public function insert(Base $record)
    {
        $baseClass = get_class($record);
        $sql = $baseClass::connection()->table($baseClass::tableName());
        return $sql->insert($record->attributes());
    }

    public function update(Base $record)
    {
        if (!$record->hasChanged()) {
            return true;
        }

        if ($record->getAttributes()->isAttribute('updated_at')) {
            $record->setAttribute('updated_at', date('Y-m-d H:i:s'));
        } elseif ($record->getAttributes()->isAttribute('updated_on')) {
            $record->setAttribute('updated_on', date('Y-m-d H:i:s'));
        }

        $values = [];
        foreach (array_keys($record->changedAttributes()) as $attrName) {
            $values[$attrName] = $record->getAttribute($attrName);
        }

        if ($this->updateRecord($record, $values)) {
            $record->getAttributes()->dirty()->changesApplied();
            return true;
        }
        return false;
    }

    public function updateColumns(Base $record, array $columnsValuesPairs)
    {
        if ($record->isNewRecord()) {
            throw new Exception\RuntimeException(
                "Can't update columns on a new record"
            );
        }

        return $this->updateRecord($record, $columnsValuesPairs);
    }

    public function delete(Base $record)
    {

        $sql = $this->buildSqlRelation($record);
        return $sql->delete();
    }

    protected function updateRecord(Base $record, array $columnsValuesPairs)
    {
        $sql = $this->buildSqlRelation($record);
        return $sql->update($columnsValuesPairs);
    }

    protected function buildSqlRelation(Base $record)
    {
        $baseClass = get_class($record);

        $sql = $baseClass::connection()->table($baseClass::tableName());
        if ($baseClass::table()->columnExists($baseClass::primaryKey())) {
            $sql->where([$baseClass::primaryKey() => $record->id()]);
        } else {
            $identifiers = $this->getRecordIdentifiers($record);
            $sql->where($identifiers);
        }

        return $sql;
    }

    protected function getRecordIdentifiers(Base $record)
    {
        $uniques     = $this->getUniqueColumns($record);
        $identifiers = [];

        if ($uniques) {
            /* Attempt to identify record by its unique columns.
             */
            foreach ($uniques as $attrName) {
                $identifiers[$attrName] = $record->getAttribute($attrName);
            }
        } else {
            /* Attempt to identify record by all its attributes.
             * This **could** be dangerous.
             */
            $identifiers = $record->attributes();
        }

        return $identifiers;
    }

    protected function getUniqueColumns($baseClass)
    {
        $keys = [];
        $tableName = $baseClass::tableName();

        foreach ($baseClass::table()->metadata()->getConstraints($tableName) as $constraint) {
            if ($constraint->getType() == 'UNIQUE') {
                $keys = array_merge($keys, $constraint->getColumns());
            }
        }

        return array_unique($keys);
    }
}


text:
<?php
/**
 * Additional user profile fields
 *
 * @package SimpleMag
 * @since 	SimpleMag 1.0
**/

/* User Profile Settings */
function user_social_profile_fields( $user ) {
?>

<?php _e('Social Profiles', 'themetext'); ?>

            	<?php _e('Twitter', 'themetext'); ?>

                <input type="text" name="sptwitter" id="sptwitter" value="<?php echo esc_attr( get_the_author_meta( 'sptwitter', $user->ID ) ); ?>" class="regular-text" />

            	<?php _e('Facebook', 'themetext'); ?>

                <input type="text" name="spfacebook" id="spfacebook" value="<?php echo esc_attr( get_the_author_meta( 'spfacebook', $user->ID ) ); ?>" class="regular-text" />

            	<?php _e('Google+', 'themetext'); ?>

                <input type="text" name="spgoogle" id="spgoogle" value="<?php echo esc_attr( get_the_author_meta( 'spgoogle', $user->ID ) ); ?>" class="regular-text" />

            	<?php _e('Pinterest', 'themetext'); ?>

                <input type="text" name="sppinterest" id="sppinterest" value="<?php echo esc_attr( get_the_author_meta( 'sppinterest', $user->ID ) ); ?>" class="regular-text" />

            	<?php _e('LinkedIn', 'themetext'); ?>

                <input type="text" name="splinkedin" id="splinkedin" value="<?php echo esc_attr( get_the_author_meta( 'splinkedin', $user->ID ) ); ?>" class="regular-text" />

                <?php _e('Instagram', 'themetext'); ?>

                <input type="text" name="spinstagram" id="spinstagram" value="<?php echo esc_attr( get_the_author_meta( 'spinstagram', $user->ID ) ); ?>" class="regular-text" />

<?php }

function save_user_social_profile_fields( $user_id ) {

    if ( !current_user_can( 'edit_user', $user_id ) )
        return false;

    update_user_meta( $user_id, 'sptwitter', $_POST['sptwitter'] );
	update_user_meta( $user_id, 'spfacebook', $_POST['spfacebook'] );
	update_user_meta( $user_id, 'spgoogle', $_POST['spgoogle'] );
	update_user_meta( $user_id, 'sppinterest', $_POST['sppinterest'] );
	update_user_meta( $user_id, 'splinkedin', $_POST['splinkedin'] );
    update_user_meta( $user_id, 'spinstagram', $_POST['spinstagram'] );
}

add_action( 'show_user_profile', 'user_social_profile_fields' );
add_action( 'edit_user_profile', 'user_social_profile_fields' );

add_action( 'personal_options_update', 'save_user_social_profile_fields' );
add_action( 'edit_user_profile_update', 'save_user_social_profile_fields' );


text:
package jsonapi

// Error represents a JSON API error object.
//
// http://jsonapi.org/format/#error-objects
type Error struct {
	ID     string                 `json:"id,omitempty"`
	Status string                 `json:"status,omitempty"`
	Code   string                 `json:"code,omitempty"`
	Title  string                 `json:"title,omitempty"`
	Detail string                 `json:"detail,omitempty"`
	Links  Links                  `json:"links,omitempty"`
	Meta   map[string]interface{} `json:"meta,omitempty"`
}


text:
package spark.scheduler.cluster

import scala.collection.mutable.ArrayBuffer
import spark.scheduler._
import spark.TaskState.TaskState
import java.nio.ByteBuffer

private[spark] trait TaskSetManager extends Schedulable {
  def taskSet: TaskSet
  def slaveOffer(execId: String, hostPort: String, availableCpus: Double,
    overrideLocality: TaskLocality.TaskLocality = null): Option[TaskDescription]
  def numPendingTasksForHostPort(hostPort: String): Int
  def numRackLocalPendingTasksForHost(hostPort :String): Int
  def numPendingTasksForHost(hostPort: String): Int
  def statusUpdate(tid: Long, state: TaskState, serializedData: ByteBuffer)
  def error(message: String)
}


text:
package com.xiaomi.linden.bql;

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

public class SemanticException extends Exception {
  private static final long serialVersionUID = 1L;
  private final ParseTree node;

  public SemanticException(ParseTree node, String message) {
    super(message);
    this.node = node;
  }

  public SemanticException(ParseTree node, String message, Throwable cause) {
    super(message, cause);
    this.node = node;
  }

  public ParseTree getNode() {
    return node;
  }
}


text:
package io.fabric8.gerrit;

import io.fabric8.repo.git.DtoSupport;

import java.util.List;
import java.util.Map;

public class ProjectInfoDTO extends DtoSupport {

        public String id;
        public String name;
        public String parent;
        public String description;
        public ProjectState state;
        public Map<String, String> branches;
        public List<WebLinkInfo> webLinks;

        public String getId() {
                return id;
        }

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

        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public String getParent() {
                return parent;
        }

        public void setParent(String parent) {
                this.parent = parent;
        }

        public String getDescription() {
                return description;
        }

        public void setDescription(String description) {
                this.description = description;
        }

        public ProjectState getState() {
                return state;
        }

        public void setState(ProjectState state) {
                this.state = state;
        }

        public Map<String, String> getBranches() {
                return branches;
        }

        public void setBranches(Map<String, String> branches) {
                this.branches = branches;
        }

        public List<WebLinkInfo> getWebLinks() {
                return webLinks;
        }

        public void setWebLinks(List<WebLinkInfo> webLinks) {
                this.webLinks = webLinks;
        }

}


text:
namespace ph
{

class Time final
{
public:
	real absoluteS;// s units of time since global beginning
	real relativeS;// s units of time since the begining of local time step
	real relativeT;// parametric time t in local time step, in [0, 1]

	Time() :
		absoluteS(0.0_r),
		relativeS(0.0_r),
		relativeT(0.0_r)
	{

	}

	Time(real absoluteS, real relativeS, real relativeT) :
		absoluteS(absoluteS),
		relativeS(relativeS),
		relativeT(relativeT)
	{

	}
};

}// end namespace ph


text:
datafolder: compose-cli
datafile: docker_compose_port
title: docker compose port
redirect_from:
- /compose/reference/port/
---
<!--
Sorry, but the contents of this page are automatically generated from
Docker's source code. If you want to suggest a change to the text that appears
here, you'll need to find the string by searching this repo:
https://github.com/docker/compose
-->
{% include cli.md datafolder=page.datafolder datafile=page.datafile %}


text:
package com.google.template.soy.types;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.template.soy.error.ErrorReporter;
import com.google.template.soy.error.SoyErrorKind;
import com.google.template.soy.error.SoyErrorKind.StyleAllowance;
import com.google.template.soy.error.SoyErrors;
import java.util.HashSet;
import java.util.Set;

/**
 * Utility for generating the return type of a template-type expression after the bind() method is
 * called on it.
 */
public final class TemplateBindingUtil {
  private static final SoyErrorKind PARAMETER_NAME_MISMATCH =
      SoyErrorKind.of(
          "Cannot bind parameter named `{0}` to template of type `{1}`; no such parameter.{2}",
          StyleAllowance.NO_PUNCTUATION);

  private static final SoyErrorKind PARAMETER_TYPE_MISMATCH =
      SoyErrorKind.of(
          "Cannot bind parameter named `{0}` to template of type `{1}`; expected `{2}` but found"
              + " `{3}`.");

  public static SoyType bindParameters(
      SoyType base,
      RecordType parameterType,
      SoyTypeRegistry typeRegistry,
      ErrorReporter.LocationBound errorReporter) {
    checkArgument(
        SoyTypes.isKindOrUnionOfKinds(
            base, ImmutableSet.of(SoyType.Kind.TEMPLATE, SoyType.Kind.TEMPLATE_TYPE)));
    Set<SoyType> types = new HashSet<>();
    for (SoyType baseType : SoyTypes.expandUnions(base)) {
      switch (baseType.getKind()) {
        case TEMPLATE:
          types.add(
              bindParametersToTemplate(
                  (TemplateType) baseType, parameterType, typeRegistry, errorReporter));
          break;
        default:
          throw new AssertionError();
      }
    }
    return typeRegistry.getOrCreateUnionType(types);
  }

  /**
   * Helper static utility for constructing types with bound parameters. Performs validations and
   * reports errors if the parameters don't match the expected names/types. If any errors are
   * reported, returns the ErrorType instead of a TemplateType.
   */
  private static SoyType bindParametersToTemplate(
      TemplateType base,
      RecordType parameters,
      SoyTypeRegistry typeRegistry,
      ErrorReporter.LocationBound errorReporter) {
    Set<String> unboundParameters = new HashSet<>(base.getParameterMap().keySet());
    boolean reportedErrors = false;
    for (RecordType.Member member : parameters.getMembers()) {
      if (!base.getParameterMap().containsKey(member.name())) {
        String didYouMeanMessage =
            SoyErrors.getDidYouMeanMessage(base.getParameterMap().keySet(), member.name());
        errorReporter.report(PARAMETER_NAME_MISMATCH, member.name(), base, didYouMeanMessage);
        reportedErrors = true;
        continue;
      }
      if (!base.getParameterMap().get(member.name()).isAssignableFromLoose(member.checkedType())) {
        errorReporter.report(
            PARAMETER_TYPE_MISMATCH,
            member.name(),
            base,
            base.getParameterMap().get(member.name()),
            member.checkedType());
        reportedErrors = true;
      }
      unboundParameters.remove(member.name());
    }
    if (reportedErrors) {
      return UnknownType.getInstance();
    }
    TemplateType.Builder builder = base.toBuilder();
    ImmutableList<TemplateType.Parameter> newParameters =
        base.getParameters().stream()
            .filter((parameter) -> unboundParameters.contains(parameter.getName()))
            .collect(toImmutableList());
    builder.setIdentifierForDebugging(
        TemplateType.stringRepresentation(newParameters, base.getContentKind(), ImmutableSet.of()));
    builder.setParameters(newParameters);
    return typeRegistry.internTemplateType(builder.build());
  }

  /** Non-instantiable. */
  private TemplateBindingUtil() {}
}


text: SELECT func1_nosql_imm(func2_read_int_vol(5)) FROM foo order by 1;


text:
code: true
type: page
title: getBodyObject
description: KuzzleRequest class getBodyObject() method
---

# getBodyObject

<SinceBadge version="2.16.9" />

Gets a parameter from the request body and checks that it is an object.
We also support lodash syntax. [(`relations.lebron[0]`)](https://lodash.com/docs/4.17.15#get)

### Arguments

```ts
getBodyObject (name: string, def: JSONObject = null): JSONObject
```

| Name   | Type              | Description    |
|--------|-------------------|----------------|
| `name` |
string
 | Parameter name |
| `def` |
JSONObject
 | Default value to return if the parameter is not set |

### Example

```ts
const metadata = request.getBodyObject('metadata');
// equivalent
const metadata = request.input.body.metadata;
//+ checks to make sure that "metadata" is of the right type
// and throw standard API error when it's not the case
```


text:
package org.apache.zookeeper.recipes.lock;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.test.ClientBase;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

/**
 * test for writelock.
 */
public class WriteLockTest extends ClientBase {

    protected int sessionTimeout = 10 * 1000;
    protected String dir = "/" + getClass().getName();
    protected WriteLock[] nodes;
    protected CountDownLatch latch = new CountDownLatch(1);
    private boolean restartServer = true;
    private boolean workAroundClosingLastZNodeFails = true;
    private boolean killLeader = true;

    @Test
    public void testRun() throws Exception {
        runTest(3);
    }

    class LockCallback implements LockListener {

        public void lockAcquired() {
            latch.countDown();
        }

        public void lockReleased() {

        }

    }
    protected void runTest(int count) throws Exception {
        nodes = new WriteLock[count];
        for (int i = 0; i < count; i++) {
            ZooKeeper keeper = createClient();
            WriteLock leader = new WriteLock(keeper, dir, null);
            leader.setLockListener(new LockCallback());
            nodes[i] = leader;

            leader.lock();
        }

        // lets wait for any previous leaders to die and one of our new
        // nodes to become the new leader
        latch.await(30, TimeUnit.SECONDS);

        WriteLock first = nodes[0];
        dumpNodes(count);

        // lets assert that the first election is the leader
        assertTrue(first.isOwner(), "The first znode should be the leader " + first.getId());

        for (int i = 1; i < count; i++) {
            WriteLock node = nodes[i];
            assertFalse(node.isOwner(), "Node should not be the leader " + node.getId());
        }

        if (count > 1) {
            if (killLeader) {
                System.out.println("Now killing the leader");
                // now lets kill the leader
                latch = new CountDownLatch(1);
                first.unlock();
                latch.await(30, TimeUnit.SECONDS);
                //Thread.sleep(10000);
                WriteLock second = nodes[1];
                dumpNodes(count);
                // lets assert that the first election is the leader
                assertTrue(second.isOwner(), "The second znode should be the leader " + second.getId());

                for (int i = 2; i < count; i++) {
                    WriteLock node = nodes[i];
                    assertFalse(node.isOwner(), "Node should not be the leader " + node.getId());
                }
            }

            if (restartServer) {
                // now lets stop the server
                System.out.println("Now stopping the server");
                stopServer();
                Thread.sleep(10000);

                // TODO lets assert that we are no longer the leader
                dumpNodes(count);

                System.out.println("Starting the server");
                startServer();
                Thread.sleep(10000);

                for (int i = 0; i < count - 1; i++) {
                    System.out.println("Calling acquire for node: " + i);
                    nodes[i].lock();
                }
                dumpNodes(count);
                System.out.println("Now closing down...");
            }
        }
    }

    protected void dumpNodes(int count) {
        for (int i = 0; i < count; i++) {
            WriteLock node = nodes[i];
            System.out.println("node: " + i + " id: " + node.getId() + " is leader: " + node.isOwner());
        }
    }

    @AfterEach
    public void tearDown() throws Exception {
        if (nodes != null) {
            for (int i = 0; i < nodes.length; i++) {
                WriteLock node = nodes[i];
                if (node != null) {
                    System.out.println("Closing node: " + i);
                    node.close();
                    if (workAroundClosingLastZNodeFails && i == nodes.length - 1) {
                        System.out.println("Not closing zookeeper: " + i + " due to bug!");
                    } else {
                        System.out.println("Closing zookeeper: " + i);
                        node.getZookeeper().close();
                        System.out.println("Closed zookeeper: " + i);
                    }
                }
            }
        }
        System.out.println("Now lets stop the server");
        super.tearDown();

    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ftfl.imageslidergallery"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
                     android:maxSdkVersion="18" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".GridViewActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".FullScreenViewActivity"
            android:label="@string/app_name" >

        </activity>
    </application>

</manifest>


text:
/**
 * UserSessionRepository.findByTelegramId()
 */
'use strict';

const NError = require('nerror');

/**
 * Find a model by Telegram ID
 * @instance
 * @method findByToken
 * @memberOf module:repositories/user-session~UserSessionRepository
 * @param {string} id                       ID to search by
 * @param {MongoClient|string} [mongo]      Will reuse the Mongo client provided, or if it is a string then will
 *                                          connect to this instance of Mongo.
 * @return {Promise}                        Resolves to array of models
 */
module.exports = async function (id, mongo) {
    let client;

    try {
        client = typeof mongo === 'object' ? mongo : await this._mongo.connect(mongo || this.constructor.instance);
        let coll = client.collection(this.constructor.table);
        let data = coll.find({ telegram_id: id }).sort({ updated_at: -1 });
        let rows = await data.toArray();

        if (typeof mongo !== 'object')
            client.done();

        return rows ? this.getModel(rows) : [];
    } catch (error) {
        if (client && typeof mongo !== 'object')
            client.done();

        throw new NError(error, { id }, 'UserSessionRepository.findByTelegramId()');
    }
};