text:
class Screenfetch < Formula
  desc "Generate ASCII art with terminal, shell, and OS info"
  homepage "https://github.com/KittyKatt/screenFetch"
  url "https://github.com/KittyKatt/screenFetch/archive/v3.9.1.tar.gz"
  sha256 "aa97dcd2a8576ae18de6c16c19744aae1573a3da7541af4b98a91930a30a3178"
  license "GPL-3.0"
  head "https://github.com/KittyKatt/screenFetch.git"

  bottle :unneeded

  def install
    bin.install "screenfetch-dev" => "screenfetch"
    man1.install "screenfetch.1"
  end

  test do
    system "#{bin}/screenfetch"
  end
end

redpajama_set_name: RedPajamaGithub


text:
package adawg.minecraftbot;

import java.util.concurrent.atomic.AtomicBoolean;

import net.minecraft.client.Minecraft;
import net.minecraft.src.*;
import net.minecraft.util.Vec3;

import org.newdawn.slick.util.pathfinding.Mover; // empty tagging interface

import adawg.minecraftbot.pathfinding.MinecraftMap;
import adawg.minecraftbot.pathfinding.AStarPathFinder3D;
import adawg.minecraftbot.pathfinding.Path3D;

public class MinecraftPathFinder implements Mover {

	private AStarPathFinder3D pathFinder;
	private Minecraft mc;

	//These store the start/end positions of a path
	private RichVec3 start;
	private RichVec3 target;
	private RichVec3 lastStart;
	private RichVec3 lastTarget;

	//This stores a calculated path
	private Path3D path;

    public MinecraftPathFinder(int dimX, int dimY, int dimZ) {
    	this.mc = Minecraft.getMinecraft();
    	pathFinder = new AStarPathFinder3D(new MinecraftMap(), true, dimX, dimY, dimZ);
    }

    public Path3D getPath() {
    	return path;
    }

    public Path3D findPath(RichVec3 start, RichVec3 target, int maxSearchDistance, AtomicBoolean shouldStop) {
    	Path3D path = pathFinder.findPath(this, start, target, maxSearchDistance, shouldStop);

    	if (path == null) {
    		System.out.println("Couldn't calculate path from " + start.toStringFancy() + " to " + target.toStringFancy());
    	} else {
    		System.out.println("Path calculated.");
    	}
    	return path;
    }

    public void calculatePath(int maxSearchDistance) {
    	/*
    	if (sx < 0 || sy < 0 || sz < 0 || tx < 0 || ty < 0 || tz < 0) {
    		System.out.println("Error: Negative coordinate(s) passed to calculatePath()");
    		return;
    	}
    	*/
    	if (start == null || target == null) {
    		System.out.println("Either start or target is missing for calculatePath");
    		return;
    	}

    	path = pathFinder.findPath(this, start, target, maxSearchDistance, new AtomicBoolean(false));
    }

    public void deletePath() {
    	path = null;
    }

    public void resetNodeStorage(int dimX, int dimY, int dimZ, int xCenter, int yOffset, int zCenter) {
    	pathFinder.resetNodeStorage(dimX, dimY, dimZ, xCenter, yOffset, zCenter);
    }

    public void printStep(int i, Path3D path) {
    	if (i < path.getLength()) {
    		System.out.println("Path step " + i + ": " + path.getX(i) + ", " + path.getY(i) + ", " + path.getZ(i));
    	}
    }

    //Print the path, just to test.
    public void printPath(Path3D path) {
    	if (path == null) {
    		System.out.println("No path to print");
    		return;
    	}

    	for (int i = 0; i < path.getLength(); i++) {
    		printStep(i, path);
    	}
    }

    /**
     * Print the path stored in this MinecraftPathFinder object.  Obsolete.
     */
    public void printPath() {
    	printPath(this.path);
    }
}


text:
require "rails_helper"

describe Renalware::HD::PrescriptionLastAdministrationComponent, type: :component do
  it "renders the last time the presription was administered" do
    user = build_stubbed(:user)
    patient = build_stubbed(:patient, by: user)
    prescription = build_stubbed(:prescription, patient: patient, by: user)
    administration = build_stubbed(
      :hd_prescription_administration,
      prescription: prescription,
      patient_id: patient.id,
      administered_by: user,
      recorded_on: Date.parse("01-01-2020"),
      notes: "abc"
    )
    allow(Renalware::HD::PrescriptionLastAdministrationQuery)
      .to receive(:call).and_return(administration)

    render_inline(described_class.new(prescription: prescription))

    expect(page).to have_content("Last given on Wed 01 Jan 2020 by #{user}")
    expect(page).to have_content("Notes: abc")
  end

  context "when prescription is nil" do
    it "renders nothing" do
      component = described_class.new(prescription: nil)

      render_inline(component)

      expect(component.render?).to be(false)
      expect(rendered_component).to eq("")
    end
  end
end


text:
package simfunctions;

import java.sql.ResultSet;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import dbdriver.MySqlDB;
import utility.Config;

public class RunProbabilityAssignment {

	public static boolean debug_mode = true;
	public static int queryTokenLength = 2;
	public static boolean replaceSpaceWithSpecialCharacter = true;
	public static int qgramSize = 2;

	public static String generateSpecialCharacters(int qgSize){
		String str="";
		for(int i=0; i < qgSize-1; i++)	str += "#";
		return str;
	}

	public static void incrementCount(String qgram, HashMap<String, Double> tokenCount) {
		if (tokenCount.containsKey(qgram)) {
			tokenCount.put(qgram, tokenCount.get(qgram) + 1);
		} else {
			tokenCount.put(qgram, 1.0);
		}
	}

	// Tokenization function
	public static HashMap<String, Double> getTF(String str) {
		HashMap<String, Double> tokenTF = new HashMap<String, Double>();
		/*
		 * String[] tokens = str.split("\\s+"); for (int i = 0; i <
		 * tokens.length; i++) { incrementCount(tokens[i], tokenTF); }
		 */
		str = str.toLowerCase();
		if(replaceSpaceWithSpecialCharacter){
			str = str.replaceAll(" ", generateSpecialCharacters(qgramSize));
			str = generateSpecialCharacters(qgramSize) + str + generateSpecialCharacters(qgramSize);
		}
		for (int i = 0; i <= str.length() - qgramSize; i++) {
			String qgram = str.substring(i, i + qgramSize);
			incrementCount(qgram, tokenTF);
		}
		return tokenTF;
	}

	public static BitSet convertToBitSet1(Set<String> stringSet){
		BitSet output = new BitSet();
		for (String qgram : stringSet) {
			output.set( qgram.charAt(0));
		}
		return output;
	}

	public static BitSet convertToBitSet(Set<String> stringSet){
		BitSet output = new BitSet();
		for (String qgram : stringSet) {
			output.set((qgram.charAt(1) << 7) | qgram.charAt(0));
		}
		return output;
	}

	public static BitSet convertToBitSet3(Set<String> stringSet){
		BitSet output = new BitSet();
		for (String qgram : stringSet) {
			output.set((qgram.charAt(2) << 14) | (qgram.charAt(1) << 7) | qgram.charAt(0));
		}
		return output;
	}

	public static Set<String> convertToStringSet(BitSet bitset){
		Set<String> output = new HashSet<String>();
		int i = bitset.nextSetBit(0);
		while (i != -1){
			char c1 = (char)(127 & i);
			char c2 = (char)(((127 << 7) & i) >> 7);
			String qgram = new String();
			qgram = qgram + c1;
			qgram = qgram + c2;
			output.add(qgram);
			i = bitset.nextSetBit(i+1);
		}
		return output;
	}

	public static HashMap<Integer, Double> getProbabilities1(HashMap<Integer, String> strs){

		int size = 0;
		BitSet repSet = new BitSet();
		HashMap<Integer, Double> repWeights = new HashMap<Integer, Double>();

		/*

		// initialize clusters
		BitSet X = new BitSet();
		BitSet Y = new BitSet();

		HashMap<Integer, Double> Yidf = new HashMap<Integer, Double>();
		HashMap<Integer, Double> SumIdf = new HashMap<Integer, Double>();
		int totalsize = 0;
		for (int tid: strs.keySet()){
			X.set(tid);
			String str = strs.get(tid);
			BitSet strSet = convertToBitSet(RunProbabilityAssignment.getTF(str).keySet());
			int i = strSet.nextSetBit(0);
			double sumidf = 0.0;
			while (i!=-1){
				Y.set(i);
				if (!Yidf.containsKey(i)) { Yidf.put(i, Math.log(1.0 + 1.0)); }
				else {
					Yidf.put( i, (1.0 / Math.log(1.0 + ((1.0/Yidf.get(i))+1.0) )) );
				}
				sumidf += Yidf.get(i);
				i = strSet.nextSetBit(i+1);
			}
			SumIdf.put(tid, sumidf);
			totalsize += strSet.cardinality();
		}

		*/

		/*
		 *
		 * Finding Cluster Representative
		 *
		 */

		HashMap<Integer, BitSet> strGrams = new HashMap<Integer, BitSet>();
		/*
		int n=0;
		BitSet striSet = new BitSet();
		HashMap<Integer, Integer> strLens = new HashMap<Integer, Integer>();
		for (int sin:strs.keySet()){
			String stri = strs.get(sin);

			BitSet bb = convertToBitSet(RunProbabilityAssignment.getTF(stri).keySet());
			strGrams.put(sin, bb);

			//strLens.put(sin, bb.cardinality());
			strLens.put(sin, stri.length());
			striSet.or(bb);
		}
		int ii = striSet.nextSetBit(0);
		while (ii!=-1){
			n++;
			ii = striSet.nextSetBit(ii+1);
		}
		//System.out.println("n: " + n);
		*/
		Double repP = 0.0;

		for (int sn:strs.keySet()){
			String str = strs.get(sn);
			BitSet strSet = convertToBitSet(RunProbabilityAssignment.getTF(str).keySet());
			strGrams.put(sn, strSet);
			//BitSet strSet = strGrams.get(sn);
			HashMap<Integer, Double> strWeights = new HashMap<Integer, Double>();

			//Double strP = ((double)strLens.get(sn)/n);

			/****  TODO: Jadid -- check /n ****/

			Double strP = ((double)strs.get(sn).length());

			int i = strSet.nextSetBit(0);
			while (i!=-1){
				//strWeights.put(i, (1.0/(double)strSet.cardinality()) );
				strWeights.put(i, (1.0/str.length()) );
				//strWeights.put(i, Yidf.get(i)/(double)SumIdf.get(sn));

				if (!repSet.get(i)) {repWeights.put(i, 0.0);}

				i = strSet.nextSetBit(i+1);
			}

			//Set<String> s = convertToStringSet(repSet);
			//System.out.println(s);
			//System.out.println(repWeights);

			repSet.or(strSet);

			i = repSet.nextSetBit(0);
			while (i!=-1){
				if (strSet.get(i)){
					//System.out.println(repWeights.get(i));
					//repWeights.put(i, (((double)size / ((double)size+1)) * repWeights.get(i)) + (1.0/((double)size+1))*strWeights.get(i) );
					repWeights.put(i, ((repP / (repP+strP)) * repWeights.get(i)) + (strP/(repP+strP))*strWeights.get(i) );
					//System.out.println(repWeights.get(i));
				}
				else {
					//System.out.println(repWeights.get(i));
					//repWeights.put(i, (((double)size / ((double)size+1)) * repWeights.get(i)));
					repWeights.put(i, ( (repP / (repP+strP)) * repWeights.get(i)));
					//System.out.println(repWeights.get(i));
				}
				i = repSet.nextSetBit(i+1);
			}

			repP += strP;

			//System.out.println(repSet);
			//Set<String> s = convertToStringSet(strSet);
			//System.out.println(s);
			//System.out.println(strWeights);
			//s =	convertToStringSet(repSet);
			//System.out.println(s);
			//System.out.println(repWeights);
			size++;
		}
		//System.out.println();
		if (debug_mode) {
			System.out.println(repWeights);
			double m = 0;
			BitSet b = new BitSet();
			for (int i:repWeights.keySet()){
				b.set(i);
				//System.out.println(convertToStringSet(b) + " " + repWeights.get(i));
				b.clear();
				m += repWeights.get(i);
			}
			//System.out.println(m);
		}

		/*
		 *
		 * Finding similarity of rep. to tuples and calculating probabilities
		 *
		 */

		HashMap<Integer, Double> probs = new HashMap<Integer, Double>();
		Double sum = 0.0;

		for (int sn:strs.keySet()){
			String str = strs.get(sn);
			//BitSet strSet = convertToBitSet(RunProbabilityAssignment.getTF(str).keySet());
			BitSet strSet = strGrams.get(sn);
			HashMap<Integer, Double> strWeights = new HashMap<Integer, Double>();

			double sim = 0.0;
			double total = 0.0;
			int i = repSet.nextSetBit(0);
			while (i!=-1){
				if (strSet.get(i)) {sim += repWeights.get(i);}
				total += repWeights.get(i);
				i = repSet.nextSetBit(i+1);
			}
			/*
			int i = strSet.nextSetBit(0);
			while (i!=-1){
				if (repSet.get(i)) {sim += repWeights.get(i);}
				i = strSet.nextSetBit(i+1);
			}
			*/

			//if (debug_mode) {System.out.println(str + " " + (sim/strSet.cardinality()));}

			probs.put(sn,sim/strSet.cardinality());
			//probs.put(sn,sim);

			//probs.put(sn,1.0/strSet.cardinality());

			sum += sim/strSet.cardinality();
			//sum += sim;
			//System.out.println(strSet.cardinality());
			//System.out.println(total); //TODO: Mashkook sum is not 1 all the time
			//sum += sim/total;

			//sum += 1.0;
			//BitSet copy = new BitSet();
			//copy = (BitSet)(strSet.clone());
			//copy.and(repSet);
			//probs.put(sn,sim/copy.cardinality());
			//sum += sim/copy.cardinality();
			//probs.put(sn,(sim/total));
			//sum += (sim/total);

		}

		for (int sn:strs.keySet()){
			//String str = strs.get(sn);
			probs.put(sn, probs.get(sn)/sum);
			if (debug_mode) {System.out.println(strs.get(sn) + " " + probs.get(sn));}
		}
		if (debug_mode) {System.out.println();}

		return probs;

	}

	public static void main(String[] args) {

		String tablename = "pe";
		//String pairTable = "pairs";
		String probTable = "probs";
		boolean log_sig_to_db = true;
		boolean show_times = true;

		Config config = new Config();
		MySqlDB mysqlDB = new MySqlDB(config.returnURL(), config.user, config.passwd);

		long t1, t2, t3, t4, t5, tf;

		/*
		 *
		 * Call Similarity Join
		 *
		 */
		t1 = System.currentTimeMillis();
		//SignatureGen.run(tablename);
		//t2 = System.currentTimeMillis();
		//System.out.println("Similarity Join (Signature Generation): " + (t2-t1) + "ms");

		/*
		 *
		 * Finding True Clusters
		 *
		 */
		HashMap<Integer,Integer> trueCluster = new HashMap<Integer,Integer>();
		HashMap<Integer,BitSet> trueMembers = new HashMap<Integer,BitSet>();
		//String clustTable = "cluster_pe02";
		//findClusters(clustTable, trueCluster, trueMembers);
		//RunClustering.findTrueClusters(tablename, trueCluster, trueMembers);

		tf = System.currentTimeMillis();
		if (debug_mode) { System.out.println("Total Time for finding clusters: " + (tf-t1) + "ms" + "\n"); };

		String sql = "";
		ResultSet rs;
		//HashMap<Integer, Integer> tid21ton = new HashMap<Integer, Integer>();
		HashMap<Integer, HashMap<Integer, String>> records = new HashMap<Integer, HashMap<Integer, String>>();
		try {
			sql = " SELECT c.tid, c.id, c.string, c.errorp  " +
			//sql = " SELECT c.tid, c.id, c.string  " +
				  " FROM " + config.dbName + "." + tablename + " c " +
			      " order by id, errorp ";
				  //" order by id ";
			rs = mysqlDB.executeQuery(sql);

			int cId = 1;
			HashMap<Integer, String> cStrings = new HashMap<Integer, String>();
			int ctid = 0;
			//System.out.println();
			while (rs.next()){
				//System.out.println(rs.getString(1));
				if (cId != rs.getInt(2)){
					records.put(cId, cStrings);
					cId = rs.getInt(2);
					cStrings = new HashMap<Integer, String>();
					cStrings.put(rs.getInt(1), rs.getString(3));
					ctid = 1;
				}
				else{
					cStrings.put(rs.getInt(1), rs.getString(3));
					ctid++;
				}
				//tid21ton.put(rs.getInt(1), ctid);
			}
			//System.out.println();
			records.put(cId, cStrings);
			//System.out.println();
			//System.out.println(records);
			//System.out.println();
		} catch (Exception e) {
			System.out.println("Database error"); e.printStackTrace();
		}

		/*
		 *  LOGGING PROBABILITY VALUES TO THE PROBABILITY TABLE
		 *  PART 1 - Create Table
		 */
		StringBuffer log_query = new StringBuffer("");
		if (log_sig_to_db) {
			try {
				String query = "drop table if exists " + config.dbName + "." + probTable;
				mysqlDB.executeUpdate(query);

				query = "create table " + config.dbName + "." + probTable
						+ " (tid int, id int, prob double)";
				mysqlDB.executeUpdate(query);
				log_query.append("INSERT INTO " + config.dbName + "." + probTable + " values ");

			} catch (Exception e) {
				System.err.println("Can't create probabilities log tables");
				e.printStackTrace();
			}

		}

		/*
		 *
		 * CALCULATING PROBABILITIES
		 *
		 */

		t1 = System.currentTimeMillis();

		int numberOfRecords = 0;

		long t = 0;
		for (int cId: records.keySet()){
			HashMap<Integer,String> strs = records.get(cId);

			debug_mode = false;
			// System.gc();
			long tt = System.currentTimeMillis();
			HashMap<Integer,Double> probs = getProbabilities1(strs);
			t += ( System.currentTimeMillis() - tt );
			debug_mode = true;

			/*
			 *  LOGGING PROBABILITY VALUES TO THE PROBABILITY TABLE
			 *  Part 2 - Log probability table to DB - INSERT value of the probability in the prob. table
			 *           Actually adding the '(tid, id, prob),' to the end of the query string
			 */
			int j = probs.keySet().size();
			if (log_sig_to_db) {
				for (int tid:probs.keySet()){
					numberOfRecords++;
					log_query.append(" (" + (tid) + "," + cId + "," + probs.get(tid) + ") ,");
				}
			}

			/*
			 *  LOGGING PROBABILITY VALUES TO THE PROBABILITY TABLE
			 *  Part 3 - Log probability table to DB
			 *   INSERT value of the probability in the prob. table for every 10,000 values
			 */
			if ((log_sig_to_db)&&(numberOfRecords % 10000 == 9999)) {
				try {
					mysqlDB.executeUpdate(log_query.deleteCharAt(log_query.length()-1).toString());
					//System.out.println(log_query.deleteCharAt(log_query.length()-1));
					log_query = new StringBuffer("INSERT INTO " + config.dbName + "." + probTable + " values ");
				} catch (Exception e) {
					System.err.println("Can't insert into probability log tables");
					e.printStackTrace();
				}
			}

		}
		tf = System.currentTimeMillis();
		System.out.println("Total Time for prob assignment: " + (t) + "ms" + "\n");
		System.out.println("Total Time for prob assignment and log: " + (tf-t1) + "ms" + "\n");

		/*
		 *  LOGGING PROBABILITY VALUES TO THE PROBABILITY TABLE
		 *  Part 4 - Log probability table to DB
		 *   INSERT all remaining values of the probabilities in the prob. table.
		 */
		//System.out.println(log_query.deleteCharAt(log_query.length()-1));
		try {
			mysqlDB.executeUpdate(log_query.deleteCharAt(log_query.length()-1).toString());
		} catch (Exception e) {
			System.err.println("Can't execute Query ");
			e.printStackTrace();
		}

		/*
		 *
		 *
		 * Evaluation
		 *
		 *
		 */

		Double sumPr = 0.0;
		int clusterCount = 0;

		ResultSet rs2;
		HashMap<Integer, Integer> tid21ton = new HashMap<Integer, Integer>(); // tid21ton Stores the sequence number of each tid in its cluster
		try {
			sql = " SELECT p.tid, p.id, c.`string`, c.errorp, p.prob " +
				  " FROM " + config.dbName + "." + probTable + " p, " + config.dbName + "." + tablename + " c" +
				  " where c.tid = p.tid " +
				  " order by id, prob desc, rand()";

			rs = mysqlDB.executeQuery(sql);

			sql = " SELECT p.tid, p.id, c.`string`, c.errorp, p.prob " +
				  " FROM " + config.dbName + "." + probTable + " p, " + config.dbName + "." + tablename + " c" +
			      " where c.tid = p.tid " +
			      " order by id, errorp, tid";

			rs2 = mysqlDB.executeQuery(sql);

			int cId = 1;
			HashMap<Integer, String> cStrings = new HashMap<Integer, String>();
			int ctid = 0;

			// Reading data and storing strings in each cluster
			while (rs2.next()){
				if (cId != rs2.getInt(2)){
					cId = rs2.getInt(2);
					ctid = 1;
				}
				else{
					ctid++;
				}
				tid21ton.put(rs2.getInt(1), ctid);
			}

			// Vector 'corr' stores correct order of results
			// Vector 'returned' stores the returned order
			Vector<Integer> corr = new Vector<Integer>();
			Vector<Integer> returned = new Vector<Integer>();
			rs.next();
			cId = rs.getInt(2);
			ctid = 1;
			corr.add(ctid);
			returned.add(tid21ton.get(rs.getInt(1)));
			while (rs.next()){
				if (cId != rs.getInt(2)){
					cId = rs.getInt(2);
					ctid = 1;

					boolean[][] correctOrder = new boolean[corr.size()][corr.size()];
					for (int i=0; i<corr.size(); i++)
						for (int j=0; j<corr.size(); j++)
							correctOrder[i][j]=false;

					int size = 0;
					for (int i=0; i<corr.size(); i++){
						for (int j=i+1; j<corr.size(); j++){
							// TODO: if scores are equal then do not set to true
							size++;
							correctOrder[corr.get(i)-1][corr.get(j)-1] = true;
							//System.out.println(v.get(i) + ", " + v.get(j));
						}
					}
					int correct = 0;
					for (int i=0; i<returned.size(); i++){
						for (int j=i+1; j<returned.size(); j++){
							if (correctOrder[returned.get(i)-1][returned.get(j)-1]) {
								correct++;
								//System.out.println(v2.get(i) + ", " + v2.get(j));
							}
						}
					}
					//System.out.println("Percentage: " + correct + "/" + size);
					sumPr += (((double)correct) / ((double)size));
					clusterCount++;
					//System.out.println(corr);
					//System.out.println(returned);

					corr = new Vector<Integer>();
					returned = new Vector<Integer>();
					corr.add(ctid);
				}
				else{
					ctid++;
					corr.add(ctid);
				}
				returned.add(tid21ton.get(rs.getInt(1)));
			}
			//System.out.println();
			//records.put(cId, cStrings);
			//System.out.println(tid21ton);
			//System.out.println();
			//System.out.println(records);
			//System.out.println();
		} catch (Exception e) {
			System.out.println("Database error"); e.printStackTrace();
		}

		System.out.println(" Total OP rate:" + ( (sumPr / (double)clusterCount) - 0.5) / 0.5 );

		/*

		HashMap<Integer,String> strs = new HashMap<Integer,String>();
		strs.put(2,"Oktie Hassanzadeh Corp");
		strs.put(3,"Oktay Hasanov");
		strs.put(4,"Oktai Hassan zadeh");
		strs.put(5,"Oktide hasssanzadeh");
		strs.put(6,"kalanjoon hoseinpour");
		HashMap<Integer,Double> probs = getProbabilities(strs);
		*/

	}

	public static void findClusters(String clusterTable,
			                            HashMap<Integer,Integer> trueCluster,
			                            HashMap<Integer,BitSet> trueMembers) {
		Config config = new Config();
		MySqlDB mysqlDB = new MySqlDB(config.returnURL(), config.user, config.passwd);
		String sql = "";
		try {
			sql = " SELECT c1.tid as tid1, c2.tid as tid2 FROM " + config.dbName +
			      "." + clusterTable + " c1," + config.dbName + "." + clusterTable + " c2" +
				  " where c1.cid=c2.cid ";
			System.out.println(sql);
			ResultSet rs = mysqlDB.executeQuery(sql);

			//t4 = System.currentTimeMillis();
			//System.out.println("DEBUG INFO: " + (t4-t3) + "ms");
			//BitSet isThere = new BitSet(count);
			BitSet isThere = new BitSet();
			int maxId = 0;

			rs.beforeFirst();
			while (rs.next()){
				//System.out.println(rs.getInt(1) + " " + rs.getInt(2));
				int tid1 = rs.getInt(1);
				int tid2 = rs.getInt(2);

				if (!isThere.get(tid1)) {
					if (!isThere.get(tid2)) {
						maxId++;
						trueCluster.put(tid1,maxId);
						trueCluster.put(tid2,maxId);

						BitSet mems = new BitSet();
						mems.set(tid1);
						mems.set(tid2);
						trueMembers.put(maxId, mems);

						isThere.set(tid1);
						isThere.set(tid2);
					}
					else {
						int cId = trueCluster.get(tid2);

						trueCluster.put(tid1, cId);

						BitSet mems = trueMembers.get(cId);
						mems.set(tid1);
						trueMembers.put(cId, mems);

						isThere.set(tid1);
					}
				}
				else {
					if (!isThere.get(tid2)) {
						int cId = trueCluster.get(tid1);

						trueCluster.put(tid2, cId);

						BitSet mems = trueMembers.get(cId);
						mems.set(tid2);
						trueMembers.put(cId, mems);

						isThere.set(tid2);
					}
				}
			}

			//System.out.println(trueCluster);
			//System.out.println(trueMembers);

		} catch (Exception e) {
			System.out.println("Database error"); e.printStackTrace();
		}

	}

}


text:
from __future__ import print_function

import sys
import time

try:
    import simplejson as json
except ImportError:
    import json

from troveclient import exceptions
from troveclient import utils

def _poll_for_status(poll_fn, obj_id, action, final_ok_states,
                     poll_period=5, show_progress=True):
    """Block while an action is being performed, periodically printing
    progress.
    """
    def print_progress(progress):
        if show_progress:
            msg = ('\rInstance %(action)s... %(progress)s%% complete'
                   % dict(action=action, progress=progress))
        else:
            msg = '\rInstance %(action)s...' % dict(action=action)

        sys.stdout.write(msg)
        sys.stdout.flush()

    print()
    while True:
        obj = poll_fn(obj_id)
        status = obj.status.lower()
        progress = getattr(obj, 'progress', None) or 0
        if status in final_ok_states:
            print_progress(100)
            print("\nFinished")
            break
        elif status == "error":
            print("\nError %(action)s instance" % {'action': action})
            break
        else:
            print_progress(progress)
            time.sleep(poll_period)

def _print_instance(instance):
    # Get rid of those ugly links
    if instance._info.get('links'):
        del(instance._info['links'])
    utils.print_dict(instance._info)

def _find_instance(cs, instance):
    """Get a instance by ID."""
    return utils.find_resource(cs.instances, instance)

def _find_flavor(cs, flavor):
    """Get a flavor by ID."""
    return utils.find_resource(cs.flavors, flavor)

def _find_backup(cs, backup):
    """Gets a backup by ID."""
    return utils.find_resource(cs.backups, backup)

# Flavor related calls

@utils.service_type('database')
def do_flavor_list(cs, args):
    """Lists available flavors."""
    flavors = cs.flavors.list()
    utils.print_list(flavors, ['id', 'name', 'ram'])

@utils.arg('flavor', metavar='<flavor>', help='ID of the flavor.')
@utils.service_type('database')
def do_flavor_show(cs, args):
    """Shows details of a flavor."""
    flavor = _find_flavor(cs, args.flavor)
    _print_instance(flavor)

# Instance related calls

@utils.service_type('database')
def do_list(cs, args):
    """Lists all the instances."""
    instances = cs.instances.list()

    for instance in instances:
        setattr(instance, 'flavor_id', instance.flavor['id'])
        if hasattr(instance, 'volume'):
            setattr(instance, 'size', instance.volume['size'])
        if hasattr(instance, 'datastore'):
            if instance.datastore.get('version'):
                setattr(instance, 'datastore_version',
                        instance.datastore['version'])
            setattr(instance, 'datastore', instance.datastore['type'])
    utils.print_list(instances, ['id', 'name', 'datastore',
                                 'datastore_version', 'status',
                                 'flavor_id', 'size'])

@utils.arg('instance', metavar='<instance>', help='ID of the instance.')
@utils.service_type('database')
def do_show(cs, args):
    """Shows details of an instance."""
    instance = _find_instance(cs, args.instance)
    instance._info['flavor'] = instance.flavor['id']
    if hasattr(instance, 'volume'):
        instance._info['volume'] = instance.volume['size']
        if 'used' in instance.volume:
            instance._info['volume_used'] = instance.volume['used']
    if hasattr(instance, 'ip'):
        instance._info['ip'] = ', '.join(instance.ip)
    if hasattr(instance, 'datastore'):
        instance._info['datastore'] = instance.datastore['type']
        instance._info['datastore_version'] = instance.datastore['version']
    if hasattr(instance, 'configuration'):
        instance._info['configuration'] = instance.configuration['id']
    _print_instance(instance)

@utils.arg('instance', metavar='<instance>', help='ID of the instance.')
@utils.service_type('database')
def do_delete(cs, args):
    """Deletes an instance."""
    cs.instances.delete(args.instance)

@utils.arg('name',
           metavar='<name>',
           type=str,
           help='Name of the instance.')
@utils.arg('--size',
           metavar='<size>',
           type=int,
           default=None,
           help='Size of the instance disk in GB.')
@utils.arg('flavor_id',
           metavar='<flavor_id>',
           help='Flavor of the instance.')
@utils.arg('--databases', metavar='<databases>',
           help='Optional list of databases.',
           nargs="+", default=[])
@utils.arg('--users', metavar='<users>',
           help='Optional list of users in the form user:password.',
           nargs="+", default=[])
@utils.arg('--backup',
           metavar='<backup>',
           default=None,
           help='A backup UUID.')
@utils.arg('--availability_zone',
           metavar='<availability_zone>',
           default=None,
           help='The Zone hint to give to nova.')
@utils.arg('--datastore',
           metavar='<datastore>',
           default=None,
           help='A datastore name or UUID.')
@utils.arg('--datastore_version',
           metavar='<datastore_version>',
           default=None,
           help='A datastore version name or UUID.')
@utils.arg('--nic',
           metavar="<net-id=net-uuid,v4-fixed-ip=ip-addr,port-id=port-uuid>",
           action='append',
           dest='nics',
           default=[],
           help="Create a NIC on the instance. "
                "Specify option multiple times to create multiple NICs. "
                "net-id: attach NIC to network with this UUID "
                "(required, if no port-id specified), "
                "v4-fixed-ip: IPv4 fixed address for NIC (optional), "
                "port-id: attach NIC to port with this UUID "
                "(required, if no net-id specified).")
@utils.arg('--configuration',
           metavar='<configuration>',
           default=None,
           help='UUID of the configuration group to attach to the instance.')
@utils.service_type('database')
def do_create(cs, args):
    """Creates a new instance."""
    volume = None
    if args.size:
        volume = {"size": args.size}
    restore_point = None
    if args.backup:
        restore_point = {"backupRef": args.backup}
    databases = [{'name': value} for value in args.databases]
    users = [{'name': n, 'password': p, 'databases': databases} for (n, p) in
             [z.split(':')[:2] for z in args.users]]
    nics = []
    for nic_str in args.nics:
        nic_info = dict([(k, v) for (k, v) in [z.split("=", 1)[:2] for z in
                                               nic_str.split(",")]])
        if not (nic_info.get('net-id') or nic_info.get('port-id')):
            err_msg = ("Invalid nic argument '%s'. Nic arguments must be of "
                       "the form --nic <net-id=net-uuid,v4-fixed-ip=ip-addr,"
                       "port-id=port-uuid>, with at minimum net-id or port-id "
                       "specified." % nic_str)
            raise exceptions.CommandError(err_msg)
        nics.append(nic_info)
    instance = cs.instances.create(args.name,
                                   args.flavor_id,
                                   volume=volume,
                                   databases=databases,
                                   users=users,
                                   restorePoint=restore_point,
                                   availability_zone=args.availability_zone,
                                   datastore=args.datastore,
                                   datastore_version=args.datastore_version,
                                   nics=nics,
                                   configuration=args.configuration)
    instance._info['flavor'] = instance.flavor['id']
    if hasattr(instance, 'volume'):
        instance._info['volume'] = instance.volume['size']
    if hasattr(instance, 'datastore'):
        instance._info['datastore'] = instance.datastore['type']
        instance._info['datastore_version'] = instance.datastore['version']
    del(instance._info['links'])
    if hasattr(instance, 'configuration'):
        instance._info['configuration'] = instance.configuration['id']
    _print_instance(instance)

@utils.arg('instance',
           metavar='<instance>',
           type=str,
           help='UUID of the instance.')
@utils.arg('flavor_id',
           metavar='<flavor_id>',
           help='Flavor of the instance.')
@utils.service_type('database')
def do_resize_flavor(cs, args):
    """Resizes the flavor of an instance."""
    cs.instances.resize_flavor(args.instance, args.flavor_id)

@utils.arg('instance',
           metavar='<instance>',
           type=str,
           help='UUID of the instance.')
@utils.arg('size',
           metavar='<size>',
           type=int,
           default=None,
           help='Size of the instance disk in GB.')
@utils.service_type('database')
def do_resize_volume(cs, args):
    """Resizes the volume size of an instance."""
    cs.instances.resize_volume(args.instance, args.size)

@utils.arg('instance',
           metavar='<instance>',
           type=str,
           help='UUID of the instance.')
@utils.service_type('database')
def do_restart(cs, args):
    """Restarts the instance."""
    cs.instances.restart(args.instance)

# Backup related commands

@utils.arg('backup', metavar='<backup>', help='ID of the backup.')
@utils.service_type('database')
def do_backup_show(cs, args):
    """Shows details of a backup."""
    backup = _find_backup(cs, args.backup)
    _print_instance(backup)

@utils.arg('--limit', metavar='<limit>',
           default=None,
           help='Return up to N number of the most recent backups.')
@utils.arg('instance', metavar='<instance>', help='ID of the instance.')
@utils.service_type('database')
def do_backup_list_instance(cs, args):
    """Lists available backups for an instance."""
    wrapper = cs.instances.backups(args.instance, limit=args.limit)
    backups = wrapper.items
    while wrapper.next and not args.limit:
        wrapper = cs.instances.backups(args.instance, marker=wrapper.next)
        backups += wrapper.items
    utils.print_list(backups, ['id', 'name', 'status',
                               'parent_id', 'updated'],
                     order_by='updated')

@utils.arg('--limit', metavar='<limit>',
           default=None,
           help='Return up to N number of the most recent backups.')
@utils.service_type('database')
def do_backup_list(cs, args):
    """Lists available backups."""
    wrapper = cs.backups.list(limit=args.limit)
    backups = wrapper.items
    while wrapper.next and not args.limit:
        wrapper = cs.backups.list(marker=wrapper.next)
        backups += wrapper.items
    utils.print_list(backups, ['id', 'instance_id', 'name',
                               'status', 'parent_id', 'updated'],
                     order_by='updated')

@utils.arg('backup', metavar='<backup>', help='ID of the backup.')
@utils.service_type('database')
def do_backup_delete(cs, args):
    """Deletes a backup."""
    cs.backups.delete(args.backup)

@utils.arg('name', metavar='<name>', help='Name of the backup.')
@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.arg('--description', metavar='<description>',
           default=None,
           help='An optional description for the backup.')
@utils.arg('--parent', metavar='<parent>', default=None,
           help='Optional UUID of the parent backup to perform an'
           ' incremental backup from.')
@utils.service_type('database')
def do_backup_create(cs, args):
    """Creates a backup."""
    backup = cs.backups.create(args.name, args.instance,
                               description=args.description,
                               parent_id=args.parent)
    _print_instance(backup)

# Database related actions

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.arg('name', metavar='<name>', help='Name of the database.')
@utils.arg('--character_set', metavar='<character_set>',
           default=None,
           help='Optional character set for database.')
@utils.arg('--collate', metavar='<collate>', default=None,
           help='Optional collation type for database.')
@utils.service_type('database')
def do_database_create(cs, args):
    """Creates a database on an instance."""
    database_dict = {'name': args.name}
    if args.collate:
        database_dict['collate'] = args.collate
    if args.character_set:
        database_dict['character_set'] = args.character_set
    cs.databases.create(args.instance,
                        [database_dict])

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.service_type('database')
def do_database_list(cs, args):
    """Lists available databases on an instance."""
    wrapper = cs.databases.list(args.instance)
    databases = wrapper.items
    while (wrapper.next):
        wrapper = cs.databases.list(args.instance, marker=wrapper.next)
        databases += wrapper.items

    utils.print_list(databases, ['name'])

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.arg('database', metavar='<database>', help='Name of the database.')
@utils.service_type('database')
def do_database_delete(cs, args):
    """Deletes a database."""
    cs.databases.delete(args.instance, args.database)

# User related actions

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.arg('name', metavar='<name>', help='Name of user.')
@utils.arg('password', metavar='<password>', help='Password of user.')
@utils.arg('--host', metavar='<host>', default=None,
           help='Optional host of user.')
@utils.arg('--databases', metavar='<databases>',
           help='Optional list of databases.',
           nargs="+", default=[])
@utils.service_type('database')
def do_user_create(cs, args):
    """Creates a user."""
    databases = [{'name': value} for value in args.databases]
    user = {'name': args.name, 'password': args.password,
            'databases': databases}
    if args.host:
        user['host'] = args.host
    cs.users.create(args.instance, [user])

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.service_type('database')
def do_user_list(cs, args):
    """Lists the users for a instance."""
    wrapper = cs.users.list(args.instance)
    users = wrapper.items
    while (wrapper.next):
        wrapper = cs.users.list(args.instance, marker=wrapper.next)
        users += wrapper.items
    for user in users:
        db_names = [db['name'] for db in user.databases]
        user.databases = ', '.join(db_names)
    utils.print_list(users, ['name', 'host', 'databases'])

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.arg('name', metavar='<name>', help='Name of user.')
@utils.arg('--host', metavar='<host>', default=None,
           help='Optional host of user.')
@utils.service_type('database')
def do_user_delete(cs, args):
    """Deletes a user from the instance."""
    cs.users.delete(args.instance, args.name, hostname=args.host)

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.arg('name', metavar='<name>', help='Name of user.')
@utils.arg('--host', metavar='<host>', default=None,
           help='Optional host of user.')
@utils.service_type('database')
# Quoting is not working now that we aren't using httplib2
# anymore and instead are using requests
def do_user_show(cs, args):
    """Gets a user from the instance."""
    user = cs.users.get(args.instance, args.name, hostname=args.host)
    _print_instance(user)

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.arg('name', metavar='<name>', help='Name of user.')
@utils.arg('--host', metavar='<host>', default=None,
           help='Optional host of user.')
@utils.service_type('database')
# Quoting is not working now that we aren't using httplib2
# anymore and instead are using requests
def do_user_show_access(cs, args):
    """Gets a users access from the instance."""
    access = cs.users.list_access(args.instance, args.name, hostname=args.host)
    utils.print_list(access, ['name'])

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.arg('name', metavar='<name>', help='Name of user.')
@utils.arg('--host', metavar='<host>', default=None,
           help='Optional host of user.')
@utils.arg('--new_name', metavar='<new_name>', default=None,
           help='Optional new name of user.')
@utils.arg('--new_password', metavar='<new_password>', default=None,
           help='Optional new password of user.')
@utils.arg('--new_host', metavar='<new_host>', default=None,
           help='Optional new host of user.')
@utils.service_type('database')
# Quoting is not working now that we aren't using httplib2
# anymore and instead are using requests
def do_user_update_attributes(cs, args):
    """Updates a users attributes from the instance."""
    new_attrs = {}
    if args.new_name:
        new_attrs['name'] = args.new_name
    if args.new_password:
        new_attrs['password'] = args.new_password
    if args.new_host:
        new_attrs['host'] = args.new_host
    cs.users.update_attributes(args.instance, args.name,
                               newuserattr=new_attrs, hostname=args.host)

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.arg('name', metavar='<name>', help='Name of user.')
@utils.arg('--host', metavar='<host>', default=None,
           help='Optional host of user.')
@utils.arg('databases', metavar='<databases>',
           help='List of databases.',
           nargs="+", default=[])
@utils.service_type('database')
def do_user_grant_access(cs, args):
    """Grants access to a database(s) for a user."""
    cs.users.grant(args.instance, args.name,
                   args.databases, hostname=args.host)

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.arg('name', metavar='<name>', help='Name of user.')
@utils.arg('database', metavar='<database>', help='A single database.')
@utils.arg('--host', metavar='<host>', default=None,
           help='Optional host of user.')
@utils.service_type('database')
def do_user_revoke_access(cs, args):
    """Revokes access to a database for a user."""
    cs.users.revoke(args.instance, args.name,
                    args.database, hostname=args.host)

# Limits related commands

@utils.service_type('database')
def do_limit_list(cs, args):
    """Lists the limits for a tenant."""
    limits = cs.limits.list()
    # Pop the first one, its absolute limits
    absolute = limits.pop(0)
    _print_instance(absolute)
    utils.print_list(limits, ['value', 'verb', 'remaining', 'unit'])

# Root related commands

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.service_type('database')
def do_root_enable(cs, args):
    """Enables root for a instance."""
    root = cs.root.create(args.instance)
    utils.print_dict({'name': root[0], 'password': root[1]})

@utils.arg('instance', metavar='<instance>', help='UUID of the instance.')
@utils.service_type('database')
def do_root_show(cs, args):
    """Gets root enabled status for a instance."""
    root = cs.root.is_root_enabled(args.instance)
    utils.print_dict({'is_root_enabled': root.rootEnabled})

# security group related functions

@utils.service_type('database')
def do_secgroup_list(cs, args):
    """Lists all security groups."""
    wrapper = cs.security_groups.list()
    sec_grps = wrapper.items
    while (wrapper.next):
        wrapper = cs.security_groups.list()
        sec_grps += wrapper.items

    utils.print_list(sec_grps, ['id', 'name', 'rules', 'instance_id'])

@utils.arg('security_group', metavar='<security_group>',
           help='ID of the security group.')
@utils.service_type('database')
def do_secgroup_show(cs, args):
    """Shows details about a security group."""
    sec_grp = cs.security_groups.get(args.security_group)
    _print_instance(sec_grp)

@utils.arg('security_group', metavar='<security_group>',
           help='Security group name.')
@utils.arg('cidr', metavar='<cidr>', help='CIDR address.')
@utils.service_type('database')
def do_secgroup_add_rule(cs, args):
    """Creates a security group rule."""
    rules = cs.security_group_rules.create(
        args.security_group, args.cidr)

    utils.print_list(rules, [
        'id', 'security_group_id', 'protocol',
        'from_port', 'to_port', 'cidr', 'created'], obj_is_dict=True)

@utils.arg('security_group_rule', metavar='<security_group_rule>',
           help='Name of security group rule.')
@utils.service_type('database')
def do_secgroup_delete_rule(cs, args):
    """Deletes a security group rule."""
    cs.security_group_rules.delete(args.security_group_rule)

@utils.service_type('database')
def do_datastore_list(cs, args):
    """Lists available datastores."""
    datastores = cs.datastores.list()
    utils.print_list(datastores, ['id', 'name'])

@utils.arg('datastore', metavar='<datastore>',
           help='ID of the datastore.')
@utils.service_type('database')
def do_datastore_show(cs, args):
    """Shows details of a datastore."""
    datastore = cs.datastores.get(args.datastore)
    if hasattr(datastore, 'default_version'):
        datastore._info['default_version'] = getattr(datastore,
                                                     'default_version')
    _print_instance(datastore)

@utils.arg('datastore', metavar='<datastore>',
           help='ID of the datastore.')
@utils.service_type('database')
def do_datastore_version_list(cs, args):
    """Lists available versions for a datastore."""
    datastore_versions = cs.datastore_versions.list(args.datastore)
    utils.print_list(datastore_versions, ['id', 'name'])

@utils.arg('--datastore', metavar='<datastore>',
           default=None,
           help='ID or name of the datastore. Optional if UUID of the'
                ' datastore_version is provided.')
@utils.arg('datastore_version', metavar='<datastore_version>',
           help='ID of the datastore version.')
@utils.service_type('database')
def do_datastore_version_show(cs, args):
    """Shows details of a datastore version."""
    if args.datastore:
        datastore_version = cs.datastore_versions.get(args.datastore,
                                                      args.datastore_version)
    elif utils.is_uuid_like(args.datastore_version):
        datastore_version = cs.datastore_versions.get_by_uuid(
            args.datastore_version)
    else:
        raise exceptions.NoUniqueMatch('The datastore name or id is required'
                                       ' to retrieve a datastore version'
                                       ' by name.')
    _print_instance(datastore_version)

# configuration group related functions

@utils.arg('configuration',
           metavar='<configuration>',
           type=str,
           help='UUID of the configuration group to attach to the instance.')
@utils.arg('instance',
           metavar='<instance>',
           type=str,
           help='UUID of the instance.')
@utils.service_type('database')
def do_configuration_attach(cs, args):
    """Attaches a configuration group to an instance."""
    cs.instances.modify(args.instance, args.configuration)

@utils.arg('name', metavar='<name>', help='Name of the configuration group.')
@utils.arg('values', metavar='<values>',
           help='Dictionary of the values to set.')
@utils.arg('--datastore', metavar='<datastore>',
           help='Datastore assigned to the configuration group.')
@utils.arg('--datastore_version', metavar='<datastore_version>',
           help='Datastore version UUID assigned to the configuration group.')
@utils.arg('--description', metavar='<description>',
           default=None,
           help='An optional description for the configuration group.')
@utils.service_type('database')
def do_configuration_create(cs, args):
    """Creates a configuration group."""
    config_grp = cs.configurations.create(
        args.name,
        args.values,
        description=args.description,
        datastore=args.datastore,
        datastore_version=args.datastore_version)
    config_grp._info['values'] = json.dumps(config_grp.values)
    _print_instance(config_grp)

@utils.arg('instance',
           metavar='<instance>',
           type=str,
           help='UUID of the instance.')
@utils.service_type('database')
def do_configuration_default(cs, args):
    """Shows the default configuration of an instance."""
    configs = cs.instances.configuration(args.instance)
    utils.print_dict(configs._info['configuration'])

@utils.arg('configuration_group', metavar='<configuration_group>',
           help='ID of the configuration group.')
@utils.service_type('database')
def do_configuration_delete(cs, args):
    """Deletes a configuration group."""
    cs.configurations.delete(args.configuration_group)

@utils.arg('instance',
           metavar='<instance>',
           type=str,
           help='UUID of the instance.')
@utils.service_type('database')
def do_configuration_detach(cs, args):
    """Detaches a configuration group from an instance."""
    cs.instances.modify(args.instance)

@utils.arg('--datastore', metavar='<datastore>',
           default=None,
           help='UUID or name of the datastore to list configuration '
                'parameters for. Optional if UUID of the'
                ' datastore_version is provided.')
@utils.arg('datastore_version',
           metavar='<datastore_version>',
           help='Datastore version name or UUID assigned to the '
                'configuration group.')
@utils.arg('parameter', metavar='<parameter>',
           help='Name of the configuration parameter.')
@utils.service_type('database')
def do_configuration_parameter_show(cs, args):
    """Shows details of a configuration parameter."""
    if args.datastore:
        param = cs.configuration_parameters.get_parameter(
            args.datastore,
            args.datastore_version,
            args.parameter)
    elif utils.is_uuid_like(args.datastore_version):
        param = cs.configuration_parameters.get_parameter_by_version(
            args.datastore_version,
            args.parameter)
    _print_instance(param)

@utils.arg('--datastore', metavar='<datastore>',
           default=None,
           help='UUID or name of the datastore to list configuration '
                'parameters for. Optional if UUID of the'
                ' datastore_version is provided.')
@utils.arg('datastore_version',
           metavar='<datastore_version>',
           help='Datastore version name or UUID assigned to the '
                'configuration group.')
@utils.service_type('database')
def do_configuration_parameter_list(cs, args):
    """Lists available parameters for a configuration group."""
    if args.datastore:
        params = cs.configuration_parameters.parameters(
            args.datastore,
            args.datastore_version)
    elif utils.is_uuid_like(args.datastore_version):
        params = cs.configuration_parameters.parameters_by_version(
            args.datastore_version)
    else:
        raise exceptions.NoUniqueMatch('The datastore name or id is required'
                                       ' to retrieve the parameters for the'
                                       ' configuration group by name.')
    utils.print_list(params, ['name', 'type', 'min', 'max',
                              'restart_required'])

@utils.arg('configuration_group', metavar='<configuration_group>',
           help='ID of the configuration group.')
@utils.arg('values', metavar='<values>',
           help='Dictionary of the values to set.')
@utils.service_type('database')
def do_configuration_patch(cs, args):
    """Patches a configuration group."""
    cs.configurations.edit(args.configuration_group,
                           args.values)

@utils.arg('configuration_group', metavar='<configuration_group>',
           help='ID of the configuration group.')
@utils.service_type('database')
def do_configuration_instances(cs, args):
    """Lists all instances associated with a configuration group."""
    params = cs.configurations.instances(args.configuration_group)
    utils.print_list(params, ['id', 'name'])

@utils.service_type('database')
def do_configuration_list(cs, args):
    """Lists all configuration groups."""
    config_grps = cs.configurations.list()
    utils.print_list(config_grps, ['id', 'name', 'description',
                                   'datastore_version_id'])

@utils.arg('configuration_group', metavar='<configuration_group>',
           help='ID of the configuration group.')
@utils.service_type('database')
def do_configuration_show(cs, args):
    """Shows details of a configuration group."""
    config_grp = cs.configurations.get(args.configuration_group)
    config_grp._info['values'] = json.dumps(config_grp.values)
    _print_instance(config_grp)

@utils.arg('configuration_group', metavar='<configuration_group>',
           help='ID of the configuration group.')
@utils.arg('values', metavar='<values>',
           help='Dictionary of the values to set.')
@utils.arg('--name', metavar='<name>', default=None,
           help='Name of the configuration group.')
@utils.arg('--description', metavar='<description>',
           default=None,
           help='An optional description for the configuration group.')
@utils.service_type('database')
def do_configuration_update(cs, args):
    """Updates a configuration group."""
    cs.configurations.update(args.configuration_group,
                             args.values,
                             args.name,
                             args.description)


text:
"use strict";

function fixtures$foo() {
  return "foobar";
}

fixtures$foo();


text:
class CreateSeasons < ActiveRecord::Migration[6.1]
  def change
    create_table :seasons do |t|

      t.references :tv_show
      t.integer :number

      t.timestamps
    end
  end
end


text:
AtalandaSignature-ruby
==================

AtalandaSignature-ruby provides a simple Ruby class that lets you sign requests to the [atalogics API](http://atalogics.com) and verify our callbacks.

Installation
============

The best way to install the library is by using bundler. Add the following to `Gemfile` in the root of your project:

```
gem "atalanda-signature"
```

Then, on the command line:

``` bash
bundle install
```

Usage
=====

Signing API calls
-----------------
Use this to add an auth_hash containing a valid signature to the parameter hash that you send to our API.
``` ruby
parameters = {
  "atalogics" => {}
}
token = Atalanda::Signature::Token.new(KEY, SECRET)
request = Atalanda::Signature::Request.new("POST", "https://atalogics.com/api/order", parameters)
signed_parameters = request.sign(token)
=>
{
  "atalogics" => {},
  "auth_timestamp" => 1391167211,
  "auth_key" => "[Your API key]",
  "auth_signature" => "552beac4b99949a556b120b7e5f7e22def46f663992a08f0f132ad4afee68b9f"
}
```
**Example**
> POST Request to https://atalogics.com/api/orderOffer with the following JSON:
``` javascript
{
  "atalogics": {
    "api_key": "5f70fd232454e5c142566dbacc3dec5",
    "offer_id": "33/2014-01-22/1/2014-01-22",
    "expected_fee": 5.59,
    "external_id": "AZDF-234",
    "url_state_update": "https://ihr-server.de/atalogics/callbacks",
    "catch": {
        "name": "Top Fashion Shop",
        "street": "Schneiderstraße 20",
        "postal_code": "5020",
        "city": "Salzburg",
        "phone_number": "123456",
        "email": "info@fashionshop.de"
    },
    "drop": {
        "name": "Marta Musterkundin",
        "street": "Kaufstr. 76",
        "postal_code": "5020",
        "city": "Salzburg",
        "phone_number": "435236",
        "email": "marta@musterkundin.de",
        "extra_services": ["R18"]
    }
  }
}
```
``` ruby
token = Atalanda::Signature::Token.new(KEY, SECRET)
request = Atalanda::Signature::Request.new("POST", "https://atalogics.com/api/orderOffer", parameters) # parameters contains a hash representing the json above
signed_parameters = request.sign(token)
# post to our API, for example with HTTParty
HTTParty.post("https://atalogics.com/api/orderOffer",
  :body => signed_parameters.to_json,
  :headers => { 'Content-Type' => 'application/json' })
```
If you do a GET Request, you also have to sign all URL parameters. Simply include them in the parameters hash. Send the produced auth parameters along with the other URL parameters, for example:
> https://atalogics.com/api/status?tracking_id=42ef32a&api_key=abcde**&auth_signature=ab332d2f&auth_timestamp=123244&auth_key=abcde**

Verifying the signature of our callbacks
--------------
Use this to verify the signature of our callbacks.
``` ruby
data = JSON.parse(body) // convert json from post body into ruby hash
token = Atalanda::Signature::Token.new(KEY, SECRET)
request = Atalanda::Signature::Request.new("POST", "api/order", data)
result = request.authenticate(token)

if result["authenticated"] == true
  // signature is valid
end
```


text:
#ifndef __WmePathUtils_H__
#define __WmePathUtils_H__

#include "DirectoryOperations.h"
#include "FileOperations.h"

	class PathUtil
	{
	public:
		static AnsiString AppendSlashToPlainDir(const AnsiString& path);
		static AnsiString UnifySeparators(const AnsiString& path);
		static AnsiString NormalizeFileName(const AnsiString& path);
		static AnsiString Combine(const AnsiString& path1, const AnsiString& path2);
		static AnsiString GetDirectoryName(const AnsiString& path);
		static AnsiString GetFileName(const AnsiString& path);
		static AnsiString GetFileNameWithoutExtension(const AnsiString& path);
		static AnsiString GetExtension(const AnsiString& path);
		static AnsiString GetAbsolutePath(const AnsiString& path);
		static bool CreateDirectory(const AnsiString& path);
		static bool MatchesMask(const AnsiString& fileName, const AnsiString& mask);

		static bool FileExists(const char* fileName);
		static bool DirectoryExists(const char* path);

		static AnsiString GetSafeLogFileName();
		static AnsiString GetUserDirectory();
		static AnsiString GetLocalSettingsDirectory();

		static void GetFilesInDirectory(const AnsiString& path, const AnsiString& mask, AnsiStringList& files);
		static generic_directory_ops* GetDirectoryAccessMethod(const AnsiString &path);
		static generic_file_ops* GetFileAccessMethod(const AnsiString &path);
	};

#endif // __WmePathUtils_H__


text:
$(document).ready(function () {

    $("[data-submit-session-form]").click(function () {
        $.blockUI({message: "Cargando..."});
        $.post("user/login", $("#login").serialize(), function (data) {
            if (data === "exito") {
                $.blockUI({message: "Bienvenido"});
                $('#login')[0].reset();
            } else {
                $.blockUI({message: "Error: verifique los datos e intente nuevamente"});
                $('#login')[0].reset();
            }
        }).always(function () {
            setTimeout(function () {
                $.unblockUI;
                location.reload();
            }, 3000);
        });
    });

    $("#form-cambiar-password").submit(function () {});

    $("#logout2").click(function () {
        $.post("user/logout", function () {
            confirm("Cerrando sesion...");
            location.href = getBaseUrl();
        });
    });

    function sendMail(user) {
        var message = 'Usuario Nuevo: ' + user + ' se ha registrado';
        //$.post("<?= base_url(); ?>email/send2/null/null/"+message,function(){});
        var post = {'message': message};
        //$.post("order/getOrderByUserDNI/"+$(this).value, function (data) {
        $.post("email/send2", post, function (data) {});
    }

    $("#create-user").submit(function () {
        var password = $("#passwordRegister").val();
        var password2 = $("#rePasswordRegister").val();
        if (password !== password2) {
            alert("Las contraseñas no coinciden!");
        } else {
            $.post("user/create", $(this).serialize(), function (data) {
                if (data === "exitoUpdated Session") {
                    $("#msj_exito").fadeIn(2000).fadeOut(4000);
                    //sendMail(username);
                    $('#create-user')[0].reset();
                    confirm("Usuario creado exitosamente");
                    // despues de crear loguea al usuario
                    location.reload();
                } else if (data === "password") {
                    $("#msj_pass").fadeIn(2000).fadeOut(6000);
                    //$('#create-user')[0].reset();
                } else if (data === "login") {
                    $("#msj_login").fadeIn(2000).fadeOut(6000);
                    $('#create-user')[0].reset();
                } else if (data === "email") {
                    $("#msj_email").fadeIn(2000).fadeOut(6000);
                    //$('#create-user')[0].reset();

                } else {
                    $("#msj_error").fadeIn(2000).fadeOut(4000);
                    //$('#create-user')[0].reset();
                }
            });
        }
        return false;
    });

    $("#update-user").submit(function () {
        $.post("user/update", $(this).serialize(), function (data) {
            console.log(data);
            if (data === "Updated Sessionexito") {
                alert("¡Cambios realizados con éxito!");
//                location.reload();
            } else if (data === "error") {
                $("#msj_error").fadeIn(2000).fadeOut(4000);
            } else if (data == "password") {
                $("#msj_pass").fadeIn(2000).fadeOut(6000);
            } else {
                $("#msj_error").fadeIn(2000).fadeOut(4000);
            }
        });
//        }
    });

    $("[data-update-user-submit]").click(function(){
         $.post("user/update", $("#update-user").serialize(), function (data) {
            console.log(data);
            if (data === "Updated Sessionexito") {
                alert("¡Cambios realizados con éxito!");
                location.reload();
            } else if (data === "error") {
                $("#msj_error").fadeIn(2000).fadeOut(4000);
            } else if (data === "password") {
                $("#msj_pass").fadeIn(2000).fadeOut(6000);
            } else {
                $("#msj_error").fadeIn(2000).fadeOut(4000);
            }
        });
    });

    $("#order-user").click(function () {
        $.post("order/getOrderByUserDNI/" + $(this).value, function (data) {
            $.each(data, function (index, value) {
                $("#accordion").append(value);
            });
        });
    });

    $('#passwordRegister, #rePasswordRegister').change(function () {
        password = $('#passwordRegister');
        repassword = $('#rePasswordRegister');

        if (password.val() !== repassword.val() && password.val().length > 0 && repassword.val().length > 0) {
            password.addClass('has-error').removeClass('has-success');
            repassword.addClass('has-error').removeClass('has-success ');
            $("#register").attr("disabled", "disabled");
            alert("contraseñas no coinciden");

        } else if ((password.val() === repassword.val())
                && password.val().length > 0 && repassword.val().length > 0) {

            password.addClass('has-success').removeClass('has-error');
            repassword.addClass('has-success').removeClass('has-error');

        } else {
            password.removeClass('has-success').removeClass('has-error');
            repassword.removeClass('has-success').removeClass('has-error');
            $("#register").attr("disabled", "disabled");
        }
    });

    $('#modalCreateUser').change(function () {
        if ($('#termscheck').prop('checked')
                && (($('#passwordRegister').val() === $('#rePasswordRegister').val())
                && $('#passwordRegister').val().length > 0
                && $('#rePasswordRegister').val().length > 0)) {
            $("#register").removeAttr("disabled");
        } else {
            $("#register").attr("disabled", "disabled");
        }
    });

    $('#checkbox').change(function () {
        if (this.checked) {
            //ocualtamos lo que no es de country
            $("#street").attr("type", "hidden");
            $("#street_number").attr("type", "hidden");
            $("#floor").attr("type", "hidden");
            $("#letter").attr("type", "hidden");

            $("#noCountry").hide();

            //Mostramos lo que si es de country
            $("#address").attr("type", "text");

            $("#country").show();
            $("#countryLabel").show();
            $("#addressLabel").show();

            //Deshabilitamos el checkbox oculto
            $("#checkboxHidden").attr("disabled", "disabled");
        } else {
            //Mostramos lo que no es de country
            $("#street").attr("type", "text");
            $("#street_number").attr("type", "text");
            $("#floor").attr("type", "text");
            $("#letter").attr("type", "text");

            $("#noCountry").show();

            //Ocultamos lo que si es de country
            $("#address").attr("type", "hidden");

            $("#country").hide();
            $("#countryLabel").hide();
            $("#addressLabel").hide();
        }
    });
});

function dataSubmitSessionForm() {
    $("[data-submit-session-form]").click();
}


text:
/**
 *
 */
package com.perforce.p4java.server;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.perforce.p4java.Log;
import com.perforce.p4java.exception.ConfigException;

// p4ic4idea: accurate exception reporting
import com.perforce.p4java.exception.ZeroconfException;

/**
 * Class designed to help the server factory with zeroconf-based duties.
 * Not intended for direct use by end-users; uses the JmDNS zeroconf package
 * if it's available through the class loader. See the comments attached to
 * ServerFactory.getZeroconfServers for a fuller explanation.<p>
 *
 * @deprecated  As of release 2013.1, ZeroConf is no longer supported by the
 * 				Perforce server 2013.1.
 */
@Deprecated
public class ZeroconfHelper {

	/**
	 * The name of the class we first try to find for zeroconf services.
	 */
	public static final String ZEROCONF_CLASS_NAME = "javax.jmdns.JmDNS";

	/**
	 * The zeroconf type string normally used to register
	 * Perforce servers.
	 */
	// p4ic4idea: final
	public static final String P4D_ZEROCONF_TYPE = "_p4._tcp.local.";

	/**
	 * The JmDNS zeroconf object. Don't touch this unless you absolutely
	 * know what you're doing.
	 */
	private Object jmdns = null;

	/**
	 * Set true if we've already logged a fatal zeroconf error. Used
	 * to stop a flood of annoying messages in the log.
	 */
	private boolean loggedZeroConfError = false;

	/**
	 * We don't want this usable outside the main P4Java server package.
	 */
	protected ZeroconfHelper() {
	}

	/**
	 * Returns true if this instance of P4Java has a suitable zeroconf implementation
	 * available to it. Should probably be used at least once before calling the
	 * getZeroConfServers method to avoid unnecessary overhead.
	 *
	 * @return true iff zeroconf services are available to the server factory.
	 */

	protected boolean isZeroConfAvailable() {
		try {
			/*
			 * We try to load a suitable JmDNS class and take a look to see
			 * if it's usable and has the correct methods.
			 */
			if (jmdns == null) {
				Class<?> jmdnsClass = Class.forName(ZEROCONF_CLASS_NAME);
				if (jmdnsClass != null) {
					Method createMethod = jmdnsClass.getMethod("create", (Class<?>[]) null);

					if (createMethod != null) {
						jmdns = createMethod.invoke(null, (Object[]) null);
					}
				}
			}
			return true;
		} catch (ClassNotFoundException cnfe) {
			return false;
		} catch (Throwable thr) {
			Log.warn("Unexpected exception in ServerFactory.zeroConfAvailable: " + thr.getLocalizedMessage());
			Log.exception(thr);
			loggedZeroConfError = true;
		}
		return false;
	}

	protected List<ZeroconfServerInfo> getZeroconfServers() throws ConfigException {
		if (!isZeroConfAvailable()) {
			// p4ic4idea: accurate exception reporting
			throw new ZeroconfException(
					"Zeroconf services are not configured for this instance of P4Java");
		}

		/*
		 * Most of the complexity here is a result of needing to *not* package
		 * up JmDNS with P4Java -- we have to find it at runtime using the standard
		 * class loader (or whatever we have) and invoke and do everything through
		 * reflection. This is due to Perforce licensing restrictions.
		 *
		 * Note that I assume the reader knows about reflection and JmDNS in what
		 * follows, as comments are a little sparse....
		 */

		List<ZeroconfServerInfo> serverList = new ArrayList<ZeroconfServerInfo>();

		try {
			if (jmdns != null) {
				Method listMethod = jmdns.getClass().getDeclaredMethod("list", String.class);
				if (listMethod != null) {
					Object[] services = (Object[]) listMethod.invoke(jmdns, P4D_ZEROCONF_TYPE);
					if (services != null) {
						Method nameMethod = null;
						Method propMethod = null;
						Method addrMethod = null;
						Method hostNameMethod = null;
						Method portMethod = null;

						for (Object info: services) {
							if (info != null) {
								if (nameMethod == null) {
									nameMethod = info.getClass().getDeclaredMethod(
																	"getName", (Class<?>[]) null);
								}
								if (hostNameMethod == null) {
									hostNameMethod = info.getClass().getDeclaredMethod(
																	"getServer", (Class<?>[]) null);
								}
								if (propMethod == null) {
									propMethod = info.getClass().getDeclaredMethod(
																"getPropertyString", String.class);
								}
								if (addrMethod == null) {
									addrMethod = info.getClass().getDeclaredMethod(
																"getHostAddress", (Class<?>[]) null);
								}
								if (portMethod == null) {
									portMethod = info.getClass().getDeclaredMethod(
											"getPort", (Class<?>[]) null);
								}

								serverList.add(new ZeroconfServerInfo(
											(String) nameMethod.invoke(info, (Object[]) null),
											P4D_ZEROCONF_TYPE,
											(String) propMethod.invoke(info, "description"),
											(String) propMethod.invoke(info, "version"),
											(String) addrMethod.invoke(info, (Object[]) null),
											(String) hostNameMethod.invoke(info, (Object[]) null),
											(Integer) portMethod.invoke(info, (Object[]) null)
									));
							}
						}
					}
				}
			}
		// p4ic4idea: be careful when catching "throwable"
		//} catch (Throwable thr) {
		} catch (Exception thr) {
			if (!loggedZeroConfError) {
				Log.warn("Unexpected exception in ZeroconfHelper.getZeroconfServers: "
						+ thr);
				Log.exception(thr);
				loggedZeroConfError = true;
			}
			// p4ic4diea: include the source error and a more accurate exception
			throw new ZeroconfException("Unexpected exception in ZeroconfHelper.getZeroconfServers: "
					+ thr, thr);
		}

		return serverList;
	}
}


text:
bootstrap_select
================

.. toctree::
   :maxdepth: 4

   bootstrap_select


text:
{-# LANGUAGE OverloadedStrings #-}

module Duckling.Distance.IT.Corpus
  ( corpus
  ) where

import Data.String
import Prelude

import Duckling.Distance.Types
import Duckling.Locale
import Duckling.Resolve
import Duckling.Testing.Types

context :: Context
context = testContext {locale = makeLocale IT Nothing}

corpus :: Corpus
corpus = (context, testOptions, allExamples)

allExamples :: [Example]
allExamples = concat
  [ examples (simple Kilometre 3)
             [ "3 kilometri"
             , "3 chilometri"
             , "3 km"
             , "3km"
             ]
  , examples (simple Kilometre 3.0)
             [ "3,0 km"
             ]
  , examples (simple Mile 8)
             [ "8 miglia"
             ]
  , examples (simple Metre 9)
             [ "9 metri"
             , "9m"
             ]
  , examples (simple Centimetre 2)
             [ "2cm"
             , "2 centimetri"
             ]
  ]


text:
#ifndef BOOST_HANA_FWD_SET_HPP
#define BOOST_HANA_FWD_SET_HPP

#include <boost/hana/config.hpp>
#include <boost/hana/fwd/core/to.hpp>
#include <boost/hana/fwd/core/make.hpp>
#include <boost/hana/fwd/erase_key.hpp>

namespace boost { namespace hana {
    //! @ingroup group-datatypes
    //! Basic unordered container requiring unique, `Comparable` and
    //! `Hashable` keys.
    //!
    //! A set is an unordered container that can hold heterogeneous keys.
    //! A set requires (and ensures) that no duplicates are present when
    //! inserting new keys.
    //!
    //! @note
    //! The actual representation of a `hana::set` is implementation-defined.
    //! In particular, one should not take for granted the order of the
    //! template parameters and the presence of any additional constructors
    //! or assignment operators than what is documented. The canonical way of
    //! creating a `hana::set` is through `hana::make_set`. More details
    //! [in the tutorial](@ref tutorial-containers-types).
    //!
    //!
    //! Modeled concepts
    //! ----------------
    //! 1. `Comparable`\n
    //! Two sets are equal iff they contain the same elements, regardless of
    //! the order.
    //! @include example/set/comparable.cpp
    //!
    //! 2. Foldable\n
    //! Folding a set is equivalent to folding the sequence of its values.
    //! However, note that the values are not required to be in any specific
    //! order, so using the folds provided here with an operation that is not
    //! both commutative and associative will yield non-deterministic behavior.
    //! @include example/set/foldable.cpp
    //!
    //! 3. Searchable\n
    //! The elements in a set act as both its keys and its values. Since the
    //! elements of a set are unique, searching for an element will return
    //! either the only element which is equal to the searched value, or
    //! `nothing`. Also note that `operator[]` can be used instead of the
    //! `at_key` function.
    //! @include example/set/searchable.cpp
    //!
    //!
    //! Conversion from any `Foldable`
    //! ------------------------------
    //! Any `Foldable` structure can be converted into a `hana::set` with
    //! `to<set_tag>`. The elements of the structure must all be compile-time
    //! `Comparable`. If the structure contains duplicate elements, only
    //! the first occurence will appear in the resulting set. More
    //! specifically, conversion from a `Foldable` is equivalent to
    //! @code
    //!     to<set_tag>(xs) == fold_left(xs, make_set(), insert)
    //! @endcode
    //!
    //! __Example__
    //! @include example/set/to.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    template <typename implementation_defined>
    struct set {
        //! Default-construct a set. This constructor only exists when all the
        //! elements of the set are default-constructible.
        constexpr set() = default;

        //! Copy-construct a set from another set. This constructor only
        //! exists when all the elements of the set are copy-constructible.
        constexpr set(set const& other) = default;

        //! Move-construct a set from another set. This constructor only
        //! exists when all the elements of the set are move-constructible.
        constexpr set(set&& other) = default;

        //! Equivalent to `hana::equal`
        template <typename X, typename Y>
        friend constexpr auto operator==(X&& x, Y&& y);

        //! Equivalent to `hana::not_equal`
        template <typename X, typename Y>
        friend constexpr auto operator!=(X&& x, Y&& y);

        //! Equivalent to `hana::at_key`
        template <typename Key>
        constexpr decltype(auto) operator[](Key&& key);
    };
#else
    template <typename ...Xs>
    struct set;
#endif

    //! Tag representing the `hana::set` container.
    //! @relates hana::set
    struct set_tag { };

    //! Function object for creating a `hana::set`.
    //! @relates hana::set
    //!
    //! Given zero or more values `xs...`, `make<set_tag>` returns a `set`
    //! containing those values. The values must all be compile-time
    //! `Comparable`, and no duplicate values may be provided. To create
    //! a `set` from a sequence with possible duplicates, use `to<set_tag>`
    //! instead.
    //!
    //!
    //! Example
    //! -------
    //! @include example/set/make.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    template <>
    constexpr auto make<set_tag> = [](auto&& ...xs) {
        return set<implementation_defined>{forwarded(xs)...};
    };
#endif

    //! Equivalent to `make<set_tag>`; provided for convenience.
    //! @relates hana::set
    //!
    //!
    //! Example
    //! -------
    //! @include example/set/make.cpp
    BOOST_HANA_INLINE_VARIABLE constexpr auto make_set = make<set_tag>;

    //! Insert an element in a `hana::set`.
    //! @relates hana::set
    //!
    //! If the set already contains an element that compares equal, then
    //! nothing is done and the set is returned as is.
    //!
    //!
    //! @param set
    //! The set in which to insert a value.
    //!
    //! @param element
    //! The value to insert. It must be compile-time `Comparable`.
    //!
    //!
    //! Example
    //! -------
    //! @include example/set/insert.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    constexpr auto insert = [](auto&& set, auto&& element) {
        return tag-dispatched;
    };
#endif

    //! Remove an element from a `hana::set`.
    //! @relates hana::set
    //!
    //! Returns a new set containing all the elements of the original,
    //! except the one comparing `equal` to the given element. If the set
    //! does not contain such an element, a new set equal to the original
    //! set is returned.
    //!
    //!
    //! @param set
    //! The set in which to remove a value.
    //!
    //! @param element
    //! The value to remove. It must be compile-time `Comparable`.
    //!
    //!
    //! Example
    //! -------
    //! @include example/set/erase_key.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    constexpr auto erase_key = [](auto&& set, auto&& element) {
        return tag-dispatched;
    };
#endif

    //! Returns the union of two sets.
    //! @relates hana::set
    //!
    //! Given two sets `xs` and `ys`, `union_(xs, ys)` is a new set containing
    //! all the elements of `xs` and all the elements of `ys`, without
    //! duplicates. For any object `x`, the following holds: `x` is in
    //! `hana::union_(xs, ys)` if and only if `x` is in `xs` or `x` is in `ys`.
    //!
    //!
    //! @param xs, ys
    //! Two sets to compute the union of.
    //!
    //!
    //! Example
    //! -------
    //! @include example/set/union.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    constexpr auto union_ = [](auto&& xs, auto&& ys) {
        return tag-dispatched;
    };
#endif

    //! Returns the intersection of two sets.
    //! @relates hana::set
    //!
    //! Given two sets `xs` and `ys`, `intersection(xs, ys)` is a new set
    //! containing exactly those elements that are present both in `xs` and
    //! in `ys`.
    //! In other words, the following holds for any object `x`:
    //! @code
    //!     x ^in^ intersection(xs, ys) if and only if x ^in^ xs && x ^in^ ys
    //! @endcode
    //!
    //!
    //! @param xs, ys
    //! Two sets to intersect.
    //!
    //!
    //! Example
    //! -------
    //! @include example/set/intersection.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    constexpr auto intersection = [](auto&& xs, auto&& ys) {
        return tag-dispatched;
    };
#endif
    //! Equivalent to `to<set_tag>`; provided for convenience.
    //! @relates hana::set
    constexpr auto to_set = to<set_tag>;

    //! Returns the set-theoretic difference of two sets.
    //! @relates hana::set
    //!
    //! Given two sets `xs` and `ys`, `difference(xs, ys)` is a new set
    //! containing all the elements of `xs` that are _not_ contained in `ys`.
    //! For any object `x`, the following holds:
    //! @code
    //!     x ^in^ difference(xs, ys) if and only if x ^in^ xs && !(x ^in^ ys)
    //! @endcode
    //!
    //!
    //! This operation is not commutative, i.e. `difference(xs, ys)` is not
    //! necessarily the same as `difference(ys, xs)`. Indeed, consider the
    //! case where `xs` is empty and `ys` isn't. Then, `difference(xs, ys)`
    //! is empty but `difference(ys, xs)` is equal to `ys`. For the symmetric
    //! version of this operation, see `symmetric_difference`.
    //!
    //!
    //! @param xs
    //! A set param to remove values from.
    //!
    //! @param ys
    //! The set whose values are removed from `xs`.
    //!
    //!
    //! Example
    //! -------
    //! @include example/set/difference.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
    constexpr auto difference = [](auto&& xs, auto&& ys) {
        return tag-dispatched;
};
#endif

    //! Returns the symmetric set-theoretic difference of two sets.
    //! @relates hana::set
    //!
    //! Given two sets `xs` and `ys`, `symmetric_difference(xs, ys)` is a new
    //! set containing all the elements of `xs` that are not contained in `ys`,
    //! and all the elements of `ys` that are not contained in `xs`. The
    //! symmetric difference of two sets satisfies the following:
    //! @code
    //!     symmetric_difference(xs, ys) == union_(difference(xs, ys), difference(ys, xs))
    //! @endcode
    //!
    //!
    //! @param xs, ys
    //! Two sets to compute the symmetric difference of.
    //!
    //!
    //! Example
    //! -------
    //! @include example/set/symmetric_difference.cpp
#ifdef BOOST_HANA_DOXYGEN_INVOKED
constexpr auto symmetric_difference = [](auto&& xs, auto&& ys) {
        return tag-dispatched;
    };
#endif

}} // end namespace boost::hana

#endif // !BOOST_HANA_FWD_SET_HPP


text:
#import "NSMutableOrderedSet.h"

@interface NSMutableOrderedSet (NSKeyValueSorting)
- (void)sortUsingDescriptors:(id)arg1;
@end


text:
package org.jerlang.type;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;

/**
 * References are Erlang objects with exactly two properties:
 *
 * * They can be created by a program (using make_ref/0), and,
 * * They can be compared for equality.
 *
 * Erlang references are unique, the system guarantees that no two
 * references created by different calls to make_ref will ever match.
 *
 * Source: http://www.erlang.org/course/advanced.html#refs
 */
public class Reference extends Term {

    private static final AtomicLong counter = new AtomicLong();

    private final long id;

    public Reference() {
        this.id = counter.incrementAndGet();
    }

    @Override
    public boolean equals(Object object) {
        if (object instanceof Reference) {
            Reference other = (Reference) object;
            return id == other.id;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public Reference toReference() {
        return this;
    }

    @Override
    public String toString() {
        return "#Ref<0." + id + ".0>";
    }

}


text:
For use with Kali Linux. Custom bash scripts used to automate various pentesting tasks.

# Licence

This project is licensed under the ```BSD 3-clause "New" or "Revised" License```. For more information please see the licence file

### Download, setup & usage
* git clone git://github.com/leebaird/discover.git /opt/discover/
* All scripts must be ran from this location.
* cd /opt/discover/
* ./setup.sh
* ./discover.sh

```
RECON
1.  Domain
2.  Person
3.  Parse salesforce

SCANNING
4.  Generate target list
5.  CIDR
6.  List
7.  IP or domain

WEB
8.  Open multiple tabs in Iceweasel
9.  Nikto
10. SSL

MISC
11. Crack WiFi
12. Parse XML
13. Start a Metasploit listener
14. Update
15. Exit
```
## RECON
### Domain
```
RECON

1.  Passive
2.  Active
3.  Previous menu
```

* Passive combines goofile, goog-mail, goohost, theHarvester, Metasploit, dnsrecon, URLCrazy, Whois and multiple webistes.
* Active combines Nmap, dnsrecon, Fierce, lbd, WAF00W, traceroute and Whatweb.

### Person
```
RECON

First name:
Last name:
```

* Combines info from multiple websites.

### Parse salesforce
```
Create a free account at salesforce (https://connect.data.com/login).
Perform a search on your target company > select the company name > see all.
Copy the results into a new file.

Enter the location of your list:
```

* Gather names and positions into a clean list.

## SCANNING
### Generate target list
```
SCANNING

1.  Local area network
2.  NetBIOS
3.  netdiscover
4.  Ping sweep
5.  Previous menu
```

* Use different tools to create a target list including Angry IP Scanner, arp-scan, netdiscover and nmap pingsweep.

### CIDR, List, IP or domain
```
Type of scan:

1.  External
2.  Internal
3.  Previous menu
```

* External scan will set the nmap source port to 53 and the max-rrt-timeout to 1500ms.
* Internal scan will set the nmap source port to 88 and the max-rrt-timeout to 500ms.
* Nmap is used to perform host discovery, port scanning, service enumeration and OS identification.
* Matching nmap scripts are used for additional enumeration.
* Matching Metasploit auxiliary modules are also leveraged.

## WEB
### Open multiple tabs in Iceweasel
```
Open multiple tabs in Iceweasel with:

1.  List
2.  Directories from a domain's robot.txt.
3.  Previous menu
```

* Use a list containing IPs and/or URLs.
* Use wget to pull a domain's robot.txt file, then open all of the directories.

### Nikto
```
Run multiple instances of Nikto in parallel.

1.  List of IPs.
2.  List of IP:port.
3.  Previous menu
```
### SSL
```
Check for SSL certificate issues.

Enter the location of your list:
```

* Use sslscan and sslyze to check for SSL/TLS certificate issues.

## MISC
### Crack WiFi

* Crack wireless networks.

### Parse XML
```
Parse XML to CSV.

1.  Burp (Base64)
2.  Nessus
3.  Nexpose
4.  Nmap
5.  Qualys
6.  Previous menu
```

### Start a Metasploit listener

* Setup a multi/handler with a windows/meterpreter/reverse_tcp payload on port 443.

### Update

* Use to update Kali Linux, Discover scripts, various tools and the locate database.


text:
#include "elektra.h"
#include "elektra/conversion.h"
#include "elektra/types.h"
#include "kdberrors.h"
#include "kdbhelper.h"
#include "kdblogger.h"
#include "kdbprivate.h"
#include <stdlib.h>

#ifdef __cplusplus
extern "C" {
#endif

static void defaultFatalErrorHandler (ElektraError * error)
{
	ELEKTRA_LOG_DEBUG ("FATAL ERROR [%s]: %s", error->code, error->description);
	elektraErrorReset (&error);
	exit (EXIT_FAILURE);
}

static void insertDefaults (KeySet * config, const Key * parentKey, KeySet * defaults);
static bool checkHighlevelContract (const char * application, KeySet * contract, ElektraError ** error);

/**
 * \defgroup highlevel High-level API
 * @{
 */

/**
 * Initializes a new Elektra instance.
 *
 * To free the memory allocated by this function call elektraClose(),
 * once you are done using this instance.
 *
 * @param application 	Your application's base name. The the simplest version for this string is
 * 			"/sw/org/<appname>/#0/current", where '<appname>' is a unique name for
 * 			your application. For more information see the man-page elektra-key-names(7).
 * @param defaults	A KeySet containing default values. If you pass NULL, trying to read
 * 			a non-existent value will cause a fatal error. It is recommended, to
 * 			only pass NULL, if you are using a specification, which provides
 * 			default values inside of the KDB.
 * 			If a key in this KeySet doesn't have a value, we will use the value of the "default"
 * 			metakey of this key.
 * @param contract      Will be passed to kdbEnsure() as the contract. If it is NULL, kdbEnsure() won't be called.
 * 			Unlike @p defaults, this KeySet is consumed and must not be used afterwards.
 * @param error		If an error occurs during initialization of the Elektra instance, this pointer
 * 			will be used to report the error.
 *
 * @return An Elektra instance initialized for the application (free with elektraClose()).
 *
 * @see elektraClose
 * @see kdbEnsure
 */
Elektra * elektraOpen (const char * application, KeySet * defaults, KeySet * contract, ElektraError ** error)
{
	Key * const parentKey = keyNew (application, KEY_END);
	KDB * const kdb = kdbOpen (parentKey);

	if (kdb == NULL)
	{
		*error = elektraErrorFromKey (parentKey);
		keyDel (parentKey);
		return NULL;
	}

	int ignoreRequireInHelpMode = 0;

	if (contract != NULL)
	{
		Key * contractCut = keyNew ("system/elektra/highlevel", KEY_END);
		KeySet * highlevelContract = ksCut (contract, contractCut);

		if (ksGetSize (highlevelContract) > 0)
		{
			if (ksLookupByName (highlevelContract, "system/elektra/highlevel/helpmode/ignore/require", 0) != NULL)
			{
				ignoreRequireInHelpMode = 1;
			}

			if (!checkHighlevelContract (application, highlevelContract, error))
			{
				keyDel (contractCut);
				ksDel (highlevelContract);
				ksDel (contract); // consume contract, like kdbEnsure would

				kdbClose (kdb, parentKey);
				keyDel (parentKey);

				return NULL;
			}
		}

		keyDel (contractCut);
		ksDel (highlevelContract);

		ksAppendKey (contract, keyNew ("system/elektra/ensure/plugins/global/spec", KEY_VALUE, "remount", KEY_END));
		ksAppendKey (contract,
			     keyNew ("system/elektra/ensure/plugins/global/spec/config/conflict/get", KEY_VALUE, "ERROR", KEY_END));
		ksAppendKey (contract,
			     keyNew ("system/elektra/ensure/plugins/global/spec/config/conflict/set", KEY_VALUE, "ERROR", KEY_END));
		ksAppendKey (contract, keyNew ("system/elektra/ensure/plugins/global/spec/config/missing/log", KEY_VALUE, "1", KEY_END));

		const int kdbEnsureResult = kdbEnsure (kdb, contract, parentKey);

		if (kdbEnsureResult == 1)
		{
			const char * reason = keyString (keyGetMeta (parentKey, "error/reason"));
			*error = elektraErrorEnsureFailed (reason);

			kdbClose (kdb, parentKey);
			keyDel (parentKey);
			return NULL;
		}
		else if (kdbEnsureResult != 0)
		{
			*error = elektraErrorFromKey (parentKey);

			kdbClose (kdb, parentKey);
			keyDel (parentKey);
			return NULL;
		}
	}

	KeySet * const config = ksNew (0, KS_END);
	if (defaults != NULL)
	{
		insertDefaults (config, parentKey, defaults);
	}

	const int kdbGetResult = kdbGet (kdb, config, parentKey);

	if (kdbGetResult == -1)
	{
		Key * helpKey = ksLookupByName (config, "proc/elektra/gopts/help", 0);
		const Key * missingKeys = keyGetMeta (parentKey, "logs/spec/missing");
		if (ignoreRequireInHelpMode == 1 && helpKey != NULL && missingKeys != NULL)
		{
			// proc/elektra/gopts/help was set -> we are in help mode
			// logs/spec/missing exists on parentKey -> spec detected missing keys
			// we ensured that spec uses conflict/get = ERROR -> the error in kdbGet must be from spec
			// --> we are in the error case that should be ignored

			// BUT: anything other than helpKey may be incorrect
			// and only helpKey should be used anyway
			// so create a new config KeySet
			Key * helpKeyDup = keyDup (helpKey);
			ksClear (config);
			ksAppendKey (config, helpKeyDup);
		}
		else
		{
			*error = elektraErrorFromKey (parentKey);

			ksDel (config);
			kdbClose (kdb, parentKey);
			keyDel (parentKey);
			return NULL;
		}
	}

	Elektra * const elektra = elektraCalloc (sizeof (struct _Elektra));
	elektra->kdb = kdb;
	elektra->parentKey = parentKey;
	elektra->parentKeyLength = keyGetNameSize (parentKey) - 1;
	elektra->config = config;
	elektra->lookupKey = keyNew (NULL, KEY_END);
	elektra->fatalErrorHandler = &defaultFatalErrorHandler;
	elektra->defaults = ksDup (defaults);

	return elektra;
}

Elektra * ELEKTRA_SYMVER (elektraOpen, v1) (const char * application, KeySet * defaults, ElektraError ** error)
{
	return elektraOpen (application, defaults, NULL, error);
}

ELEKTRA_SYMVER_DECLARE ("libelektra_0.8", elektraOpen, v1)

/**
 * Promote an ElektraError to fatal and call the fatal error handler.
 *
 * @param elektra    Elektra instance whose fatal error handler shall be used.
 * @param fatalError The error that will be raised.
 */
void elektraFatalError (Elektra * elektra, ElektraError * fatalError)
{
	elektra->fatalErrorHandler (fatalError);
}

/**
 * This function is only intended for use with code-generation.
 *
 * It looks for the key proc/elektra/gopts/help (absolute name) created by gopts,
 * and returns it if found.
 *
 * @param elektra The Elektra instance to check
 *
 * @return the help key if found, NULL otherwise
 *   The pointer returned may become invalid, when any `elektraSet*()` function or
 *   any other function that modifies the state of @p elektra is called.
 *   It will always become invalid, when elektraClose() is called on @p elektra.
 */
Key * elektraHelpKey (Elektra * elektra)
{
	return ksLookupByName (elektra->config, "proc/elektra/gopts/help", 0);
}

/**
 * Sets the fatal error handler that will be called, whenever a fatal error occurs.
 *
 * Errors occurring in a function, which does not take a pointer to ElektraError,
 * are always considered fatal.
 *
 * If this function returns, i.e. it does not call exit() or interrupt the thread of
 * execution in some other way, the behaviour of the function from which the error
 * originated is generally undefined.
 *
 * @param elektra           An Elektra instance.
 * @param fatalErrorHandler The error handler that will be used henceforth.
 */
void elektraFatalErrorHandler (Elektra * elektra, ElektraErrorHandler fatalErrorHandler)
{
	elektra->fatalErrorHandler = fatalErrorHandler;
}

/**
 * Releases all resources used by the given elektra instance. The elektra instance must not be used anymore after calling this.
 * @param elektra An Elektra instance.
 */
void elektraClose (Elektra * elektra)
{
	kdbClose (elektra->kdb, elektra->parentKey);
	keyDel (elektra->parentKey);
	ksDel (elektra->config);
	keyDel (elektra->lookupKey);

	if (elektra->resolvedReference != NULL)
	{
		elektraFree (elektra->resolvedReference);
	}

	if (elektra->defaults != NULL)
	{
		ksDel (elektra->defaults);
	}

	elektraFree (elektra);
}

/**
 * @}
 */

// Private definitions

KDBType KDB_TYPE_STRING = "string";
KDBType KDB_TYPE_BOOLEAN = "boolean";
KDBType KDB_TYPE_CHAR = "char";
KDBType KDB_TYPE_OCTET = "octet";
KDBType KDB_TYPE_SHORT = "short";
KDBType KDB_TYPE_UNSIGNED_SHORT = "unsigned_short";
KDBType KDB_TYPE_LONG = "long";
KDBType KDB_TYPE_UNSIGNED_LONG = "unsigned_long";
KDBType KDB_TYPE_LONG_LONG = "long_long";
KDBType KDB_TYPE_UNSIGNED_LONG_LONG = "unsigned_long_long";
KDBType KDB_TYPE_FLOAT = "float";
KDBType KDB_TYPE_LONG_DOUBLE = "long_double";
KDBType KDB_TYPE_DOUBLE = "double";
KDBType KDB_TYPE_ENUM = "enum";

void elektraSetLookupKey (Elektra * elektra, const char * name)
{
	keySetName (elektra->lookupKey, keyName (elektra->parentKey));
	keyAddName (elektra->lookupKey, name);
}

void elektraSetArrayLookupKey (Elektra * elektra, const char * name, kdb_long_long_t index)
{
	elektraSetLookupKey (elektra, name);
	char arrayPart[ELEKTRA_MAX_ARRAY_SIZE];
	elektraWriteArrayNumber (arrayPart, index);
	keyAddName (elektra->lookupKey, arrayPart);
}

void elektraSaveKey (Elektra * elektra, Key * key, ElektraError ** error)
{
	int ret = 0;
	do
	{
		ksAppendKey (elektra->config, key);

		ret = kdbSet (elektra->kdb, elektra->config, elektra->parentKey);
		if (ret == -1)
		{
			ElektraError * kdbSetError = elektraErrorFromKey (elektra->parentKey);
			if (strcmp (elektraErrorCode (kdbSetError), ELEKTRA_ERROR_CONFLICTING_STATE) != 0)
			{
				*error = kdbSetError;
				return;
			}

			elektraErrorReset (&kdbSetError);

			Key * problemKey = ksCurrent (elektra->config);
			if (problemKey != NULL)
			{
				ELEKTRA_LOG_DEBUG ("problemKey: %s\n", keyName (problemKey));
			}

			key = keyDup (key);
			kdbGet (elektra->kdb, elektra->config, elektra->parentKey);
		}
	} while (ret == -1);
}

void insertDefaults (KeySet * config, const Key * parentKey, KeySet * defaults)
{
	ksRewind (defaults);
	for (Key * key = ksNext (defaults); key != NULL; key = ksNext (defaults))
	{
		Key * const dup = keyDup (key);
		const char * name = keyName (key);
		keySetName (dup, keyName (parentKey));
		keyAddName (dup, name);

		if (strlen (keyString (dup)) == 0)
		{
			const Key * defaultMeta = keyGetMeta (dup, "default");
			if (defaultMeta != NULL)
			{
				keySetString (dup, keyString (defaultMeta));
			}
		}

		ksAppendKey (config, dup);
	}
}

static bool minimalValidation (const char * application)
{
	Key * parent = keyNew ("system/elektra/mountpoints", KEY_END);
	KDB * kdb = kdbOpen (parent);
	KeySet * mountpoints = ksNew (0, KS_END);
	if (kdbGet (kdb, mountpoints, parent) < 0)
	{
		ksDel (mountpoints);
		kdbClose (kdb, parent);
		keyDel (parent);
		return false;
	}

	char * specName = elektraFormat ("spec%s", application);
	Key * lookup = keyNew ("system/elektra/mountpoints", KEY_END);
	keyAddBaseName (lookup, specName);
	elektraFree (specName);

	if (ksLookup (mountpoints, lookup, 0) == NULL)
	{
		keyDel (lookup);

		ksDel (mountpoints);
		kdbClose (kdb, parent);
		keyDel (parent);
		return false;
	}

	keyDel (lookup);

	lookup = keyNew ("system/elektra/mountpoints", KEY_END);
	keyAddBaseName (lookup, application);

	if (ksLookup (mountpoints, lookup, 0) == NULL)
	{
		keyDel (lookup);

		ksDel (mountpoints);
		kdbClose (kdb, parent);
		keyDel (parent);
		return false;
	}
	keyDel (lookup);

	ksDel (mountpoints);
	kdbClose (kdb, parent);
	keyDel (parent);

	return true;
}

bool checkHighlevelContract (const char * application, KeySet * contract, ElektraError ** error)
{
	Key * validationKey = ksLookupByName (contract, "system/elektra/highlevel/validation", 0);
	if (validationKey != NULL)
	{
		if (strcmp (keyString (validationKey), "minimal") == 0 && !minimalValidation (application))
		{
			*error = elektraErrorMinimalValidationFailed (application);
			return false;
		}
	}

	return true;
}

#ifdef __cplusplus
};
#endif


text:
MAKEFLAGS = -s

all:
	go run ./../../bin/generate-lr-parser -o grammar.go grammar.lr

clean:
	rm -f grammar.go


text:
package com.vmware.vim25;

/**
@author Steve Jin (sjin@vmware.com)
*/

public class VirtualMachineCdromInfo extends VirtualMachineTargetInfo
{
}


text:
const { EventEmitter } = require("events");
const { app: { DEFAULT_USERNAME } } = require("../config");
const { getPlayableSets, getLatestReleasedSet, getBoosterRulesVersion } = require("./data");
const { getVersion } = require("./mtgjson");

// All sockets currently connected to the server.
let allSocks = [];

function broadcastNumUsers() {
  Sock.broadcast("set", {
    numUsers: allSocks.length
  });
}

function message(msg) {
  const [type, data] = JSON.parse(msg);
  this.emit(type, data, this);
}

const mixins = {
  err(msg) {
    this.send("error", msg);
  },
  send(type, data) {
    this.ws.send(JSON.stringify([type, data]));
  },
  exit() {
    this.emit("exit", this);
  }
};

class Sock extends EventEmitter {
  constructor(ws) {
    super();
    this.ws = ws;
    const {id = "", name = DEFAULT_USERNAME} = ws.request._query;
    this.id = id.slice(0, 25);
    this.name = name.slice(0, 15);

    for (let key in mixins)
      this[key] = mixins[key].bind(this);

    this.send("set", {
      availableSets: getPlayableSets(),
      latestSet: getLatestReleasedSet(),
      mtgJsonVersion: getVersion(),
      boosterRulesVersion: getBoosterRulesVersion()
    });
    allSocks.push(this);
    broadcastNumUsers();
    ws.on("message", message.bind(this));
    ws.on("leave", this.exit);
    ws.on("close", this.exit);

    // `this.exit` may be called for other reasons than the socket closing.
    let sock = this;
    ws.on("close", () => {
      let index = allSocks.indexOf(sock);
      if (index !== -1) {
        allSocks.splice(index, 1);
        broadcastNumUsers();
      }
    });
  }
  mixin(h) {
    h.sock = this;
    this.h = h;
    for (const key in mixins) {
      h[key] = this[key];
    }
  }
  static broadcast(...args) {
    allSocks.forEach((sock) => sock.send(...args));
  }
}
module.exports = Sock;


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

namespace WinSync.Service
{
    public class FileConflictInfo : ElementConflictInfo
    {
        public FileConflictInfo(SyncFileInfo syncFileInfo, ConflictType type, int conflictPath, string context, string message, Exception exception)
            : base(syncFileInfo, type, conflictPath, context, message, exception) {}
    }
}