text:
*boltons should be builtins.*

**Boltons** is a set of over 100 BSD-licensed, pure-Python utilities
in the same spirit as — and yet conspicuously missing from —
[the standard library][stdlib], including:

  * [Atomic file saving][atomic], bolted on with [fileutils][fileutils]
  * A highly-optimized [OrderedMultiDict][omd], in [dictutils][dictutils]
  * *Two* types of [PriorityQueue][pq], in [queueutils][queueutils]
  * [Chunked][chunked] and [windowed][windowed] iteration, in [iterutils][iterutils]
  * A full-featured [TracebackInfo][tbinfo] type, for representing stack traces,
    in [tbutils][tbutils]

Boltons is tested against Python 2.6, 2.7, 3.4, and
PyPy. [Full and extensive docs are available on Read The Docs.][rtd]
See what's new [by checking the CHANGELOG][changelog].

[stdlib]: https://docs.python.org/2.7/library/index.html
[rtd]: https://boltons.readthedocs.org/en/latest/
[changelog]: https://github.com/mahmoud/boltons/blob/master/CHANGELOG.md

[atomic]: https://boltons.readthedocs.org/en/latest/fileutils.html#boltons.fileutils.atomic_save
[omd]: https://boltons.readthedocs.org/en/latest/dictutils.html#boltons.dictutils.OrderedMultiDict
[pq]: https://boltons.readthedocs.org/en/latest/queueutils.html#boltons.queueutils.PriorityQueue
[chunked]: https://boltons.readthedocs.org/en/latest/iterutils.html#boltons.iterutils.chunked
[windowed]: https://boltons.readthedocs.org/en/latest/iterutils.html#boltons.iterutils.windowed
[tbinfo]: https://boltons.readthedocs.org/en/latest/tbutils.html#boltons.tbutils.TracebackInfo

[fileutils]: https://boltons.readthedocs.org/en/latest/fileutils.html#module-boltons.fileutils
[dictutils]: https://boltons.readthedocs.org/en/latest/dictutils.html#module-boltons.dictutils
[queueutils]: https://boltons.readthedocs.org/en/latest/queueutils.html#module-boltons.queueutils
[iterutils]: https://boltons.readthedocs.org/en/latest/iterutils.html#module-boltons.iterutils
[tbutils]: https://boltons.readthedocs.org/en/latest/tbutils.html#module-boltons.tbutils

## Installation

Boltons can be added to a project in a few ways. There's the obvious one:

```
    pip install boltons
```

Then, [thanks to PyPI][boltons_pypi], dozens of boltons are just an import away:

```python
    from boltons.cacheutils import LRU
    my_cache = LRU()
```

However, due to the nature of utilities, application developers might
want to consider other options. Boltons is pure-Python and has no
dependencies. See the [Integration][integration] section of the docs
for more details.

[boltons_pypi]: https://pypi.python.org/pypi/boltons
[integration]: https://boltons.readthedocs.org/en/latest/architecture.html#integration

## Third-party packages

The majority of boltons strive to be "good enough" for a wide range of
basic uses, leaving advanced use cases to Python's [myriad specialized
3rd-party libraries][pypi]. In many cases the respective ``boltons`` module
will describe 3rd-party alternatives worth investigating when use
cases outgrow `boltons`. If you've found a natural "next-step"
library worth mentioning, see the next section!

[pypi]: https://pypi.python.org/pypi

## Gaps

Found something missing in the standard library that should be in
`boltons`? Found something missing in `boltons`? First, take a
moment to read the very brief [architecture statement][architecture] to make
sure the functionality would be a good fit.

Then, if you are very motivated, submit [a Pull Request][prs]. Otherwise,
submit a short feature request on [the Issues page][issues], and we will
figure something out.

[architecture]: https://boltons.readthedocs.org/en/latest/architecture.html
[issues]: https://github.com/mahmoud/boltons/issues
[prs]: https://github.com/mahmoud/boltons/pulls


text:
/*
 * NOTE :
 * There are various problems with this package :
 *	o the hash function for ints is pathetic (but could be changed)
 *	o locking is sometime suspicious (especially during enumeration)
 *	o most users have only a few elements (== overhead)
 *	o most users never use seach, so don't benefit from hashing
 * Problem already fixed :
 *	o not 64 bit compliant (most users do hashv = (int) self)
 *	o hashbin_remove() is broken => use hashbin_remove_this()
 * I think most users would be better served by a simple linked list
 * (like include/linux/list.h) with a global spinlock per list.
 * Jean II
 */

/*
 * Notes on the concurrent access to hashbin and other SMP issues
 * -------------------------------------------------------------
 *	Hashbins are very often in the IrDA stack a global repository of
 * information, and therefore used in a very asynchronous manner following
 * various events (driver calls, timers, user calls...).
 *	Therefore, very often it is highly important to consider the
 * management of concurrent access to the hashbin and how to guarantee the
 * consistency of the operations on it.
 *
 *	First, we need to define the objective of locking :
 *		1) Protect user data (content pointed by the hashbin)
 *		2) Protect hashbin structure itself (linked list in each bin)
 *
 *			     OLD LOCKING
 *			     -----------
 *
 *	The previous locking strategy, either HB_LOCAL or HB_GLOBAL were
 * both inadequate in *both* aspect.
 *		o HB_GLOBAL was using a spinlock for each bin (local locking).
 *		o HB_LOCAL was disabling irq on *all* CPUs, so use a single
 *		  global semaphore.
 *	The problems were :
 *		A) Global irq disabling is no longer supported by the kernel
 *		B) No protection for the hashbin struct global data
 *			o hashbin_delete()
 *			o hb_current
 *		C) No protection for user data in some cases
 *
 *	A) HB_LOCAL use global irq disabling, so doesn't work on kernel
 * 2.5.X. Even when it is supported (kernel 2.4.X and earlier), its
 * performance is not satisfactory on SMP setups. Most hashbins were
 * HB_LOCAL, so (A) definitely need fixing.
 *	B) HB_LOCAL could be modified to fix (B). However, because HB_GLOBAL
 * lock only the individual bins, it will never be able to lock the
 * global data, so can't do (B).
 *	C) Some functions return pointer to data that is still in the
 * hashbin :
 *		o hashbin_find()
 *		o hashbin_get_first()
 *		o hashbin_get_next()
 *	As the data is still in the hashbin, it may be changed or free'd
 * while the caller is examinimg the data. In those case, locking can't
 * be done within the hashbin, but must include use of the data within
 * the caller.
 *	The caller can easily do this with HB_LOCAL (just disable irqs).
 * However, this is impossible with HB_GLOBAL because the caller has no
 * way to know the proper bin, so don't know which spinlock to use.
 *
 *	Quick summary : can no longer use HB_LOCAL, and HB_GLOBAL is
 * fundamentally broken and will never work.
 *
 *			     NEW LOCKING
 *			     -----------
 *
 *	To fix those problems, I've introduce a few changes in the
 * hashbin locking :
 *		1) New HB_LOCK scheme
 *		2) hashbin->hb_spinlock
 *		3) New hashbin usage policy
 *
 * HB_LOCK :
 * -------
 *	HB_LOCK is a locking scheme intermediate between the old HB_LOCAL
 * and HB_GLOBAL. It uses a single spinlock to protect the whole content
 * of the hashbin. As it is a single spinlock, it can protect the global
 * data of the hashbin and not only the bins themselves.
 *	HB_LOCK can only protect some of the hashbin calls, so it only lock
 * call that can be made 100% safe and leave other call unprotected.
 *	HB_LOCK in theory is slower than HB_GLOBAL, but as the hashbin
 * content is always small contention is not high, so it doesn't matter
 * much. HB_LOCK is probably faster than HB_LOCAL.
 *
 * hashbin->hb_spinlock :
 * --------------------
 *	The spinlock that HB_LOCK uses is available for caller, so that
 * the caller can protect unprotected calls (see below).
 *	If the caller want to do entirely its own locking (HB_NOLOCK), he
 * can do so and may use safely this spinlock.
 *	Locking is done like this :
 *		spin_lock_irqsave(&hashbin->hb_spinlock, flags);
 *	Releasing the lock :
 *		spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
 *
 * Safe & Protected calls :
 * ----------------------
 *	The following calls are safe or protected via HB_LOCK :
 *		o hashbin_new()		-> safe
 *		o hashbin_delete()
 *		o hashbin_insert()
 *		o hashbin_remove_first()
 *		o hashbin_remove()
 *		o hashbin_remove_this()
 *		o HASHBIN_GET_SIZE()	-> atomic
 *
 *	The following calls only protect the hashbin itself :
 *		o hashbin_lock_find()
 *		o hashbin_find_next()
 *
 * Unprotected calls :
 * -----------------
 *	The following calls need to be protected by the caller :
 *		o hashbin_find()
 *		o hashbin_get_first()
 *		o hashbin_get_next()
 *
 * Locking Policy :
 * --------------
 *	If the hashbin is used only in a single thread of execution
 * (explicitly or implicitely), you can use HB_NOLOCK
 *	If the calling module already provide concurrent access protection,
 * you may use HB_NOLOCK.
 *
 *	In all other cases, you need to use HB_LOCK and lock the hashbin
 * every time before calling one of the unprotected calls. You also must
 * use the pointer returned by the unprotected call within the locked
 * region.
 *
 * Extra care for enumeration :
 * --------------------------
 *	hashbin_get_first() and hashbin_get_next() use the hashbin to
 * store the current position, in hb_current.
 *	As long as the hashbin remains locked, this is safe. If you unlock
 * the hashbin, the current position may change if anybody else modify
 * or enumerate the hashbin.
 *	Summary : do the full enumeration while locked.
 *
 *	Alternatively, you may use hashbin_find_next(). But, this will
 * be slower, is more complex to use and doesn't protect the hashbin
 * content. So, care is needed here as well.
 *
 * Other issues :
 * ------------
 *	I believe that we are overdoing it by using spin_lock_irqsave()
 * and we should use only spin_lock_bh() or similar. But, I don't have
 * the balls to try it out.
 *	Don't believe that because hashbin are now (somewhat) SMP safe
 * that the rest of the code is. Higher layers tend to be safest,
 * but LAP and LMP would need some serious dedicated love.
 *
 * Jean II
 */
#include <linux/module.h>

#include <net/irda/irda.h>
#include <net/irda/irqueue.h>

/************************ QUEUE SUBROUTINES ************************/

/*
 * Hashbin
 */
#define GET_HASHBIN(x) ( x & HASHBIN_MASK )

/*
 * Function hash (name)
 *
 *    This function hash the input string 'name' using the ELF hash
 *    function for strings.
 */
static __u32 hash( const char* name)
{
	__u32 h = 0;
	__u32 g;

	while(*name) {
		h = (h<<4) + *name++;
		if ((g = (h & 0xf0000000)))
			h ^=g>>24;
		h &=~g;
	}
	return h;
}

/*
 * Function enqueue_first (queue, proc)
 *
 *    Insert item first in queue.
 *
 */
static void enqueue_first(irda_queue_t **queue, irda_queue_t* element)
{

	IRDA_DEBUG( 4, "%s()\n", __func__);

	/*
	 * Check if queue is empty.
	 */
	if ( *queue == NULL ) {
		/*
		 * Queue is empty.  Insert one element into the queue.
		 */
		element->q_next = element->q_prev = *queue = element;

	} else {
		/*
		 * Queue is not empty.  Insert element into front of queue.
		 */
		element->q_next          = (*queue);
		(*queue)->q_prev->q_next = element;
		element->q_prev          = (*queue)->q_prev;
		(*queue)->q_prev         = element;
		(*queue)                 = element;
	}
}

/*
 * Function dequeue (queue)
 *
 *    Remove first entry in queue
 *
 */
static irda_queue_t *dequeue_first(irda_queue_t **queue)
{
	irda_queue_t *ret;

	IRDA_DEBUG( 4, "dequeue_first()\n");

	/*
	 * Set return value
	 */
	ret =  *queue;

	if ( *queue == NULL ) {
		/*
		 * Queue was empty.
		 */
	} else if ( (*queue)->q_next == *queue ) {
		/*
		 *  Queue only contained a single element. It will now be
		 *  empty.
		 */
		*queue = NULL;
	} else {
		/*
		 * Queue contained several element.  Remove the first one.
		 */
		(*queue)->q_prev->q_next = (*queue)->q_next;
		(*queue)->q_next->q_prev = (*queue)->q_prev;
		*queue = (*queue)->q_next;
	}

	/*
	 * Return the removed entry (or NULL of queue was empty).
	 */
	return ret;
}

/*
 * Function dequeue_general (queue, element)
 *
 *
 */
static irda_queue_t *dequeue_general(irda_queue_t **queue, irda_queue_t* element)
{
	irda_queue_t *ret;

	IRDA_DEBUG( 4, "dequeue_general()\n");

	/*
	 * Set return value
	 */
	ret =  *queue;

	if ( *queue == NULL ) {
		/*
		 * Queue was empty.
		 */
	} else if ( (*queue)->q_next == *queue ) {
		/*
		 *  Queue only contained a single element. It will now be
		 *  empty.
		 */
		*queue = NULL;

	} else {
		/*
		 *  Remove specific element.
		 */
		element->q_prev->q_next = element->q_next;
		element->q_next->q_prev = element->q_prev;
		if ( (*queue) == element)
			(*queue) = element->q_next;
	}

	/*
	 * Return the removed entry (or NULL of queue was empty).
	 */
	return ret;
}

/************************ HASHBIN MANAGEMENT ************************/

/*
 * Function hashbin_create ( type, name )
 *
 *    Create hashbin!
 *
 */
hashbin_t *hashbin_new(int type)
{
	hashbin_t* hashbin;

	/*
	 * Allocate new hashbin
	 */
	hashbin = kzalloc(sizeof(*hashbin), GFP_ATOMIC);
	if (!hashbin)
		return NULL;

	/*
	 * Initialize structure
	 */
	hashbin->hb_type = type;
	hashbin->magic = HB_MAGIC;
	//hashbin->hb_current = NULL;

	/* Make sure all spinlock's are unlocked */
	if ( hashbin->hb_type & HB_LOCK ) {
		spin_lock_init(&hashbin->hb_spinlock);
	}

	return hashbin;
}
EXPORT_SYMBOL(hashbin_new);

/*
 * Function hashbin_delete (hashbin, free_func)
 *
 *    Destroy hashbin, the free_func can be a user supplied special routine
 *    for deallocating this structure if it's complex. If not the user can
 *    just supply kfree, which should take care of the job.
 */
#ifdef CONFIG_LOCKDEP
static int hashbin_lock_depth = 0;
#endif
int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func)
{
	irda_queue_t* queue;
	unsigned long flags = 0;
	int i;

	IRDA_ASSERT(hashbin != NULL, return -1;);
	IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;);

	/* Synchronize */
	if ( hashbin->hb_type & HB_LOCK ) {
		spin_lock_irqsave_nested(&hashbin->hb_spinlock, flags,
					 hashbin_lock_depth++);
	}

	/*
	 *  Free the entries in the hashbin, TODO: use hashbin_clear when
	 *  it has been shown to work
	 */
	for (i = 0; i < HASHBIN_SIZE; i ++ ) {
		queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]);
		while (queue ) {
			if (free_func)
				(*free_func)(queue);
			queue = dequeue_first(
				(irda_queue_t**) &hashbin->hb_queue[i]);
		}
	}

	/* Cleanup local data */
	hashbin->hb_current = NULL;
	hashbin->magic = ~HB_MAGIC;

	/* Release lock */
	if ( hashbin->hb_type & HB_LOCK) {
		spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
#ifdef CONFIG_LOCKDEP
		hashbin_lock_depth--;
#endif
	}

	/*
	 *  Free the hashbin structure
	 */
	kfree(hashbin);

	return 0;
}
EXPORT_SYMBOL(hashbin_delete);

/********************* HASHBIN LIST OPERATIONS *********************/

/*
 * Function hashbin_insert (hashbin, entry, name)
 *
 *    Insert an entry into the hashbin
 *
 */
void hashbin_insert(hashbin_t* hashbin, irda_queue_t* entry, long hashv,
		    const char* name)
{
	unsigned long flags = 0;
	int bin;

	IRDA_DEBUG( 4, "%s()\n", __func__);

	IRDA_ASSERT( hashbin != NULL, return;);
	IRDA_ASSERT( hashbin->magic == HB_MAGIC, return;);

	/*
	 * Locate hashbin
	 */
	if ( name )
		hashv = hash( name );
	bin = GET_HASHBIN( hashv );

	/* Synchronize */
	if ( hashbin->hb_type & HB_LOCK ) {
		spin_lock_irqsave(&hashbin->hb_spinlock, flags);
	} /* Default is no-lock  */

	/*
	 * Store name and key
	 */
	entry->q_hash = hashv;
	if ( name )
		strlcpy( entry->q_name, name, sizeof(entry->q_name));

	/*
	 * Insert new entry first
	 */
	enqueue_first( (irda_queue_t**) &hashbin->hb_queue[ bin ],
		       entry);
	hashbin->hb_size++;

	/* Release lock */
	if ( hashbin->hb_type & HB_LOCK ) {
		spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
	} /* Default is no-lock  */
}
EXPORT_SYMBOL(hashbin_insert);

/*
 *  Function hashbin_remove_first (hashbin)
 *
 *    Remove first entry of the hashbin
 *
 * Note : this function no longer use hashbin_remove(), but does things
 * similar to hashbin_remove_this(), so can be considered safe.
 * Jean II
 */
void *hashbin_remove_first( hashbin_t *hashbin)
{
	unsigned long flags = 0;
	irda_queue_t *entry = NULL;

	/* Synchronize */
	if ( hashbin->hb_type & HB_LOCK ) {
		spin_lock_irqsave(&hashbin->hb_spinlock, flags);
	} /* Default is no-lock  */

	entry = hashbin_get_first( hashbin);
	if ( entry != NULL) {
		int	bin;
		long	hashv;
		/*
		 * Locate hashbin
		 */
		hashv = entry->q_hash;
		bin = GET_HASHBIN( hashv );

		/*
		 * Dequeue the entry...
		 */
		dequeue_general( (irda_queue_t**) &hashbin->hb_queue[ bin ],
				 (irda_queue_t*) entry );
		hashbin->hb_size--;
		entry->q_next = NULL;
		entry->q_prev = NULL;

		/*
		 *  Check if this item is the currently selected item, and in
		 *  that case we must reset hb_current
		 */
		if ( entry == hashbin->hb_current)
			hashbin->hb_current = NULL;
	}

	/* Release lock */
	if ( hashbin->hb_type & HB_LOCK ) {
		spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
	} /* Default is no-lock  */

	return entry;
}

/*
 *  Function hashbin_remove (hashbin, hashv, name)
 *
 *    Remove entry with the given name
 *
 *  The use of this function is highly discouraged, because the whole
 *  concept behind hashbin_remove() is broken. In many cases, it's not
 *  possible to guarantee the unicity of the index (either hashv or name),
 *  leading to removing the WRONG entry.
 *  The only simple safe use is :
 *		hashbin_remove(hasbin, (int) self, NULL);
 *  In other case, you must think hard to guarantee unicity of the index.
 *  Jean II
 */
void* hashbin_remove( hashbin_t* hashbin, long hashv, const char* name)
{
	int bin, found = FALSE;
	unsigned long flags = 0;
	irda_queue_t* entry;

	IRDA_DEBUG( 4, "%s()\n", __func__);

	IRDA_ASSERT( hashbin != NULL, return NULL;);
	IRDA_ASSERT( hashbin->magic == HB_MAGIC, return NULL;);

	/*
	 * Locate hashbin
	 */
	if ( name )
		hashv = hash( name );
	bin = GET_HASHBIN( hashv );

	/* Synchronize */
	if ( hashbin->hb_type & HB_LOCK ) {
		spin_lock_irqsave(&hashbin->hb_spinlock, flags);
	} /* Default is no-lock  */

	/*
	 * Search for entry
	 */
	entry = hashbin->hb_queue[ bin ];
	if ( entry ) {
		do {
			/*
			 * Check for key
			 */
			if ( entry->q_hash == hashv ) {
				/*
				 * Name compare too?
				 */
				if ( name ) {
					if ( strcmp( entry->q_name, name) == 0)
					{
						found = TRUE;
						break;
					}
				} else {
					found = TRUE;
					break;
				}
			}
			entry = entry->q_next;
		} while ( entry != hashbin->hb_queue[ bin ] );
	}

	/*
	 * If entry was found, dequeue it
	 */
	if ( found ) {
		dequeue_general( (irda_queue_t**) &hashbin->hb_queue[ bin ],
				 (irda_queue_t*) entry );
		hashbin->hb_size--;

		/*
		 *  Check if this item is the currently selected item, and in
		 *  that case we must reset hb_current
		 */
		if ( entry == hashbin->hb_current)
			hashbin->hb_current = NULL;
	}

	/* Release lock */
	if ( hashbin->hb_type & HB_LOCK ) {
		spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
	} /* Default is no-lock  */

	/* Return */
	if ( found )
		return entry;
	else
		return NULL;

}
EXPORT_SYMBOL(hashbin_remove);

/*
 *  Function hashbin_remove_this (hashbin, entry)
 *
 *    Remove entry with the given name
 *
 * In some cases, the user of hashbin can't guarantee the unicity
 * of either the hashv or name.
 * In those cases, using the above function is guaranteed to cause troubles,
 * so we use this one instead...
 * And by the way, it's also faster, because we skip the search phase ;-)
 */
void* hashbin_remove_this( hashbin_t* hashbin, irda_queue_t* entry)
{
	unsigned long flags = 0;
	int	bin;
	long	hashv;

	IRDA_DEBUG( 4, "%s()\n", __func__);

	IRDA_ASSERT( hashbin != NULL, return NULL;);
	IRDA_ASSERT( hashbin->magic == HB_MAGIC, return NULL;);
	IRDA_ASSERT( entry != NULL, return NULL;);

	/* Synchronize */
	if ( hashbin->hb_type & HB_LOCK ) {
		spin_lock_irqsave(&hashbin->hb_spinlock, flags);
	} /* Default is no-lock  */

	/* Check if valid and not already removed... */
	if((entry->q_next == NULL) || (entry->q_prev == NULL)) {
		entry = NULL;
		goto out;
	}

	/*
	 * Locate hashbin
	 */
	hashv = entry->q_hash;
	bin = GET_HASHBIN( hashv );

	/*
	 * Dequeue the entry...
	 */
	dequeue_general( (irda_queue_t**) &hashbin->hb_queue[ bin ],
			 (irda_queue_t*) entry );
	hashbin->hb_size--;
	entry->q_next = NULL;
	entry->q_prev = NULL;

	/*
	 *  Check if this item is the currently selected item, and in
	 *  that case we must reset hb_current
	 */
	if ( entry == hashbin->hb_current)
		hashbin->hb_current = NULL;
out:
	/* Release lock */
	if ( hashbin->hb_type & HB_LOCK ) {
		spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);
	} /* Default is no-lock  */

	return entry;
}
EXPORT_SYMBOL(hashbin_remove_this);

/*********************** HASHBIN ENUMERATION ***********************/

/*
 * Function hashbin_common_find (hashbin, hashv, name)
 *
 *    Find item with the given hashv or name
 *
 */
void* hashbin_find( hashbin_t* hashbin, long hashv, const char* name )
{
	int bin;
	irda_queue_t* entry;

	IRDA_DEBUG( 4, "hashbin_find()\n");

	IRDA_ASSERT( hashbin != NULL, return NULL;);
	IRDA_ASSERT( hashbin->magic == HB_MAGIC, return NULL;);

	/*
	 * Locate hashbin
	 */
	if ( name )
		hashv = hash( name );
	bin = GET_HASHBIN( hashv );

	/*
	 * Search for entry
	 */
	entry = hashbin->hb_queue[ bin];
	if ( entry ) {
		do {
			/*
			 * Check for key
			 */
			if ( entry->q_hash == hashv ) {
				/*
				 * Name compare too?
				 */
				if ( name ) {
					if ( strcmp( entry->q_name, name ) == 0 ) {
						return entry;
					}
				} else {
					return entry;
				}
			}
			entry = entry->q_next;
		} while ( entry != hashbin->hb_queue[ bin ] );
	}

	return NULL;
}
EXPORT_SYMBOL(hashbin_find);

/*
 * Function hashbin_lock_find (hashbin, hashv, name)
 *
 *    Find item with the given hashv or name
 *
 * Same, but with spinlock protection...
 * I call it safe, but it's only safe with respect to the hashbin, not its
 * content. - Jean II
 */
void* hashbin_lock_find( hashbin_t* hashbin, long hashv, const char* name )
{
	unsigned long flags = 0;
	irda_queue_t* entry;

	/* Synchronize */
	spin_lock_irqsave(&hashbin->hb_spinlock, flags);

	/*
	 * Search for entry
	 */
	entry = (irda_queue_t* ) hashbin_find( hashbin, hashv, name );

	/* Release lock */
	spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);

	return entry;
}
EXPORT_SYMBOL(hashbin_lock_find);

/*
 * Function hashbin_find (hashbin, hashv, name, pnext)
 *
 *    Find an item with the given hashv or name, and its successor
 *
 * This function allow to do concurrent enumerations without the
 * need to lock over the whole session, because the caller keep the
 * context of the search. On the other hand, it might fail and return
 * NULL if the entry is removed. - Jean II
 */
void* hashbin_find_next( hashbin_t* hashbin, long hashv, const char* name,
			 void ** pnext)
{
	unsigned long flags = 0;
	irda_queue_t* entry;

	/* Synchronize */
	spin_lock_irqsave(&hashbin->hb_spinlock, flags);

	/*
	 * Search for current entry
	 * This allow to check if the current item is still in the
	 * hashbin or has been removed.
	 */
	entry = (irda_queue_t* ) hashbin_find( hashbin, hashv, name );

	/*
	 * Trick hashbin_get_next() to return what we want
	 */
	if(entry) {
		hashbin->hb_current = entry;
		*pnext = hashbin_get_next( hashbin );
	} else
		*pnext = NULL;

	/* Release lock */
	spin_unlock_irqrestore(&hashbin->hb_spinlock, flags);

	return entry;
}

/*
 * Function hashbin_get_first (hashbin)
 *
 *    Get a pointer to first element in hashbin, this function must be
 *    called before any calls to hashbin_get_next()!
 *
 */
irda_queue_t *hashbin_get_first( hashbin_t* hashbin)
{
	irda_queue_t *entry;
	int i;

	IRDA_ASSERT( hashbin != NULL, return NULL;);
	IRDA_ASSERT( hashbin->magic == HB_MAGIC, return NULL;);

	if ( hashbin == NULL)
		return NULL;

	for ( i = 0; i < HASHBIN_SIZE; i ++ ) {
		entry = hashbin->hb_queue[ i];
		if ( entry) {
			hashbin->hb_current = entry;
			return entry;
		}
	}
	/*
	 *  Did not find any item in hashbin
	 */
	return NULL;
}
EXPORT_SYMBOL(hashbin_get_first);

/*
 * Function hashbin_get_next (hashbin)
 *
 *    Get next item in hashbin. A series of hashbin_get_next() calls must
 *    be started by a call to hashbin_get_first(). The function returns
 *    NULL when all items have been traversed
 *
 * The context of the search is stored within the hashbin, so you must
 * protect yourself from concurrent enumerations. - Jean II
 */
irda_queue_t *hashbin_get_next( hashbin_t *hashbin)
{
	irda_queue_t* entry;
	int bin;
	int i;

	IRDA_ASSERT( hashbin != NULL, return NULL;);
	IRDA_ASSERT( hashbin->magic == HB_MAGIC, return NULL;);

	if ( hashbin->hb_current == NULL) {
		IRDA_ASSERT( hashbin->hb_current != NULL, return NULL;);
		return NULL;
	}
	entry = hashbin->hb_current->q_next;
	bin = GET_HASHBIN( entry->q_hash);

	/*
	 *  Make sure that we are not back at the beginning of the queue
	 *  again
	 */
	if ( entry != hashbin->hb_queue[ bin ]) {
		hashbin->hb_current = entry;

		return entry;
	}

	/*
	 *  Check that this is not the last queue in hashbin
	 */
	if ( bin >= HASHBIN_SIZE)
		return NULL;

	/*
	 *  Move to next queue in hashbin
	 */
	bin++;
	for ( i = bin; i < HASHBIN_SIZE; i++ ) {
		entry = hashbin->hb_queue[ i];
		if ( entry) {
			hashbin->hb_current = entry;

			return entry;
		}
	}
	return NULL;
}
EXPORT_SYMBOL(hashbin_get_next);

redpajama_set_name: RedPajamaGithub


text:
from twitter import *
import json
print "parody parrot"

twitter_stream = TwitterStream(auth=OAuth("183299989-LE4WbYNKTLxibK5vx1meVMEdZpUjFQcfRoEdtkfX", "uhREnKogXj49HgqeX1uxvTC7WgEJHQkOVci2lKRrRGw7j", "zbsCXr4Bel5pxuHGi9KXcDFaR", "cgBUYOlgGKC1f4A57bn1iHnV3PlVq4B0nV13m98V2I3rpQonu7"))

iterator = twitter_stream.statuses.sample()

for tweet in iterator:
	print json.dumps(tweet, indent=2)
	if "favorite_count" in tweet:
		print tweet["favorite_count"]


text:
package esilatest

/*
Not found */
type GetUniverseTypesTypeIdNotFound struct {
	/*
	 Not found message */
	Error_ string `json:"error,omitempty"`
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace stGeo
{
    [Serializable]
    public class stGeoRange
    {
        public uint ipStart = 0;
        public uint ipEnd = 0;
        public int  ipASNumber = 0;
        public int  ipCountry = 0;
    }

    [Serializable]
    public class stGeoCountry
    {
        public int Id = 0;
        public string Tag = String.Empty;
        public string Name = String.Empty;
    }
}


text:
package com.twitter.zipkin.collector.filter

import com.twitter.zipkin.collector.sampler.{EverythingGlobalSampler, NullGlobalSampler}
import com.twitter.zipkin.common.Span
import org.scalatest.mock.MockitoSugar
import org.scalatest.{FunSuite, Matchers}

class SamplerFilterSpec extends FunSuite with Matchers with MockitoSugar {

  test("let the span pass if debug flag is set") {
    val span = Span(12345, "methodcall", 666, debug = Some(true))
    val samplerProcessor = new SamplerFilter(NullGlobalSampler)

    samplerProcessor(Seq(span)) should be (Seq(span))
  }

  test("let the span pass if debug flag false and sampler says yes") {
    val span = Span(12345, "methodcall", 666, debug = Some(false))
    val samplerProcessor = new SamplerFilter(EverythingGlobalSampler)

    samplerProcessor(Seq(span)) should be (Seq(span))
  }

  test("not let the span pass if debug flag false and sampler says no") {
    val span = Span(12345, "methodcall", 666, debug = Some(false))
    val samplerProcessor = new SamplerFilter(NullGlobalSampler)

    samplerProcessor(Seq(span)) should be (empty)
  }
}


text:
package fi.jumi.core.discovery;

import fi.jumi.actors.ActorRef;
import fi.jumi.core.api.TestFile;
import fi.jumi.core.discovery.dummies.DummyTest;
import org.junit.Test;

import java.net.*;
import java.nio.file.*;

import static org.mockito.Mockito.*;

public class PathMatcherTestFileFinderTest {

    private final Path classesDirectory = getClassesDirectory(DummyTest.class);
    private final TestFileFinderListener listener = mock(TestFileFinderListener.class);

    @Test
    public void finds_all_classes_from_a_directory_matching_a_pattern() {
        PathMatcher matcher = classesDirectory.getFileSystem().getPathMatcher("glob:fi/jumi/core/discovery/dummies/*Test.class");
        PathMatcherTestFileFinder finder = new PathMatcherTestFileFinder(matcher, classesDirectory);

        finder.findTestFiles(ActorRef.wrap(listener));

        verify(listener).onTestFileFound(TestFile.fromPath(Paths.get("fi/jumi/core/discovery/dummies/DummyTest.class")));
        verify(listener).onTestFileFound(TestFile.fromPath(Paths.get("fi/jumi/core/discovery/dummies/AnotherDummyTest.class")));
        verify(listener).onAllTestFilesFound();
        verifyNoMoreInteractions(listener);
    }

    @Test
    public void does_nothing_when_finds_no_matches() {
        PathMatcher matcher = classesDirectory.getFileSystem().getPathMatcher("glob:NoMatches");
        PathMatcherTestFileFinder finder = new PathMatcherTestFileFinder(matcher, classesDirectory);

        finder.findTestFiles(ActorRef.wrap(listener));

        verify(listener).onAllTestFilesFound();
        verifyNoMoreInteractions(listener);
    }

    private static Path getClassesDirectory(Class<?> clazz) {
        try {
            URL classFile = clazz.getResource(clazz.getSimpleName() + ".class");
            Path path = Paths.get(classFile.toURI());

            int directoryDepth = clazz.getName().split("\\.").length;
            for (int i = 0; i < directoryDepth; i++) {
                path = path.getParent();
            }
            return path;

        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
class CreateImportResults < ActiveRecord::Migration
  def change
    create_table :import_results do |t|
      t.references  :import, index: true, foreign_key: true
      t.integer     :status, default: 0
      t.datetime    :source_data_modified
      t.datetime    :start_time
      t.datetime    :end_time
      t.text        :found_listing_keys, :limit => 4294967295
      t.text        :removed_listing_keys, :limit => 4294967295
      t.text        :snapshots, :limit => 4294967295

      t.timestamps null: false
    end
  end
end


text:
package com.linkedin.pinot.query.transform;

import com.linkedin.pinot.core.operator.transform.function.AdditionTransform;
import com.linkedin.pinot.core.operator.transform.function.TransformFunction;
import java.util.Random;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Test of {@link AdditionTransform} class.
 */
public class AdditionTransformTest {

  private static final int NUM_ROWS = 1000;
  private static final double EPSILON = 1e-5;

  /**
   * Tests that addition for three columns (one int, one float and one double)
   * are as expected.
   */
  @Test
  public void test() {
    long seed = System.nanoTime();
    Random random = new Random(seed);

    double[] input1 = new double[NUM_ROWS];
    double[] input2 = new double[NUM_ROWS];
    double[] input3 = new double[NUM_ROWS];

    double[] expected = new double[NUM_ROWS];

    for (int i = 0; i < NUM_ROWS; i++) {
      input1[i] = random.nextInt();
      input2[i] = random.nextFloat();
      input3[i] = random.nextDouble();
      expected[i] = input1[i] + input2[i] + input3[i];
    }

    TransformFunction function = new AdditionTransform();
    double[] actual = function.transform(NUM_ROWS, new TransformTestUtils.TestBlockValSet(input1, NUM_ROWS),
        new TransformTestUtils.TestBlockValSet(input2, NUM_ROWS),
        new TransformTestUtils.TestBlockValSet(input3, NUM_ROWS));

    for (int i = 0; i < NUM_ROWS; i++) {
      Assert.assertEquals(actual[i], expected[i], EPSILON, ("Random seed: " + seed));
    }
  }
}


text:
use anyhow::Result;
use clap::{ArgMatches, Command};

use crate::api::Api;
use crate::utils::formatting::Table;

pub fn make_command(command: Command) -> Command {
    command.about("List all organizations available to the authenticated token.")
}

pub fn execute(_matches: &ArgMatches) -> Result<()> {
    let api = Api::current();
    let mut organizations = api.list_organizations()?;

    organizations.sort_by_key(|o| o.name.clone().to_lowercase());

    let mut table = Table::new();
    table
        .title_row()
        .add("ID")
        .add("Name")
        .add("Slug")
        .add("Date Created")
        .add("Early Adopter")
        .add("Requires 2FA");

    for organization in &organizations {
        table
            .add_row()
            .add(&organization.id)
            .add(&organization.name)
            .add(&organization.slug)
            .add(&organization.date_created.format("%F"))
            .add(organization.is_early_adopter)
            .add(organization.require_2fa);
    }

    table.print();

    Ok(())
}


text:
<?php

/**
 * Created by PhpStorm.
 * User: Buddhi
 * Date: 1/13/2016
 * Time: 5:51 PM
 */
namespace Model;

class School
{
    private $school_id;
    private $name;
    private $address;
    private $district;
    private $divisional_sec_area;
    private $telephone;
    private $category;
    private $is_rural;
    private $capacity;
    /**
     * School constructor.
     * @param $address
     * @param $category
     * @param $district
     * @param $divisional_sec_area
     * @param $name
     * @param $school_id
     * @param $telephone
     */
    public function __construct($address, $category, $district, $divisional_sec_area, $name, $school_id, $telephone,$is_rural,$capacity)
    {
        $this->is_rural = $is_rural;
        $this->address = $address;
        $this->category = $category;
        $this->district = $district;
        $this->divisional_sec_area = $divisional_sec_area;
        $this->name = $name;
        $this->school_id = $school_id;
        $this->telephone = $telephone;
        $this->capacity=$capacity;
    }

    /**
     * @return mixed
     */
    public function getCapacity()
    {
        return $this->capacity;
    }

    /**
     * @param mixed $capacity
     */
    public function setCapacity($capacity)
    {
        $this->capacity = $capacity;
    }

    /**
     * @return mixed
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * @param mixed $address
     */
    public function setAddress($address)
    {
        $this->address = $address;
    }

    /**
     * @return mixed
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * @param mixed $category
     */
    public function setCategory($category)
    {
        $this->category = $category;
    }

    /**
     * @return mixed
     */
    public function getDistrict()
    {
        return $this->district;
    }

    /**
     * @param mixed $district
     */
    public function setDistrict($district)
    {
        $this->district = $district;
    }

    /**
     * @return mixed
     */
    public function getDivisionalSecArea()
    {
        return $this->divisional_sec_area;
    }

    /**
     * @param mixed $divisional_sec_area
     */
    public function setDivisionalSecArea($divisional_sec_area)
    {
        $this->divisional_sec_area = $divisional_sec_area;
    }

    /**
     * @return mixed
     */
    public function getIsRural()
    {
        return $this->is_rural;
    }

    /**
     * @param mixed $is_rural
     */
    public function setIsRural($is_rural)
    {
        $this->is_rural = $is_rural;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return mixed
     */
    public function getSchoolId()
    {
        return $this->school_id;
    }

    /**
     * @param mixed $school_id
     */
    public function setSchoolId($school_id)
    {
        $this->school_id = $school_id;
    }

    /**
     * @return mixed
     */
    public function getTelephone()
    {
        return $this->telephone;
    }

    /**
     * @param mixed $telephone
     */
    public function setTelephone($telephone)
    {
        $this->telephone = $telephone;
    }

}


text:
<?php

namespace App\Models\Relations;

use DB;
use InvalidArgumentException;
use App\Models\Device;
use App\Models\Measurement;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\Relation;

class HasManyMeasurements extends Relation {
	function __construct (Device $parent) {
		$related = new Measurement();

		parent::__construct($related->newQuery(), $parent);
	}

	function addConstraints () {
		if ( ! static::$constraints) return;

		$this->addDeviceConstraints($this->parent);
	}

	function addEagerConstraints (array $models) {
		if ( ! $models) return;

		if (count($models) > 1) {
			throw new InvalidArgumentException('Eager loading for multiple devices not supported.');
		}

		$this->addDeviceConstraints($models[0]);
	}

	function addDeviceConstraints (Device $device) {
		$this->query
			->from($device->udid)
			->where('timestamp', '<=', DB::raw('NOW()'));
	}

	function initRelation (array $models, $relation) {
		foreach ($models as $model) {
			$model->setRelation($relation, null);
		}

		return $models;
	}

	function match (array $models, Collection $results, $relation) {
		foreach ($models as $model) {
			$model->setRelation($relation, $results->first());
		}

		return $models;
	}

	function getResults () {
		return $this->query->get();
	}
}


text:
<?php

namespace ZfcRbac\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use ZfcRbac\Options\ModuleOptions;

/**
 * Factory for the module options
 *
 * @author  Michaël Gallego <mic.gallego@gmail.com>
 * @license MIT
 */
class ModuleOptionsFactory implements FactoryInterface
{
    /**
     * {@inheritDoc}
     * @return ModuleOptions
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return new ModuleOptions($serviceLocator->get('Config')['zfc_rbac']);
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovieMakerUpload : MonoBehaviour {

    [SerializeField]
    private bool CanUpload = false;

    [SerializeField]
    private bool IsDiffOne = false;

    [SerializeField]
    private bool IsFirst = false;

    public void Upload () {
        CanUpload = true;
        if (!IsFirst)
        {
            GetComponent<Animator>().SetBool("Glow", true);
        }
        if (IsDiffOne)
        {
            MicrogameController.instance.setVictory(victory: true, final: true);
            GameObject.Find("BlackScreen").GetComponent<Animator>().SetBool("Expand", true);
        }
	}

    private void OnMouseDown()
    {
        if (CanUpload)
        {
            MicrogameController.instance.setVictory(victory: true, final: true);
            GameObject.Find("BlackScreen").GetComponent<Animator>().SetBool("Expand", true);
        }
    }
}


text:
package org.apache.sis.measure;

import java.util.Locale;
import java.time.Instant;
import org.apache.sis.test.TestCase;
import org.junit.Test;

import static org.junit.Assume.assumeTrue;
import static org.apache.sis.test.Assert.*;

/**
 * Tests the {@link Range} class.
 *
 * @author  Joe White
 * @author  Martin Desruisseaux (Geomatys)
 * @version 1.1
 * @since   0.3
 * @module
 */
public final strictfp class RangeTest extends TestCase {
    /**
     * Tests the creation of {@link Range} objects under normal conditions.
     */
    @Test
    public void testConstructor() {
        Range<Integer> range = new Range<>(Integer.class, 3, true, 5, true);
        assertEquals(Integer.valueOf(3), range.getMinValue());
        assertEquals(Integer.valueOf(5), range.getMaxValue());
        assertTrue  (range.isMaxIncluded());
        assertTrue  (range.isMinIncluded());
        assertFalse (range.isEmpty());

        range = new Range<>(Integer.class, 3, false, 5, true);
        assertEquals(Integer.valueOf(3), range.getMinValue());
        assertEquals(Integer.valueOf(5), range.getMaxValue());
        assertTrue  (range.isMaxIncluded());
        assertFalse (range.isMinIncluded());
        assertFalse (range.isEmpty());

        range = new Range<>(Integer.class, 2, true, 7, false);
        assertEquals(Integer.valueOf(2), range.getMinValue());
        assertEquals(Integer.valueOf(7), range.getMaxValue());
        assertFalse (range.isMaxIncluded());
        assertTrue  (range.isMinIncluded());
        assertFalse (range.isEmpty());

        range = new Range<>(Integer.class, 3, false, 10, false);
        assertEquals(Integer.valueOf( 3), range.getMinValue());
        assertEquals(Integer.valueOf(10), range.getMaxValue());
        assertFalse (range.isMaxIncluded());
        assertFalse (range.isMinIncluded());
        assertFalse (range.isEmpty());

        range = new Range<>(Integer.class, 10, true, 2, true);
        assertEquals(Integer.valueOf(10), range.getMinValue());
        assertEquals(Integer.valueOf( 2), range.getMaxValue());
        assertTrue (range.isEmpty());
    }

    /**
     * Tests the detection of illegal arguments at {@link Range} creation time.
     * Note that such error should never happen when parameterized types are used.
     * The check performed by the constructor is a safety in case the user bypass
     * the parameterized type check by using the raw type instead.
     *
     *
This test requires assertions to be enabled.

     */
    @Test(expected = IllegalArgumentException.class)
    @SuppressWarnings({"unchecked", "rawtypes", "ResultOfObjectAllocationIgnored"})
    public void testConstructorErrors00() {
        assumeTrue(Range.class.desiredAssertionStatus());
        new Range(Double.class, "error", true, "blast", true);
    }

    /**
     * Tests the detection of illegal arguments at {@link Range} creation time.
     * Note that such error should never happen when parameterized types are used.
     * The check performed by the constructor is a safety in case the user bypass
     * the parameterized type check by using the raw type instead.
     *
     *
This test requires assertions to be enabled.

     */
    @Test(expected = IllegalArgumentException.class)
    @SuppressWarnings({"unchecked", "rawtypes", "ResultOfObjectAllocationIgnored"})
    public void testConstructorErrors01() {
        assumeTrue(Range.class.desiredAssertionStatus());
        new Range(String.class, 123.233, true, 8740.09, true);
    }

    /**
     * Tests the {@link Range#contains(Comparable)} method.
     */
    @Test
    public void testContains() {
        final Range<Integer> range = new Range<>(Integer.class, 3, true, 5, true);
        assertTrue (range.contains(4));
        assertFalse(range.contains(6));
        assertFalse(range.contains(2));
        assertTrue (range.contains(3));
        assertTrue (range.contains(5));
    }

    /**
     * Tests the {@link Range#contains(Comparable)} method with an exclusive minimal value.
     */
    @Test
    public void testContainsNotInclusiveMinimum() {
        final Range<Integer> range = new Range<>(Integer.class, 2, false, 5, true);
        assertTrue (range.contains(4));
        assertFalse(range.contains(6));
        assertFalse(range.contains(2));
        assertTrue (range.contains(3));
        assertTrue (range.contains(5));

    }

    /**
     * Tests the {@link Range#contains(Comparable)} method with an exclusive maximal value.
     */
    @Test
    public void testContainsNotInclusiveMaximum() {
        final Range<Integer> range = new Range<>(Integer.class, 3, true, 6, false);
        assertTrue (range.contains(4));
        assertFalse(range.contains(6));
        assertFalse(range.contains(2));
        assertTrue (range.contains(3));
        assertTrue (range.contains(5));
    }

    /**
     * Tests the {@link Range#contains(Comparable)} method without lower endpoint.
     */
    @Test
    public void testContainsNoLowerEndpoint() {
        final Range<Integer> range = new Range<>(Integer.class, null, true, 5, true);
        assertTrue (range.contains(-555));
        assertTrue (range.contains(5));
        assertFalse(range.contains(6));
    }

    /**
     * Tests the {@link Range#contains(Comparable)} method without upper endpoint.
     */
    @Test
    public void testContainsNoUpperEndpoint() {
        final Range<Integer> range = new Range<>(Integer.class, 3, true, null, true);
        assertFalse(range.contains(1));
        assertTrue (range.contains(3));
        assertTrue (range.contains(10000));
    }

    /**
     * Tests the {@link Range#contains(Comparable)} method without lower or upper endpoints.
     */
    @Test
    public void testContainsNoEndpoints() {
        final Range<Integer> range = new Range<>(Integer.class, null, true, null, true);
        assertTrue(range.contains(-55555));
        assertTrue(range.contains(100000));
    }

    /**
     * Tests the {@link Range#contains(Range)} method.
     */
    @Test
    public void testContainsRange() {
        final Range<Integer> range  = new Range<>(Integer.class, -10, true, 10, true);
        final Range<Integer> inside = new Range<>(Integer.class,  -5, true,  5, true);

        assertTrue(range.contains(inside));
        assertFalse(inside.contains(range));
    }

    /**
     * Tests the {@link Range#contains(Range)} method without lower endpoint.
     */
    @Test
    public void testContainsRangeNoLowerEndpoint() {
        final Range<Integer> range  = new Range<>(Integer.class,  null, true, 500, true);
        final Range<Integer> inside = new Range<>(Integer.class, -2500, true, 305, true);

        assertTrue (range.contains(inside));
        assertFalse(inside.contains(range));
    }

    /**
     * Tests the {@link Range#contains(Range)} method without upper endpoint.
     */
    @Test
    public void testContainsRangeNoUpperEndpoint() {
        final Range<Integer> range  = new Range<>(Integer.class, -2500, true, null, true);
        final Range<Integer> inside = new Range<>(Integer.class,    17, true,  305, true);

        assertTrue(range.contains(inside));
        assertFalse(inside.contains(range));
    }

    /**
     * Tests the {@link Range#intersects(Range)} method.
     */
    @Test
    public void testIntersects() {
        final Range<Character> range1 = new Range<>(Character.class, 'a', true, 'g', true);
        final Range<Character> range2 = new Range<>(Character.class, 'c', true, 'm', true);
        final Range<Character> range3 = new Range<>(Character.class, 'o', true, 'z', true);

        assertTrue (range1.intersects(range2));
        assertTrue (range2.intersects(range1));
        assertFalse(range1.intersects(range3));
        assertFalse(range3.intersects(range1));
    }

    /**
     * Tests the {@link Range#intersect(Range)} method.
     */
    @Test
    @SuppressWarnings("UnnecessaryBoxing")
    public void testIntersection() {
        final Range<Integer> range1 = new Range<>(Integer.class, 1, true, 5, true);
        final Range<Integer> range2 = new Range<>(Integer.class, 4, true, 6, true);

        final Range<?> intersection = range1.intersect(range2);
        assertEquals(Integer.class, intersection.getElementType());
        assertEquals(Integer.valueOf(4), intersection.getMinValue());
        assertEquals(Integer.valueOf(5), intersection.getMaxValue());
    }

    /**
     * Tests the {@link Range#intersect(Range)} method with arguments resulting in empty range.
     */
    @Test
    public void testIntersectionOfNonIntersectingRanges() {
        final Range<Integer> range1 = new Range<>(Integer.class, 1, true,  5, true);
        final Range<Integer> range2 = new Range<>(Integer.class, 8, true, 10, true);

        final Range<?> intersection = range1.intersect(range2);
        assertEquals(Integer.class, intersection.getElementType());
        assertTrue(intersection.isEmpty());
    }

    /**
     * Tests the {@link Range#union(Range)} method.
     */
    @Test
    @SuppressWarnings("UnnecessaryBoxing")
    public void testUnion() {
        final Range<Character> range1 = new Range<>(Character.class, 'a', true, 'f', true);
        final Range<Character> range2 = new Range<>(Character.class, 'd', true, 'h', true);

        final Range<?> union = range1.union(range2);
        assertFalse(union.isEmpty());
        assertEquals(Character.valueOf('a'), union.getMinValue());
        assertEquals(Character.valueOf('h'), union.getMaxValue());
    }

    /**
     * Tests the {@link Range#union(Range)} method with disjoint ranges.
     */
    @Test
    @SuppressWarnings("UnnecessaryBoxing")
    public void testDisjointUnion() {
        final Range<Character> range1 = new Range<>(Character.class, 'a', true, 'f', true);
        final Range<Character> range2 = new Range<>(Character.class, 'm', true, 'v', true);

        final Range<?> unionRange = range1.union(range2);
        assertFalse(unionRange.isEmpty());
        assertEquals(Character.valueOf('a'), unionRange.getMinValue());
        assertEquals(Character.valueOf('v'), unionRange.getMaxValue());
    }

    /**
     * Tests the {@link Range#subtract(Range)} method.
     */
    @Test
    public void testSubtract() {
        final Range<Integer> range1 = new Range<>(Integer.class, 10, true, 40, true);
        final Range<Integer> range2 = new Range<>(Integer.class, 20, true, 25, true);
        final Range<Integer>[] subtract = range1.subtract(range2);
        assertEquals(2, subtract.length);
        assertEquals(new Range<>(Integer.class, 10, true,  20, false), subtract[0]);
        assertEquals(new Range<>(Integer.class, 25, false, 40, true),  subtract[1]);
    }

    /**
     * Tests the {@link Range#toString()} method.
     */
    @Test
    public void testToString() {
        assertEquals("{}",        new Range<>(Integer.class, 10, false, 10, false).toString());
        assertEquals("{10}",      new Range<>(Integer.class, 10, true,  10, true ).toString());
        assertEquals("[10 … 20]", new Range<>(Integer.class, 10, true,  20, true ).toString());
        assertEquals("(10 … 20)", new Range<>(Integer.class, 10, false, 20, false).toString());
        assertEquals("[10 … 20)", new Range<>(Integer.class, 10, true,  20, false).toString());
        assertEquals("(10 … 20]", new Range<>(Integer.class, 10, false, 20, true ).toString());
    }

    /**
     * Tests the {@link Range#formatTo(Formatter, int, int, int)} method.
     */
    @Test
    public void testFormatTo() {
        final Range<Integer> range = new Range<>(Integer.class, 10, true,  20, false);
        assertEquals("[10 … 20)",    String.format(Locale.CANADA, "%s", range));
        assertEquals("[10 … 20)",    String.format(Locale.CANADA, "%4s", range));
        assertEquals("[10 … 20)   ", String.format(Locale.CANADA, "%-12s", range));
        assertEquals("   [10 … 20)", String.format(Locale.CANADA, "%12s", range));
        assertEquals("[10 … 20[   ", String.format(Locale.CANADA, "%#-12s", range));
    }

    /**
     * Tests the {@link Range#formatTo(Formatter, int, int, int)} method with a range of instants.
     *
     * @see RangeFormatTest#testFormatInstant()
     */
    @Test
    public void testFormatInstantTo() {
        final Range<Instant> range = new Range<>(Instant.class,
                Instant.parse("2019-12-23T06:00:00Z"), true,
                Instant.parse("2020-05-14T18:00:00Z"), true);
        /*
         * The result depends on time zone and we have no API for forcing the time zone to some specific
         * value in a call to 'Range.formatTo(Formatter, …)`. So we verify only the year and the month.
         */
        final String result = String.format(Locale.CANADA, "%s", range);
        assertTrue(result, result.matches("\\[2019-12-.+ … 2020-05-.+\\]"));
    }

    /**
     * Tests the {@link Range#equals(Object)} method.
     */
    @Test
    public void testEquality() {
        // Positive test - success case
        final Range<Character> range1 = new Range<>(Character.class, 'a', true, 'f', true);
        final Range<Character> range2 = new Range<>(Character.class, 'a', true, 'f', true);
        assertTrue(range1.equals(range2));

        // Positive test - failure case
        final Range<Character> range3 = new Range<>(Character.class, 'a', true, 'g', true);
        assertFalse(range1.equals(range3));

        // Failure due to type incompatibility
        final Range<String> range4 = new Range<>(String.class, "a", true, "g", true);
        assertFalse(range3.equals(range4));

        final Range<Character> range5 = new Range<>(Character.class, 'g', true, 'a', true);
        final Range<Character> range6 = new Range<>(Character.class, 'g', true, 'a', true);
        assertTrue(range5.isEmpty());
        assertTrue(range6.isEmpty());
        assertTrue(range5.equals(range6));
    }

    /**
     * Tests serialization.
     */
    @Test
    public void testSerialization() {
        final Range<Integer> range  = new Range<>(Integer.class, -10, true, 10, true);
        assertNotSame(range, assertSerializedEquals(range));
    }
}


text:
#ifndef _REG_DECL_PLUGINS_H_
#define _REG_DECL_PLUGINS_H_

class ast_manager;

void reg_decl_plugins(ast_manager & m);

#endif


text:
import unittest
import mock
import tempfile
import time

from six.moves import range
from test import safe_repr
from test.unit import MockTrue

from swift.common.swob import HTTPBadRequest, Request, HTTPException
from swift.common.http import HTTP_REQUEST_ENTITY_TOO_LARGE, \
    HTTP_BAD_REQUEST, HTTP_LENGTH_REQUIRED, HTTP_NOT_IMPLEMENTED
from swift.common import constraints, utils

class TestConstraints(unittest.TestCase):

    def assertIn(self, member, container, msg=None):
        """Copied from 2.7"""
        if member not in container:
            standardMsg = '%s not found in %s' % (safe_repr(member),
                                                  safe_repr(container))
            self.fail(self._formatMessage(msg, standardMsg))

    def test_check_metadata_empty(self):
        headers = {}
        self.assertEquals(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object'), None)

    def test_check_metadata_good(self):
        headers = {'X-Object-Meta-Name': 'Value'}
        self.assertEquals(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object'), None)

    def test_check_metadata_empty_name(self):
        headers = {'X-Object-Meta-': 'Value'}
        self.assertTrue(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object'), HTTPBadRequest)

    def test_check_metadata_name_length(self):
        name = 'a' * constraints.MAX_META_NAME_LENGTH
        headers = {'X-Object-Meta-%s' % name: 'v'}
        self.assertEquals(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object'), None)
        name = 'a' * (constraints.MAX_META_NAME_LENGTH + 1)
        headers = {'X-Object-Meta-%s' % name: 'v'}
        self.assertEquals(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object').status_int, HTTP_BAD_REQUEST)
        self.assertIn(
            ('X-Object-Meta-%s' % name).lower(),
            constraints.check_metadata(Request.blank(
                '/', headers=headers), 'object').body.lower())

    def test_check_metadata_value_length(self):
        value = 'a' * constraints.MAX_META_VALUE_LENGTH
        headers = {'X-Object-Meta-Name': value}
        self.assertEquals(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object'), None)
        value = 'a' * (constraints.MAX_META_VALUE_LENGTH + 1)
        headers = {'X-Object-Meta-Name': value}
        self.assertEquals(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object').status_int, HTTP_BAD_REQUEST)
        self.assertIn(
            'x-object-meta-name',
            constraints.check_metadata(Request.blank(
                '/', headers=headers),
                'object').body.lower())
        self.assertIn(
            str(constraints.MAX_META_VALUE_LENGTH),
            constraints.check_metadata(Request.blank(
                '/', headers=headers),
                'object').body)

    def test_check_metadata_count(self):
        headers = {}
        for x in range(constraints.MAX_META_COUNT):
            headers['X-Object-Meta-%d' % x] = 'v'
        self.assertEquals(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object'), None)
        headers['X-Object-Meta-Too-Many'] = 'v'
        self.assertEquals(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object').status_int, HTTP_BAD_REQUEST)

    def test_check_metadata_size(self):
        headers = {}
        size = 0
        chunk = constraints.MAX_META_NAME_LENGTH + \
            constraints.MAX_META_VALUE_LENGTH
        x = 0
        while size + chunk < constraints.MAX_META_OVERALL_SIZE:
            headers['X-Object-Meta-%04d%s' %
                    (x, 'a' * (constraints.MAX_META_NAME_LENGTH - 4))] = \
                'v' * constraints.MAX_META_VALUE_LENGTH
            size += chunk
            x += 1
        self.assertEquals(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object'), None)
        # add two more headers in case adding just one falls exactly on the
        # limit (eg one header adds 1024 and the limit is 2048)
        headers['X-Object-Meta-%04d%s' %
                (x, 'a' * (constraints.MAX_META_NAME_LENGTH - 4))] = \
            'v' * constraints.MAX_META_VALUE_LENGTH
        headers['X-Object-Meta-%04d%s' %
                (x + 1, 'a' * (constraints.MAX_META_NAME_LENGTH - 4))] = \
            'v' * constraints.MAX_META_VALUE_LENGTH
        self.assertEquals(constraints.check_metadata(Request.blank(
            '/', headers=headers), 'object').status_int, HTTP_BAD_REQUEST)

    def test_check_object_creation_content_length(self):
        headers = {'Content-Length': str(constraints.MAX_FILE_SIZE),
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), 'object_name'), None)

        headers = {'Content-Length': str(constraints.MAX_FILE_SIZE + 1),
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(
            Request.blank('/', headers=headers), 'object_name').status_int,
            HTTP_REQUEST_ENTITY_TOO_LARGE)

        headers = {'Transfer-Encoding': 'chunked',
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), 'object_name'), None)

        headers = {'Transfer-Encoding': 'gzip',
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), 'object_name').status_int,
            HTTP_BAD_REQUEST)

        headers = {'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(
            Request.blank('/', headers=headers), 'object_name').status_int,
            HTTP_LENGTH_REQUIRED)

        headers = {'Content-Length': 'abc',
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), 'object_name').status_int,
            HTTP_BAD_REQUEST)

        headers = {'Transfer-Encoding': 'gzip,chunked',
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), 'object_name').status_int,
            HTTP_NOT_IMPLEMENTED)

    def test_check_object_creation_copy(self):
        headers = {'Content-Length': '0',
                   'X-Copy-From': 'c/o2',
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), 'object_name'), None)

        headers = {'Content-Length': '1',
                   'X-Copy-From': 'c/o2',
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), 'object_name').status_int,
            HTTP_BAD_REQUEST)

        headers = {'Transfer-Encoding': 'chunked',
                   'X-Copy-From': 'c/o2',
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), 'object_name'), None)

        # a content-length header is always required
        headers = {'X-Copy-From': 'c/o2',
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), 'object_name').status_int,
            HTTP_LENGTH_REQUIRED)

    def test_check_object_creation_name_length(self):
        headers = {'Transfer-Encoding': 'chunked',
                   'Content-Type': 'text/plain'}
        name = 'o' * constraints.MAX_OBJECT_NAME_LENGTH
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), name), None)
        name = 'o' * (constraints.MAX_OBJECT_NAME_LENGTH + 1)
        self.assertEquals(constraints.check_object_creation(
            Request.blank('/', headers=headers), name).status_int,
            HTTP_BAD_REQUEST)

    def test_check_object_creation_content_type(self):
        headers = {'Transfer-Encoding': 'chunked',
                   'Content-Type': 'text/plain'}
        self.assertEquals(constraints.check_object_creation(Request.blank(
            '/', headers=headers), 'object_name'), None)
        headers = {'Transfer-Encoding': 'chunked'}
        self.assertEquals(constraints.check_object_creation(
            Request.blank('/', headers=headers), 'object_name').status_int,
            HTTP_BAD_REQUEST)

    def test_check_object_creation_bad_content_type(self):
        headers = {'Transfer-Encoding': 'chunked',
                   'Content-Type': '\xff\xff'}
        resp = constraints.check_object_creation(
            Request.blank('/', headers=headers), 'object_name')
        self.assertEquals(resp.status_int, HTTP_BAD_REQUEST)
        self.assertTrue('Content-Type' in resp.body)

    def test_check_object_creation_bad_delete_headers(self):
        headers = {'Transfer-Encoding': 'chunked',
                   'Content-Type': 'text/plain',
                   'X-Delete-After': 'abc'}
        resp = constraints.check_object_creation(
            Request.blank('/', headers=headers), 'object_name')
        self.assertEquals(resp.status_int, HTTP_BAD_REQUEST)
        self.assertTrue('Non-integer X-Delete-After' in resp.body)

        t = str(int(time.time() - 60))
        headers = {'Transfer-Encoding': 'chunked',
                   'Content-Type': 'text/plain',
                   'X-Delete-At': t}
        resp = constraints.check_object_creation(
            Request.blank('/', headers=headers), 'object_name')
        self.assertEquals(resp.status_int, HTTP_BAD_REQUEST)
        self.assertTrue('X-Delete-At in past' in resp.body)

    def test_check_delete_headers(self):

        # X-Delete-After
        headers = {'X-Delete-After': '60'}
        resp = constraints.check_delete_headers(
            Request.blank('/', headers=headers))
        self.assertTrue(isinstance(resp, Request))
        self.assertTrue('x-delete-at' in resp.headers)

        headers = {'X-Delete-After': 'abc'}
        try:
            resp = constraints.check_delete_headers(
                Request.blank('/', headers=headers))
        except HTTPException as e:
            self.assertEquals(e.status_int, HTTP_BAD_REQUEST)
            self.assertTrue('Non-integer X-Delete-After' in e.body)
        else:
            self.fail("Should have failed with HTTPBadRequest")

        headers = {'X-Delete-After': '60.1'}
        try:
            resp = constraints.check_delete_headers(
                Request.blank('/', headers=headers))
        except HTTPException as e:
            self.assertEquals(e.status_int, HTTP_BAD_REQUEST)
            self.assertTrue('Non-integer X-Delete-After' in e.body)
        else:
            self.fail("Should have failed with HTTPBadRequest")

        headers = {'X-Delete-After': '-1'}
        try:
            resp = constraints.check_delete_headers(
                Request.blank('/', headers=headers))
        except HTTPException as e:
            self.assertEquals(e.status_int, HTTP_BAD_REQUEST)
            self.assertTrue('X-Delete-After in past' in e.body)
        else:
            self.fail("Should have failed with HTTPBadRequest")

        # X-Delete-At
        t = str(int(time.time() + 100))
        headers = {'X-Delete-At': t}
        resp = constraints.check_delete_headers(
            Request.blank('/', headers=headers))
        self.assertTrue(isinstance(resp, Request))
        self.assertTrue('x-delete-at' in resp.headers)
        self.assertEquals(resp.headers.get('X-Delete-At'), t)

        headers = {'X-Delete-At': 'abc'}
        try:
            resp = constraints.check_delete_headers(
                Request.blank('/', headers=headers))
        except HTTPException as e:
            self.assertEquals(e.status_int, HTTP_BAD_REQUEST)
            self.assertTrue('Non-integer X-Delete-At' in e.body)
        else:
            self.fail("Should have failed with HTTPBadRequest")

        t = str(int(time.time() + 100)) + '.1'
        headers = {'X-Delete-At': t}
        try:
            resp = constraints.check_delete_headers(
                Request.blank('/', headers=headers))
        except HTTPException as e:
            self.assertEquals(e.status_int, HTTP_BAD_REQUEST)
            self.assertTrue('Non-integer X-Delete-At' in e.body)
        else:
            self.fail("Should have failed with HTTPBadRequest")

        t = str(int(time.time()))
        headers = {'X-Delete-At': t}
        try:
            resp = constraints.check_delete_headers(
                Request.blank('/', headers=headers))
        except HTTPException as e:
            self.assertEquals(e.status_int, HTTP_BAD_REQUEST)
            self.assertTrue('X-Delete-At in past' in e.body)
        else:
            self.fail("Should have failed with HTTPBadRequest")

        t = str(int(time.time() - 1))
        headers = {'X-Delete-At': t}
        try:
            resp = constraints.check_delete_headers(
                Request.blank('/', headers=headers))
        except HTTPException as e:
            self.assertEquals(e.status_int, HTTP_BAD_REQUEST)
            self.assertTrue('X-Delete-At in past' in e.body)
        else:
            self.fail("Should have failed with HTTPBadRequest")

    def test_check_delete_headers_sets_delete_at(self):
        t = time.time() + 1000
        # check delete-at is passed through
        headers = {'Content-Length': '0',
                   'Content-Type': 'text/plain',
                   'X-Delete-At': str(int(t))}
        req = Request.blank('/', headers=headers)
        constraints.check_delete_headers(req)
        self.assertTrue('X-Delete-At' in req.headers)
        self.assertEqual(req.headers['X-Delete-At'], str(int(t)))

        # check delete-after is converted to delete-at
        headers = {'Content-Length': '0',
                   'Content-Type': 'text/plain',
                   'X-Delete-After': '42'}
        req = Request.blank('/', headers=headers)
        with mock.patch('time.time', lambda: t):
            constraints.check_delete_headers(req)
        self.assertTrue('X-Delete-At' in req.headers)
        expected = str(int(t) + 42)
        self.assertEqual(req.headers['X-Delete-At'], expected)

        # check delete-after takes precedence over delete-at
        headers = {'Content-Length': '0',
                   'Content-Type': 'text/plain',
                   'X-Delete-After': '42',
                   'X-Delete-At': str(int(t) + 40)}
        req = Request.blank('/', headers=headers)
        with mock.patch('time.time', lambda: t):
            constraints.check_delete_headers(req)
        self.assertTrue('X-Delete-At' in req.headers)
        self.assertEqual(req.headers['X-Delete-At'], expected)

        headers = {'Content-Length': '0',
                   'Content-Type': 'text/plain',
                   'X-Delete-After': '42',
                   'X-Delete-At': str(int(t) + 44)}
        req = Request.blank('/', headers=headers)
        with mock.patch('time.time', lambda: t):
            constraints.check_delete_headers(req)
        self.assertTrue('X-Delete-At' in req.headers)
        self.assertEqual(req.headers['X-Delete-At'], expected)

    def test_check_dir(self):
        self.assertFalse(constraints.check_dir('', ''))
        with mock.patch("os.path.isdir", MockTrue()):
            self.assertTrue(constraints.check_dir('/srv', 'foo/bar'))

    def test_check_mount(self):
        self.assertFalse(constraints.check_mount('', ''))
        with mock.patch("swift.common.utils.ismount", MockTrue()):
            self.assertTrue(constraints.check_mount('/srv', '1'))
            self.assertTrue(constraints.check_mount('/srv', 'foo-bar'))
            self.assertTrue(constraints.check_mount(
                '/srv', '003ed03c-242a-4b2f-bee9-395f801d1699'))
            self.assertFalse(constraints.check_mount('/srv', 'foo bar'))
            self.assertFalse(constraints.check_mount('/srv', 'foo/bar'))
            self.assertFalse(constraints.check_mount('/srv', 'foo?bar'))

    def test_check_float(self):
        self.assertFalse(constraints.check_float(''))
        self.assertTrue(constraints.check_float('0'))

    def test_valid_timestamp(self):
        self.assertRaises(HTTPException,
                          constraints.valid_timestamp,
                          Request.blank('/'))
        self.assertRaises(HTTPException,
                          constraints.valid_timestamp,
                          Request.blank('/', headers={
                              'X-Timestamp': 'asdf'}))
        timestamp = utils.Timestamp(time.time())
        req = Request.blank('/', headers={'X-Timestamp': timestamp.internal})
        self.assertEqual(timestamp, constraints.valid_timestamp(req))
        req = Request.blank('/', headers={'X-Timestamp': timestamp.normal})
        self.assertEqual(timestamp, constraints.valid_timestamp(req))

    def test_check_utf8(self):
        unicode_sample = u'\uc77c\uc601'
        valid_utf8_str = unicode_sample.encode('utf-8')
        invalid_utf8_str = unicode_sample.encode('utf-8')[::-1]
        unicode_with_null = u'abc\u0000def'
        utf8_with_null = unicode_with_null.encode('utf-8')

        for false_argument in [None,
                               '',
                               invalid_utf8_str,
                               unicode_with_null,
                               utf8_with_null]:
            self.assertFalse(constraints.check_utf8(false_argument))

        for true_argument in ['this is ascii and utf-8, too',
                              unicode_sample,
                              valid_utf8_str]:
            self.assertTrue(constraints.check_utf8(true_argument))

    def test_check_utf8_non_canonical(self):
        self.assertFalse(constraints.check_utf8('\xed\xa0\xbc\xed\xbc\xb8'))
        self.assertFalse(constraints.check_utf8('\xed\xa0\xbd\xed\xb9\x88'))

    def test_check_utf8_lone_surrogates(self):
        self.assertFalse(constraints.check_utf8('\xed\xa0\xbc'))
        self.assertFalse(constraints.check_utf8('\xed\xb9\x88'))

    def test_validate_bad_meta(self):
        req = Request.blank(
            '/v/a/c/o',
            headers={'x-object-meta-hello':
                     'ab' * constraints.MAX_HEADER_SIZE})
        self.assertEquals(constraints.check_metadata(req, 'object').status_int,
                          HTTP_BAD_REQUEST)
        self.assertIn('x-object-meta-hello', constraints.check_metadata(req,
                      'object').body.lower())

    def test_validate_constraints(self):
        c = constraints
        self.assertTrue(c.MAX_META_OVERALL_SIZE > c.MAX_META_NAME_LENGTH)
        self.assertTrue(c.MAX_META_OVERALL_SIZE > c.MAX_META_VALUE_LENGTH)
        self.assertTrue(c.MAX_HEADER_SIZE > c.MAX_META_NAME_LENGTH)
        self.assertTrue(c.MAX_HEADER_SIZE > c.MAX_META_VALUE_LENGTH)

    def test_validate_copy_from(self):
        req = Request.blank(
            '/v/a/c/o',
            headers={'x-copy-from': 'c/o2'})
        src_cont, src_obj = constraints.check_copy_from_header(req)
        self.assertEqual(src_cont, 'c')
        self.assertEqual(src_obj, 'o2')
        req = Request.blank(
            '/v/a/c/o',
            headers={'x-copy-from': 'c/subdir/o2'})
        src_cont, src_obj = constraints.check_copy_from_header(req)
        self.assertEqual(src_cont, 'c')
        self.assertEqual(src_obj, 'subdir/o2')
        req = Request.blank(
            '/v/a/c/o',
            headers={'x-copy-from': '/c/o2'})
        src_cont, src_obj = constraints.check_copy_from_header(req)
        self.assertEqual(src_cont, 'c')
        self.assertEqual(src_obj, 'o2')

    def test_validate_bad_copy_from(self):
        req = Request.blank(
            '/v/a/c/o',
            headers={'x-copy-from': 'bad_object'})
        self.assertRaises(HTTPException,
                          constraints.check_copy_from_header, req)

    def test_validate_destination(self):
        req = Request.blank(
            '/v/a/c/o',
            headers={'destination': 'c/o2'})
        src_cont, src_obj = constraints.check_destination_header(req)
        self.assertEqual(src_cont, 'c')
        self.assertEqual(src_obj, 'o2')
        req = Request.blank(
            '/v/a/c/o',
            headers={'destination': 'c/subdir/o2'})
        src_cont, src_obj = constraints.check_destination_header(req)
        self.assertEqual(src_cont, 'c')
        self.assertEqual(src_obj, 'subdir/o2')
        req = Request.blank(
            '/v/a/c/o',
            headers={'destination': '/c/o2'})
        src_cont, src_obj = constraints.check_destination_header(req)
        self.assertEqual(src_cont, 'c')
        self.assertEqual(src_obj, 'o2')

    def test_validate_bad_destination(self):
        req = Request.blank(
            '/v/a/c/o',
            headers={'destination': 'bad_object'})
        self.assertRaises(HTTPException,
                          constraints.check_destination_header, req)

    def test_check_account_format(self):
        req = Request.blank(
            '/v/a/c/o',
            headers={'X-Copy-From-Account': 'account/with/slashes'})
        self.assertRaises(HTTPException,
                          constraints.check_account_format,
                          req, req.headers['X-Copy-From-Account'])
        req = Request.blank(
            '/v/a/c/o',
            headers={'X-Copy-From-Account': ''})
        self.assertRaises(HTTPException,
                          constraints.check_account_format,
                          req, req.headers['X-Copy-From-Account'])

    def test_check_container_format(self):
        invalid_versions_locations = (
            'container/with/slashes',
            '',  # empty
        )
        for versions_location in invalid_versions_locations:
            req = Request.blank(
                '/v/a/c/o', headers={
                    'X-Versions-Location': versions_location})
            try:
                constraints.check_container_format(
                    req, req.headers['X-Versions-Location'])
            except HTTPException as e:
                self.assertTrue(e.body.startswith('Container name cannot'))
            else:
                self.fail('check_container_format did not raise error for %r' %
                          req.headers['X-Versions-Location'])

class TestConstraintsConfig(unittest.TestCase):

    def test_default_constraints(self):
        for key in constraints.DEFAULT_CONSTRAINTS:
            # if there is local over-rides in swift.conf we just continue on
            if key in constraints.OVERRIDE_CONSTRAINTS:
                continue
            # module level attrs (that aren't in OVERRIDE) should have the
            # same value as the DEFAULT map
            module_level_value = getattr(constraints, key.upper())
            self.assertEquals(constraints.DEFAULT_CONSTRAINTS[key],
                              module_level_value)

    def test_effective_constraints(self):
        for key in constraints.DEFAULT_CONSTRAINTS:
            # module level attrs should always mirror the same value as the
            # EFFECTIVE map
            module_level_value = getattr(constraints, key.upper())
            self.assertEquals(constraints.EFFECTIVE_CONSTRAINTS[key],
                              module_level_value)
            # if there are local over-rides in swift.conf those should be
            # reflected in the EFFECTIVE, otherwise we expect the DEFAULTs
            self.assertEquals(constraints.EFFECTIVE_CONSTRAINTS[key],
                              constraints.OVERRIDE_CONSTRAINTS.get(
                                  key, constraints.DEFAULT_CONSTRAINTS[key]))

    def test_override_constraints(self):
        try:
            with tempfile.NamedTemporaryFile() as f:
                f.write('[swift-constraints]\n')
                # set everything to 1
                for key in constraints.DEFAULT_CONSTRAINTS:
                    f.write('%s = 1\n' % key)
                f.flush()
                with mock.patch.object(utils, 'SWIFT_CONF_FILE', f.name):
                    constraints.reload_constraints()
            for key in constraints.DEFAULT_CONSTRAINTS:
                # module level attrs should all be 1
                module_level_value = getattr(constraints, key.upper())
                self.assertEquals(module_level_value, 1)
                # all keys should be in OVERRIDE
                self.assertEquals(constraints.OVERRIDE_CONSTRAINTS[key],
                                  module_level_value)
                # module level attrs should always mirror the same value as
                # the EFFECTIVE map
                self.assertEquals(constraints.EFFECTIVE_CONSTRAINTS[key],
                                  module_level_value)
        finally:
            constraints.reload_constraints()

    def test_reload_reset(self):
        try:
            with tempfile.NamedTemporaryFile() as f:
                f.write('[swift-constraints]\n')
                # set everything to 1
                for key in constraints.DEFAULT_CONSTRAINTS:
                    f.write('%s = 1\n' % key)
                f.flush()
                with mock.patch.object(utils, 'SWIFT_CONF_FILE', f.name):
                    constraints.reload_constraints()
            self.assertTrue(constraints.SWIFT_CONSTRAINTS_LOADED)
            self.assertEquals(sorted(constraints.DEFAULT_CONSTRAINTS.keys()),
                              sorted(constraints.OVERRIDE_CONSTRAINTS.keys()))
            # file is now deleted...
            with mock.patch.object(utils, 'SWIFT_CONF_FILE', f.name):
                constraints.reload_constraints()
            # no constraints have been loaded from non-existent swift.conf
            self.assertFalse(constraints.SWIFT_CONSTRAINTS_LOADED)
            # no constraints are in OVERRIDE
            self.assertEquals([], constraints.OVERRIDE_CONSTRAINTS.keys())
            # the EFFECTIVE constraints mirror DEFAULT
            self.assertEquals(constraints.EFFECTIVE_CONSTRAINTS,
                              constraints.DEFAULT_CONSTRAINTS)
        finally:
            constraints.reload_constraints()

if __name__ == '__main__':
    unittest.main()


text:
//--------------------------------------
// XerialJ
//
// SnappyInputStreamTest.java
// Since: 2011/03/31 22:31:51
//
// $URL$
// $Author$
//--------------------------------------
package org.xerial.snappy;

import static org.junit.Assert.*;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.junit.Test;
import org.xerial.util.FileResource;
import org.xerial.util.log.Logger;

public class SnappyInputStreamTest
{
    private static Logger _logger = Logger.getLogger(SnappyInputStreamTest.class);

    public static byte[] readResourceFile(String fileName)
            throws IOException
    {
        BufferedInputStream input = new BufferedInputStream(FileResource.find(SnappyOutputStreamTest.class, fileName)
                .openStream());
        assertNotNull(input);
        return readFully(input);
    }

    public static byte[] readFully(InputStream input)
            throws IOException
    {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[4096];
            for (int readBytes = 0; (readBytes = input.read(buf)) != -1; ) {
                out.write(buf, 0, readBytes);
            }
            out.flush();
            return out.toByteArray();
        }
        finally {
            input.close();
        }
    }

    public static byte[] byteWiseReadFully(InputStream input)
            throws IOException
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        for (int readData = 0; (readData = input.read()) != -1; ) {
            out.write(readData);
        }
        out.flush();
        return out.toByteArray();
    }

    @Test
    public void read()
            throws Exception
    {
        ByteArrayOutputStream compressedBuf = new ByteArrayOutputStream();
        SnappyOutputStream snappyOut = new SnappyOutputStream(compressedBuf);
        byte[] orig = readResourceFile("alice29.txt");
        snappyOut.write(orig);
        snappyOut.close();
        byte[] compressed = compressedBuf.toByteArray();
        _logger.debug("compressed size: " + compressed.length);

        SnappyInputStream in = new SnappyInputStream(new ByteArrayInputStream(compressed));
        byte[] uncompressed = readFully(in);

        assertEquals(orig.length, uncompressed.length);
        assertArrayEquals(orig, uncompressed);
    }

    @Test
    public void readBlockCompressedData()
            throws Exception
    {
        byte[] orig = readResourceFile("alice29.txt");
        byte[] compressed = Snappy.compress(orig);

        SnappyInputStream in = new SnappyInputStream(new ByteArrayInputStream(compressed));
        byte[] uncompressed = readFully(in);

        assertEquals(orig.length, uncompressed.length);
        assertArrayEquals(orig, uncompressed);
    }

    @Test
    public void biteWiseRead()
            throws Exception
    {
        byte[] orig = readResourceFile("testdata/calgary/paper6");
        byte[] compressed = Snappy.compress(orig);

        SnappyInputStream in = new SnappyInputStream(new ByteArrayInputStream(compressed));
        byte[] uncompressed = byteWiseReadFully(in);

        assertEquals(orig.length, uncompressed.length);
        assertArrayEquals(orig, uncompressed);
    }

    @Test
    public void available()
            throws Exception
    {
        byte[] orig = readResourceFile("testdata/calgary/paper6");
        byte[] compressed = Snappy.compress(orig);

        SnappyInputStream in = new SnappyInputStream(new ByteArrayInputStream(compressed));
        byte[] buf = new byte[4];
        for (int readBytes = 0; (readBytes = in.read(buf)) != -1; ) {
            assertTrue(in.available() >= 0);
        }
        assertTrue(in.available() == 0);
        in.close();
    }

    @Test
    public void emptyStream()
            throws Exception
    {
        try {
            SnappyInputStream in = new SnappyInputStream(new ByteArrayInputStream(new byte[0]));
            byte[] uncompressed = readFully(in);
            assertEquals(0, uncompressed.length);
            fail("should not reach here");
        }
        catch (SnappyIOException e) {
            assertEquals(SnappyErrorCode.EMPTY_INPUT, e.getErrorCode());
        }
    }

    public static byte[] compressResource(String resourcePath)
            throws Exception
    {
        ByteArrayOutputStream compressedBuf = new ByteArrayOutputStream();
        SnappyOutputStream snappyOut = new SnappyOutputStream(compressedBuf);
        byte[] orig = readResourceFile(resourcePath);
        snappyOut.write(orig);
        snappyOut.close();
        return compressedBuf.toByteArray();
    }

    @Test
    public void chunkRead()
            throws Exception
    {
        byte[] chunk1 = compressResource("alice29.txt");
        byte[] chunk2 = compressResource("testdata/calgary/paper6");

        byte[] concatenated = new byte[chunk1.length + chunk2.length];
        System.arraycopy(chunk1, 0, concatenated, 0, chunk1.length);
        System.arraycopy(chunk2, 0, concatenated, chunk1.length, chunk2.length);

        SnappyInputStream in = new SnappyInputStream(new ByteArrayInputStream(concatenated));
        byte[] uncompressed = readFully(in);

        byte[] orig1 = readResourceFile("alice29.txt");
        byte[] orig2 = readResourceFile("testdata/calgary/paper6");
        assertEquals(orig1.length + orig2.length, uncompressed.length);
        byte[] uncompressed1 = new byte[orig1.length];
        byte[] uncompressed2 = new byte[orig2.length];
        System.arraycopy(uncompressed, 0, uncompressed1, 0, orig1.length);
        System.arraycopy(uncompressed, orig1.length, uncompressed2, 0, orig2.length);

        assertArrayEquals(orig1, uncompressed1);
        assertArrayEquals(orig2, uncompressed2);
    }

    @Test
    public void readSnappyCompressResult()
            throws Exception
    {
        byte[] orig = readResourceFile("alice29.txt");
        byte[] compressed = Snappy.compress(orig);
        SnappyInputStream in = new SnappyInputStream(new ByteArrayInputStream(compressed));
        byte[] uncompressed = readFully(in);

        assertArrayEquals(orig, uncompressed);
    }
}


text:
require 'spec_helper'
require 'warp/dir'

RSpec.describe Warp::Dir::Point do
  include_context :fake_serializer
  include_context :initialized_store

  let(:path_absolute) { "#{::Dir.home}/workspace" }
  let(:path_relative) { '~/workspace' }
  let(:p1) { Warp::Dir::Point.new('p', "#{::Dir.home}/workspace") }
  let(:p2) { Warp::Dir::Point.new('n', "#{::Dir.home}/workspace/new-project") }

  describe 'with two distinct but identical objects' do
    let(:p2) { Warp::Dir::Point.new('p', "#{::Dir.home}/workspace") }
    it 'correctly defines #eql?' do
      expect(p1).to eql(p2)
    end
    it 'correctly defines #hash' do
      expect(p1.hash).to eql(p2.hash)
    end
    it '#file.path' do
      expect(file.path.length > 0).to be_truthy
    end
  end

  describe 'instance methods' do
    it '#to_s' do
      expect(p1.to_s).to eql('p  ->  ~/workspace')
    end
    it '#inspect' do
      expect(p1.inspect).to match(%r(name: '#{p1.name}', path: '#{p1.relative_path}'))
    end
  end

  describe '#filtered_paths' do
    describe 'automatically creates accessors to full_path based on filters' do
      let(:rel_path) { '~/workspace' }
      let(:abs_path) { "#{::Dir.home}/workspace" }
      let(:p) { Warp::Dir::Point.new('boo', rel_path ) }

      it 'should properly define absolute_path accessor' do
        expect(p.absolute_path).to eql(abs_path)
      end
      it 'should properly define absolute_path accessor' do
        expect(p.relative_path).to eql(rel_path)
      end
      it 'should properly define absolute_path accessor' do
        expect(p.path).to eql(abs_path)
      end
    end

    describe 'when point warps to a folder with a space in the name' do
      let(:long_path) { '/Documents/My Long Ass Name With Space' }
      let(:pl) { Warp::Dir::Point.new('boo', ::Dir.home + long_path) }
      context 'should return quoted result when called' do
        it '#absolute_path' do
          expect(pl.absolute_path).to eql(%Q("#{::Dir.home}#{long_path}"))
        end
        it '#relative_path' do
          expect(pl.relative_path).to eql(%Q("~#{long_path}"))
        end
        it '#path' do
          expect(pl.path).to eql(pl.absolute_path)
        end
      end
    end

    describe 'serialization' do
      let(:path) { '~/Documents/My Long Ass Name With Space' }
      let(:name) { 'boo' }
      let(:point) { Warp::Dir::Point.new(name, path) }
      let(:serialized_string) { "#{name}:#{Warp::Dir.absolute(path)}" }

      context '#serialize' do
        it 'should correctly serialize warp point' do
          expect(point.serialize).to eql(serialized_string)
        end
      end
      context '#deserialize' do
        let(:restored_point) { Warp::Dir::Point.deserialize(serialized_string) }
        it 'should correctly serialize warp point' do
          expect(point).to eql(restored_point)
        end
      end
    end
  end
end


text:
@interface MockRatesRepository : NSObject<iRatesRepository>

@end


text:
package org.wso2.carbon.identity.oauth2.authz.handlers;

import org.apache.amber.oauth2.common.exception.OAuthSystemException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.oauth.cache.OAuthCacheKey;
import org.wso2.carbon.identity.oauth.common.OAuthConstants;
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO;
import org.wso2.carbon.identity.oauth2.model.AuthzCodeDO;
import org.wso2.carbon.identity.oauth2.util.OAuth2Util;

import java.sql.Timestamp;
import java.util.Date;

public class CodeResponseTypeHandler extends AbstractResponseTypeHandler {

    private static Log log = LogFactory.getLog(CodeResponseTypeHandler.class);

    @Override
    public OAuth2AuthorizeRespDTO issue(OAuthAuthzReqMessageContext oauthAuthzMsgCtx)
            throws IdentityOAuth2Exception {
        OAuth2AuthorizeRespDTO respDTO = new OAuth2AuthorizeRespDTO();
        String authorizationCode;

        OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();

        try {
            authorizationCode = oauthIssuerImpl.authorizationCode();
        } catch (OAuthSystemException e) {
            throw new IdentityOAuth2Exception(e.getMessage(), e);
        }

        Timestamp timestamp = new Timestamp(new Date().getTime());

        long validityPeriod = OAuthServerConfiguration.getInstance()
                .getAuthorizationCodeValidityPeriodInSeconds();

        // if a VALID callback is set through the callback handler, use
        // it instead of the default one
        long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod();

        if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD)
                && callbackValidityPeriod > 0) {
            validityPeriod = callbackValidityPeriod;
        }
        // convert to milliseconds
        validityPeriod = validityPeriod * 1000;

        AuthzCodeDO authzCodeDO = new AuthzCodeDO(authorizationReqDTO.getUsername(),
                oauthAuthzMsgCtx.getApprovedScope(), timestamp, validityPeriod, authorizationReqDTO.getCallbackUrl());

        tokenMgtDAO.storeAuthorizationCode(authorizationCode, authorizationReqDTO.getConsumerKey(),
                authorizationReqDTO.getCallbackUrl(), authzCodeDO);

        if (cacheEnabled) {
            // Cache the authz Code, here we prepend the client_key to avoid collisions with
            // AccessTokenDO instances. In database level, these are in two databases. But access
            // tokens and authorization codes are in a single cache.
            String cacheKeyString = OAuth2Util.buildCacheKeyStringForAuthzCode(
                    authorizationReqDTO.getConsumerKey(), authorizationCode);
            oauthCache.addToCache(new OAuthCacheKey(cacheKeyString), authzCodeDO);
            if (log.isDebugEnabled()) {
                log.debug("Authorization Code info was added to the cache for client id : " +
                        authorizationReqDTO.getConsumerKey());
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Issued Authorization Code to user : " + authorizationReqDTO.getUsername() +
                    ", Using the redirect url : " + authorizationReqDTO.getCallbackUrl() +
                    ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) +
                    ", validity period : " + validityPeriod);
        }

        respDTO.setCallbackURI(authorizationReqDTO.getCallbackUrl());
        respDTO.setAuthorizationCode(authorizationCode);
        return respDTO;
    }

}


text:
using NUnit.Framework;

namespace React.Tests.Core
{
	[TestFixture]
	public class BabelConfigTests
	{
		[Test]
		public void SerializesAllLoose()
		{
			var config = new BabelConfig
			{
				AllLoose = true,
			};
			var result = config.Serialize();
			Assert.AreEqual(@"{""externalHelpers"":false,""optional"":null,""stage"":2,""loose"":""all""}", result);
		}

		[Test]
		public void SerializesSomeLoose()
		{
			var config = new BabelConfig
			{
				Loose = new[] { "foo" },
			};
			var result = config.Serialize();
			Assert.AreEqual(@"{""externalHelpers"":false,""optional"":null,""stage"":2,""loose"":[""foo""]}", result);
		}
	}
}


text:
repo = github.com/ipfs/fs-repo-migrations
# sub-package to build (omit when building the main package)
package = fs-repo-8-to-9

include ../../common.mk


text:
import alt from '../alt';

class PostActions {
  newPost(post) {
    this.dispatch(post);
  }

}

export default alt.createActions(PostActions);


text:
layout: post
title: "Formatting objects in PowerShell with Format-Custom, Format-List, Format-Table, and Format-Wide"
date:   2018-09-28 09:00
comments: true
description: "Formatting objects in PowerShell with Format-Custom, Format-List, Format-Table, and Format-Wide"
categories:
    - PowerShell
tags:
    - PowerShell
---

This article follows the theme of my last one: Formatting object output in PowerShell with Format.ps1xml files. Here we'll look at the built-in cmdlets Format-Custom, Format-List, Format-Table, and Format-Wide that PowerShell provides to format your output.

From my previous article, we know *.format.ps1xml files in the PowerShell installation directory ($pshome) control object formatting. PowerShell provides Format-* cmdlets that let the user change object appearance when writing them back to the console.

To see the available format cmdlets and the ones I will be discussing in this article, let's turn to Get-Command....

To continue reading please follow the below link.

[4sysops article continues here...](https://4sysops.com/archives/formatting-objects-in-powershell-with-format-custom-format-list-format-table-and-format-wide/)


text:
package com.justplay1.shoppist.repository.datasource.local.database;

import android.content.ContentValues;
import android.content.Context;

import com.justplay1.shoppist.eventbus.DataEventBus;
import com.justplay1.shoppist.eventbus.ListItemsDataUpdatedEvent;
import com.justplay1.shoppist.data.R;
import com.justplay1.shoppist.entity.CurrencyDAO;
import com.justplay1.shoppist.repository.datasource.local.LocalCurrencyDataStore;
import com.squareup.sqlbrite.BriteDatabase;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Singleton;

import rx.Observable;

/**
 * Created by Mkhytar Mkhoian.
 */
@Singleton
public class LocalCurrencyDataStoreImpl extends BaseLocalDataStore<CurrencyDAO> implements LocalCurrencyDataStore {

    private static String CURRENCY_QUERY(String selection) {
        if (selection == null) {
            return "SELECT * FROM " + CurrencyDAO.TABLE;
        }
        return "SELECT * FROM " + CurrencyDAO.TABLE +
                " WHERE " + selection;
    }

    private Context context;

    @Inject
    public LocalCurrencyDataStoreImpl(BriteDatabase db, Context context) {
        super(db);
        this.context = context;
    }

    public Observable<Map<String, CurrencyDAO>> getDefaultData() {
        String[] currency = context.getResources().getStringArray(R.array.currency);
        Map<String, CurrencyDAO> currencyList = new HashMap<>(currency.length);
        for (String c : currency) {
            String[] currencyId = c.split(" ! ");
            String id = currencyId[1];
            String name = currencyId[0];
            CurrencyDAO currency1 = new CurrencyDAO(id, name);
            currencyList.put(currency1.getId(), currency1);
        }
        return Observable.just(currencyList);
    }

    @Override
    public Observable<List<CurrencyDAO>> getItems() {
        return db.createQuery(CurrencyDAO.TABLE, CURRENCY_QUERY(null), new String[]{})
                .mapToList(CurrencyDAO.MAPPER);
    }

    @Override
    public Observable<CurrencyDAO> getItem(String id) {
        return db.createQuery(CurrencyDAO.TABLE, CURRENCY_QUERY(CurrencyDAO.WHERE_STRING), id)
                .mapToOne(CurrencyDAO.MAPPER);
    }

    @Override
    public void save(Collection<CurrencyDAO> data) {
        BriteDatabase.Transaction transaction = db.newTransaction();
        try {
            for (CurrencyDAO currency : data) {
                db.insert(CurrencyDAO.TABLE, getValue(currency));
            }
            transaction.markSuccessful();
        } finally {
            transaction.end();
        }
        notifyShoppingListItemsChange();
    }

    @Override
    public void delete(Collection<CurrencyDAO> data) {
        BriteDatabase.Transaction transaction = db.newTransaction();
        try {
            for (CurrencyDAO currency : data) {
                db.delete(CurrencyDAO.TABLE, CurrencyDAO.WHERE_STRING, currency.getId());
            }
            transaction.markSuccessful();
        } finally {
            transaction.end();
        }
        notifyShoppingListItemsChange();
    }

    @Override
    public void update(Collection<CurrencyDAO> data) {
        BriteDatabase.Transaction transaction = db.newTransaction();
        try {
            for (CurrencyDAO currency : data) {
                db.update(CurrencyDAO.TABLE, getValue(currency), CurrencyDAO.WHERE_STRING, currency.getId());
            }
            transaction.markSuccessful();
        } finally {
            transaction.end();
        }
        notifyShoppingListItemsChange();
    }

    @Override
    public int clear() {
        return clear(CurrencyDAO.TABLE);
    }

    private void notifyShoppingListItemsChange() {
        DataEventBus.instanceOf().post(new ListItemsDataUpdatedEvent());
    }

    @Override
    protected ContentValues getValue(CurrencyDAO data) {
        return new CurrencyDAO.Builder()
                .id(data.getId())
                .name(data.getName())
                .build();
    }
}