text:
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)

using System;

using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;

namespace Org.BouncyCastle.Crypto.Agreement
{
    /**
     * P1363 7.2.1 ECSVDP-DH
     *
     * ECSVDP-DH is Elliptic Curve Secret Value Derivation Primitive,
     * Diffie-Hellman version. It is based on the work of [DH76], [Mil86],
     * and [Kob87]. This primitive derives a shared secret value from one
     * party's private key and another party's public key, where both have
     * the same set of EC domain parameters. If two parties correctly
     * execute this primitive, they will produce the same output. This
     * primitive can be invoked by a scheme to derive a shared secret key;
     * specifically, it may be used with the schemes ECKAS-DH1 and
     * DL/ECKAS-DH2. It assumes that the input keys are valid (see also
     * Section 7.2.2).
     */
    public class ECDHBasicAgreement
        : IBasicAgreement
    {
        protected internal ECPrivateKeyParameters privKey;

        public virtual void Init(
            ICipherParameters parameters)
        {
            if (parameters is ParametersWithRandom)
            {
                parameters = ((ParametersWithRandom)parameters).Parameters;
            }

            this.privKey = (ECPrivateKeyParameters)parameters;
        }

        public virtual int GetFieldSize()
        {
            return (privKey.Parameters.Curve.FieldSize + 7) / 8;
        }

        public virtual BigInteger CalculateAgreement(
            ICipherParameters pubKey)
        {
            ECPublicKeyParameters pub = (ECPublicKeyParameters) pubKey;
            ECPoint P = pub.Q.Multiply(privKey.D).Normalize();

            if (P.IsInfinity)
                throw new InvalidOperationException("Infinity is not a valid agreement value for ECDH");

            return P.AffineXCoord.ToBigInteger();
        }
    }
}

#endif


text:
      <button class="btn btn-link btn-control-link btn-toggle"
              ng-if="node.children.length"
              ng-click="toggleOpen()">

      </button>

      <button class="btn btn-link btn-control-link btn-control remove"
              ng-click="deselect($event)">

      </button>

        {{ node.name }}

redpajama_set_name: RedPajamaGithub


text:
package com.logpresso.client;

/**
 * @since 1.1.3
 * @author xeraph
 *
 */
public class ProcedureParameter {
	private String key;
	private String type;
	private String name;
	private String description;

	public ProcedureParameter() {
	}

	public ProcedureParameter(String type, String key) {
		this.type = type;
		this.key = key;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getName() {
		return name;
	}

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

	public String getDescription() {
		return description;
	}

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

	@Override
	public String toString() {
		return type + " " + key;
	}
}


text:
var request = ('request');

var request = require('request').defaults({
    json: true
})
var stream = require('stream')
var url = require('url')
var qs = require('querystring')
var redditStats = require('measured').createCollection();

var requests_per_second = function() {
    try {
        var reqsPerSec = redditStats.toJSON().requestsPerSecond.mean;
    } catch (err) {
        var reqsPerSec = 0;
    }
    return reqsPerSec;
}

module.exports = function(username, lastParsed) {
    if (lastParsed === null || lastParsed === undefined) lastParsed = 0;
    var last = '';
    var started = false;
    var readStream = new stream.Readable({
        objectMode: true
    });

    function pullJSON(path, callback) {
        redditStats.meter('requestsPerSecond').mark();
        request({
            url: 'http://www.reddit.com/' + path,
            json: true
        }, callback);
    }

    function userJSON(username) {
        var username_path = 'user/' + username + '/about.json';
        pullJSON(username_path, function(error, res, user_data) {
            if (error || user_data.error) {
                readStream.emit('user', userObj);
            } else {
                try {
                    var userObj = {};
                    userObj.username = user_data.data.name;
                    userObj.created = user_data.data.created;
                    userObj.link_karma = user_data.data.link_karma;
                    userObj.comment_karma = user_data.data.comment_karma;
                    userObj.kind = 'usr';
                    readStream.emit('user', userObj);
                } catch (err) {

                }

            };
        });
    };
    //
    function exportUserHistory(username, next) {
        var path = '/user/' + username + '/.json?limit=100&after=' + last
        pullJSON(path, function(err, res, body) {
            if (err || body.error) return next;
            try {
                last = body.data.after
                var count = 0
                body.data.children.forEach(function(item) {
                    if (item.data.created > lastParsed) {
                        if (item.kind === 't1') readStream.emit('comment', item);
                        if (item.kind === 't3') readStream.emit('submission', item);
                        readStream.push(item);
                        count++;
                    } else {
                        body.data.after = null;
                    }
                });
                readStream.emit('page', last, count);
                if (body.data.after) next();
                else readStream.push(null)

            } catch (err) {
                readStream.emit('error', err, body);
            }
        });
    }
    setTimeout(function() {
        readStream.emit('metrics', requests_per_second());
    }, 5 * 1000);

    function loop() {
        exportUserHistory(username, function(err) {
            if (err) return console.log(err);
            setTimeout(loop, 2000);
        });
    }
    readStream._read = function(n) {
        if (!started) loop();
        if (!started) userJSON(username);
        started = true;
    };
    return readStream
};


text:
package org.wso2.carbon.identity.application.authenticator.social.internal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.identity.application.authentication.framework.ApplicationAuthenticator;
import org.wso2.carbon.identity.application.authenticator.social.facebook.FacebookAuthenticator;
import org.wso2.carbon.identity.application.authenticator.social.google.GoogleOAuth2Authenticator;
import org.wso2.carbon.identity.application.authenticator.social.live.WindowsLiveOAuth2Authenticator;
import org.wso2.carbon.identity.application.authenticator.social.yahoo.YahooOAuth2Authenticator;

/**
 * @scr.component name="identity.application.authenticator.social.component"
 * immediate="true"
 */
public class SocialAuthenticatorServiceComponent {

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

    protected void activate(ComponentContext ctxt) {
        try {

            FacebookAuthenticator facebookAuthenticator = new FacebookAuthenticator();
            ctxt.getBundleContext().registerService(ApplicationAuthenticator.class.getName(),
                    facebookAuthenticator,
                    null);

            WindowsLiveOAuth2Authenticator windowsLiveOAuth2Authenticator = new WindowsLiveOAuth2Authenticator();
            ctxt.getBundleContext().registerService(ApplicationAuthenticator.class.getName(),
                    windowsLiveOAuth2Authenticator,
                    null);

            GoogleOAuth2Authenticator googleAuthenticator = new GoogleOAuth2Authenticator();
            ctxt.getBundleContext().registerService(ApplicationAuthenticator.class.getName(),
                    googleAuthenticator,
                    null);

            YahooOAuth2Authenticator yahooOAuth2Authenticator = new YahooOAuth2Authenticator();
            ctxt.getBundleContext().registerService(ApplicationAuthenticator.class.getName(),
                    yahooOAuth2Authenticator,
                    null);

            if (log.isDebugEnabled()) {
                log.debug("Social Authenticator bundle is activated.");
            }

        } catch (Throwable e) {
            log.fatal("Error while activating Social authenticator bundle.", e);
        }
    }

    protected void deactivate(ComponentContext ctxt) {
        if (log.isDebugEnabled()) {
            log.debug("Social Authenticator bundle is deactivated.");
        }
    }
}


text:
package acme.util.identityhash;

import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;

import acme.util.Util;

/**
 * A modified version of the Java library class that uses
 * Util.identityHashcode.
 */

/**
 * A hash table supporting full concurrency of retrievals and
 * adjustable expected concurrency for updates. This class obeys the
 * same functional specification as {@link java.util.Hashtable}, and
 * includes versions of methods corresponding to each method of
 * <tt>Hashtable</tt>. However, even though all operations are
 * thread-safe, retrieval operations do not entail locking,
 * and there is not any support for locking the entire table
 * in a way that prevents all access.  This class is fully
 * interoperable with <tt>Hashtable</tt> in programs that rely on its
 * thread safety but not on its synchronization details.
 *
 *
 Retrieval operations (including <tt>get</tt>) generally do not
 * block, so may overlap with update operations (including
 * <tt>put</tt> and <tt>remove</tt>). Retrievals reflect the results
 * of the most recently completed update operations holding
 * upon their onset.  For aggregate operations such as <tt>putAll</tt>
 * and <tt>clear</tt>, concurrent retrievals may reflect insertion or
 * removal of only some entries.  Similarly, Iterators and
 * Enumerations return elements reflecting the state of the hash table
 * at some point at or since the creation of the iterator/enumeration.
 * They do not throw
 * {@link ConcurrentModificationException}.  However, iterators are
 * designed to be used by only one thread at a time.
 *
 *
 The allowed concurrency among update operations is guided by
 * the optional <tt>concurrencyLevel</tt> constructor argument
 * (default 16), which is used as a hint for internal sizing.  The
 * table is internally partitioned to try to permit the indicated
 * number of concurrent updates without contention. Because placement
 * in hash tables is essentially random, the actual concurrency will
 * vary.  Ideally, you should choose a value to accommodate as many
 * threads as will ever concurrently modify the table. Using a
 * significantly higher value than you need can waste space and time,
 * and a significantly lower value can lead to thread contention. But
 * overestimates and underestimates within an order of magnitude do
 * not usually have much noticeable impact. A value of one is
 * appropriate when it is known that only one thread will modify and
 * all others will only read. Also, resizing this or any other kind of
 * hash table is a relatively slow operation, so, when possible, it is
 * a good idea to provide estimates of expected table sizes in
 * constructors.
 *
 *
This class and its views and iterators implement all of the
 * optional methods of the {@link Map} and {@link Iterator}
 * interfaces.
 *
 *
 Like {@link java.util.Hashtable} but unlike {@link
 * java.util.HashMap}, this class does NOT allow <tt>null</tt> to be
 * used as a key or value.
 *
 *
This class is a member of the
 *
 * Java Collections Framework.
 *
 * @since 1.5
 * @author Doug Lea
 * @param <K> the type of keys maintained by this map
 * @param <V> the type of mapped values
 */
public class ConcurrentIdentityHashMap<K, V> extends AbstractMap<K, V> {

	/*
	 * The basic strategy is to subdivide the table among Segments,
	 * each of which itself is a concurrently readable hash table.
	 */

	/* ---------------- Constants -------------- */

	/**
	 * The default initial number of table slots for this table.
	 * Used when not otherwise specified in constructor.
	 */
	static int DEFAULT_INITIAL_CAPACITY = 16;

	/**
	 * The maximum capacity, used if a higher value is implicitly
	 * specified by either of the constructors with arguments.  MUST
	 * be a power of two <= 1<<30 to ensure that entries are indexible
	 * using ints.
	 */
	static final int MAXIMUM_CAPACITY = 1 << 30;

	/**
	 * The default load factor for this table.  Used when not
	 * otherwise specified in constructor.
	 */
	static final float DEFAULT_LOAD_FACTOR = 0.75f;

	/**
	 * The default number of concurrency control segments.
	 **/
	static final int DEFAULT_SEGMENTS = 16;

	/**
	 * The maximum number of segments to allow; used to bound
	 * constructor arguments.
	 */
	static final int MAX_SEGMENTS = 1 << 16; // slightly conservative

	/**
	 * Number of unsynchronized retries in size and containsValue
	 * methods before resorting to locking. This is used to avoid
	 * unbounded retries if tables undergo continuous modification
	 * which would make it impossible to obtain an accurate result.
	 */
	static final int RETRIES_BEFORE_LOCK = 2;

	/* ---------------- Fields -------------- */

	/**
	 * Mask value for indexing into segments. The upper bits of a
	 * key's hash code are used to choose the segment.
	 **/
	final int segmentMask;

	/**
	 * Shift value for indexing within segments.
	 **/
	final int segmentShift;

	/**
	 * The segments, each of which is a specialized hash table
	 */
	final Segment[] segments;

	transient Set<K> keySet;
	transient Set<Map.Entry<K,V>> entrySet;
	transient Collection<V> values;

	/* ---------------- Small Utilities -------------- */

	/**
	 * Returns a hash code for non-null Object x.
	 * Uses the same hash code spreader as most other java.util hash tables.
	 * @param x the object serving as a key
	 * @return the hash code
	 */
	static int hash(Object x) {
		int h = Util.identityHashCode(x);
		return h;
	}

	/**
	 * Returns the segment that should be used for key with given hash
	 * @param hash the hash code for the key
	 * @return the segment
	 */
	final Segment<K,V> segmentFor(int hash) {
		return segments[(hash >>> segmentShift) & segmentMask];
	}

	/* ---------------- Inner Classes -------------- */

	/**
	 * ConcurrentHashMap list entry. Note that this is never exported
	 * out as a user-visible Map.Entry.
	 *
	 * Because the value field is volatile, not final, it is legal wrt
	 * the Java Memory Model for an unsynchronized reader to see null
	 * instead of initial value when read via a data race.  Although a
	 * reordering leading to this is not likely to ever actually
	 * occur, the Segment.readValueUnderLock method is used as a
	 * backup in case a null (pre-initialized) value is ever seen in
	 * an unsynchronized access method.
	 */
	static final class HashEntry<K,V> {
		final K key;
		final int hash;
		volatile V value;
		final HashEntry<K,V> next;

		HashEntry(K key, int hash, HashEntry<K,V> next, V value) {
			this.key = key;
			this.hash = hash;
			this.next = next;
			this.value = value;
		}
	}

	/**
	 * Segments are specialized versions of hash tables.  This
	 * subclasses from ReentrantLock opportunistically, just to
	 * simplify some locking and avoid separate construction.
	 **/
	static final class Segment<K,V> extends ReentrantLock implements Serializable {
		/*
		 * Segments maintain a table of entry lists that are ALWAYS
		 * kept in a consistent state, so can be read without locking.
		 * Next fields of nodes are immutable (final).  All list
		 * additions are performed at the front of each bin. This
		 * makes it easy to check changes, and also fast to traverse.
		 * When nodes would otherwise be changed, new nodes are
		 * created to replace them. This works well for hash tables
		 * since the bin lists tend to be short. (The average length
		 * is less than two for the default load factor threshold.)
		 *
		 * Read operations can thus proceed without locking, but rely
		 * on selected uses of volatiles to ensure that completed
		 * write operations performed by other threads are
		 * noticed. For most purposes, the "count" field, tracking the
		 * number of elements, serves as that volatile variable
		 * ensuring visibility.  This is convenient because this field
		 * needs to be read in many read operations anyway:
		 *
		 *   - All (unsynchronized) read operations must first read the
		 *     "count" field, and should not look at table entries if
		 *     it is 0.
		 *
		 *   - All (synchronized) write operations should write to
		 *     the "count" field after structurally changing any bin.
		 *     The operations must not take any action that could even
		 *     momentarily cause a concurrent read operation to see
		 *     inconsistent data. This is made easier by the nature of
		 *     the read operations in Map. For example, no operation
		 *     can reveal that the table has grown but the threshold
		 *     has not yet been updated, so there are no atomicity
		 *     requirements for this with respect to reads.
		 *
		 * As a guide, all critical volatile reads and writes to the
		 * count field are marked in code comments.
		 */

		private static final long serialVersionUID = 2249069246763182397L;

		/**
		 * The number of elements in this segment's region.
		 **/
		transient volatile int count;

		/**
		 * Number of updates that alter the size of the table. This is
		 * used during bulk-read methods to make sure they see a
		 * consistent snapshot: If modCounts change during a traversal
		 * of segments computing size or checking containsValue, then
		 * we might have an inconsistent view of state so (usually)
		 * must retry.
		 */
		transient int modCount;

		/**
		 * The table is rehashed when its size exceeds this threshold.
		 * (The value of this field is always (int)(capacity *
		 * loadFactor).)
		 */
		transient int threshold;

		/**
		 * The per-segment table. Declared as a raw type, casted
		 * to HashEntry<K,V> on each use.
		 */
		transient volatile HashEntry[] table;

		/**
		 * The load factor for the hash table.  Even though this value
		 * is same for all segments, it is replicated to avoid needing
		 * links to outer object.
		 * @serial
		 */
		final float loadFactor;

		Segment(int initialCapacity, float lf) {
			loadFactor = lf;
			setTable(new HashEntry[initialCapacity]);
		}

		/**
		 * Set table to new HashEntry target.
		 * Call only while holding targe or in constructor.
		 **/
		void setTable(HashEntry[] newTable) {
			threshold = (int)(newTable.length * loadFactor);
			table = newTable;
		}

		/**
		 * Return properly casted first entry of bin for given hash
		 */
		HashEntry<K,V> getFirst(int hash) {
			HashEntry[] tab = table;
			return tab[hash & (tab.length - 1)];
		}

		/**
		 * Read value field of an entry under targe. Called if value
		 * field ever appears to be null. This is possible only if a
		 * compiler happens to reorder a HashEntry initialization with
		 * its table assignment, which is legal under memory model
		 * but is not known to ever occur.
		 */
		V readValueUnderLock(HashEntry<K,V> e) {
			lock();
			try {
				return e.value;
			} finally {
				unlock();
			}
		}

		/* Specialized implementations of map methods */

		V get(Object key, int hash) {
			if (count != 0) { // read-volatile
				HashEntry<K,V> e = getFirst(hash);
				while (e != null) {
					if (e.hash == hash && key == e.key) {
						V v = e.value;
						if (v != null)
							return v;
						return readValueUnderLock(e); // recheck
					}
					e = e.next;
				}
			}
			return null;
		}

		boolean containsKey(Object key, int hash) {
			if (count != 0) { // read-volatile
				HashEntry<K,V> e = getFirst(hash);
				while (e != null) {
					if (e.hash == hash && key == e.key)
						return true;
					e = e.next;
				}
			}
			return false;
		}

		boolean containsValue(Object value) {
			if (count != 0) { // read-volatile
				HashEntry[] tab = table;
				int len = tab.length;
				for (int i = 0 ; i < len; i++) {
					for (HashEntry<K,V> e = tab[i];
					e != null ;
					e = e.next) {
						V v = e.value;
						if (v == null) // recheck
							v = readValueUnderLock(e);
						if (value.equals(v))
							return true;
					}
				}
			}
			return false;
		}

		boolean replace(K key, int hash, V oldValue, V newValue) {
			lock();
			try {
				HashEntry<K,V> e = getFirst(hash);
				while (e != null && (e.hash != hash || key != e.key))
					e = e.next;

				boolean replaced = false;
				if (e != null && oldValue.equals(e.value)) {
					replaced = true;
					e.value = newValue;
				}
				return replaced;
			} finally {
				unlock();
			}
		}

		V replace(K key, int hash, V newValue) {
			lock();
			try {
				HashEntry<K,V> e = getFirst(hash);
				while (e != null && (e.hash != hash || key != e.key))
					e = e.next;

				V oldValue = null;
				if (e != null) {
					oldValue = e.value;
					e.value = newValue;
				}
				return oldValue;
			} finally {
				unlock();
			}
		}

		V put(K key, int hash, V value, boolean onlyIfAbsent) {
			lock();
			try {
				int c = count;
				if (c++ > threshold) {// ensure capacity
					rehash();
				}
				HashEntry[] tab = table;
				int index = hash & (tab.length - 1);
				HashEntry<K,V> first = tab[index];
				HashEntry<K,V> e = first;
				while (e != null && (e.hash != hash || key != e.key))
					e = e.next;

				V oldValue;
				if (e != null) {
					oldValue = e.value;
					if (!onlyIfAbsent)
						e.value = value;
				}
				else {
					oldValue = null;
					++modCount;
					tab[index] = new HashEntry<K,V>(key, hash, first, value);
					count = c; // write-volatile
				}
				return oldValue;
			} finally {
				unlock();
			}
		}

		void rehash() {
			HashEntry[] oldTable = table;
			int oldCapacity = oldTable.length;
			if (oldCapacity >= MAXIMUM_CAPACITY)
				return;

			/*
			 * Reclassify nodes in each list to new Map.  Because we are
			 * using power-of-two expansion, the elements from each bin
			 * must either stay at same index, or move with a power of two
			 * offset. We eliminate unnecessary node creation by catching
			 * cases where old nodes can be reused because their next
			 * fields won't change. Statistically, at the default
			 * threshold, only about one-sixth of them need cloning when
			 * a table doubles. The nodes they replace will be garbage
			 * collectable as soon as they are no longer referenced by any
			 * reader thread that may be in the midst of traversing table
			 * right now.
			 */

			HashEntry[] newTable = new HashEntry[oldCapacity << 1];
			threshold = (int)(newTable.length * loadFactor);
			int sizeMask = newTable.length - 1;
			for (int i = 0; i < oldCapacity ; i++) {
				// We need to guarantee that any existing reads of old Map can
				//  proceed. So we cannot yet null out each bin.
				HashEntry<K,V> e = oldTable[i];

				if (e != null) {
					HashEntry<K,V> next = e.next;
					int idx = e.hash & sizeMask;

					//  Single node on list
					if (next == null)
						newTable[idx] = e;

					else {
						// Reuse trailing consecutive sequence at same slot
						HashEntry<K,V> lastRun = e;
						int lastIdx = idx;
						for (HashEntry<K,V> last = next;
						last != null;
						last = last.next) {
							int k = last.hash & sizeMask;
							if (k != lastIdx) {
								lastIdx = k;
								lastRun = last;
							}
						}
						newTable[lastIdx] = lastRun;

						// Clone all remaining nodes
						for (HashEntry<K,V> p = e; p != lastRun; p = p.next) {
							int k = p.hash & sizeMask;
							HashEntry<K,V> n = newTable[k];
							newTable[k] = new HashEntry<K,V>(p.key, p.hash,
									n, p.value);
						}
					}
				}
			}
			table = newTable;
		}

		/**
		 * Remove; match on key only if value null, else match both.
		 */
		V remove(Object key, int hash, Object value) {
			lock();
			try {
				int c = count - 1;
				HashEntry[] tab = table;
				int index = hash & (tab.length - 1);
				HashEntry<K,V> first = tab[index];
				HashEntry<K,V> e = first;
				while (e != null && (e.hash != hash || key != e.key))
					e = e.next;

				V oldValue = null;
				if (e != null) {
					V v = e.value;
					if (value == null || value.equals(v)) {
						oldValue = v;
						// All entries following removed node can stay
						// in list, but all preceding ones need to be
						// cloned.
						++modCount;
						HashEntry<K,V> newFirst = e.next;
						for (HashEntry<K,V> p = first; p != e; p = p.next)
							newFirst = new HashEntry<K,V>(p.key, p.hash,
									newFirst, p.value);
						tab[index] = newFirst;
						count = c; // write-volatile
					}
				}
				return oldValue;
			} finally {
				unlock();
			}
		}

		void clear() {
			if (count != 0) {
				lock();
				try {
					HashEntry[] tab = table;
					for (int i = 0; i < tab.length ; i++)
						tab[i] = null;
					++modCount;
					count = 0; // write-volatile
				} finally {
					unlock();
				}
			}
		}
	}

	/* ---------------- Public operations -------------- */

	/**
	 * Creates a new, empty map with the specified initial
	 * capacity, load factor, and concurrency level.
	 *
	 * @param initialCapacity the initial capacity. The implementation
	 * performs internal sizing to accommodate this many elements.
	 * @param loadFactor  the load factor threshold, used to control resizing.
	 * Resizing may be performed when the average number of elements per
	 * bin exceeds this threshold.
	 * @param concurrencyLevel the estimated number of concurrently
	 * updating threads. The implementation performs internal sizing
	 * to try to accommodate this many threads.
	 * @throws IllegalArgumentException if the initial capacity is
	 * negative or the load factor or concurrencyLevel are
	 * nonpositive.
	 */
	public ConcurrentIdentityHashMap(int initialCapacity,
			float loadFactor, int concurrencyLevel) {
		if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0)
			throw new IllegalArgumentException();

		if (concurrencyLevel > MAX_SEGMENTS)
			concurrencyLevel = MAX_SEGMENTS;

		// Find power-of-two sizes best matching arguments
		int sshift = 0;

		int ssize = 1;
		while (ssize < concurrencyLevel) {
			++sshift;
			ssize <<= 1;
		}
		segmentShift = 32 - sshift;
		segmentMask = ssize - 1;
		this.segments = new Segment[ssize];

		if (initialCapacity > MAXIMUM_CAPACITY)
			initialCapacity = MAXIMUM_CAPACITY;
		int c = initialCapacity / ssize;
		if (c * ssize < initialCapacity)
			++c;
		int cap = 1;
		while (cap < c)
			cap <<= 1;

		for (int i = 0; i < this.segments.length; ++i)
			this.segments[i] = new Segment<K,V>(cap, loadFactor);
	}

	/**
	 * Creates a new, empty map with the specified initial
	 * capacity, and with default load factor and concurrencyLevel.
	 *
	 * @param initialCapacity the initial capacity. The implementation
	 * performs internal sizing to accommodate this many elements.
	 * @throws IllegalArgumentException if the initial capacity of
	 * elements is negative.
	 */
	public ConcurrentIdentityHashMap(int initialCapacity) {
		this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
	}

	/**
	 * Creates a new, empty map with a default initial capacity,
	 * load factor, and concurrencyLevel.
	 */
	public ConcurrentIdentityHashMap() {
		this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
	}

	/**
	 * Creates a new map with the same mappings as the given map.  The
	 * map is created with a capacity of twice the number of mappings in
	 * the given map or 11 (whichever is greater), and a default load factor
	 * and concurrencyLevel.
	 * @param t the map
	 */
	public ConcurrentIdentityHashMap(Map<? extends K, ? extends V> t) {
		this(Math.max((int) (t.size() / DEFAULT_LOAD_FACTOR) + 1,
				11),
				DEFAULT_LOAD_FACTOR, DEFAULT_SEGMENTS);
		putAll(t);
	}

	// inherit Map javadoc
	@Override
	public boolean isEmpty() {
		final Segment[] segments = this.segments;
		/*
		 * We keep track of per-segment modCounts to avoid ABA
		 * problems in which an element in one segment was added and
		 * in another removed during traversal, in which case the
		 * table was never actually empty at any point. Note the
		 * similar use of modCounts in the size() and containsValue()
		 * methods, which are the only other methods also susceptible
		 * to ABA problems.
		 */
		int[] mc = new int[segments.length];
		int mcsum = 0;
		for (int i = 0; i < segments.length; ++i) {
			if (segments[i].count != 0)
				return false;
			else
				mcsum += mc[i] = segments[i].modCount;
		}
		// If mcsum happens to be zero, then we know we got a snapshot
		// before any modifications at all were made.  This is
		// probably common enough to bother tracking.
		if (mcsum != 0) {
			for (int i = 0; i < segments.length; ++i) {
				if (segments[i].count != 0 ||
						mc[i] != segments[i].modCount)
					return false;
			}
		}
		return true;
	}

	// inherit Map javadoc
	@Override
	public int size() {
		final Segment[] segments = this.segments;
		long sum = 0;
		long check = 0;
		int[] mc = new int[segments.length];
		// Try a few times to get accurate count. On failure due to
		// continuous async changes in table, resort to locking.
		for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
			check = 0;
			sum = 0;
			int mcsum = 0;
			for (int i = 0; i < segments.length; ++i) {
				sum += segments[i].count;
				mcsum += mc[i] = segments[i].modCount;
			}
			if (mcsum != 0) {
				for (int i = 0; i < segments.length; ++i) {
					check += segments[i].count;
					if (mc[i] != segments[i].modCount) {
						check = -1; // force retry
						break;
					}
				}
			}
			if (check == sum)
				break;
		}
		if (check != sum) { // Resort to locking all segments
			sum = 0;
			for (int i = 0; i < segments.length; ++i)
				segments[i].lock();
			for (int i = 0; i < segments.length; ++i)
				sum += segments[i].count;
			for (int i = 0; i < segments.length; ++i)
				segments[i].unlock();
		}
		if (sum > Integer.MAX_VALUE)
			return Integer.MAX_VALUE;
		else
			return (int)sum;
	}

	/**
	 * Returns the value to which the specified key is mapped in this table.
	 *
	 * @param   key   a key in the table.
	 * @return  the value to which the key is mapped in this table;
	 *          <tt>null</tt> if the key is not mapped to any value in
	 *          this table.
	 * @throws  NullPointerException  if the key is
	 *               <tt>null</tt>.
	 */
	@Override
	public V get(Object key) {
		int hash = hash(key); // throws NullPointerException if key null
		return segmentFor(hash).get(key, hash);
	}

	public V get(Object key, int hash) {
		return segmentFor(hash).get(key, hash);
	}

	/**
	 * Tests if the specified object is a key in this table.
	 *
	 * @param   key   possible key.
	 * @return  <tt>true</tt> if and only if the specified object
	 *          is a key in this table, as determined by the
	 *          <tt>equals</tt> method; <tt>false</tt> otherwise.
	 * @throws  NullPointerException  if the key is
	 *               <tt>null</tt>.
	 */
	@Override
	public boolean containsKey(Object key) {
		int hash = hash(key); // throws NullPointerException if key null
		return segmentFor(hash).containsKey(key, hash);
	}

	/**
	 * Returns <tt>true</tt> if this map maps one or more keys to the
	 * specified value. Note: This method requires a full internal
	 * traversal of the hash table, and so is much slower than
	 * method <tt>containsKey</tt>.
	 *
	 * @param value value whose presence in this map is to be tested.
	 * @return <tt>true</tt> if this map maps one or more keys to the
	 * specified value.
	 * @throws  NullPointerException  if the value is <tt>null</tt>.
	 */
	@Override
	public boolean containsValue(Object value) {
		if (value == null)
			throw new NullPointerException();

		// See explanation of modCount use above

		final Segment[] segments = this.segments;
		int[] mc = new int[segments.length];

		// Try a few times without locking
		for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
			int mcsum = 0;
			for (int i = 0; i < segments.length; ++i) {
				mcsum += mc[i] = segments[i].modCount;
				if (segments[i].containsValue(value))
					return true;
			}
			boolean cleanSweep = true;
			if (mcsum != 0) {
				for (int i = 0; i < segments.length; ++i) {
					if (mc[i] != segments[i].modCount) {
						cleanSweep = false;
						break;
					}
				}
			}
			if (cleanSweep)
				return false;
		}
		// Resort to locking all segments
		for (int i = 0; i < segments.length; ++i)
			segments[i].lock();
		boolean found = false;
		try {
			for (int i = 0; i < segments.length; ++i) {
				if (segments[i].containsValue(value)) {
					found = true;
					break;
				}
			}
		} finally {
			for (int i = 0; i < segments.length; ++i)
				segments[i].unlock();
		}
		return found;
	}

	/**
	 * Legacy method testing if some key maps into the specified value
	 * in this table.  This method is identical in functionality to
	 * {@link #containsValue}, and  exists solely to ensure
	 * full compatibility with class {@link java.util.Hashtable},
	 * which supported this method prior to introduction of the
	 * Java Collections framework.

	 * @param      value   a value to search for.
	 * @return     <tt>true</tt> if and only if some key maps to the
	 *             <tt>value</tt> argument in this table as
	 *             determined by the <tt>equals</tt> method;
	 *             <tt>false</tt> otherwise.
	 * @throws  NullPointerException  if the value is <tt>null</tt>.
	 */
	public boolean contains(Object value) {
		return containsValue(value);
	}

	/**
	 * Maps the specified <tt>key</tt> to the specified
	 * <tt>value</tt> in this table. Neither the key nor the
	 * value can be <tt>null</tt>.
	 *
	 *
 The value can be retrieved by calling the <tt>get</tt> method
	 * with a key that is equal to the original key.
	 *
	 * @param      key     the table key.
	 * @param      value   the value.
	 * @return     the previous value of the specified key in this table,
	 *             or <tt>null</tt> if it did not have one.
	 * @throws  NullPointerException  if the key or value is
	 *               <tt>null</tt>.
	 */
	@Override
	public V put(K key, V value) {
		if (value == null)
			throw new NullPointerException();
		int hash = hash(key);
		return segmentFor(hash).put(key, hash, value, false);
	}

	/**
	 * If the specified key is not already associated
	 * with a value, associate it with the given value.
	 * This is equivalent to
	 *

	 *   if (!map.containsKey(key))
	 *      return map.put(key, value);
	 *   else
	 *      return map.get(key);
	 *

	 * Except that the action is performed atomically.
	 * @param key key with which the specified value is to be associated.
	 * @param value value to be associated with the specified key.
	 * @return previous value associated with specified key, or <tt>null</tt>
	 *         if there was no mapping for key.
	 * @throws NullPointerException if the specified key or value is
	 *            <tt>null</tt>.
	 */
	public V putIfAbsent(K key, V value) {
		if (value == null)
			throw new NullPointerException();
		int hash = hash(key);
		return segmentFor(hash).put(key, hash, value, true);
	}

	public V putIfAbsent(K key, V value, int hash) {
		if (value == null)
			throw new NullPointerException();
		return segmentFor(hash).put(key, hash, value, true);
	}

	/**
	 * Copies all of the mappings from the specified map to this one.
	 *
	 * These mappings replace any mappings that this map had for any of the
	 * keys currently in the specified Map.
	 *
	 * @param t Mappings to be stored in this map.
	 */
	@Override
	public void putAll(Map<? extends K, ? extends V> t) {
		for (Iterator<? extends Map.Entry<? extends K, ? extends V>> it = t.entrySet().iterator(); it.hasNext(); ) {
			Entry<? extends K, ? extends V> e = it.next();
			put(e.getKey(), e.getValue());
		}
	}

	/**
	 * Removes the key (and its corresponding value) from this
	 * table. This method does nothing if the key is not in the table.
	 *
	 * @param   key   the key that needs to be removed.
	 * @return  the value to which the key had been mapped in this table,
	 *          or <tt>null</tt> if the key did not have a mapping.
	 * @throws  NullPointerException  if the key is
	 *               <tt>null</tt>.
	 */
	@Override
	public V remove(Object key) {
		int hash = hash(key);
		return segmentFor(hash).remove(key, hash, null);
	}

	/**
	 * Remove entry for key only if currently mapped to given value.
	 * Acts as
	 *

	 *  if (map.get(key).equals(value)) {
	 *     map.remove(key);
	 *     return true;
	 * } else return false;
	 *

	 * except that the action is performed atomically.
	 * @param key key with which the specified value is associated.
	 * @param value value associated with the specified key.
	 * @return true if the value was removed
	 * @throws NullPointerException if the specified key is
	 *            <tt>null</tt>.
	 */
	public boolean remove(Object key, Object value) {
		int hash = hash(key);
		return segmentFor(hash).remove(key, hash, value) != null;
	}

	/**
	 * Replace entry for key only if currently mapped to given value.
	 * Acts as
	 *

	 *  if (map.get(key).equals(oldValue)) {
	 *     map.put(key, newValue);
	 *     return true;
	 * } else return false;
	 *

	 * except that the action is performed atomically.
	 * @param key key with which the specified value is associated.
	 * @param oldValue value expected to be associated with the specified key.
	 * @param newValue value to be associated with the specified key.
	 * @return true if the value was replaced
	 * @throws NullPointerException if the specified key or values are
	 * <tt>null</tt>.
	 */
	public boolean replace(K key, V oldValue, V newValue) {
		if (oldValue == null || newValue == null)
			throw new NullPointerException();
		int hash = hash(key);
		return segmentFor(hash).replace(key, hash, oldValue, newValue);
	}

	/**
	 * Replace entry for key only if currently mapped to some value.
	 * Acts as
	 *

	 *  if ((map.containsKey(key)) {
	 *     return map.put(key, value);
	 * } else return null;
	 *

	 * except that the action is performed atomically.
	 * @param key key with which the specified value is associated.
	 * @param value value to be associated with the specified key.
	 * @return previous value associated with specified key, or <tt>null</tt>
	 *         if there was no mapping for key.
	 * @throws NullPointerException if the specified key or value is
	 *            <tt>null</tt>.
	 */
	public V replace(K key, V value) {
		if (value == null)
			throw new NullPointerException();
		int hash = hash(key);
		return segmentFor(hash).replace(key, hash, value);
	}

	/**
	 * Removes all mappings from this map.
	 */
	@Override
	public void clear() {
		for (int i = 0; i < segments.length; ++i)
			segments[i].clear();
	}

	/**
	 * Returns a set view of the keys contained in this map.  The set is
	 * backed by the map, so changes to the map are reflected in the set, and
	 * vice-versa.  The set supports element removal, which removes the
	 * corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
	 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
	 * <tt>clear</tt> operations.  It does not support the <tt>add</tt> or
	 * <tt>addAll</tt> operations.
	 * The view's returned <tt>iterator</tt> is a "weakly consistent" iterator that
	 * will never throw {@link java.util.ConcurrentModificationException},
	 * and guarantees to traverse elements as they existed upon
	 * construction of the iterator, and may (but is not guaranteed to)
	 * reflect any modifications subsequent to construction.
	 *
	 * @return a set view of the keys contained in this map.
	 */
	@Override
	public Set<K> keySet() {
		Set<K> ks = keySet;
		return (ks != null) ? ks : (keySet = new KeySet());
	}

	/**
	 * Returns a collection view of the values contained in this map.  The
	 * collection is backed by the map, so changes to the map are reflected in
	 * the collection, and vice-versa.  The collection supports element
	 * removal, which removes the corresponding mapping from this map, via the
	 * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
	 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
	 * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
	 * The view's returned <tt>iterator</tt> is a "weakly consistent" iterator that
	 * will never throw {@link java.util.ConcurrentModificationException},
	 * and guarantees to traverse elements as they existed upon
	 * construction of the iterator, and may (but is not guaranteed to)
	 * reflect any modifications subsequent to construction.
	 *
	 * @return a collection view of the values contained in this map.
	 */
	@Override
	public Collection<V> values() {
		Collection<V> vs = values;
		return (vs != null) ? vs : (values = new Values());
	}

	/**
	 * Returns a collection view of the mappings contained in this map.  Each
	 * element in the returned collection is a <tt>Map.Entry</tt>.  The
	 * collection is backed by the map, so changes to the map are reflected in
	 * the collection, and vice-versa.  The collection supports element
	 * removal, which removes the corresponding mapping from the map, via the
	 * <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
	 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
	 * It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
	 * The view's returned <tt>iterator</tt> is a "weakly consistent" iterator that
	 * will never throw {@link java.util.ConcurrentModificationException},
	 * and guarantees to traverse elements as they existed upon
	 * construction of the iterator, and may (but is not guaranteed to)
	 * reflect any modifications subsequent to construction.
	 *
	 * @return a collection view of the mappings contained in this map.
	 */
	@Override
	public Set<Map.Entry<K,V>> entrySet() {
		Set<Map.Entry<K,V>> es = entrySet;
		return (es != null) ? es : (entrySet = new EntrySet());
	}

	/**
	 * Returns an enumeration of the keys in this table.
	 *
	 * @return  an enumeration of the keys in this table.
	 * @see     #keySet
	 */
	public Iterator<K> keys() {
		return new KeyIterator();
	}

	/**
	 * Returns an enumeration of the values in this table.
	 *
	 * @return  an enumeration of the values in this table.
	 * @see     #values
	 */
	public Iterator<V> elements() {
		return new ValueIterator();
	}

	/* ---------------- Iterator Support -------------- */

	abstract class HashIterator {
		int nextSegmentIndex;
		int nextTableIndex;
		HashEntry[] currentTable;
		HashEntry<K, V> nextEntry;
		HashEntry<K, V> lastReturned;

		HashIterator() {
			nextSegmentIndex = segments.length - 1;
			nextTableIndex = -1;
			advance();
		}

		public boolean hasMoreElements() { return hasNext(); }

		final void advance() {
			if (nextEntry != null && (nextEntry = nextEntry.next) != null)
				return;

			while (nextTableIndex >= 0) {
				if ( (nextEntry = currentTable[nextTableIndex--]) != null)
					return;
			}

			while (nextSegmentIndex >= 0) {
				Segment<K,V> seg = segments[nextSegmentIndex--];
				if (seg.count != 0) {
					currentTable = seg.table;
					for (int j = currentTable.length - 1; j >= 0; --j) {
						if ( (nextEntry = currentTable[j]) != null) {
							nextTableIndex = j - 1;
							return;
						}
					}
				}
			}
		}

		public boolean hasNext() { return nextEntry != null; }

		HashEntry<K,V> nextEntry() {
			if (nextEntry == null)
				throw new NoSuchElementException();
			lastReturned = nextEntry;
			advance();
			return lastReturned;
		}

		public void remove() {
			if (lastReturned == null)
				throw new IllegalStateException();
			ConcurrentIdentityHashMap.this.remove(lastReturned.key);
			lastReturned = null;
		}
	}

	final class KeyIterator extends HashIterator implements Iterator<K> {
		public K next() { return super.nextEntry().key; }
		public K nextElement() { return super.nextEntry().key; }
	}

	final class ValueIterator extends HashIterator implements Iterator<V> {
		public V next() { return super.nextEntry().value; }
		public V nextElement() { return super.nextEntry().value; }
	}

	/**
	 * Entry iterator. Exported Entry objects must write-through
	 * changes in setValue, even if the nodes have been cloned. So we
	 * cannot return internal HashEntry objects. Instead, the iterator
	 * itself acts as a forwarding pseudo-entry.
	 */
	final class EntryIterator extends HashIterator implements Map.Entry<K,V>, Iterator<Entry<K,V>> {
		public Map.Entry<K,V> next() {
			nextEntry();
			return this;
		}

		public K getKey() {
			if (lastReturned == null)
				throw new IllegalStateException("Entry was removed");
			return lastReturned.key;
		}

		public V getValue() {
			if (lastReturned == null)
				throw new IllegalStateException("Entry was removed");
			return ConcurrentIdentityHashMap.this.get(lastReturned.key);
		}

		public V setValue(V value) {
			if (lastReturned == null)
				throw new IllegalStateException("Entry was removed");
			return ConcurrentIdentityHashMap.this.put(lastReturned.key, value);
		}

		@Override
		public boolean equals(Object o) {
			// If not acting as entry, just use default.
			if (lastReturned == null)
				return super.equals(o);
			if (!(o instanceof Map.Entry))
				return false;
			Map.Entry e = (Map.Entry)o;
			return eq(getKey(), e.getKey()) && eq(getValue(), e.getValue());
		}

		@Override
		public int hashCode() {
			// If not acting as entry, just use default.
			if (lastReturned == null)
				return super.hashCode();

			Object k = getKey();
			Object v = getValue();
			return ((k == null) ? 0 : Util.identityHashCode(k)) ^
			((v == null) ? 0 : Util.identityHashCode(v));
		}

		@Override
		public String toString() {
			// If not acting as entry, just use default.
			if (lastReturned == null)
				return super.toString();
			else
				return getKey() + "=" + getValue();
		}

		boolean eq(Object o1, Object o2) {
			return (o1 == null ? o2 == null : o1.equals(o2));
		}

	}

	final class KeySet extends AbstractSet<K> {
		@Override
		public Iterator<K> iterator() {
			return new KeyIterator();
		}
		@Override
		public int size() {
			return ConcurrentIdentityHashMap.this.size();
		}
		@Override
		public boolean contains(Object o) {
			return ConcurrentIdentityHashMap.this.containsKey(o);
		}
		@Override
		public boolean remove(Object o) {
			return ConcurrentIdentityHashMap.this.remove(o) != null;
		}
		@Override
		public void clear() {
			ConcurrentIdentityHashMap.this.clear();
		}
	}

	final class Values extends AbstractCollection<V> {
		@Override
		public Iterator<V> iterator() {
			return new ValueIterator();
		}
		@Override
		public int size() {
			return ConcurrentIdentityHashMap.this.size();
		}
		@Override
		public boolean contains(Object o) {
			return ConcurrentIdentityHashMap.this.containsValue(o);
		}
		@Override
		public void clear() {
			ConcurrentIdentityHashMap.this.clear();
		}
	}

	final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
		@Override
		public Iterator<Map.Entry<K,V>> iterator() {
			return new EntryIterator();
		}
		@Override
		public int size() {
			return ConcurrentIdentityHashMap.this.size();
		}
		@Override
		public void clear() {
			ConcurrentIdentityHashMap.this.clear();
		}
	}

	/**
	 * This duplicates java.util.AbstractMap.SimpleEntry until this class
	 * is made accessible.
	 */
	static final class SimpleEntry<K,V> implements Entry<K,V> {
		K key;
		V value;

		public SimpleEntry(K key, V value) {
			this.key   = key;
			this.value = value;
		}

		public SimpleEntry(Entry<K,V> e) {
			this.key   = e.getKey();
			this.value = e.getValue();
		}

		public K getKey() {
			return key;
		}

		public V getValue() {
			return value;
		}

		public V setValue(V value) {
			V oldValue = this.value;
			this.value = value;
			return oldValue;
		}

		@Override
		public boolean equals(Object o) {
			if (!(o instanceof Map.Entry))
				return false;
			Map.Entry e = (Map.Entry)o;
			return eq(key, e.getKey()) && eq(value, e.getValue());
		}

		@Override
		public int hashCode() {
			return ((key == null) ? 0 : Util.identityHashCode(key)) ^
			((value == null) ? 0 : Util.identityHashCode(value));
		}

		@Override
		public String toString() {
			return key + "=" + value;
		}

		static boolean eq(Object o1, Object o2) {
			return (o1 == null ? o2 == null : o1.equals(o2));
		}
	}
}


text:
package hr.fer.zemris.jcms.service.assessments;

public class StudentFlag {

	private Long assessmentFlagID;
	private Long userID;
	private boolean value;
	private boolean errorOccured;

	public StudentFlag(Long assessmentFlagID, Long userID, boolean value, boolean errorOccured) {
		super();
		this.assessmentFlagID = assessmentFlagID;
		this.userID = userID;
		this.value = value;
		this.errorOccured = errorOccured;
	}

	public Long getAssessmentFlagID() {
		return assessmentFlagID;
	}

	public Long getUserID() {
		return userID;
	}

	public boolean getValue() {
		return value;
	}

	public boolean hasErrorOccured() {
		return errorOccured;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder(100);
		sb.append("score[uid=").append(userID).append(",")
		  .append("afid=").append(assessmentFlagID).append(",")
		  .append("value=").append(value).append(",")
		  .append("error=").append(errorOccured)
		  .append("]");
		return sb.toString();
	}

}


text:
var MD = ( function( $ ) {
    'use strict';

    var $fields;
    var $widgets;
    var $doc = $('document');

    $doc.ready( init );
    $.fn.mdwidget = mdwidgets;

    function init() {
        $fields = $('.md-field');
        $fields.mdwidget();
    };

    function mdwidgets() {
        if( this.length > 0 ) {
            if( cms_admin_style() === true ) {
                this.addClass('cms-admin-style')
            }
            load_help();
            for ( var i = 0; i < this.length; i++ ) {
                var $widget = $( this[ i ] );
                if( $widget.attr('id').indexOf('__prefix__') > -1 ) {
                    // do something helpful
                } else {
                    $widget.addClass('active');
                    mdwidget( $widget );
                }
            }
            $widgets = $fields.filter('.active');
        }
        return this;
    };

    function mdwidget( $widget ) {
        var widget = $widget[0];
        var $help_button = $('.md-button.help', $widget );

        $help_button.on({ click: toggle_help });
        function toggle_help( e ) {
            e.preventDefault();
            if( $widget.hasClass('show-help') ) {
                $widget.removeClass('show-help');
            } else {
                $widget.addClass('show-help');
            }
        }
        //var $help =
        //console.log ( $widget )
    }

    function load_help() {
        var url = $('.md-button.help', $fields.first() ).attr('href');
        if( url ) {
            $.ajax({ url: url, method: 'get', success: render_help });
        }
    };

    function render_help( data ) {
        var html = $( data ).filter('#mdhelp').html()
        for ( var i = 0; i < $widgets.length; i++ ) {
            var $widget = $( $widgets[ i ] );
            var $help = $('.md-help', $widget).append( html );
        }
    };

    function cms_admin_style() {
        // TODO better workaround for cms-admin-style
        return $('.toolbar-item').length > 0 || $('body.popup').length > 0;
    };

})( django.jQuery || jQuery );


text:
layout: post
title: "Thoughts on an If/Else: Perl Challenge 87"
author: "Dave Jacoby"
date: "2020-11-18 11:40:04 -0500"
categories: ""
---

First, we consider the challenge.

### TASK #1 › Longest Consecutive Sequence

> Submitted by: Mohammad S Anwar
> You are given an unsorted array of integers @N.
>
> Write a script to find the longest consecutive sequence. Print 0 if none sequence found.

First, let us note words that are not in this challenge. _Positive_ and _unique_ stand out to me. _Non-zero_ is also absent. This will have to accept `-1, -1, 0, -1` as an acceptable input, even if the examples all use unique, positive, non-zero integers.

My take on this is to first sort the unsorted array, then create an array of arrays, each sub-array being a sequence.

![First Form of Sequence Array](https://jacoby.github.io/images/87-01.jpg)

Taking the array `-1, -1, 0, -1, 7, 13, 15` as an example, the multidimensional array would look like:

```json
[[-1, 0], [7], [13, 15]];
```

But that isn't the most helpful. We can then sort by sequence length to ensure that the longest ones are first.

![Text](https://jacoby.github.io/images/87-02.jpg)

```json
[[-1, 0], [13, 15], [7]];
```

We then take the first and go from there.

![Text](https://jacoby.github.io/images/87-03.jpg)

```json
[-1, 0]
```

#### Aside

Looking back, I'm struck that having two arrays, _current_ and _longest_, and copying _current_ onto _longest_ when _current_ is as long or longer than _longest_. It's a _good_ implementation, but it is not what I wrote.

#### What I wrote

I use subroutine signatures. Your syntax may vary.

```perl
    my $zed = [];
    my $n   = 0;
    for my $i ( uniq sort { $a <=> $b } @array ) {

        if ( !$zed->[$n][-1] || $i == $zed->[$n][-1] + 1 ) {
            # this is intentionally empty
        }
        else {
            $n++;
        }
        push $zed->[$n]->@*, $i;
    }
```

Two words: _sorted_ and _unique_. Sorting makes the process easier, because then you only have to compare the current integer with the previous integer, instead of the whole array. And uniqueness removes a hinderance, because with `1, 2, 2, 3`, the second `2` is not `2 + 1`, so you might end up with `1, 2` as your longest sequence if you're not careful. Thus `uniq sort { $a <=> $b }`.

(By default, Perl sorts alphabetically, which gives the order `69,7,70` instead of `7,69,70`. Perl things more in terms of text than numbers, which is fine but important to remember.)

Which gets to the reason I decided to blog this.

```perl
        if ( !$zed->[$n][-1] || $i == $zed->[$n][-1] + 1 ) {
            # this is intentionally empty
        }
        else {
            $n++;
        }
```

In long form: _if there's nothing in the current sequence, or if the current integer is the integer following the last integer in the current sequence, do nothing. Otherwise, increment the sequence index._

Or as I wrote on Twitter the other day,

```perl
        if ( conditions ) { }
        else { $n++ }
```

This works. It is clear. It contains a no-op block. I hate it, but I hate it not quite enough to rewrite it.

I mean, the logic is clear to me, and changing it to negate it all is likely going to be pretzel logic, or instead:

```perl
        if ( !( conditions ) ) { $n++ }
```

Which looks to me like a code version of this _My Cousin Vinny_ line:

!["Everything that guy just said is bullshit."](https://jacoby.github.io/images/bull.gif)

Sawyer X suggests

```perl
        conditions or $n++ ;
```

That's nice. I like that. I'm going with it.

#### If you have any questions or comments, I would be glad to hear it. Ask me on [Twitter](https://twitter.com/jacobydave) or [make an issue on my blog repo.](https://github.com/jacoby/jacoby.github.io)


text:
package com.github.dockerjava.jaxrs;

import static javax.ws.rs.client.Entity.entity;

import java.io.InputStream;

import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.RequestEntityProcessing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.dockerjava.api.command.BuildImageCmd;

public class BuildImageCmdExec extends AbstrDockerCmdExec<BuildImageCmd, InputStream> implements BuildImageCmd.Exec {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(BuildImageCmdExec.class);

	public BuildImageCmdExec(WebTarget baseResource) {
		super(baseResource);
	}

	@Override
	protected InputStream execute(BuildImageCmd command) {
		WebTarget webResource = getBaseResource().path("/build");

		if(command.getTag() != null) {
			webResource = webResource.queryParam("t", command.getTag());
		}
        if (command.hasNoCacheEnabled()) {
            webResource = webResource.queryParam("nocache", "true");
        }
        if (command.hasRemoveEnabled()) {
            webResource = webResource.queryParam("rm", "true");
        }
        if (command.isQuiet()) {
            webResource = webResource.queryParam("q", "true");
        }

	  webResource.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.CHUNKED);
	  webResource.property(ClientProperties.CHUNKED_ENCODING_SIZE, 1024*1024);

		LOGGER.debug("POST: {}", webResource);
		return webResource
                .request()
				.accept(MediaType.TEXT_PLAIN)
				.post(entity(command.getTarInputStream(), "application/tar"), Response.class).readEntity(InputStream.class);

	}

}


text:
layout: page
title: Vision Enterprises Show
date: 2016-05-24
author: Kenneth Valentine
tags: weekly links, java
status: published
summary: Quisque in fermentum mauris. Sed justo.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 01/19/2019
  endDate: 01/23/2019
  ctyhocn: APFBSHX
  groupCode: VES
published: true
---
Donec vitae dolor non sapien aliquam placerat. Vestibulum maximus porttitor semper. Integer pulvinar malesuada urna, sit amet sollicitudin urna feugiat in. In hac habitasse platea dictumst. Donec nec sodales enim. Aenean viverra arcu a tellus blandit semper. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

* Fusce non velit malesuada, tincidunt erat in, dictum augue
* Donec molestie dolor in diam consequat, at congue nibh varius
* Vestibulum eu risus ac turpis imperdiet varius ut ut massa
* Praesent malesuada nibh vitae auctor porta
* Nulla et risus in quam euismod sagittis in ac felis.

Curabitur eget aliquam velit, in varius erat. Pellentesque eget sollicitudin lorem. Donec id sodales libero. Vivamus ipsum tortor, iaculis ut metus eget, molestie ultricies nisi. Nullam justo sem, pretium et consectetur ac, pretium at velit. Aliquam suscipit magna condimentum nibh molestie, eget tincidunt odio interdum. Donec id dui arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In hac habitasse platea dictumst. Etiam ac tempus magna.
Suspendisse finibus placerat purus. Nulla vel molestie nisl. Nulla id orci in ex pellentesque blandit eget in sapien. Praesent placerat semper dignissim. Donec lobortis vehicula tempor. Quisque vestibulum scelerisque aliquet. Donec non mollis erat. Pellentesque convallis eros nec turpis condimentum, id tempus nisi viverra. Vestibulum quis tincidunt nisi. Proin porttitor sem tincidunt egestas semper. Ut suscipit, neque at dapibus laoreet, erat metus ornare diam, eget interdum purus erat ac ipsum. Donec varius finibus pellentesque.


text:
@protocol PTRegisterViewControllerDelegate <NSObject>

- (void)registerViewControllerDidFinishRegister;

@end

@interface PTRegisterViewController : UIViewController

@property (nonatomic,weak) id<PTRegisterViewControllerDelegate> delegate;

@end


text:
Journals

  We will Get Back To You Soon

Sort Journals

              A to Z <input type="radio" class="sort_journals" name="atoz" id="atoz" value="atoz">

              Category Wise<input type="radio" class="sort_journals" name="category-wise" id="category-wise" value="category-wise" checked="checked">

              A to Z in Category<input type="radio" class="sort_journals" name="atozincat" id="atozincat" value="atozincat">

Filter Journals

              All Categories<input type="radio" name="all-categories" class="sort_journals" id="all-categories" value="atoz">

              Medical<input type="radio" name="medical" class="sort_journals" id="medical" value="medical">

              Biotechnology<input type="radio" name="biotechnology" class="sort_journals" id="biotechnology" value="biotechnology">

              Biology<input type="radio" name="biology" class="sort_journals" id="biology" value="biology">

              Pharmaceutical<input type="radio" name="pharmaceutical" class="sort_journals" id="pharmaceutical" value="pharmaceutical">

        <?php
        echo '

';

        foreach ($j_info as $key => $value) {
          if($value['category_name'] == 'Medical') {
            if($key == '0'){
              echo '
Medical
';
            }
            echo '
';
            echo '
'.$value['journal_name'].'';
            if($value['issn_number']) {
              echo '

';
            }
            echo '
'.$value['issn_number'].'
';
            echo '
';
            echo '
';
          }
        }
        foreach ($j_info as $key => $value) {
          if($key == '0'){
            echo '
Biotechnology
';
          }
          if($value['category_name'] == 'Biotechnology') {
            echo '
';
            echo '
'.$value['journal_name'].'';
            if($value['issn_number']) {
              echo '

';
            }
            echo '
'.$value['issn_number'].'
';
            echo '
';
            echo '
';
          }
        }
        foreach ($j_info as $key => $value) {
          if($key == '0'){
            echo '
Biology
';
          }
          if($value['category_name'] == 'Biology') {
            echo '
';
            echo '
'.$value['journal_name'].'';
            if($value['issn_number']) {
              echo '

';
            }
            echo '
'.$value['issn_number'].'
';
            echo '
';
            echo '
';
          }
        }
        foreach ($j_info as $key => $value) {
          if($key == '0'){
            echo '
Pharmaceutical
';
          }
          if($value['category_name'] == 'Pharmaceutical') {
            echo '
';
            echo '
'.$value['journal_name'].'';
            if($value['issn_number']) {
              echo '

';
            }
            echo '
'.$value['issn_number'].'
';
            echo '
';
            echo '
';
          }
        }
        echo '

';
        ?>


text:
module MSpec
  module Matchers
    module DSL
      MISING_PREFIXES = []

      def self.define(name, klass=nil, &definition)
        klass ||= Builder.build(&definition)

        define_method name do |*expected|
          klass.new(*expected)
        end
      end

      def self.define_missing(prefix, klass=nil, &definition)
        klass ||= Builder.build(&definition)

        MISING_PREFIXES << [prefix,klass]
      end

      def method_missing(method,*args,&block)

        MISING_PREFIXES.each do |prefix,klass|
          if method.to_s[0,prefix.length] == prefix
            return klass.new(method,*args,&block)
          end
        end

        super
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;

namespace Divan.Test
{
    /// <summary>
    /// Unit tests for Divan. Operates in a separate CouchDB database called divan_unit_tests.
    /// If you are not running a CouchDB on localhost:5984 you will need to first edit
    /// the Tests/App.config file to point somewhere else.
    ///
    /// NOTE: App.config is copied to Tests/bin/Debug/Divan.Test.dll.config as a
    /// Custom Command in the Makefile! if someone can tell me how to handle this better on
    /// Mono/Monodevelop I am all ears.
    ///
    /// Run from command line using something like:
    /// 	nunit-console2 --labels -run=Divan.Test.CouchTest Tests/bin/Debug/Tests.dll
    /// </summary>
    [TestFixture]
    public class CouchTest
    {
        #region Setup/Teardown

        [SetUp]
        public void SetUp()
        {
            var host = ConfigurationManager.AppSettings["CouchHost"] ?? "localhost";
            var port = Convert.ToInt32(ConfigurationManager.AppSettings["CouchPort"] ?? "5984");
            server = new CouchServer(host, port);
            DbName = GetNewDbName();
            db = server.GetNewDatabase(DbName);
        }

        [TearDown]
        public void TearDown()
        {
            try
            {
                db.Delete();
            }
            catch
            {
            }
        }

        #endregion

        private ICouchServer server;
        private ICouchDatabase db;
        private string DbName;

        private static string GetNewDbName()
        {
            return "divan_unit_tests" + DateTime.Now.Ticks;
        }

        [Test]
        public void ShouldCheckChangedDocument()
        {
            CouchJsonDocument doc = db.CreateDocument("{\"CPU\": \"Intel\"}");
            CouchJsonDocument doc2 = db.GetDocument(doc.Id);
            Assert.That(db.HasDocumentChanged(doc), Is.False);
            doc2.Obj["CPU"] = JToken.FromObject("AMD");
            db.WriteDocument(doc2);
            Assert.That(db.HasDocumentChanged(doc), Is.True);
        }

        [Test]
        public void ShouldCountDocuments()
        {
            Assert.That(db.CountDocuments(), Is.EqualTo(0));
            db.CreateDocument("{\"CPU\": \"Intel\"}");
            Assert.That(db.CountDocuments(), Is.EqualTo(1));
        }

        [Test]
        public void ShouldCreateDocument()
        {
            var doc = new CouchJsonDocument("{\"CPU\": \"Intel\"}");
            ICouchDocument cd = db.CreateDocument(doc);
            Assert.That(db.CountDocuments(), Is.EqualTo(1));
            Assert.That(cd.Id, Is.Not.Null);
            Assert.That(cd.Rev, Is.Not.Null);
        }

        [Test]
        public void ShouldCreateDocuments()
        {
            const string doc = "{\"CPU\": \"Intel\"}";
            var doc1 = new CouchJsonDocument(doc);
            var doc2 = new CouchJsonDocument(doc);
            IList<ICouchDocument> list = new List<ICouchDocument> { doc1, doc2 };
            db.SaveDocuments(list, true);
            Assert.That(db.CountDocuments(), Is.EqualTo(2));
            Assert.That(doc1.Id, Is.Not.Null);
            Assert.That(doc1.Rev, Is.Not.Null);
            Assert.That(doc2.Id, Is.Not.Null);
            Assert.That(doc2.Rev, Is.Not.Null);
            Assert.That(doc1.Id, Is.Not.EqualTo(doc2.Id));
        }

        [Test]
        public void ShouldCreateDocumentWithSpecifiedId()
        {
            const string doc = "{\"_id\": \"foo\"}";
            var doc1 = new CouchJsonDocument(doc);
            db.SaveDocument(doc1);
            Assert.That(db.CountDocuments(), Is.EqualTo(1));
            Assert.That(doc1.Id, Is.EqualTo("foo"));
            Assert.That(doc1.Rev, Is.Not.Null);
        }

        [Test, ExpectedException(typeof(CouchNotFoundException))]
        public void ShouldDeleteDatabase()
        {
            db.Delete();
            Assert.That(server.HasDatabase(db.Name), Is.EqualTo(false));
            server.DeleteDatabase(db.Name); // one more time should fail
        }

        [Test]
        public void ShouldDeleteDocuments()
        {
            const string doc = "{\"CPU\": \"Intel\"}";
            CouchJsonDocument doc1 = db.CreateDocument(doc);
            CouchJsonDocument doc2 = db.CreateDocument(doc);
            if (String.Compare(doc1.Id, doc2.Id) < 0)
            {
                db.DeleteDocuments(doc1.Id, doc2.Id);
            }
            else
            {
                db.DeleteDocuments(doc2.Id, doc1.Id);
            }
            Assert.That(db.HasDocument(doc1.Id), Is.False);
            Assert.That(db.HasDocument(doc2.Id), Is.False);
        }

        [Test, ExpectedException(typeof(CouchException))]
        public void ShouldFailCreateDatabase()
        {
            server.CreateDatabase(db.Name); // one more time should fail
        }

        [Test]
        public void ShouldGetDatabaseNames()
        {
            bool result = server.GetDatabaseNames().Contains(db.Name);
            Assert.That(result, Is.EqualTo(true));
        }

        [Test]
        public void ShouldGetDocument()
        {
            const string doc = "{\"CPU\": \"Intel\"}";
            CouchJsonDocument oldDoc = db.CreateDocument(doc);
            CouchJsonDocument newDoc = db.GetDocument(oldDoc.Id);
            Assert.That(oldDoc.Id, Is.EqualTo(newDoc.Id));
            Assert.That(oldDoc.Rev, Is.EqualTo(newDoc.Rev));
        }

        [Test]
        public void ShouldGetDocuments()
        {
            const string doc = "{\"CPU\": \"Intel\"}";
            CouchJsonDocument doc1 = db.CreateDocument(doc);
            CouchJsonDocument doc2 = db.CreateDocument(doc);
            var ids = new List<string> { doc1.Id, doc2.Id };

            // Bulk request for multiple keys.
            var docs = db.GetDocuments(ids);
            Assert.That(doc1.Id, Is.EqualTo(docs.First().Id));
            Assert.That(doc2.Id, Is.EqualTo(docs.Last().Id));

            var keys = new List<object> { doc1.Id, doc2.Id };
            // Bulk query on a view for multple keys.
            docs = db.QueryAllDocuments().Keys(keys).IncludeDocuments().GetResult().Documents();
            Assert.That(doc1.Id, Is.EqualTo(docs.First().Id));
            Assert.That(doc2.Id, Is.EqualTo(docs.Last().Id));
        }

        [Test]
        public void ShouldReturnNullWhenNotFound()
        {
            var doc = db.GetDocument<CouchJsonDocument>("jadda");
            Assert.That(doc, Is.Null);
            CouchJsonDocument doc2 = db.GetDocument("jadda");
            Assert.That(doc2, Is.Null);
        }

        [Test]
        public void ShouldSaveDocumentWithId()
        {
            var doc = new CouchJsonDocument("{\"_id\":\"123\", \"CPU\": \"Intel\"}");
            ICouchDocument cd = db.SaveDocument(doc);
            Assert.That(db.CountDocuments(), Is.EqualTo(1));
            Assert.That(cd.Id, Is.Not.Null);
            Assert.That(cd.Rev, Is.Not.Null);
        }

        [Test]
        public void ShouldSaveDocumentWithoutId()
        {
            var doc = new CouchJsonDocument("{\"CPU\": \"Intel\"}");
            ICouchDocument cd = db.SaveDocument(doc);
            Assert.That(db.CountDocuments(), Is.EqualTo(1));
            Assert.That(cd.Id, Is.Not.Null);
            Assert.That(cd.Rev, Is.Not.Null);
        }

        private class LittleCar
        {
            public string _id, _rev;
            public string Make, Model, docType;
        }

        [Test]
        public void ShouldSaveArbitraryDocument()
        {
            var littleCar = new LittleCar() { docType = "car", Make = "Yugo", Model = "Hell if i know" };
            littleCar = db.SaveArbitraryDocument(littleCar);
            Assert.IsNotNull(littleCar._id);
        }

        [Test]
        public void ShouldSaveArbitraryDocuments()
        {
            var littleCar1 = new LittleCar { docType = "car", Make = "Make1" };
            var littleCar2 = new LittleCar { docType = "car", Make = "Make2" };
            var docs = new List<LittleCar> { littleCar1, littleCar2 };

            db.SaveArbitraryDocuments(docs, true);
            var documentIds = db.GetAllDocuments().Select(doc => doc.Id);
            var loadedCars = db.GetArbitraryDocuments(documentIds, () => new LittleCar());

            Assert.AreEqual(littleCar1.Make, loadedCars.ElementAt(0).Make);
            Assert.AreEqual(littleCar2.Make, loadedCars.ElementAt(1).Make);
        }

        [Test]
        public void ShouldLoadArbitraryDocument()
        {
            var firstCar = new LittleCar() { docType = "car", Make = "Yugo", Model = "Hell if i know" };
            firstCar = db.SaveArbitraryDocument(firstCar);
            var otherCar = db.GetArbitraryDocument<LittleCar>(firstCar._id, () => new LittleCar());
            Assert.IsNotNull(otherCar);
            Assert.IsNotNull(otherCar._id);
        }

        [Test]
        public void ShouldStoreGetAndDeleteAttachment()
        {
            var doc = new CouchJsonDocument("{\"CPU\": \"Intel\"}");
            ICouchDocument cd = db.CreateDocument(doc);
            var attachmentName = "someAttachment.txt";
            Assert.That(db.HasAttachment(cd, attachmentName), Is.False);
            db.WriteAttachment(cd, attachmentName, "jabbadabba", "text/plain");
            Assert.That(db.HasAttachment(cd, attachmentName), Is.True);

            using (var response = db.ReadAttachment(cd, attachmentName))
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    Assert.That(reader.ReadToEnd(), Is.EqualTo("jabbadabba"));
                }
            }

            db.WriteAttachment(cd, attachmentName, "jabbadabba-doo", "text/plain");
            Assert.That(db.HasAttachment(cd, attachmentName), Is.True);

            using (var response = db.ReadAttachment(cd, attachmentName))
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    Assert.That(reader.ReadToEnd(), Is.EqualTo("jabbadabba-doo"));
                }
            }

            db.DeleteAttachment(cd, attachmentName);

            Assert.That(db.HasAttachment(cd, attachmentName), Is.False);
        }

        [Test, ExpectedException(typeof(CouchConflictException))]
        public void ShouldThrowConflictExceptionOnAlreadyExists()
        {
            const string doc = "{\"CPU\": \"Intel\"}";
            CouchJsonDocument doc1 = db.CreateDocument(doc);
            var doc2 = new CouchJsonDocument(doc) { Id = doc1.Id };
            db.WriteDocument(doc2);
        }

        [Test, ExpectedException(typeof(CouchConflictException))]
        public void ShouldThrowConflictExceptionOnStaleWrite()
        {
            const string doc = "{\"CPU\": \"Intel\"}";
            CouchJsonDocument doc1 = db.CreateDocument(doc);
            CouchJsonDocument doc2 = db.GetDocument(doc1.Id);
            doc1.Obj["CPU"] = JToken.FromObject("AMD");
            db.SaveDocument(doc1);
            doc2.Obj["CPU"] = JToken.FromObject("Via");
            db.SaveDocument(doc2);
        }

        [Test, ExpectedException(typeof(CouchNotFoundException))]
        public void ShouldHaveExtendedExceptionMessages()
        {
            try
            {
                db.Query("invalid", "view").GetResult();
            }
            catch (CouchException ex)
            {
                Assert.That(ex.Message.Contains("reason: "), String.Format("Expected extended exception text, with 'reason' field, received '{0}'", ex.Message));
            }
        }

        [Test]
        public void ShouldUseETagForView()
        {
            var design = db.NewDesignDocument("computers");
            design.AddView("by_cpumake",
                           @"function(doc) {
                        emit(doc.CPU, doc);
                    }");
            db.WriteDocument(design);

            CouchJsonDocument doc1 = db.CreateDocument("{\"CPU\": \"Intel\"}");
            db.CreateDocument("{\"CPU\": \"AMD\"}");
            db.CreateDocument("{\"CPU\": \"Via\"}");
            db.CreateDocument("{\"CPU\": \"Sparq\"}");

            CouchQuery query = db.Query("computers", "by_cpumake").StartKey("Intel").EndKey("Via").CheckETagUsingHead();
            // Query has no result yet so should not be cached
            Assert.That(query.IsCachedAndValid(), Is.False);
            query.GetResult();
            // Now it is cached and should be valid
            Assert.That(query.IsCachedAndValid(), Is.True);
            // Make a change invalidating the view
            db.SaveDocument(doc1);
            // It should now be false
            Assert.That(query.IsCachedAndValid(), Is.False);
            query.GetResult();
            // And now it should be cached again
            Assert.That(query.IsCachedAndValid(), Is.True);
            query.GetResult();
            // Still cached of course
            Assert.That(query.IsCachedAndValid(), Is.True);
        }

        [Test]
        public void ShouldWriteDocument()
        {
            var doc = new CouchJsonDocument("{\"_id\":\"123\", \"CPU\": \"Intel\"}");
            ICouchDocument cd = db.WriteDocument(doc);
            Assert.That(db.CountDocuments(), Is.EqualTo(1));
            Assert.That(cd.Id, Is.Not.Null);
            Assert.That(cd.Rev, Is.Not.Null);
        }

        [Test]
        public void ShouldSyncDesignDocuments()
        {
            var design = db.NewDesignDocument("computers");
            design.AddView("by_cpumake",
                           @"function(doc) {
                        emit(doc.CPU, doc);
                    }");
            db.SynchDesignDocuments(); // This writes them to the db.

            var db2 = server.GetDatabase(DbName);
            design = db2.NewDesignDocument("computers");
            design.AddView("by_cpumake",
                           @"function(doc) {
                        emit(doc.CPU, nil);
                    }");
            db2.SynchDesignDocuments(); // This should detect difference and overwrite the one in the db

            Assert.That(db.GetDocument<CouchDesignDocument>("_design/computers").Definitions[0].Map,
                        Is.EqualTo(
                            @"function(doc) {
                        emit(doc.CPU, nil);
                    }"));
        }

        /// <summary>
        /// Test that keys can be given as C# types representing proper JSON values:
        ///  string, number, true, false, null, JSON array and JSON object.
        /// </summary>
        [Test]
        public void ShouldGetProperJsonValueForQueryKey()
        {
            var query = db.Query("test", "test");
            query.Key("a string");
            Assert.That(query.Options["key"].Equals("\"a string\""));
            query.Key(12);
            Assert.That(query.Options["key"].Equals("12"));
            query.Key(-12.0);
            Assert.That(query.Options["key"].Equals("-12.0"));
            query.Key(true);
            Assert.That(query.Options["key"].Equals("true"));
            query.Key(false);
            Assert.That(query.Options["key"].Equals("false"));
            query.Key(null);
            Assert.That(query.Options["key"].Equals("null"));

            query.Key(new[] { "one", "two" });
            var json = Regex.Replace(query.Options["key"], @"\s", ""); // removes all whitespace
            Assert.That(json.Equals("[\"one\",\"two\"]"));

            var dict = new Dictionary<string, string>();
            dict["one"] = "two";
            dict["three"] = "four";
            query.Key(dict);
            json = Regex.Replace(query.Options["key"], @"\s", ""); // removes all whitespace
            Assert.That(json.Equals("{\"one\":\"two\",\"three\":\"four\"}"));

            query.Key("one", "two");
            json = Regex.Replace(query.Options["key"], @"\s", ""); // removes all whitespace
            Assert.That(json.Equals("[\"one\",\"two\"]"));
        }

        [Test, ExpectedException(typeof(InvalidOperationException))]
        public void ShouldHandleStreaming()
        {
            var design = new CouchDesignDocument("test", db);
            design.AddView("docs", "function (doc) { emit(null, null); } ");
            design.Synch();

            var doc = new CouchJsonDocument("{\"_id\":\"123\", \"CPU\": \"Intel\"}");
            db.SaveDocument(doc);

            var result = db.Query("test", "docs").StreamResult<CouchDocument>();

            Assert.That(result.FirstOrDefault() != null, "there should be one doc present");

            try
            {
                // this should throw an invalid operation exception
                result.FirstOrDefault();
            }
            finally
            {
                db.DeleteDocument(doc);
                db.DeleteDocument(design);
            }
        }

        private class Car : CouchDocument
        {
            public string Make;
            public string Model;
            public int HorsePowers;
        }
    }
}


text:
/*************************************************/
/* Bacteria - The interesting bacteria simulator */
/*      (c) Kristian K. Skordal 2009 - 2012      */
/*************************************************/

#include "application.h"
#include "window.h"

using namespace std;

// The main window object:
window * window::main_window = 0;

// Creates the main window:
window * window::create(int width, int height)
{
	if(main_window != 0)
	{
		cerr << "WARNING: Main window already created!" << endl;
		return 0;
	}

	// Initialize SDL:
	clog << "Initializing SDL... ";
	if(SDL_Init(SDL_INIT_TIMER|SDL_INIT_VIDEO) == -1)
	{
		clog << "failed!" << endl;
		cerr << "ERROR: Could not initialize SDL!" << endl;
		return 0;
	} else
		clog << "ok" << endl;
	atexit(SDL_Quit);

	// Initialize SDL_TTF:
	clog << "Initializing SDL_ttf... ";
	if(TTF_Init() == -1)
	{
		clog << "failed!" << endl;
		cerr << "ERROR: Could not initialize SDL_TTF!" << endl;
		return 0;
	} else
		clog << "ok" << endl;
	atexit(TTF_Quit);

	// Finally, create the main window, if possible:
	try {
		main_window = new window(width, height);
		atexit(window::cleanup);
	} catch(exception & error)
	{
		cerr << "ERROR: " << error.what() << endl;
		return 0;
	}

	return main_window;
}

// Draws an image to the screen:
void window::draw(const image & img, int x, int y)
{
	SDL_Rect position;

	position.x = x;
	position.y = y;

	SDL_BlitSurface(img.get_image(), 0, screen, &position);
}

// Draws a string to the screen:
void window::draw(const string & text, int x, int y)
{
	SDL_Rect position;
	SDL_Surface * temp = TTF_RenderText_Solid(font, text.c_str(), STATUS_TEXT_COLOR);

	if(temp == 0)
	{
		cerr << "WARNING: Could not render string: \"" << text << "\"" << endl;
		return;
	}

	position.x = x;
	position.y = y;
	SDL_BlitSurface(temp, 0, screen, &position);
	SDL_FreeSurface(temp);
}

window::window(int width, int height)
{
	// Load the font for printing text to the screen:
	font = TTF_OpenFont(STATUS_FONT, STATUS_FONT_SIZE);
	if(font == 0)
		throw runtime_error(string("Could not load font from ").append(STATUS_FONT));

	// Create the window surface:
	clog << "Creating window (" << config_db::get().get_int_value("ScreenWidth") << " x "
		<< config_db::get().get_int_value("ScreenHeight") << ")...";
	screen = SDL_SetVideoMode(width, height, 0,
		config_db::get().get_bool_value("Fullscreen")
		? SDL_HWSURFACE|SDL_DOUBLEBUF|SDL_FULLSCREEN
		: SDL_HWSURFACE|SDL_DOUBLEBUF);
	if(screen == 0)
	{
		clog << "failed!" << endl;
		throw runtime_error("Could not create window!");
	} else
		clog << "ok" << endl;

	// Set window decoration specifics:
	SDL_WM_SetCaption("Bacteria Simulator", "Bacteria");
	window_icon = SDL_LoadBMP(ICON_FILENAME);
	if(window_icon != 0)
	{
		SDL_SetColorKey(window_icon, SDL_SRCCOLORKEY,
			SDL_MapRGB(window_icon->format, 255, 0, 255));
		SDL_WM_SetIcon(window_icon, 0);
	} else
		cerr << "WARNING: Could not load icon file: " << ICON_FILENAME << endl;
}

window::~window()
{
	TTF_CloseFont(font);
}

void window::cleanup()
{
	if(main_window != 0)
		delete main_window;
}

// Clears the window:
void window::clear()
{
	SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, BACKGROUND_R, BACKGROUND_G, BACKGROUND_B));
}


text:
<html>
<head>
<meta http-equiv="refresh" content="0; url=https://developers.liveperson.com/test-post-from-last-year.html" />
</head>
</html>


text:
package com.alibaba.csp.sentinel.util;

import org.junit.Assert;
import org.junit.Test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Properties;

import static com.alibaba.csp.sentinel.log.LogBase.LOG_DIR;
import static com.alibaba.csp.sentinel.log.LogBase.LOG_OUTPUT_TYPE;
import static com.alibaba.csp.sentinel.util.ConfigUtil.addSeparator;

/**
 * @author lianglin
 * @since 1.7.0
 */
public class ConfigUtilTest {

    @Test
    public void testLoadProperties() throws IOException {

        File file = null;
        String logOutputType = "utf-8",
                dir = "/data/logs/",
                fileName = "propertiesTest.properties";
        try {
            String userDir = System.getProperty("user.dir");
            file = new File(addSeparator(userDir) + "target/classes/" + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(LOG_OUTPUT_TYPE + "=" + logOutputType);
            out.write(System.getProperty("line.separator"));
            out.write(LOG_DIR + "=" + dir);
            out.flush();
            out.close();

            //Load from absolutePath
            Properties properties = ConfigUtil.loadProperties(file.getAbsolutePath());
            Assert.assertTrue(logOutputType.equals(properties.getProperty(LOG_OUTPUT_TYPE)));
            Assert.assertTrue(dir.equals(properties.getProperty(LOG_DIR)));

            //Load from classPath
            properties = ConfigUtil.loadProperties(ConfigUtil.CLASSPATH_FILE_FLAG + fileName);
            Assert.assertTrue(logOutputType.equals(properties.getProperty(LOG_OUTPUT_TYPE)));
            Assert.assertTrue(dir.equals(properties.getProperty(LOG_DIR)));

            //Load from relativePath
            properties = ConfigUtil.loadProperties("target/classes/" + fileName);
            Assert.assertTrue(logOutputType.equals(properties.getProperty(LOG_OUTPUT_TYPE)));
            Assert.assertTrue(dir.equals(properties.getProperty(LOG_DIR)));

        } finally {
            if (file != null) {
                file.delete();
            }
        }

    }

    //add Jvm parameter
    //-Dcsp.sentinel.charset="UTF-16"
    //@Test
    public void testLoadPropertiesWithCustomizedCharset() throws IOException {

        String charset = "UTF-16";

        File file = null;
        String dir = "/data/logs/",
                fileName = "propertiesTest.properties";
        try {
            String userDir = System.getProperty("user.dir");
            file = new File(addSeparator(userDir) + "target/classes/" + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), charset);
            out.write(LOG_DIR + "=" + dir);
            out.flush();
            out.close();

            //Load from absolutePath
            Properties properties = ConfigUtil.loadProperties(file.getAbsolutePath());
            Assert.assertTrue(dir.equals(properties.getProperty(LOG_DIR)));

            //Load from classPath
            properties = ConfigUtil.loadProperties(ConfigUtil.CLASSPATH_FILE_FLAG + fileName);
            Assert.assertTrue(dir.equals(properties.getProperty(LOG_DIR)));

            //Load from relativePath
            properties = ConfigUtil.loadProperties("target/classes/" + fileName);
            Assert.assertTrue(dir.equals(properties.getProperty(LOG_DIR)));

        } finally {
            if (file != null) {
                file.delete();
            }
        }

    }

}


text:
/**
 *
 */
package com.nagarro.ycompany.ehr.dao.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * @author vivekmalhotra
 *
 */
@Entity
@Table(name = "USER_ROLES")
public class UserRole {

	private Integer id;

	private UserCredential userCredential;

	private String role;

	/**
	 * @return the id
	 */
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "ROLE_ID", unique = true, nullable = false)
	public Integer getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}

	/**
	 * @return the userCredential
	 */
	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "USERNAME", nullable = false)
	public UserCredential getUserCredential() {
		return userCredential;
	}

	/**
	 * @param userCredential the userCredential to set
	 */
	public void setUserCredential(UserCredential userCredential) {
		this.userCredential = userCredential;
	}

	/**
	 * @return the role
	 */
	@Column(name = "ROLE", nullable = false)
	public String getRole() {
		return role;
	}

	/**
	 * @param role the role to set
	 */
	public void setRole(String role) {
		this.role = role;
	}

}