text:
/** Apache License 2.0 Applies for Scripts here, see NOTICE and LICENSE **/
/** @author Sun Sibai & Liu Yu & Tian Chuang & Zhuo Junbao & Zhai Aonan **/

/** matching content string parallelly **/
/**  dependency: kernel/swgraph.js **/
/**  dependency: kernel/swfmswitch.js **/

// SWMatcher
var ENFAmatcher = function(graph, content, strategy) { // Matcher for ENFA is compatible for NFA and DFA, so once we accomplished ENFA Matcher, NFA and DFA Matchers are already here.
 content=content||""; // for Chrome compatibility (only Firefox supports default parameter feature)
 strategy=strategy||{"start":"last","final":"first"}; // default: irreducible matches
 /*
  * graph network:
  *   entry = start state,
  *   nodes = states set Q (sub-list of Node.all)
  *   final = accept set F (sub-list of Node.allfin)
  *   active = active states (new!)
  */
 if (graph.entry!=undefined) {this.graph=graph;}
 else if (graph.initial!=undefined) {this.graph=Model.dict2graph(graph);}
 else {console.log("ENFAmatcher init: invalid graph!");}
 /*
  * ctt: content string
  * pos: position of char in content we are dealing with
  */
 this.ctt=content;
 this.pos=0;
 /*
  * active nodes: stimulated by transition process, nodes become active. if a final node is active, it matches.
  * active order: for non-strict start matching, entry node is stimulated on each character receiving step. in order to obtain the start position of the matching part, stimulations should be distinguishable by order. besides, when two stimulation collide, usually it means a substring of a matching string is also matching. There are four strategies:
  *   0. 'strict' start: only order=0 happens. (identical to pattern begins with '^')
  *   1. 'first' stimuation predominated strategy: only keep the lesser order stimulation.
  *   2. 'last'  stimuation predominated strategy: only keep the larger order stimulation.
  *   3. keep 'all' strategy: keep all the orders. this returns results identical to cascade matching process.
  * Usually 1('first') and 2('last') are commonly used since we usually don't need redundant matches.
  * Strategy 'first' usually tells us the largest matches, which is usually used in text searching and replacing procedures.
  * Strategy 'last' usually tells us the irreducible matches, which is usually used in xml grasping and data retrieving.
  * Here is the start position part. Notice that the final position part should be related.
  */
 this.strategy=strategy;
 this.graph.active={};
 if (this.graph&&this.graph.entry) {
  this.graph.active[this.graph.entry.idx]={};
  this.graph.active[this.graph.entry.idx]['-']=true; // use dict as set
 }
 this.matches=[]; // matched string
 var actlen=-1,tmpindex;
 while (Object.keys(this.graph.active).length!=actlen) { // recursive check non-char transit update
  actlen=Object.keys(this.graph.active).length;
  for (it1 in this.graph.active) {
   for (it2 in this.graph.active[it1]) {
    for (it3 in this.graph.nodes[it1].lkt) {
     tmpindex=this.graph.nodes[it1].lkt[it3].node.idx;
     if (!this.graph.nodes[it1].lkt[it3].char) { // non-char trans
      if (!this.graph.active[tmpindex]) {this.graph.active[tmpindex]={};}
      this.graph.active[tmpindex]['-']=true;
      this.graph.nodes[it1].lkt[it3].phase=1;
     }
    }
   }
  }
 }
}

ENFAmatcher.prototype = {
 aux_addact(index,order,active,strategy) { // update active list, warning: modify active
  var tmp;
  switch (strategy.start) {
  case 'strict':
  case 'all':
   if (!active[index]) {active[index]={};}
   active[index][order]=true;
   break;
  case 'first':
   tmp={};
   if (!active[index]||active[index][Object.keys(active[index])[0]]>order) {tmp[order]=true;active[index]=tmp;}
   break;
  case 'last':
   tmp={};
   if (!active[index]||active[index][Object.keys(active[index])[0]]<order) {tmp[order]=true;active[index]=tmp;}
   break;
  default:
  }
  return active;
 },
 aux_updateNonCharTrans:function(actList,strategy) { // check NonCharTransit effect on active states
  strategy=strategy||this.strategy; // for Chrome compatibility (only Firefox supports default parameter feature)
  var actlen=-1;
  while (Object.keys(actList).length!=actlen) { // recursive check
   actlen=Object.keys(actList).length;
   for (it1 in actList) {
    for (it2 in actList[it1]) {
     for (it3 in this.graph.nodes[it1].lkt) {
      if (!this.graph.nodes[it1].lkt[it3].char) {
       newact=this.aux_addact(this.graph.nodes[it1].lkt[it3].node.idx,it2,actList,strategy);
       this.graph.nodes[it1].lkt[it3].phase=1;
      }
     }
    }
   }
  }
 },
 reset:function() { // clear all active states
  this.graph.active={};
  if (this.graph&&this.graph.entry) {
   this.graph.active[this.graph.entry.idx]={};this.graph.active[this.graph.entry.idx][this.pos]=true;
  }
  this.matches=[];
  this.aux_updateNonCharTrans(this.graph.active);
 },
 clean:function() { // free all space
  if (this.graph&&this.graph.nodes) {
   for (it in this.graph.nodes) {SWNode.unregister(it);}
  }
 },

 high:function() { // return nodes with active order
  var ret={}; // return
  for (it in this.graph.active) {
   if (this.graph.active[it]) {ret[it]=this.graph.active[it];}
  }
  return ret;
 },

 aux_copy_active(graph,map) { // add active info which left when cloning, warning: modify graph
  graph['active']={};
  for (it in this.graph.active) { // nodes
   graph.active[map[it]]={};
   for (it1 in this.graph.active[it]) {
    graph.active[map[it]][it1]=this.graph.active[it][it1];
   }
  }
  for (it in this.graph.nodes) { // links
   for (it1 in this.graph.nodes[it].lkt) {
    graph.nodes[map[it]].lkt[it1].phase=this.graph.nodes[it].lkt[it1].phase;
   }
  }
  return {'graph':graph,'mapping':map};
 },
 dump:function(showMap) { // return graph of current ENFA
  showMap=showMap||false;
  var ret,reglist=SWNode.register; // backup
  SWNode.clearAll();
  ret=this.graph.clone(true);
  SWNode.register=reglist; // restore
  ret=this.aux_copy_active(ret.graph,ret.mapping)
  return showMap?ret:ret.graph;
 },
 dumpsort:function(showMap) { // return graph of current ENFA
  showMap=showMap||false;
  var ret,reglist=SWNode.register; // backup
  SWNode.clearAll();
  ret=this.graph.copy(true);
  SWNode.register=reglist; // restore
  ret=this.aux_copy_active(ret.graph,ret.mapping)
  return showMap?ret:ret.graph;
 },
 dumpauto:function(showMap) { // return graph of current ENFA
  showMap=showMap||false;
  var ret,reglist=SWNode.register; // backup
  SWNode.clearAll();
  if (this.is_end()) {
   ret=this.graph.copy(true);
  } else {
   ret=this.graph.clone(true);
  }
  SWNode.register=reglist; // restore
  ret=this.aux_copy_active(ret.graph,ret.mapping)
  return showMap?ret:ret.graph;
 },

 aux_checkmatch(final,order,active,strategy) { // check if there are any matches should be reported
  var ret=[];
  switch (strategy.final) {
 /* There are also 4 strategies for final check:
  *   0. 'strict' final: only check when the whole string was read over. (identical to pattern begins with '$')
  *   1. 'first' stimuation predominated strategy: return on any final state being activated.
  *   2. 'last'  stimuation predominated strategy: return on any final state fading.
  *   3. keep 'all' strategy: keep all the orders. this returns results identical to cascade matching process.
  * Same with start strategy, usually 1('first') and 2('last') are commonly used since we usually don't need redundant matches.
  * Strategy 'last' usually tells us the largest matches, which is usually used in text searching and replacing procedures.
  * Strategy 'first' usually tells us the irreducible matches, which is usually used in xml grasping and data retrieving.
  * Here is the final position part. Notice that the start position part should be related.
  */
  case 'all':
   if (this.pos<this.ctt.length) { for (it in final) {
    if (active[final[it]]) {
     for (it1 in active[final[it]]) {
      ret.push(this.ctt.substr(it1,this.pos+1));
     }
    }
   }}
   break;
  case 'last':
   for (it in final) {
    if (this.graph.active[final[it]]) {
     for (it1 in this.graph.active[final[it]]) {
      if (!active[final[it]]||!active[final[it]][it1]) { // on exit
       ret.push(this.ctt.substr(active[final[it]][it1],this.pos));
      }
//      if (this.pos>=this.ctt.length&&!active[final[it]]) {ret.push(this.ctt.substr(active[final[it]][it1],this.pos));}
     }
    }
   }
   break;
  case 'first':
   for (it in final) {
    if (active[final[it]]) {
     for (it1 in active[final[it]]) {
      if (!this.graph.active[final[it]]||!this.graph.active[final[it]][it1]) { // on enter
       ret.push(this.ctt.substr(this.graph.active[final[it]][it1],this.pos+1));
      }
     }
    }
   }
   break;
  case 'strict':
   if (this.pos==this.ctt.length) { for (it in final) {
    if (active[final[it]]) {
     for (it1 in active[final[it]]) {
      ret.push(this.ctt.substr(it1,this.pos));
     }
    }
   }}
   break;
  }
  return ret;
 },
 steponce:function(char,strategy) {
 strategy=strategy||this.strategy; // for Chrome compatibility (only Firefox supports default parameter feature)
 char=char||this.ctt[this.pos]; // for Chrome compatibility (only Firefox supports default parameter feature)
 var newact={}; // new active list
 var regex; // transition character
  for (it1 in this.graph.nodes) {
   for (it2 in this.graph.nodes[it1].lkt) {
    this.graph.nodes[it1].lkt[it2].phase=0;
   }
  }
  for (it1 in this.graph.active) {
   for (it2 in this.graph.active[it1]) {
    for (it3 in this.graph.nodes[it1].lkt) {
     if (!this.graph.nodes[it1].lkt[it3].char) continue; // skip non-char transit
     regex=new RegExp(this.graph.nodes[it1].lkt[it3].char);
     if (regex.test(char)) {
      newact=this.aux_addact(this.graph.nodes[it1].lkt[it3].node.idx,it2,newact,strategy);
      this.graph.nodes[it1].lkt[it3].phase=1;
     }
    }
   }
  }
  if (strategy.start!='strict') {newact=this.aux_addact(this.graph.entry.idx,this.pos,newact,strategy);}
  this.aux_updateNonCharTrans(newact);
  this.matches=this.matches.concat(this.aux_checkmatch(this.graph.final,this.pos,newact,strategy)); // using this.graph.active as old active states list, so it should be put before this.graph.active=newact;
  if (this.pos<this.ctt.length) this.graph.active=newact;
  this.pos+=1;
 },

 is_end:function() { // fully evolved or not
  if (this.strategy.start=='strict'&&this.pos>0&&Object.keys(this.graph.active).length==0) {return true;}
  return this.pos>this.ctt.length;
 },

 step:function() { // try to step
  if (!this.is_end()) {this.steponce();}
 },

 result:function() { // return matched results
  return this.matches;
 },

 run:function() { // keep stepping until end
  while (this.pos<this.ctt.length) {
   this.step();
  }
  return this.dump();
 }
}


text:
package com.badlogic.gdx.utils;

import java.util.Arrays;

/** A bitset, without size limitation, allows comparison via bitwise operators to other bitfields.
 *
 * @author mzechner
 * @author jshapcott */
public class Bits {

	long[] bits = {0};

	public Bits () {
	}

	/** Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through
	 * nbits-1.
	 * @param nbits the initial size of the bit set */
	public Bits (int nbits) {
		checkCapacity(nbits >>> 6);
	}

	/** @param index the index of the bit
	 * @return whether the bit is set
	 * @throws ArrayIndexOutOfBoundsException if index < 0 */
	public boolean get (int index) {
		final int word = index >>> 6;
		if (word >= bits.length) return false;
		return (bits[word] & (1L << (index & 0x3F))) != 0L;
	}

	/** Returns the bit at the given index and clears it in one go.
	 * @param index the index of the bit
	 * @return whether the bit was set before invocation
	 * @throws ArrayIndexOutOfBoundsException if index < 0 */
	public boolean getAndClear (int index) {
		final int word = index >>> 6;
		if (word >= bits.length) return false;
		long oldBits = bits[word];
		bits[word] &= ~(1L << (index & 0x3F));
		return bits[word] != oldBits;
	}

	/** Returns the bit at the given index and sets it in one go.
	 * @param index the index of the bit
	 * @return whether the bit was set before invocation
	 * @throws ArrayIndexOutOfBoundsException if index < 0 */
	public boolean getAndSet (int index) {
		final int word = index >>> 6;
		checkCapacity(word);
		long oldBits = bits[word];
		bits[word] |= 1L << (index & 0x3F);
		return bits[word] == oldBits;
	}

	/** @param index the index of the bit to set
	 * @throws ArrayIndexOutOfBoundsException if index < 0 */
	public void set (int index) {
		final int word = index >>> 6;
		checkCapacity(word);
		bits[word] |= 1L << (index & 0x3F);
	}

	/** @param index the index of the bit to flip */
	public void flip (int index) {
		final int word = index >>> 6;
		checkCapacity(word);
		bits[word] ^= 1L << (index & 0x3F);
	}

	private void checkCapacity (int len) {
		if (len >= bits.length) {
			long[] newBits = new long[len + 1];
			System.arraycopy(bits, 0, newBits, 0, bits.length);
			bits = newBits;
		}
	}

	/** @param index the index of the bit to clear
	 * @throws ArrayIndexOutOfBoundsException if index < 0 */
	public void clear (int index) {
		final int word = index >>> 6;
		if (word >= bits.length) return;
		bits[word] &= ~(1L << (index & 0x3F));
	}

	/** Clears the entire bitset */
	public void clear () {
		long[] bits = this.bits;
		int length = bits.length;
		for (int i = 0; i < length; i++) {
			bits[i] = 0L;
		}
	}

	/** @return the number of bits currently stored, not the highset set bit! */
	public int numBits () {
		return bits.length << 6;
	}

	/** Returns the "logical size" of this bitset: the index of the highest set bit in the bitset plus one. Returns zero if the
	 * bitset contains no set bits.
	 *
	 * @return the logical size of this bitset */
	public int length () {
		long[] bits = this.bits;
		for (int word = bits.length - 1; word >= 0; --word) {
			long bitsAtWord = bits[word];
			if (bitsAtWord != 0) {
				for (int bit = 63; bit >= 0; --bit) {
					if ((bitsAtWord & (1L << (bit & 0x3F))) != 0L) {
						return (word << 6) + bit + 1;
					}
				}
			}
		}
		return 0;
	}

	/** @return true if this bitset contains no bits that are set to true */
	public boolean isEmpty () {
		long[] bits = this.bits;
		int length = bits.length;
		for (int i = 0; i < length; i++) {
			if (bits[i] != 0L) {
				return false;
			}
		}
		return true;
	}

	/** Returns the index of the first bit that is set to true that occurs on or after the specified starting index. If no such bit
	 * exists then -1 is returned. */
	public int nextSetBit (int fromIndex) {
		long[] bits = this.bits;
		int word = fromIndex >>> 6;
		int bitsLength = bits.length;
		if (word >= bitsLength) return -1;
		long bitsAtWord = bits[word];
		if (bitsAtWord != 0) {
			for (int i = fromIndex & 0x3f; i < 64; i++) {
				if ((bitsAtWord & (1L << (i & 0x3F))) != 0L) {
					return (word << 6) + i;
				}
			}
		}
		for (word++; word < bitsLength; word++) {
			if (word != 0) {
				bitsAtWord = bits[word];
				if (bitsAtWord != 0) {
					for (int i = 0; i < 64; i++) {
						if ((bitsAtWord & (1L << (i & 0x3F))) != 0L) {
							return (word << 6) + i;
						}
					}
				}
			}
		}
		return -1;
	}

	/** Returns the index of the first bit that is set to false that occurs on or after the specified starting index. If no such bit
	 * exists then -1 is returned. */
	public int nextClearBit (int fromIndex) {
		long[] bits = this.bits;
		int word = fromIndex >>> 6;
		int bitsLength = bits.length;
		if (word >= bitsLength) return -1;
		long bitsAtWord = bits[word];
		for (int i = fromIndex & 0x3f; i < 64; i++) {
			if ((bitsAtWord & (1L << (i & 0x3F))) == 0L) {
				return (word << 6) + i;
			}
		}
		for (word++; word < bitsLength; word++) {
			if (word == 0) {
				return word << 6;
			}
			bitsAtWord = bits[word];
			for (int i = 0; i < 64; i++) {
				if ((bitsAtWord & (1L << (i & 0x3F))) == 0L) {
					return (word << 6) + i;
				}
			}
		}
		return -1;
	}

	/** Performs a logical AND of this target bit set with the argument bit set. This bit set is modified so that each bit in
	 * it has the value true if and only if it both initially had the value true and the corresponding bit in the bit set argument
	 * also had the value true.
	 * @param other a bit set */
	public void and (Bits other) {
		int commonWords = Math.min(bits.length, other.bits.length);
		for (int i = 0; commonWords > i; i++) {
			bits[i] &= other.bits[i];
		}

		if (bits.length > commonWords) {
			for (int i = commonWords, s = bits.length; s > i; i++) {
				bits[i] = 0L;
			}
		}
	}

	/** Clears all of the bits in this bit set whose corresponding bit is set in the specified bit set.
	 *
	 * @param other a bit set */
	public void andNot (Bits other) {
		for (int i = 0, j = bits.length, k = other.bits.length; i < j && i < k; i++) {
			bits[i] &= ~other.bits[i];
		}
	}

	/** Performs a logical OR of this bit set with the bit set argument. This bit set is modified so that a bit in it has the
	 * value true if and only if it either already had the value true or the corresponding bit in the bit set argument has the
	 * value true.
	 * @param other a bit set */
	public void or (Bits other) {
		int commonWords = Math.min(bits.length, other.bits.length);
		for (int i = 0; commonWords > i; i++) {
			bits[i] |= other.bits[i];
		}

		if (commonWords < other.bits.length) {
			checkCapacity(other.bits.length);
			for (int i = commonWords, s = other.bits.length; s > i; i++) {
				bits[i] = other.bits[i];
			}
		}
	}

	/** Performs a logical XOR of this bit set with the bit set argument. This bit set is modified so that a bit in it has
	 * the value true if and only if one of the following statements holds:
	 *

	 *
The bit initially has the value true, and the corresponding bit in the argument has the value false.

	 *
The bit initially has the value false, and the corresponding bit in the argument has the value true.

	 *

	 * @param other */
	public void xor (Bits other) {
		int commonWords = Math.min(bits.length, other.bits.length);

		for (int i = 0; commonWords > i; i++) {
			bits[i] ^= other.bits[i];
		}

		if (commonWords < other.bits.length) {
			checkCapacity(other.bits.length);
			for (int i = commonWords, s = other.bits.length; s > i; i++) {
				bits[i] = other.bits[i];
			}
		}
	}

	/** Returns true if the specified BitSet has any bits set to true that are also set to true in this BitSet.
	 *
	 * @param other a bit set
	 * @return boolean indicating whether this bit set intersects the specified bit set */
	public boolean intersects (Bits other) {
		long[] bits = this.bits;
		long[] otherBits = other.bits;
		for (int i = Math.min(bits.length, otherBits.length) - 1; i >= 0; i--) {
			if ((bits[i] & otherBits[i]) != 0) {
				return true;
			}
		}
		return false;
	}

	/** Returns true if this bit set is a super set of the specified set, i.e. it has all bits set to true that are also set to true
	 * in the specified BitSet.
	 *
	 * @param other a bit set
	 * @return boolean indicating whether this bit set is a super set of the specified set */
	public boolean containsAll (Bits other) {
		long[] bits = this.bits;
		long[] otherBits = other.bits;
		int otherBitsLength = otherBits.length;
		int bitsLength = bits.length;

		for (int i = bitsLength; i < otherBitsLength; i++) {
			if (otherBits[i] != 0) {
				return false;
			}
		}
		for (int i = Math.min(bitsLength, otherBitsLength) - 1; i >= 0; i--) {
			if ((bits[i] & otherBits[i]) != otherBits[i]) {
				return false;
			}
		}
		return true;
	}

	@Override
	public int hashCode() {
		final int word = length() >>> 6;
		int hash = 0;
		for (int i = 0; word >= i; i++) {
			hash = 127 * hash + (int)(bits[i] ^ (bits[i] >>> 32));
		}
		return hash;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;

		Bits other = (Bits) obj;
		long[] otherBits = other.bits;

		int commonWords = Math.min(bits.length, otherBits.length);
		for (int i = 0; commonWords > i; i++) {
			if (bits[i] != otherBits[i])
				return false;
		}

		if (bits.length == otherBits.length)
			return true;

		return length() == other.length();
	}
}

redpajama_set_name: RedPajamaGithub


text:
var view = ko.views.manager.currentView;
if (!('extensions' in ko)) {
    ko.extensions = {};
}
if (!('togglers' in ko.extensions)) {
    ko.extensions.togglers = {};
}
var methodName = "*[[%tabstop1:togglerName]]*" + view.uid;
var methodObject;
if (!(methodName in ko.extensions.togglers)) {
    var scimoz = view.scimoz;
    methodObject = ko.extensions.togglers[methodName] = function(event) {
		[[%tabstop0:code]]
        else if (event.keyCode == event.DOM_VK_ESCAPE) {
            methodObject.toggleOff();
        }
    };
    methodObject.active = false;
    var macro = ko.macros.current;
    methodObject.macro = macro;
    methodObject.orig_iconurl = macro.iconurl;

    methodObject.toggleOn = function() {
        view.addEventListener('keypress', methodObject, true);
        dump("[[%tabstop1]] on!\n");
        methodObject.active = true;
        methodObject.columnPos = scimoz.getColumn(scimoz.currentPos);
        methodObject.macro.iconurl = 'chrome://famfamfamsilk/skin/icons/[[%tabstop3:iconName]].png';
        methodObject.macro.save();
        window.addEventListener('current_view_changed', methodObject.toggleOff, false);
    }

    methodObject.toggleOff = function() {
        dump("[[%tabstop1]] off!\n");
        view.removeEventListener('keypress', methodObject, true);
        window.removeEventListener('current_view_changed', methodObject.toggleOff, false);
        methodObject.active = false;
        methodObject.macro.iconurl = "";
        methodObject.macro.save();
    }
    view.scintilla.focus();
} else {
    methodObject = ko.extensions.togglers[methodName];
}

if (!methodObject.active) {
    methodObject.toggleOn();
} else {
    methodObject.toggleOff();
}
[[%tabstop4://]]dump("Running macro " + methodObject.macro.id + "\n");


text:
package com.lambdaworks.redis.cluster;

import static com.lambdaworks.redis.cluster.ClusterTestUtil.getOwnPartition;
import static org.assertj.core.api.Assertions.assertThat;

import java.util.Collections;
import java.util.List;

import org.junit.*;
import org.junit.runners.MethodSorters;

import rx.Observable;

import com.lambdaworks.TestClientResources;
import com.lambdaworks.redis.FastShutdown;
import com.lambdaworks.redis.RedisClient;
import com.lambdaworks.redis.RedisException;
import com.lambdaworks.redis.RedisURI;
import com.lambdaworks.redis.cluster.api.StatefulRedisClusterConnection;
import com.lambdaworks.redis.cluster.api.rx.RedisAdvancedClusterReactiveCommands;
import com.lambdaworks.redis.cluster.api.sync.RedisAdvancedClusterCommands;
import com.lambdaworks.redis.cluster.models.partitions.RedisClusterNode;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SuppressWarnings("unchecked")
public class RedisRxClusterClientTest extends AbstractClusterTest {

    protected static RedisClient client;

    protected StatefulRedisClusterConnection<String, String> connection;
    protected RedisAdvancedClusterCommands<String, String> sync;
    protected RedisAdvancedClusterReactiveCommands<String, String> rx;

    @BeforeClass
    public static void setupClient() throws Exception {
        setupClusterClient();
        client = RedisClient.create(TestClientResources.get(), RedisURI.Builder.redis(host, port1).build());
        clusterClient = RedisClusterClient.create(TestClientResources.get(),
                Collections.singletonList(RedisURI.Builder.redis(host, port1).build()));
    }

    @AfterClass
    public static void shutdownClient() {
        shutdownClusterClient();
        FastShutdown.shutdown(client);
        FastShutdown.shutdown(clusterClient);
    }

    @Before
    public void before() throws Exception {

        clusterRule.getClusterClient().reloadPartitions();

        clusterClient.reloadPartitions();
        connection = clusterClient.connect();
        sync = connection.sync();
        rx = connection.reactive();
    }

    @After
    public void after() throws Exception {
        connection.close();
    }

    @Test
    public void testClusterCommandRedirection() throws Exception {
        // Command on node within the default connection
        assertThat(getSingle(rx.set(KEY_B, "myValue1"))).isEqualTo("OK");

        // gets redirection to node 3
        assertThat(getSingle(rx.set(KEY_A, "myValue1"))).isEqualTo("OK");
    }

    @Test
    public void getKeysInSlot() throws Exception {

        sync.set(KEY_A, value);
        sync.set(KEY_B, value);

        List<String> keysA = getSingle(rx.clusterGetKeysInSlot(SLOT_A, 10).toList());
        assertThat(keysA).isEqualTo(Collections.singletonList(KEY_A));

        List<String> keysB = getSingle(rx.clusterGetKeysInSlot(SLOT_B, 10).toList());
        assertThat(keysB).isEqualTo(Collections.singletonList(KEY_B));
    }

    @Test
    public void countKeysInSlot() throws Exception {

        sync.set(KEY_A, value);
        sync.set(KEY_B, value);

        Long result = getSingle(rx.clusterCountKeysInSlot(SLOT_A));
        assertThat(result).isEqualTo(1L);

        result = getSingle(rx.clusterCountKeysInSlot(SLOT_B));
        assertThat(result).isEqualTo(1L);

        int slotZZZ = SlotHash.getSlot("ZZZ".getBytes());
        result = getSingle(rx.clusterCountKeysInSlot(slotZZZ));
        assertThat(result).isEqualTo(0L);
    }

    @Test
    public void testClusterCountFailureReports() throws Exception {
        RedisClusterNode ownPartition = getOwnPartition(sync);
        assertThat(getSingle(rx.clusterCountFailureReports(ownPartition.getNodeId()))).isGreaterThanOrEqualTo(0);
    }

    @Test
    public void testClusterKeyslot() throws Exception {
        assertThat(getSingle(rx.clusterKeyslot(KEY_A))).isEqualTo(SLOT_A);
        assertThat(SlotHash.getSlot(KEY_A)).isEqualTo(SLOT_A);
    }

    @Test
    public void testClusterSaveconfig() throws Exception {
        assertThat(getSingle(rx.clusterSaveconfig())).isEqualTo("OK");
    }

    @Test
    public void testClusterSetConfigEpoch() throws Exception {
        try {
            getSingle(rx.clusterSetConfigEpoch(1L));
        } catch (RedisException e) {
            assertThat(e).hasMessageContaining("ERR The user can assign a config epoch only");
        }
    }

    private <T> T getSingle(Observable<T> observable) {
        return observable.toBlocking().single();
    }

}


text:
package com.amazonaws.services.workdocs.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.workdocs.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * UserStorageMetadata JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UserStorageMetadataJsonUnmarshaller implements Unmarshaller<UserStorageMetadata, JsonUnmarshallerContext> {

    public UserStorageMetadata unmarshall(JsonUnmarshallerContext context) throws Exception {
        UserStorageMetadata userStorageMetadata = new UserStorageMetadata();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("StorageUtilizedInBytes", targetDepth)) {
                    context.nextToken();
                    userStorageMetadata.setStorageUtilizedInBytes(context.getUnmarshaller(Long.class).unmarshall(context));
                }
                if (context.testExpression("StorageRule", targetDepth)) {
                    context.nextToken();
                    userStorageMetadata.setStorageRule(StorageRuleTypeJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return userStorageMetadata;
    }

    private static UserStorageMetadataJsonUnmarshaller instance;

    public static UserStorageMetadataJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new UserStorageMetadataJsonUnmarshaller();
        return instance;
    }
}


text:
namespace boost { namespace python { namespace objects {

// This type is used as a "generalized Python callback", wrapping the
// function signature:
//
//      PyObject* (PyObject* args, PyObject* keywords)

struct BOOST_PYTHON_DECL py_function_impl_base
{
    virtual ~py_function_impl_base();
    virtual PyObject* operator()(PyObject*, PyObject*) = 0;
    virtual unsigned min_arity() const = 0;
    virtual unsigned max_arity() const;
    virtual python::detail::py_func_sig_info signature() const = 0;
};

template <class Caller>
struct caller_py_function_impl : py_function_impl_base
{
    caller_py_function_impl(Caller const& caller)
        : m_caller(caller)
    {}

    PyObject* operator()(PyObject* args, PyObject* kw)
    {
        return m_caller(args, kw);
    }

    virtual unsigned min_arity() const
    {
        return m_caller.min_arity();
    }

    virtual python::detail::py_func_sig_info signature() const
    {
        return m_caller.signature();
    }

 private:
    Caller m_caller;
};

template <class Caller, class Sig>
struct signature_py_function_impl : py_function_impl_base
{
    signature_py_function_impl(Caller const& caller)
        : m_caller(caller)
    {}

    PyObject* operator()(PyObject* args, PyObject* kw)
    {
        return m_caller(args, kw);
    }

    virtual unsigned min_arity() const
    {
        return mpl::size<Sig>::value - 1;
    }

    virtual python::detail::py_func_sig_info signature() const
    {
        python::detail::signature_element const* sig = python::detail::signature<Sig>::elements();
        python::detail::py_func_sig_info res = {sig, sig};
        return  res;
    }

 private:
    Caller m_caller;
};

template <class Caller, class Sig>
struct full_py_function_impl : py_function_impl_base
{
    full_py_function_impl(Caller const& caller, unsigned min_arity, unsigned max_arity)
      : m_caller(caller)
      , m_min_arity(min_arity)
      , m_max_arity(max_arity > min_arity ? max_arity : min_arity)
    {}

    PyObject* operator()(PyObject* args, PyObject* kw)
    {
        return m_caller(args, kw);
    }

    virtual unsigned min_arity() const
    {
        return m_min_arity;
    }

    virtual unsigned max_arity() const
    {
        return m_max_arity;
    }

    virtual python::detail::py_func_sig_info signature() const
    {
        python::detail::signature_element const* sig = python::detail::signature<Sig>::elements();
        python::detail::py_func_sig_info res = {sig, sig};
        return  res;
    }

 private:
    Caller m_caller;
    unsigned m_min_arity;
    unsigned m_max_arity;
};

struct py_function
{
    template <class Caller>
    py_function(Caller const& caller)
        : m_impl(new caller_py_function_impl<Caller>(caller))
    {}

    template <class Caller, class Sig>
    py_function(Caller const& caller, Sig)
      : m_impl(new signature_py_function_impl<Caller, Sig>(caller))
    {}

    template <class Caller, class Sig>
    py_function(Caller const& caller, Sig, int min_arity, int max_arity = 0)
      : m_impl(new full_py_function_impl<Caller, Sig>(caller, min_arity, max_arity))
    {}

    py_function(py_function const& rhs)
        : m_impl(rhs.m_impl)
    {}

    PyObject* operator()(PyObject* args, PyObject* kw) const
    {
        return (*m_impl)(args, kw);
    }

    unsigned min_arity() const
    {
        return m_impl->min_arity();
    }

    unsigned max_arity() const
    {
        return m_impl->max_arity();
    }

    python::detail::signature_element const* signature() const
    {
        return m_impl->signature().signature;
    }

    python::detail::signature_element const& get_return_type() const
    {
        return *m_impl->signature().ret;
    }

 private:
    mutable std::auto_ptr<py_function_impl_base> m_impl;
};

}}} // namespace boost::python::objects

#endif // PY_FUNCTION_DWA200286_HPP


text: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">


text:
import TextBase from './TextBase';

export default class Textarea extends TextBase {
  createFormTag(target){
    return (
      <textarea
        className="form-control text-element"
        name=""
        data-id={target.id}
        cols="30"
        rows="10"
        onChange={(e) => this.onValueChange(e)} value={target.value||""}
      >
      </textarea>
    )
  }
}

Textarea.defaultProps = {
  values: []
}


text:
import getpass
import logging
import sys
# IPython
from IPython.core.magic import (Magics, magics_class, line_magic,
                                cell_magic, line_cell_magic)
# KBase
import biokbase.auth

from biokbase.narrative.common.url_config import URLS
from biokbase.narrative.common.log_common import EVENT_MSG_SEP

# Logging
g_log = logging.getLogger(__name__)

# Module variables for maintaining KBase Notebook state
user_id = None
token = None
user_profile = None
ws_client = None

# Flag set by a JS callback to let is know if we have a browser or not
have_browser = None

# End points for various services
endpoint = {'workspace': URLS.workspace}

# IPython interpreter object
ip = None

# default start directory
workdir = "/tmp/narrative"

def user_msg(s):
    """Show a message to the user.
    Adds a newline.
    Also logs it for posterity.
    """
    g_log.debug("user_msg{}len={:d}".format(
               EVENT_MSG_SEP, len(s)))
    sys.stderr.write(s + "\n")

def set_token(newtoken):
    global user_id, token, user_profile
    if newtoken:
        token = newtoken
        biokbase.auth.set_environ_token(token)
        user_profile = biokbase.auth.User(token=token)
        user_id = user_profile.user_id
        # If we had a previous session, clear it out
        ws_client = None

def clear_token():
    global user_id, token, user_profile
    if token is not None:
        user_msg("Clearing credentials and profile for {}".format(user_id))
        user_id = None
        token = None
        user_profile = None
    biokbase.auth.set_environ_token(None)
    ws_client = None

# Define the KBase notebook magics

@magics_class
class kbasemagics(Magics):

    @line_magic
    def kblogin(self, line):
        """
        Login using username and password to KBase and then push login token into the environment.
        Usage is: kblogin {userid}
        If you have an ssh-agent with keys loaded, kblogin will attempt to use your ssh-key to
        get an Globus token, if not, then you will be prompted for your password.
        The token will be pushed into the KBASE_AUTH_TOKEN environment variable and picked up
        by any libraries that have implemented that support.
        """
        try:
            (user, password) = line.strip().split()
        except ValueError:
            user = line
            password = None
        global user_id, token, user_profile

        if user_id is not None:
            user_msg("Already logged in as {}. "
                     "Please kblogout first if you want to re-login"
                     .format(user_id))
        elif user is None:
            user_msg("kblogin requires at least a username")
        else:
            try:
                # XXX: SSH_AGENT NOT WORKING, so it's been deprecated
                # try to login with only user_id in case there is
                # an ssh_agent running
                # t = biokbase.auth.Token(user_id=user)
                # if t.token is None:
                if password is None:
                    password = getpass.getpass("Please enter the KBase "
                                               "password for '%s': " % user)
                t = biokbase.auth.Token(user_id=user, password=password)
                if t.token:
                    set_token(t.token)
                else:
                    raise biokbase.auth.AuthFail(
                        "Could not get token with username and password given")
            except biokbase.auth.AuthFail:
                user_msg("Failed to login with username password provided. "
                         "Please try again.")
                token = None
        if token is not None:
            return user_id
        else:
            return None

    @line_magic
    def kblogout(self, line):
        """Logout by removing credentials from environment and
           clearing session objects
        """
        # Call the clear_token method
        clear_token()
        return


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;

namespace OpenRiaServices.DomainServices.Client
{
    /// <summary>
    /// Represents a domain operation to be performed on an entity. This is the message
    /// type passed between <see cref="DomainClient"/> and DomainService both for sending operations to
    /// the DomainService as well as for returning operation results back to the <see cref="DomainClient"/>.
    /// </summary>
    [DataContract(Namespace = "DomainServices")]
    [DebuggerDisplay("Operation = {Operation}, Type = {Entity.GetType().Name}")]
    public sealed class ChangeSetEntry
    {
        private Entity _clientEntity;
        private Entity _entity;
        private Entity _originalEntity;
        private Entity _storeEntity;
        private EntityOperationType _operationType;
        private int _id;
        private bool _hasMemberChanges;

        /// <summary>
        /// Gets a value indicating whether any errors were encountered
        /// during processing of the operation.
        /// </summary>
        internal bool HasError
        {
            get
            {
                return this.HasConflict || (this.ValidationErrors != null && this.ValidationErrors.Any());
            }
        }

        /// <summary>
        /// Gets a value indicating whether the <see cref="ChangeSetEntry"/> contains conflicts.
        /// </summary>
        public bool HasConflict
        {
            get
            {
                return (this.IsDeleteConflict || (this.ConflictMembers != null && this.ConflictMembers.Any()));
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ChangeSetEntry"/> class
        /// </summary>
        /// <param name="entity">The entity being operated on</param>
        /// <param name="id">The client ID for the entity, used to correlate server results
        /// with their client entity instances.</param>
        /// <param name="operationType">The operation to be performed</param>
        public ChangeSetEntry(Entity entity, int id, EntityOperationType operationType)
        {
            this._entity = entity;
            this._id = id;
            this._operationType = operationType;
        }

        /// <summary>
        /// Gets or sets the <see cref="Entity"/> being operated on. After a submit operation
        /// has completed, this member may contain updated entity state returned from the
        /// DomainService.
        /// </summary>
        [DataMember]
        public Entity Entity
        {
            get
            {
                return this._entity;
            }
            set
            {
                this._entity = value;
            }
        }

        /// <summary>
        /// Gets or sets the original state of the entity being operated on
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public Entity OriginalEntity
        {
            get
            {
                return this._originalEntity;
            }
            set
            {
                this._originalEntity = value;

                if (value != null)
                {
                    this._hasMemberChanges = true;
                }
            }
        }

        /// <summary>
        /// Gets or sets the state of the entity in the data store
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public Entity StoreEntity
        {
            get
            {
                return this._storeEntity;
            }
            set
            {
                this._storeEntity = value;
            }
        }

        /// <summary>
        /// Gets or sets the entity that was originally submitted <see cref="Entity"/>. Used to correlate
        /// an <see cref="ChangeSetEntry"/> result back to its originally submitted client entity instance.
        /// </summary>
        public Entity ClientEntity
        {
            get
            {
                return this._clientEntity ?? this._entity;
            }
            set
            {
                this._clientEntity = value;
            }
        }

        /// <summary>
        /// Gets or sets the client Id for the entity. This value is used to correlate server
        /// results with their client entity instances.
        /// </summary>
        [DataMember]
        public int Id
        {
            get
            {
                return this._id;
            }
            set
            {
                this._id = value;
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether the entity for
        /// this operation has property modifications.
        /// <remarks>Note that even if OriginalEntity hasn't been
        /// set, in the case of entities using a timestamp member
        /// for concurrency, the entity may still be modified. This
        /// flag allows us to distinguish that case from an Update
        /// operation that represents a custom method invocation only.
        /// </remarks>
        /// </summary>
        [DataMember]
        public bool HasMemberChanges
        {
            get
            {
                return this._hasMemberChanges;
            }
            set
            {
                this._hasMemberChanges = value;
            }
        }

        /// <summary>
        /// Gets or sets the <see cref="EntityOperationType"/> for this <see cref="ChangeSetEntry"/>
        /// </summary>
        [DataMember]
        public EntityOperationType Operation
        {
            get
            {
                return this._operationType;
            }
            set
            {
                this._operationType = value;
            }
        }

        /// <summary>
        /// Gets or sets the custom methods invoked on the entity, as a set
        /// of method name / parameter set pairs.
        /// </summary>
        [DataMember]
        public IDictionary<string, object[]> EntityActions
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the validation errors encountered during the processing of the operation.
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public IEnumerable<ValidationResultInfo> ValidationErrors
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the collection of members in conflict. The <see cref="StoreEntity"/> property
        /// contains the current store value for each member in conflict.
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public IEnumerable<string> ConflictMembers
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets whether the conflict is a delete conflict, meaning the
        /// entity no longer exists in the store.
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public bool IsDeleteConflict
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the collection of IDs of the associated entities for
        /// each association of the Entity
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public IDictionary<string, int[]> Associations
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the collection of IDs for each association of the <see cref="OriginalEntity"/>
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public IDictionary<string, int[]> OriginalAssociations
        {
            get;
            set;
        }
    }
}


text:
package org.tylproject.vaadin.addon.fields.zoom;

import com.vaadin.data.Container;
import com.vaadin.ui.*;
import org.tylproject.vaadin.addon.fields.FilterableGrid;

/**
 * A ZoomDialog that uses a FilterableGrid by default
 */
public class GridZoomDialog extends AbstractZoomDialog {

    private final Grid grid;

    public GridZoomDialog(Grid grid) {
        this.grid = grid;
        setupDialog(grid);
    }

    public GridZoomDialog(Grid grid, Object propertyId, String caption) {
        this(grid, propertyId);
        this.setCaption(caption);
    }

    public GridZoomDialog(Grid grid, Object propertyId) {
        this(grid);
        Container c = grid.getContainerDataSource();
        withContainerPropertyId(propertyId, c.getType(propertyId));
        setCaption(DefaultFieldFactory.createCaptionByPropertyId(propertyId));
    }

    public GridZoomDialog(Object propertyId, Container.Indexed container) {
        withContainerPropertyId(propertyId, container.getType(propertyId));

        FilterableGrid grid = new FilterableGrid(container);

        grid.setSelectionMode(Grid.SelectionMode.SINGLE);

        grid.setSizeFull();
        grid.setWidth("100%");
        grid.setHeight("100%");
        grid.setVisibileColumns("firstName", "lastName", "birthDate");

        this.grid = grid;

        setupDialog(grid);

    }

    private void setupDialog(Grid grid) {
        if (!(grid.getSelectionModel() instanceof Grid.SingleSelectionModel)) {
            throw new AssertionError(
                    "Selection mode must be "+Grid.SelectionMode.SINGLE.getClass()+", "+
                            grid.getSelectionModel().getClass() +" was given");
        }

        addComponent(grid);
        setExpandRatio(getGrid(), 1f);
        setSizeFull();
    }

    public GridZoomDialog withContainerPropertyId(Object propertyId, Class<?> propertyType) {
        super.withContainerPropertyId(propertyId, propertyType);
        return this;
    }

    @Override
    public Container getContainer() {
        return grid.getContainerDataSource();
    }

    public final Grid getGrid() {
        return grid;
    }

    @Override
    public void show(Object value) {
        if (isReadOnly()) {
            grid.setSelectionMode(Grid.SelectionMode.NONE);
        } else {
            grid.setSelectionMode(Grid.SelectionMode.SINGLE);
        }
    }

    public Object getSelectedItemId() {
        return getGrid().getSelectedRow();
    }

    public void dismiss() {
        super.dismiss();
        Container c = getGrid().getContainerDataSource();
        if (c instanceof Container.Filterable) {
            ((Container.Filterable) c).removeAllContainerFilters();
        }
    }
}


text:
#!/usr/bin/env bash
#
#

# Set environment variables here.

# This script sets variables multiple times over the course of starting an hbase process,
# so try to keep things idempotent unless you want to take an even deeper look
# into the startup scripts (bin/hbase, etc.)

# The java implementation to use.  Java 1.8+ required.
# export JAVA_HOME=/usr/java/jdk1.8.0/

# Extra Java CLASSPATH elements.  Optional.
# export HBASE_CLASSPATH=

# The maximum amount of heap to use. Default is left to JVM default.
# export HBASE_HEAPSIZE=1G

# Uncomment below if you intend to use off heap cache. For example, to allocate 8G of
# offheap, set the value to "8G". See http://hbase.apache.org/book.html#direct.memory
# in the refguide for guidance setting this config.
# export HBASE_OFFHEAPSIZE=1G

# Extra Java runtime options.
# Default settings are applied according to the detected JVM version. Override these default
# settings by specifying a value here. For more details on possible settings,
# see http://hbase.apache.org/book.html#_jvm_tuning
# export HBASE_OPTS

# Uncomment one of the below three options to enable java garbage collection logging for the server-side processes.

# This enables basic gc logging to the .out file.
# export SERVER_GC_OPTS="-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps"

# This enables basic gc logging to its own file.
# If FILE-PATH is not replaced, the log file(.gc) would still be generated in the HBASE_LOG_DIR .
# export SERVER_GC_OPTS="-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:<FILE-PATH>"

# This enables basic GC logging to its own file with automatic log rolling. Only applies to jdk 1.6.0_34+ and 1.7.0_2+.
# If FILE-PATH is not replaced, the log file(.gc) would still be generated in the HBASE_LOG_DIR .
# export SERVER_GC_OPTS="-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:<FILE-PATH> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=1 -XX:GCLogFileSize=512M"

# Uncomment one of the below three options to enable java garbage collection logging for the client processes.

# This enables basic gc logging to the .out file.
# export CLIENT_GC_OPTS="-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps"

# This enables basic gc logging to its own file.
# If FILE-PATH is not replaced, the log file(.gc) would still be generated in the HBASE_LOG_DIR .
# export CLIENT_GC_OPTS="-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:<FILE-PATH>"

# This enables basic GC logging to its own file with automatic log rolling. Only applies to jdk 1.6.0_34+ and 1.7.0_2+.
# If FILE-PATH is not replaced, the log file(.gc) would still be generated in the HBASE_LOG_DIR .
# export CLIENT_GC_OPTS="-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:<FILE-PATH> -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=1 -XX:GCLogFileSize=512M"

# See the package documentation for org.apache.hadoop.hbase.io.hfile for other configurations
# needed setting up off-heap block caching.

# Uncomment and adjust to enable JMX exporting
# See jmxremote.password and jmxremote.access in $JRE_HOME/lib/management to configure remote password access.
# More details at: http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html
# NOTE: HBase provides an alternative JMX implementation to fix the random ports issue, please see JMX
# section in HBase Reference Guide for instructions.

# export HBASE_JMX_BASE="-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"
# export HBASE_MASTER_OPTS="$HBASE_MASTER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10101"
# export HBASE_REGIONSERVER_OPTS="$HBASE_REGIONSERVER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10102"
# export HBASE_THRIFT_OPTS="$HBASE_THRIFT_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10103"
# export HBASE_ZOOKEEPER_OPTS="$HBASE_ZOOKEEPER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10104"
# export HBASE_REST_OPTS="$HBASE_REST_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10105"

# File naming hosts on which HRegionServers will run.  $HBASE_HOME/conf/regionservers by default.
# export HBASE_REGIONSERVERS=${HBASE_HOME}/conf/regionservers

# Uncomment and adjust to keep all the Region Server pages mapped to be memory resident
#HBASE_REGIONSERVER_MLOCK=true
#HBASE_REGIONSERVER_UID="hbase"

# File naming hosts on which backup HMaster will run.  $HBASE_HOME/conf/backup-masters by default.
# export HBASE_BACKUP_MASTERS=${HBASE_HOME}/conf/backup-masters

# Extra ssh options.  Empty by default.
# export HBASE_SSH_OPTS="-o ConnectTimeout=1 -o SendEnv=HBASE_CONF_DIR"

# Where log files are stored.  $HBASE_HOME/logs by default.
# export HBASE_LOG_DIR=${HBASE_HOME}/logs

# Enable remote JDWP debugging of major HBase processes. Meant for Core Developers
# export HBASE_MASTER_OPTS="$HBASE_MASTER_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8070"
# export HBASE_REGIONSERVER_OPTS="$HBASE_REGIONSERVER_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8071"
# export HBASE_THRIFT_OPTS="$HBASE_THRIFT_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8072"
# export HBASE_ZOOKEEPER_OPTS="$HBASE_ZOOKEEPER_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8073"
# export HBASE_REST_OPTS="$HBASE_REST_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8074"

# A string representing this instance of hbase. $USER by default.
# export HBASE_IDENT_STRING=$USER

# The scheduling priority for daemon processes.  See 'man nice'.
# export HBASE_NICENESS=10

# The directory where pid files are stored. /tmp by default.
# export HBASE_PID_DIR=/var/hadoop/pids

# Seconds to sleep between slave commands.  Unset by default.  This
# can be useful in large clusters, where, e.g., slave rsyncs can
# otherwise arrive faster than the master can service them.
# export HBASE_SLAVE_SLEEP=0.1

# Tell HBase whether it should manage it's own instance of ZooKeeper or not.
# export HBASE_MANAGES_ZK=true

# The default log rolling policy is RFA, where the log file is rolled as per the size defined for the
# RFA appender. Please refer to the log4j2.properties file to see more details on this appender.
# In case one needs to do log rolling on a date change, one should set the environment property
# HBASE_ROOT_LOGGER to "<DESIRED_LOG LEVEL>,DRFA".
# For example:
# export HBASE_ROOT_LOGGER=INFO,DRFA
# The reason for changing default to RFA is to avoid the boundary case of filling out disk space as
# DRFA doesn't put any cap on the log size. Please refer to HBase-5655 for more context.

# Tell HBase whether it should include Hadoop's lib when start up,
# the default value is false,means that includes Hadoop's lib.
# export HBASE_DISABLE_HADOOP_CLASSPATH_LOOKUP="true"

# Override text processing tools for use by these launch scripts.
# export GREP="${GREP-grep}"
# export SED="${SED-sed}"

#
## OpenTelemetry Tracing
#
# HBase is instrumented for tracing using OpenTelemetry. None of the other OpenTelemetry signals
# are supported at this time. Configuring tracing involves setting several configuration points,
# via environment variable or system property. This configuration prefers setting environment
# variables whenever possible because they are picked up by all processes launched by `bin/hbase`.
# Use system properties when you launch multiple processes from the same configuration directory --
# when you need to specify different configuration values for different hbase processes that are
# launched using the same HBase configuration (i.e., a single-host pseudo-distributed cluster or
# launching the `bin/hbase shell` from a host that is also running an instance of the master). See
# https://github.com/open-telemetry/opentelemetry-java/tree/v1.15.0/sdk-extensions/autoconfigure
# for an inventory of configuration points and detailed explanations of each of them.
#
# Note also that as of this writing, the javaagent logs to stderr and is not configured along with
# the rest of HBase's logging configuration.
#
# `HBASE_OTEL_TRACING_ENABLED`, required. Enable attaching the opentelemetry javaagent to the
# process via support provided by `bin/hbase`. When this value us `false`, the agent is not added
# to the process launch arguments and all further OpenTelemetry configuration is ignored.
#export HBASE_OTEL_TRACING_ENABLED=true
#
# `OPENTELEMETRY_JAVAAGENT_PATH`, optional. Override the javaagent provided by HBase in `lib/trace`
# with an alternate. Use when you need to upgrade the agent version or swap out the official one
# for an alternative implementation.
#export OPENTELEMETRY_JAVAAGENT_PATH=""
#
# `OTEL_FOO_EXPORTER`, required. Specify an Exporter implementation per signal type. HBase only
# makes explicit use of the traces signal at this time, so the important one is
# `OTEL_TRACES_EXPORTER`. Specify its value based on the exporter required for your tracing
# environment. The other two should be uncommented and specified as `none`, otherwise the agent
# may report errors while attempting to export these other signals to an unconfigured destination.
# https://github.com/open-telemetry/opentelemetry-java/tree/v1.15.0/sdk-extensions/autoconfigure#exporters
#export OTEL_TRACES_EXPORTER=""
#export OTEL_METRICS_EXPORTER="none"
#export OTEL_LOGS_EXPORTER="none"
#
# `OTEL_SERVICE_NAME`, required. Specify "resource attributes", and specifically the `service.name`,
# as a unique value for each HBase process. OpenTelemetry allows for specifying this value in one
# of two ways, via environment variables with the `OTEL_` prefix, or via system properties with the
# `otel.` prefix. Which you use with HBase is decided based on whether this configuration file is
# read by a single process or shared by multiple HBase processes. For the default standalone mode
# or an environment where all processes share the same configuration file, use the `otel` system
# properties by uncommenting all of the `HBASE_FOO_OPTS` exports below. When this configuration file
# is being consumed by only a single process -- for example, from a systemd configuration or in a
# container template -- replace use of `HBASE_FOO_OPTS` with the standard `OTEL_SERVICE_NAME` and/or
# `OTEL_RESOURCE_ATTRIBUTES` environment variables. For further details, see
# https://github.com/open-telemetry/opentelemetry-java/tree/v1.15.0/sdk-extensions/autoconfigure#opentelemetry-resource
#export HBASE_CANARY_OPTS="${HBASE_CANARY_OPTS} -Dotel.resource.attributes=service.name=hbase-canary"
#export HBASE_HBCK_OPTS="${HBASE_HBCK_OPTS} -Dotel.resource.attributes=service.name=hbase-hbck"
#export HBASE_HBTOP_OPTS="${HBASE_HBTOP_OPTS} -Dotel.resource.attributes=service.name=hbase-hbtop"
#export HBASE_JSHELL_OPTS="${HBASE_JSHELL_OPTS} -Dotel.resource.attributes=service.name=hbase-jshell"
#export HBASE_LTT_OPTS="${HBASE_LTT_OPTS} -Dotel.resource.attributes=service.name=hbase-loadtesttool"
#export HBASE_MASTER_OPTS="${HBASE_MASTER_OPTS} -Dotel.resource.attributes=service.name=hbase-master"
#export HBASE_PE_OPTS="${HBASE_PE_OPTS} -Dotel.resource.attributes=service.name=hbase-performanceevaluation"
#export HBASE_REGIONSERVER_OPTS="${HBASE_REGIONSERVER_OPTS} -Dotel.resource.attributes=service.name=hbase-regionserver"
#export HBASE_REST_OPTS="${HBASE_REST_OPTS} -Dotel.resource.attributes=service.name=hbase-rest"
#export HBASE_SHELL_OPTS="${HBASE_SHELL_OPTS} -Dotel.resource.attributes=service.name=hbase-shell"
#export HBASE_THRIFT_OPTS="${HBASE_THRIFT_OPTS} -Dotel.resource.attributes=service.name=hbase-thrift"
#export HBASE_ZOOKEEPER_OPTS="${HBASE_ZOOKEEPER_OPTS} -Dotel.resource.attributes=service.name=hbase-zookeeper"

#
# JDK11+ JShell
#
# Additional arguments passed to jshell invocation
# export HBASE_JSHELL_ARGS="--startup DEFAULT --startup PRINTING --startup hbase_startup.jsh"


text:
#ifndef __LIBRETRO_SDK_HASH_H
#define __LIBRETRO_SDK_HASH_H

#include <stdint.h>
#include <stddef.h>

#include <compat/msvc.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <retro_inline.h>

#include <retro_common_api.h>

RETRO_BEGIN_DECLS

/**
 * sha256_hash:
 * @out               : Output.
 * @in                : Input.
 * @size              : Size of @out.
 *
 * Hashes SHA256 and outputs a human readable string.
 **/
void sha256_hash(char *out, const uint8_t *in, size_t size);

int sha1_calculate(const char *path, char *result);

struct sha1_context
{
   unsigned Message_Digest[5]; /* Message Digest (output)          */

   unsigned Length_Low;        /* Message length in bits           */
   unsigned Length_High;       /* Message length in bits           */

   unsigned char Message_Block[64]; /* 512-bit message blocks      */
   int Message_Block_Index;    /* Index into message block array   */

   int Computed;               /* Is the digest computed?          */
   int Corrupted;              /* Is the message digest corruped?  */
};

void SHA1Reset(struct sha1_context *context);
int SHA1Result(struct sha1_context *context);
void SHA1Input(struct sha1_context *context,
      const unsigned char *message_array,
      unsigned length);

uint32_t djb2_calculate(const char *str);

/* Any 32-bit or wider unsigned integer data type will do */
typedef unsigned int MD5_u32plus;

typedef struct {
	MD5_u32plus lo, hi;
	MD5_u32plus a, b, c, d;
	unsigned char buffer[64];
	MD5_u32plus block[16];
} MD5_CTX;

/*
 * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
 * MD5 Message-Digest Algorithm (RFC 1321).
 *
 * Homepage:
 * http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5
 *
 * Author:
 * Alexander Peslyak, better known as Solar Designer <solar at openwall.com>
 *
 * This software was written by Alexander Peslyak in 2001.  No copyright is
 * claimed, and the software is hereby placed in the public domain.
 * In case this attempt to disclaim copyright and place the software in the
 * public domain is deemed null and void, then the software is
 * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
 * general public under the following terms:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted.
 *
 * There's ABSOLUTELY NO WARRANTY, express or implied.
 *
 * See md5.c for more information.
 */

void MD5_Init(MD5_CTX *ctx);
void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size);
void MD5_Final(unsigned char *result, MD5_CTX *ctx);

RETRO_END_DECLS

#endif


text:
package org.apache.mahout.classifier.naivebayes.training;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.mahout.common.MahoutTestCase;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.VectorWritable;
import org.apache.mahout.math.map.OpenObjectIntHashMap;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;

public class IndexInstancesMapperTest extends MahoutTestCase {

  private Mapper.Context ctx;
  private OpenObjectIntHashMap<String> labelIndex;
  private VectorWritable instance;

  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();

    ctx = EasyMock.createMock(Mapper.Context.class);
    instance = new VectorWritable(new DenseVector(new double[] { 1, 0, 1, 1, 0 }));

    labelIndex = new OpenObjectIntHashMap<String>();
    labelIndex.put("bird", 0);
    labelIndex.put("cat", 1);
  }

  @Test
  public void index() throws Exception {

    ctx.write(new IntWritable(0), instance);

    EasyMock.replay(ctx);

    IndexInstancesMapper indexInstances = new IndexInstancesMapper();
    setField(indexInstances, "labelIndex", labelIndex);

    indexInstances.map(new Text("/bird/"), instance, ctx);

    EasyMock.verify(ctx);
  }

  @Test
  public void skip() throws Exception {

    Counter skippedInstances = EasyMock.createMock(Counter.class);

    EasyMock.expect(ctx.getCounter(IndexInstancesMapper.Counter.SKIPPED_INSTANCES)).andReturn(skippedInstances);
    skippedInstances.increment(1);

    EasyMock.replay(ctx, skippedInstances);

    IndexInstancesMapper indexInstances = new IndexInstancesMapper();
    setField(indexInstances, "labelIndex", labelIndex);

    indexInstances.map(new Text("/fish/"), instance, ctx);

    EasyMock.verify(ctx, skippedInstances);
  }

}


text:
Need Help

        <form method="post" action="/contact" id="contactForm">

                <input type="text" name="name" class="form-control" placeholder="Name">

                <input type="tel" name="mobile" class="form-control" placeholder="Mobile">

                <input type="email" name="email" class="form-control" placeholder="E-mail">

                <textarea class="form-control" name="message" placeholder="Message" style="overflow: hidden; word-wrap: break-word; height: 68px;"></textarea>

            <button type="reset" id="contactFormClear" class="btn hidden-lg hidden-sm hidden-xs hidden-md">Clear</button>
			<button type="submit" class="btn-secondary pull-right">Post Message</button>
        </form>


text:
require "fileutils"

require 'puppet/util/execution'

Puppet::Type.type(:ruby).provide(:rubybuild) do
  include Puppet::Util::Execution

  def self.rubylist
    @rubylist ||= Dir["/opt/rubies/*"].map do |ruby|
      if File.directory?(ruby) && File.executable?("#{ruby}/bin/ruby")
        File.basename(ruby)
      end
    end.compact
  end

  def self.instances
    rubylist.map do |ruby|
      new({
        :name     => ruby,
        :version  => ruby,
        :ensure   => :present,
        :provider => "rubybuild",
      })
    end
  end

  def query
    if self.class.rubylist.member?(version)
      { :ensure => :present, :name => version, :version => version}
    else
      { :ensure => :absent,  :name => version, :version => version}
    end
  end

  def create
    destroy if File.directory?(prefix)

    if Facter.value(:offline) == "true"
      if File.exist?("#{cache_path}/ruby-#{version}.tar.gz")
        build_ruby
      else
        raise Puppet::Error, "Can't install ruby because we're offline and the tarball isn't cached"
      end
    else
      build_ruby
    end
  rescue => e
    raise Puppet::Error, "install failed with an error: #{e.message} #{e.backtrace}"
  end

  def destroy
    FileUtils.rm_rf prefix
  end

private

  def build_ruby
    execute "#{ruby_build} #{version} #{prefix}", command_options.merge(:failonfail => true)
  end

  def tmp
    "/tmp/ruby-#{version}.tar.bz2"
  end

  # Keep in sync with same-named function in:
  # https://github.com/boxen/our-boxen/blob/master/script/sync
  def s3_cellar
    homebrew_cellar = "#{Facter.value(:homebrew_root)}/Cellar"
    case homebrew_cellar
    when "/Cellar", "/opt/boxen/homebrew/Cellar" then ""
    when "/usr/local/Cellar" then "default/"
    else "#{Base64.strict_encode64(homebrew_cellar)}/"
    end
  end

  def os_release
    case Facter.value(:operatingsystem)
    when "Darwin"
      Facter.value(:macosx_productversion_major)
    when "Debian", "Ubuntu"
      Facter.value(:lsbdistcodename)
    else
      Facter.value(:operatingsystem)
    end
  end

  def ruby_build
    @resource[:ruby_build]
  end

  def command_options
    {
      :combine            => true,
      :custom_environment => environment,
      :uid                => @resource[:user],
      :failonfail         => true,
    }
  end

  def environment
    return @environment if defined?(@environment)

    @environment = Hash.new

    @environment["HOME"] = prefix
    @environment["BUNDLE_BIN_PATH"] = ""
    @environment["RUBY_BUILD_CACHE_PATH"] = cache_path
    @environment["GEM_HOME"] = nil
    @environment["GEM_PATH"] = nil
    @environment["BUNDLE_GEMFILE"] = nil
    @environment["BUNDLE_BIN_PATH"] = nil
    @environment["RUBYOPT"] = nil
    @environment["RUBYLIB"] = nil

    @environment.merge!(@resource[:environment])
  end

  def cache_path
    @cache_path ||= if Facter.value(:boxen_home)
      "#{Facter.value(:boxen_home)}/cache/rubies"
    else
      "/tmp/rubies"
    end
  end

  def version
    @resource[:version]
  end

  def prefix
    if Facter.value(:boxen_home)
      "#{Facter.value(:boxen_home)}/rbenv"
    else
      "/opt/rubies"
    end
  end
end


text:
using namespace IECore;

PrimitiveVariable::PrimitiveVariable()
	: interpolation( Invalid ), data( 0 )
{
}

PrimitiveVariable::PrimitiveVariable( Interpolation i, DataPtr d )
	: interpolation( i ), data( d )
{
}

PrimitiveVariable::PrimitiveVariable( const PrimitiveVariable &other )
{
	interpolation = other.interpolation;
	data = other.data;
}

PrimitiveVariable::PrimitiveVariable( const PrimitiveVariable &other, bool deepCopy )
{
	interpolation = other.interpolation;
	if( deepCopy )
	{
		data = other.data ? other.data->copy() : 0;
	}
	else
	{
		data = other.data;
	}
}

bool PrimitiveVariable::operator==( const PrimitiveVariable &other ) const
{
	if( interpolation != other.interpolation )
	{
		return false;
	}
	if( data && other.data )
	{
		return data->isEqualTo( other.data.get() );
	}
	return !data && !other.data;
}

bool PrimitiveVariable::operator!=( const PrimitiveVariable &other ) const
{
	return !(*this == other);
}


text:
require 'json'
require 'swagger/blocks/version'

module Swagger
  module Blocks

    # Some custom error classes.
    class Error < Exception; end
    class DeclarationError < Error; end
    class NotFoundError < Error; end
    class NotSupportedError < Error; end

    # Inject the swagger_root, swagger_api_root, and swagger_model class methods.
    def self.included(base)
      base.extend(ClassMethods)
    end

    def self.build_root_json(swaggered_classes)
      data = Swagger::Blocks::InternalHelpers.parse_swaggered_classes(swaggered_classes)

      if data[:root_node].is_swagger_2_0?
        data[:root_node].key(:paths, data[:path_nodes]) # Required, so no empty check.
        if data[:schema_nodes] && !data[:schema_nodes].empty?
          data[:root_node].key(:definitions, data[:schema_nodes])
        end
      end

      data[:root_node].as_json
    end

    def self.build_api_json(resource_name, swaggered_classes)
      data = Swagger::Blocks::InternalHelpers.parse_swaggered_classes(swaggered_classes)
      if !data[:root_node].is_swagger_1_2?
        raise NotSupportedError.new(
          'build_api_json only supports Swagger 1.2, you do not need to call this method ' +
          'for Swagger >= 2.0 definitions.'
        )
      end

      api_node = data[:api_node_map][resource_name.to_sym]
      raise Swagger::Blocks::NotFoundError.new(
        "Not found: swagger_api_root named #{resource_name}") if !api_node

      # Aggregate all model definitions into a new ModelsNode tree and add it to the JSON.
      temp_models_node = Swagger::Blocks::ModelsNode.call(name: 'models') { }
      data[:models_nodes].each { |models_node| temp_models_node.merge!(models_node) }
      result = api_node.as_json
      result.merge!(temp_models_node.as_json) if temp_models_node
      result
    end

    module InternalHelpers
      # Return [root_node, api_node_map] from all of the given swaggered_classes.
      def self.parse_swaggered_classes(swaggered_classes)
        root_nodes = []

        api_node_map = {}
        models_nodes = []

        path_node_map = {}
        schema_node_map = {}
        swaggered_classes.each do |swaggered_class|
          next unless swaggered_class.respond_to?(:_swagger_nodes, true)
          swagger_nodes = swaggered_class.send(:_swagger_nodes)
          root_node = swagger_nodes[:root_node]
          root_nodes << root_node if root_node

          # 2.0
          if swagger_nodes[:path_node_map]
            path_node_map.merge!(swagger_nodes[:path_node_map])
          end
          if swagger_nodes[:schema_node_map]
            schema_node_map.merge!(swagger_nodes[:schema_node_map])
          end

          # 1.2
          if swagger_nodes[:api_node_map]
            api_node_map.merge!(swagger_nodes[:api_node_map])
          end
          if swagger_nodes[:models_node]
            models_nodes << swagger_nodes[:models_node]
          end
        end
        data = {root_node: self.limit_root_node(root_nodes)}
        if data[:root_node].is_swagger_2_0?
          data[:path_nodes] = path_node_map
          data[:schema_nodes] = schema_node_map
        else
          data[:api_node_map] = api_node_map
          data[:models_nodes] = models_nodes
        end
        data
      end

      # Make sure there is exactly one root_node and return it.
      # TODO should this merge the contents of the root nodes instead?
      def self.limit_root_node(root_nodes)
        if root_nodes.length == 0
          raise Swagger::Blocks::DeclarationError.new(
            'swagger_root must be declared')
        elsif root_nodes.length > 1
          raise Swagger::Blocks::DeclarationError.new(
            'Only one swagger_root declaration is allowed.')
        end
        root_nodes.first
      end
    end

    module ClassMethods
      private

      # v1.2: Defines a Swagger Resource Listing.
      # v1.2: http://goo.gl/PvwUXj#51-resource-listing
      # v2.0: Defines a Swagger Object
      # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object
      def swagger_root(&block)
        @swagger_root_node ||= Swagger::Blocks::RootNode.call(&block)
      end

      # v1.2: Defines a Swagger API Declaration.
      # v1.2: http://goo.gl/PvwUXj#52-api-declaration
      # v1.2:
      # v1.2: @param resource_name [Symbol] An identifier for this API. All swagger_api_root declarations
      # v1.2:   with the same resource_name will be  into a single API root node.
      def swagger_api_root(resource_name, &block)
        resource_name = resource_name.to_sym

        # Map of path names to ApiDeclarationNodes.
        @swagger_api_root_node_map ||= {}

        # Grab a previously declared node if it exists, otherwise create a new ApiDeclarationNode.
        # This merges all declarations of swagger_api_root with the same resource_name key.
        api_node = @swagger_api_root_node_map[resource_name]
        if api_node
          # Merge this swagger_api_root declaration into the previous one by the same resource_name.
          api_node.instance_eval(&block)
        else
          # First time we've seen this `swagger_api_root :resource_name`.
          api_node = Swagger::Blocks::ApiDeclarationNode.call(version: '1.2', &block)
        end

        # Add it into the resource_name to node map (may harmlessly overwrite the same object).
        @swagger_api_root_node_map[resource_name] = api_node
      end

      # v2.0: Defines a Swagger Path Item object
      # https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#path-item-object
      def swagger_path(path, &block)
        path = path.to_sym

        # TODO enforce that path name begins with a '/'
        #   (or x- , but need to research Vendor Extensions first)

        @swagger_path_node_map ||= {}

        path_node = @swagger_path_node_map[path]
        if path_node
          # Merge this path declaration into the previous one
          path_node.instance_eval(&block)
        else
          # First time we've seen this path
          @swagger_path_node_map[path] = Swagger::Blocks::PathNode.call(version: '2.0', &block)
        end
      end

      # v1.2: Defines a Swagger Model.
      # v1.2: http://goo.gl/PvwUXj#526-models-object
      def swagger_model(name, &block)
        @swagger_models_node ||= Swagger::Blocks::ModelsNode.new
        @swagger_models_node.version = '1.2'
        @swagger_models_node.model(name, &block)
      end

      # v2.0: Defines a Swagger Definition Schema,
      # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#definitionsObject and
      # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#schema-object
      def swagger_schema(name, &block)
        @swagger_schema_node_map ||= {}

        schema_node = @swagger_schema_node_map[name]
        if schema_node
          # Merge this schema_node declaration into the previous one
          schema_node.instance_eval(&block)
        else
          # First time we've seen this schema_node
          @swagger_schema_node_map[name] = Swagger::Blocks::SchemaNode.call(version: '2.0', &block)
        end
      end

      def _swagger_nodes
        # Avoid initialization warnings.
        @swagger_root_node ||= nil
        @swagger_path_node_map ||= {}
        @swagger_schema_node_map ||= nil
        @swagger_api_root_node_map ||= {}
        @swagger_models_node ||= nil

        data = {root_node: @swagger_root_node}
        data[:path_node_map] = @swagger_path_node_map
        data[:schema_node_map] = @swagger_schema_node_map
        data[:api_node_map] = @swagger_api_root_node_map
        data[:models_node] = @swagger_models_node
        data
      end

    end

    # -----

    # Base node for representing every object in the Swagger DSL.
    class Node
      attr_accessor :name
      attr_writer :version

      def self.call(options = {}, &block)
        # Create a new instance and evaluate the block into it.
        instance = new
        instance.name = options[:name] if options[:name]
        instance.version = options[:version]
        instance.instance_eval(&block)
        instance
      end

      def as_json
        result = {}

        self.data.each do |key, value|
          if value.is_a?(Node)
            result[key] = value.as_json
          elsif value.is_a?(Array)
            result[key] = []
            value.each { |v| result[key] << (v.respond_to?(:as_json) ? v.as_json : v) }
          elsif is_swagger_2_0? && value.is_a?(Hash)
            result[key] = {}
            value.each_pair {|k, v| result[key][k] = (v.respond_to?(:as_json) ? v.as_json : v) }
          elsif is_swagger_2_0? && key.to_s.eql?('$ref') && (value.to_s !~ %r{^#/})
            result[key] = "#/definitions/#{value}"
          else
            result[key] = value
          end
        end
        return result if !name
        # If 'name' is given to this node, wrap the data with a root element with the given name.
        {name => result}
      end

      def data
        @data ||= {}
      end

      def key(key, value)
        self.data[key] = value
      end

      def version
        return @version if instance_variable_defined?('@version') && @version
        if data.has_key?(:swagger) && data[:swagger] == '2.0'
          '2.0'
        elsif data.has_key?(:swaggerVersion) && data[:swaggerVersion] == '1.2'
          '1.2'
        else
          raise DeclarationError.new("You must specify swaggerVersion '1.2' or swagger '2.0'")
        end
      end

      def is_swagger_1_2?
        version == '1.2'
      end

      def is_swagger_2_0?
        version == '2.0'
      end
    end

    class RootNode < Node
      def initialize(*args)
        # An internal list of the user-defined names that uniquely identify each API tree.
        # Only used in Swagger 1.2, but when initializing a root node we haven't seen the
        # swaggerVersion/swagger key yet
        @api_paths = []
        super
      end

      def has_api_path?(api_path)
        raise NotSupportedError unless is_swagger_1_2?

        api_paths = self.data[:apis].map { |x| x.data[:path] }
        api_paths.include?(api_path)
      end

      def authorization(name, &block)
        raise NotSupportedError unless is_swagger_1_2?

        self.data[:authorizations] ||= Swagger::Blocks::ResourceListingAuthorizationsNode.new
        self.data[:authorizations].version = version
        self.data[:authorizations].authorization(name, &block)
      end

      def info(&block)
        self.data[:info] = Swagger::Blocks::InfoNode.call(version: version, &block)
      end

      def api(&block)
        raise NotSupportedError unless is_swagger_1_2?

        self.data[:apis] ||= []
        self.data[:apis] << Swagger::Blocks::ResourceNode.call(version: version, &block)
      end

      def parameter(param, &block)
        raise NotSupportedError unless is_swagger_2_0?

        # TODO validate 'param' is as per spec
        self.data[:parameters] ||= {}
        self.data[:parameters][param] = Swagger::Blocks::ParameterNode.call(version: version, &block)
      end

      def response(resp, &block)
        raise NotSupportedError unless is_swagger_2_0?

        # TODO validate 'resp' is as per spec
        self.data[:responses] ||= {}
        self.data[:responses][resp] = Swagger::Blocks::ResponseNode.call(version: version, &block)
      end

      def security_definition(name, &block)
        raise NotSupportedError unless is_swagger_2_0?

        self.data[:securityDefinitions] ||= {}
        self.data[:securityDefinitions][name] = Swagger::Blocks::SecuritySchemeNode.call(version: version, &block)
      end

      def security(&block)
        raise NotSupportedError unless is_swagger_2_0?

        self.data[:security] ||= []
        self.data[:security] << Swagger::Blocks::SecurityRequirementNode.call(version: version, &block)
      end

      def tag(&block)
        raise NotSupportedError unless is_swagger_2_0?

        self.data[:tags] ||= []
        self.data[:tags] << Swagger::Blocks::TagNode.call(version: version, &block)
      end

      # Use 'tag' instead.
      # @deprecated
      alias_method :tags, :tag
    end

    # v1.2: http://goo.gl/PvwUXj#512-resource-object
    class ResourceNode < Node; end

    # v1.2: NOTE: in the spec this is different than API Declaration authorizations.
    # v1.2: http://goo.gl/PvwUXj#514-authorizations-object
    class ResourceListingAuthorizationsNode < Node
      def authorization(name, &block)
        self.data[name] = Swagger::Blocks::ResourceListingAuthorizationNode.call(version: version, &block)
      end
    end

    # v1.2: NOTE: in the spec this is different than API Declaration authorization.
    # v1.2: http://goo.gl/PvwUXj#515-authorization-object
    class ResourceListingAuthorizationNode < Node
      GRANT_TYPES = [:implicit, :authorization_code].freeze

      def scope(&block)
        self.data[:scopes] ||= []
        self.data[:scopes] << Swagger::Blocks::ScopeNode.call(version: version, &block)
      end

      def grant_type(name, &block)
        raise ArgumentError.new("#{name} not in #{GRANT_TYPES}") if !GRANT_TYPES.include?(name)
        self.data[:grantTypes] ||= Swagger::Blocks::GrantTypesNode.new
        self.data[:grantTypes].version = version
        self.data[:grantTypes].implicit(&block) if name == :implicit
        self.data[:grantTypes].authorization_code(&block) if name == :authorization_code
      end
    end

    # v1.2: http://goo.gl/PvwUXj#513-info-object
    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#infoObject
    class InfoNode < Node
      def contact(&block)
        raise NotSupportedError unless is_swagger_2_0?

        self.data[:contact] = Swagger::Blocks::ContactNode.call(version: version, &block)
      end

      def license(&block)
        raise NotSupportedError unless is_swagger_2_0?

        self.data[:license] = Swagger::Blocks::LicenseNode.call(version: version, &block)
      end
    end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#contact-object
    class ContactNode < Node; end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#license-object
    class LicenseNode < Node; end

    # v1.2: http://goo.gl/PvwUXj#516-scope-object
    class ScopeNode < Node; end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#scopes-object
    class ScopesNode < Node; end

    # v1.2: http://goo.gl/PvwUXj#517-grant-types-object
    class GrantTypesNode < Node
      def implicit(&block)
        self.data[:implicit] = Swagger::Blocks::ImplicitNode.call(version: version, &block)
      end

      def authorization_code(&block)
        self.data[:authorization_code] = Swagger::Blocks::AuthorizationCodeNode.call(version: version, &block)
      end
    end

    # v1.2: http://goo.gl/PvwUXj#518-implicit-object
    class ImplicitNode < Node
      def login_endpoint(&block)
        self.data[:loginEndpoint] = Swagger::Blocks::LoginEndpointNode.call(version: version, &block)
      end
    end

    # v1.2: http://goo.gl/PvwUXj#5110-login-endpoint-object
    class LoginEndpointNode < Node; end

    # v1.2: http://goo.gl/PvwUXj#519-authorization-code-object
    class AuthorizationCodeNode < Node
      def token_request_endpoint(&block)
        self.data[:tokenRequestEndpoint] = Swagger::Blocks::TokenRequestEndpointNode.call(version: version, &block)
      end

      def token_endpoint(&block)
        self.data[:tokenEndpoint] = Swagger::Blocks::TokenEndpointNode.call(version: version, &block)
      end
    end

    # v1.2: http://goo.gl/PvwUXj#5111-token-request-endpoint-object
    class TokenRequestEndpointNode < Node; end

    # v1.2: http://goo.gl/PvwUXj#5112-token-endpoint-object
    class TokenEndpointNode < Node; end

    # -----
    # v1.2: Nodes for API Declarations.
    # -----

    # v1.2: http://goo.gl/PvwUXj#52-api-declaration
    class ApiDeclarationNode < Node
      def api(&block)
        self.data[:apis] ||= []

        # Important: to conform with the Swagger spec, merge with any previous API declarations
        # that have the same :path key. This ensures that operations affecting the same resource
        # are all in the same operations node.
        #
        # http://goo.gl/PvwUXj#522-api-object
        # - The API Object describes one or more operations on a single path. In the apis array,
        #   there MUST be only one API Object per path.
        temp_api_node = Swagger::Blocks::ApiNode.call(version: version, &block)
        api_node = self.data[:apis].select do |api|
          api.data[:path] == temp_api_node.data[:path]
        end[0]  # Embrace Ruby wtfs.

        if api_node
          # Merge this block with the previous ApiNode by the same path key.
          api_node.instance_eval(&block)
        else
          # First time we've seen an api block with the given path key.
          self.data[:apis] << temp_api_node
        end
      end
    end

    # v1.2: http://goo.gl/PvwUXj#522-api-object
    class ApiNode < Node
      def operation(&block)
        self.data[:operations] ||= []
        self.data[:operations] << Swagger::Blocks::OperationNode.call(version: version, &block)
      end
    end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#path-item-object
    class PathNode < Node
      OPERATION_TYPES = [:get, :put, :post, :delete, :options, :head, :patch].freeze

      # TODO support ^x- Vendor Extensions
      def operation(op, &block)
        op = op.to_sym
        raise ArgumentError.new("#{name} not in #{OPERATION_TYPES}") if !OPERATION_TYPES.include?(op)
        self.data[op] = Swagger::Blocks::OperationNode.call(version: version, &block)
      end
    end

    # v1.2: http://goo.gl/PvwUXj#523-operation-object
    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operation-object
    class OperationNode < Node

      def parameter(&block)
        self.data[:parameters] ||= []
        self.data[:parameters] << Swagger::Blocks::ParameterNode.call(version: version, &block)
      end

      def response_message(&block)
        raise NotSupportedError unless is_swagger_1_2?

        self.data[:responseMessages] ||= []
        self.data[:responseMessages] << Swagger::Blocks::Node.call(version: version, &block)
      end

      def authorization(name, &block)
        raise NotSupportedError unless is_swagger_1_2?

        self.data[:authorizations] ||= Swagger::Blocks::ApiAuthorizationsNode.new
        self.data[:authorizations].version = version
        self.data[:authorizations].authorization(name, &block)
      end

      def items(&block)
        raise NotSupportedError unless is_swagger_1_2?

        self.data[:items] = Swagger::Blocks::ItemsNode.call(version: version, &block)
      end

      def response(resp, &block)
        raise NotSupportedError unless is_swagger_2_0?

        # TODO validate 'resp' is as per spec
        self.data[:responses] ||= {}
        self.data[:responses][resp] = Swagger::Blocks::ResponseNode.call(version: version, &block)
      end

      def externalDocs(&block)
        raise NotSupportedError unless is_swagger_2_0?

        self.data[:externalDocs] = Swagger::Blocks::ExternalDocsNode.call(version: version, &block)
      end

      def security(&block)
        raise NotSupportedError unless is_swagger_2_0?

        self.data[:security] ||= []
        self.data[:security] << Swagger::Blocks::SecurityRequirementNode.call(version: version, &block)
      end
    end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#externalDocumentationObject
    class ExternalDocsNode < Node; end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#securityRequirementObject
    class SecurityRequirementNode < Node; end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#security-scheme-object
    class SecuritySchemeNode < Node
      # TODO support ^x- Vendor Extensions

      def scopes(&block)
        self.data[:scopes] = Swagger::Blocks::ScopesNode.call(version: version, &block)
      end
    end

    # v1.2: NOTE: in the spec this is different than Resource Listing's authorizations.
    # v1.2: http://goo.gl/PvwUXj#514-authorizations-object
    class ApiAuthorizationsNode < Node
      def authorization(name, &block)
        self.data[name] ||= Swagger::Blocks::ApiAuthorizationNode.call(version: version, &block)
      end
    end

    # v1.2: NOTE: in the spec this is different than Resource Listing's authorization.
    # v1.2: http://goo.gl/PvwUXj#515-authorization-object
    class ApiAuthorizationNode < Node
      def as_json
        # Special case: the API Authorization object is weirdly the only array of hashes.
        # Override the default hash behavior and return an array.
        self.data[:_scopes] ||= []
        self.data[:_scopes].map { |s| s.as_json }
      end

      def scope(&block)
        self.data[:_scopes] ||= []
        self.data[:_scopes] << Swagger::Blocks::ApiAuthorizationScopeNode.call(version: version, &block)
      end
    end

    # v1.2: NOTE: in the spec this is different than Resource Listing's scope object.
    # v1.2: http://goo.gl/PvwUXj#5211-scope-object
    class ApiAuthorizationScopeNode < Node; end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#responseObject
    class ResponseNode < Node
      def schema(&block)
        self.data[:schema] = Swagger::Blocks::SchemaNode.call(version: version, &block)
      end

      def header(head, &block)
        # TODO validate 'head' is as per spec
        self.data[:headers] ||= {}
        self.data[:headers][head] = Swagger::Blocks::HeaderNode.call(version: version, &block)
      end

      def example(exam, &block)
        # TODO validate 'exam' is as per spec
        self.data[:examples] ||= {}
        self.data[:examples][exam] = Swagger::Blocks::ExampleNode.call(version: version, &block)
      end
    end

    class AllOfNode < Node
      def as_json
        result = []

        self.data.each do |value|
          if value.is_a?(Node)
            result << value.as_json
          elsif value.is_a?(Array)
            r = []
            value.each { |v| r << (v.respond_to?(:as_json) ? v.as_json : v) }
            result << r
          elsif is_swagger_2_0? && value.is_a?(Hash)
            r = {}
            value.each_pair {|k, v| r[k] = (v.respond_to?(:as_json) ? v.as_json : v) }
            result << r
          else
            result = value
          end
        end
        return result if !name
        # If 'name' is given to this node, wrap the data with a root element with the given name.
        {name => result}
      end

      def data
        @data ||= []
      end

      def key(key, value)
        raise NotSupportedError
      end

      def schema(&block)
        data << Swagger::Blocks::SchemaNode.call(version: version, &block)
      end
    end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#schema-object
    class SchemaNode < Node
      def items(&block)
        self.data[:items] = Swagger::Blocks::ItemsNode.call(version: version, &block)
      end

      def allOf(&block)
        self.data[:allOf] = Swagger::Blocks::AllOfNode.call(version: version, &block)
      end

      def property(name, &block)
        self.data[:properties] ||= Swagger::Blocks::PropertiesNode.new
        self.data[:properties].version = version
        self.data[:properties].property(name, &block)
      end

      def xml(&block)
        self.data[:xml] = Swagger::Blocks::XmlNode.call(version: version, &block)
      end

      def externalDocs(&block)
        self.data[:externalDocs] = Swagger::Blocks::ExternalDocsNode.call(version: version, &block)
      end
    end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#headerObject
    class HeaderNode < Node
      def items(&block)
        self.data[:items] = Swagger::Blocks::ItemsNode.call(version: version, &block)
      end
    end

    # v2.0:
    class XmlNode < Node; end

    # v2.0:
    class ExampleNode < Node; end

    # v1.2:
    # v2.0:
    class ItemsNode < Node; end

    # v1.2: http://goo.gl/PvwUXj#524-parameter-object
    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameter-object
    class ParameterNode < Node
      def schema(&block)
        raise NotSupportedError unless is_swagger_2_0?

        self.data[:schema] = Swagger::Blocks::SchemaNode.call(version: version, &block)
      end

      def items(&block)
        raise NotSupportedError unless is_swagger_2_0?

        self.data[:items] = Swagger::Blocks::ItemsNode.call(version: version, &block)
      end
    end

    # v2.0: https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#tag-object
    class TagNode < Node

      # TODO support ^x- Vendor Extensions

      def externalDocs(&block)
        self.data[:externalDocs] = Swagger::Blocks::ExternalDocsNode.call(version: version, &block)
      end
    end

    # -----
    # v1.2: Nodes for Models.
    # -----

    # v1.2: http://goo.gl/PvwUXj#526-models-object
    class ModelsNode < Node
      def merge!(other_models_node)
        self.data.merge!(other_models_node.data)
      end

      def model(name, &block)
        self.data[name] ||= Swagger::Blocks::ModelNode.call(version: version, &block)
      end
    end

    # v1.2: http://goo.gl/PvwUXj#527-model-object
    class ModelNode < Node
      def property(name, &block)
        self.data[:properties] ||= Swagger::Blocks::PropertiesNode.new
        self.data[:properties].version = version
        self.data[:properties].property(name, &block)
      end
    end

    # v1.2: http://goo.gl/PvwUXj#527-model-object
    class PropertiesNode < Node
      def property(name, &block)
        self.data[name] = Swagger::Blocks::PropertyNode.call(version: version, &block)
      end
    end

    # v1.2: http://goo.gl/PvwUXj#527-model-object
    class PropertyNode < Node
      def items(&block)
        self.data[:items] = Swagger::Blocks::ItemsNode.call(version: version, &block)
      end
    end
  end
end


text:
package servicekey

import (
	"github.com/cloudfoundry/cli/cf/api"
	"github.com/cloudfoundry/cli/cf/command_metadata"
	"github.com/cloudfoundry/cli/cf/configuration/core_config"
	"github.com/cloudfoundry/cli/cf/errors"
	"github.com/cloudfoundry/cli/cf/flag_helpers"
	"github.com/cloudfoundry/cli/cf/requirements"
	"github.com/cloudfoundry/cli/cf/terminal"
	"github.com/cloudfoundry/cli/json"
	"github.com/codegangsta/cli"

	. "github.com/cloudfoundry/cli/cf/i18n"
)

type CreateServiceKey struct {
	ui             terminal.UI
	config         core_config.Reader
	serviceRepo    api.ServiceRepository
	serviceKeyRepo api.ServiceKeyRepository
}

func NewCreateServiceKey(ui terminal.UI, config core_config.Reader, serviceRepo api.ServiceRepository, serviceKeyRepo api.ServiceKeyRepository) (cmd CreateServiceKey) {
	return CreateServiceKey{
		ui:             ui,
		config:         config,
		serviceRepo:    serviceRepo,
		serviceKeyRepo: serviceKeyRepo,
	}
}

func (cmd CreateServiceKey) Metadata() command_metadata.CommandMetadata {
	return command_metadata.CommandMetadata{
		Name:        "create-service-key",
		ShortName:   "csk",
		Description: T("Create key for a service instance"),
		Usage: T(`CF_NAME create-service-key SERVICE_INSTANCE SERVICE_KEY [-c PARAMETERS_AS_JSON]

  Optionally provide service-specific configuration parameters in a valid JSON object in-line.
  CF_NAME create-service-key SERVICE_INSTANCE SERVICE_KEY -c '{"name":"value","name":"value"}'

  Optionally provide a file containing service-specific configuration parameters in a valid JSON object. The path to the parameters file can be an absolute or relative path to a file.
  CF_NAME create-service-key SERVICE_INSTANCE SERVICE_KEY -c PATH_TO_FILE

   Example of valid JSON object:
   {
     "permissions": "read-only"
   }

EXAMPLE:
   CF_NAME create-service-key mydb mykey -c '{"permissions":"read-only"}'
   CF_NAME create-service-key mydb mykey -c ~/workspace/tmp/instance_config.json`),
		Flags: []cli.Flag{
			flag_helpers.NewStringFlag("c", T("Valid JSON object containing service-specific configuration parameters, provided either in-line or in a file. For a list of supported configuration parameters, see documentation for the particular service offering.")),
		},
	}
}

func (cmd CreateServiceKey) GetRequirements(requirementsFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {
	if len(c.Args()) != 2 {
		cmd.ui.FailWithUsage(c)
	}

	loginRequirement := requirementsFactory.NewLoginRequirement()
	serviceInstanceRequirement := requirementsFactory.NewServiceInstanceRequirement(c.Args()[0])
	targetSpaceRequirement := requirementsFactory.NewTargetedSpaceRequirement()

	reqs = []requirements.Requirement{loginRequirement, serviceInstanceRequirement, targetSpaceRequirement}

	return reqs, nil
}

func (cmd CreateServiceKey) Run(c *cli.Context) {
	serviceInstanceName := c.Args()[0]
	serviceKeyName := c.Args()[1]
	params := c.String("c")

	paramsMap, err := json.ParseJsonFromFileOrString(params)
	if err != nil {
		cmd.ui.Failed(T("Invalid configuration provided for -c flag. Please provide a valid JSON object or path to a file containing a valid JSON object."))
	}

	cmd.ui.Say(T("Creating service key {{.ServiceKeyName}} for service instance {{.ServiceInstanceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceInstanceName": terminal.EntityNameColor(serviceInstanceName),
			"ServiceKeyName":      terminal.EntityNameColor(serviceKeyName),
			"CurrentUser":         terminal.EntityNameColor(cmd.config.Username()),
		}))

	serviceInstance, err := cmd.serviceRepo.FindInstanceByName(serviceInstanceName)
	if err != nil {
		cmd.ui.Failed(err.Error())
		return
	}

	err = cmd.serviceKeyRepo.CreateServiceKey(serviceInstance.Guid, serviceKeyName, paramsMap)
	switch err.(type) {
	case nil:
		cmd.ui.Ok()
	case *errors.ModelAlreadyExistsError:
		cmd.ui.Ok()
		cmd.ui.Warn(err.Error())
	default:
		cmd.ui.Failed(err.Error())
	}
}