text:
package org.mmtk.utility.deque;

import org.mmtk.plan.TransitiveClosure;
import org.mmtk.utility.Constants;
import org.mmtk.vm.VM;

import org.vmmagic.pragma.*;
import org.vmmagic.unboxed.*;

/**
 * This class is a combination of a Deque and a TraceStep, designed to include
 * intelligent processing of child references as objects are scanned.
 *
 * @see org.mmtk.plan.TransitiveClosure
 */
@Uninterruptible
public abstract class ObjectReferenceBuffer extends TransitiveClosure implements Constants {
  /****************************************************************************
   *
   * Instance variables
   */
  private final ObjectReferenceDeque values;

  /****************************************************************************
   *
   * Initialization
   */

  /**
   * Constructor
   *
   * @param name The name of the underlying deque.
   * @param queue The shared deque that is used.
   */
  public ObjectReferenceBuffer(String name, SharedDeque queue) {
    values = new ObjectReferenceDeque(name, queue);
  }

  /**
   * Trace an edge during GC.
   *
   * @param source The source of the reference.
   * @param slot The location containing the object reference.
   */
  @Inline
  public final void processEdge(ObjectReference source, Address slot) {
    ObjectReference object = VM.activePlan.collector().loadObjectReference(slot);
    process(object);
  }

  /**
   * This is the method that ensures
   *
   * @param object The object to process.
   */
  protected abstract void process(ObjectReference object);

  /**
   * Process each of the child objects for the passed object.
   *
   * @param object The object to process the children of.
   */
  @Inline
  public final void processChildren(ObjectReference object) {
    VM.scanning.scanObject(this, object);
  }

  /**
   * Pushes an object onto the queue, forcing an inlined sequence.
   *
   * @param object The object to push.
   */
  @Inline
  public final void push(ObjectReference object) {
    values.push(object);
  }

  /**
   * Pushes an object onto the queue, forcing an out of line sequence.
   *
   * @param object The object to push.
   */
  @Inline
  public final void pushOOL(ObjectReference object) {
    values.pushOOL(object);
  }

  /**
   * Retrives an object.
   *
   * @return The object retrieved.
   */
  @Inline
  public final ObjectReference pop() {
    return values.pop();
  }

  /**
   * Flushes all local state back to the shared queue.
   */
  public final void flushLocal() {
    values.flushLocal();
  }
}


text:
import time
import unittest
from chirp.stream import looper

class MockLooper(looper.Looper):

    # How many times _loop_once() has been called.
    loop_count = 0

    # Set to true when _begin_looping() has been called.
    begin_looping_called = False

    # Set to true when _done_looping() has been called.
    done_looping_called = False

    # If true, always raise an exception when _loop_once() or _done_looping()
    # is called.
    raise_exception = False

    def _begin_looping(self):
        self.begin_looping_called = True
        if self.raise_exception:
            raise ValueError("Test of exception handling for _begin_looping")

    def _loop_once(self):
        self.loop_count += 1
        if self.raise_exception:
            raise ValueError("Test of exception handling for _loop_once")

    def _done_looping(self):
        self.done_looping_called = True
        if self.raise_exception:
            raise ValueError("Test of exception handling for _done_looping")

class LooperTestCase(unittest.TestCase):

    def test_basic(self):
        # Make sure we can spin up a looper in a thread, then stop it
        # and wait for it to terminate.
        lpr = MockLooper()
        lpr.loop_in_thread()
        lpr.wait_until_looped_once()
        lpr.stop()
        lpr.wait()
        # Make sure the loop actually ran.
        self.assertTrue(lpr.loop_count > 0)
        # Make sure the begin and done hooks were called.
        self.assertTrue(lpr.begin_looping_called)
        self.assertTrue(lpr.done_looping_called)

    def test_exception_handling(self):
        # Test that exceptions are managed properly.
        lpr = MockLooper()
        lpr.raise_exception = True
        start_t = time.time()
        lpr.loop_in_thread()
        lpr.wait_until_looped_once()
        lpr.stop()
        lpr.wait()
        end_t = time.time()

        # Check that the loop ran as expected.
        self.assertTrue(lpr.loop_count > 0)
        self.assertTrue(lpr.begin_looping_called)
        self.assertTrue(lpr.done_looping_called)
        # Check that we successfully trapped some exceptions.
        self.assertTrue(len(lpr.trapped_exceptions) > 0)
        # Check that the trapped exceptions have the correct type
        # and have sane timestamps.
        for when, what in lpr.trapped_exceptions:
            self.assertTrue(start_t <= when and when <= end_t)
            self.assertTrue(isinstance(what, ValueError))

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

redpajama_set_name: RedPajamaGithub


text:
package io.joshworks.snappy.it.util;

import io.joshworks.snappy.ext.ServerData;
import io.joshworks.snappy.ext.SnappyExtension;
import io.joshworks.snappy.property.AppProperties;

/**
 * Created by Josh Gontijo on 3/26/17.
 */
public class DummyExtension implements SnappyExtension {

    public boolean startedCalled = false;
    public boolean stopCalled = false;
    public String valueFromProperties;

    @Override
    public void onStart(ServerData config) {
        startedCalled = true;
        valueFromProperties = AppProperties.get("dummy.value").get();
    }

    @Override
    public void onShutdown() {
        stopCalled = true;
    }

    @Override
    public String name() {
        return "DUMMY";
    }
}


text:
namespace google_breakpad {

// Default functor to compare keys.
template<typename Key>
class DefaultCompare {
 public:
  int operator()(const Key &k1, const Key &k2) const {
    if (k1 < k2) return -1;
    if (k1 == k2) return 0;
    return 1;
  }
};

template<typename Key, typename Value, typename Compare = DefaultCompare<Key> >
class StaticMap {
 public:
  typedef StaticMapIterator<Key, Value, Compare> iterator;
  typedef StaticMapIterator<Key, Value, Compare> const_iterator;

  StaticMap() : raw_data_(0),
                num_nodes_(0),
                offsets_(0),
                compare_() { }

  explicit StaticMap(const char* raw_data);

  inline bool empty() const { return num_nodes_ == 0; }
  inline unsigned int size() const { return num_nodes_; }

  // Return iterators.
  inline iterator begin() const { return IteratorAtIndex(0); }
  inline iterator last() const { return IteratorAtIndex(num_nodes_ - 1); }
  inline iterator end() const { return IteratorAtIndex(num_nodes_); }
  inline iterator IteratorAtIndex(int index) const {
    return iterator(raw_data_, index);
  }

  // Lookup operations.
  iterator find(const Key &k) const;

  // lower_bound(k) searches in a sorted range for the first element that has a
  // key not less than the argument k.
  iterator lower_bound(const Key &k) const;

  // upper_bound(k) searches in a sorted range for the first element that has a
  // key greater than the argument k.
  iterator upper_bound(const Key &k) const;

  // Checks if the underlying memory data conforms to the predefined pattern:
  // first check the number of nodes is non-negative,
  // then check both offsets and keys are strictly increasing (sorted).
  bool ValidateInMemoryStructure() const;

 private:
  const Key GetKeyAtIndex(int i) const;

  // Start address of a raw memory chunk with serialized data.
  const char* raw_data_;

  // Number of nodes in the static map.
  int32_t num_nodes_;

  // Array of offset addresses for stored values.
  // For example:
  // address_of_i-th_node_value = raw_data_ + offsets_[i]
  const u_int32_t* offsets_;

  // keys_[i] = key of i_th node
  const Key* keys_;

  Compare compare_;
};

}  // namespace google_breakpad

#endif  // PROCESSOR_STATIC_MAP_H__


text:
package com.github.lindenb.jvarkit.tools.phylo;

import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import htsjdk.samtools.util.CloserUtil;
import htsjdk.variant.variantcontext.Allele;
import htsjdk.variant.variantcontext.Genotype;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.vcf.VCFHeader;

import com.github.lindenb.jvarkit.util.AbstractCommandLineProgram;
import com.github.lindenb.jvarkit.util.Counter;
import com.github.lindenb.jvarkit.util.vcf.VCFUtils;
import com.github.lindenb.jvarkit.util.vcf.VcfIterator;
import com.github.lindenb.jvarkit.util.vcf.bdb.AlleleBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.CursorConfig;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.Transaction;

public class VcfPhyloTree extends AbstractCommandLineProgram
	{
	private enum GType
		{
		HOM_REF,
		HOM_ALT,
		HET
		//,UNAVAILABLE
		}

	/** position on genome */
	private static class ChromPosRef
		{
		String chrom;
		int pos1;
		Allele ref;
		}

	private static class Call
		{
		int sample_index;
		GType gtype;
		int depth;
		int qual;
		}

	private static class CallBinding
		extends TupleBinding<Call>
		{
		private final GType[] GTYPES=GType.values();
		@Override
		public Call entryToObject(TupleInput in) {
			int sample_index= in.readInt();
			if(sample_index==-1) return null;
			Call call= new Call();
			call.sample_index=sample_index;
			call.gtype=GTYPES[(int)in.readByte()];
			call.depth = in.readInt();
			call.qual = in.readInt();
			return call;
			}
		@Override
		public void objectToEntry(Call g, TupleOutput w)
			{
			if(g==null || g.sample_index==-1)
				{
				w.writeInt(-1);
				return;
				}
			w.writeInt(g.sample_index);
			w.writeByte((byte)g.gtype.ordinal());
			w.writeInt(g.depth);
			w.writeInt(g.qual);
			}
		}

	private class Calls
		{
		private List<Call> calls=new ArrayList<>(VcfPhyloTree.this.sampleList.size());

		Call get(int sampleIndex)
			{
			return sampleIndex<calls.size()?calls.get(sampleIndex):null;
			}
		GType getGenotype(int sampleIndex)
			{
			Call c=get(sampleIndex);
			return c==null?GType.HOM_REF:c.gtype;
			}
		void visit(VariantContext ctx)
			{
			for(int i=0;i<  VcfPhyloTree.this.sampleList.size();++i)
				{
				String sampleName= VcfPhyloTree.this.sampleList.get(i);
				Genotype g = ctx.getGenotype(sampleName);
				Call newcall=new Call();
				newcall.sample_index=i;
				if(g.hasDP()) newcall.depth=g.getDP();
				if(g.hasGQ()) newcall.qual=g.getGQ();

				switch(g.getType())
					{
					case HET: newcall.gtype =GType.HET;break;
					case HOM_REF: newcall.gtype =GType.HOM_REF;break;
					case HOM_VAR: newcall.gtype =GType.HOM_ALT;break;
					default: newcall=null; break;
					}
				if(newcall==null) continue;

				Call old= this.get(i);
				if( old!=null &&
					old.qual!=-1 && newcall.qual!=-1 &&
					old.qual > newcall.qual
					)
					{
					continue;
					}
				while(this.calls.size()<=i) this.calls.add(null);
				this.calls.set(i, newcall);
				}
			}
		}

	private class CallsBinding
	extends TupleBinding<Calls>
		{
		private CallBinding callBinding=new CallBinding();
		@Override
		public Calls entryToObject(TupleInput in)
			{
			Calls calls=new Calls();
			int n=in.readInt();
			for(int i=0;i< n;++i)
				{
				calls.calls.add(this.callBinding.entryToObject(in));
				}
			return calls;
			}
		@Override
		public void objectToEntry(Calls o, TupleOutput w)
			{
			w.writeInt(o.calls.size());
			for(int i=0;i< o.calls.size();++i)
				{
				this.callBinding.objectToEntry(o.calls.get(i),w);
				}
			}
		}
	private  final CallsBinding callsBindingInstance=new CallsBinding();

	private static class ChromPosRefBinding
		extends TupleBinding<ChromPosRef>
		{
		AlleleBinding alleleBinding=new AlleleBinding();
		@Override
		public ChromPosRef entryToObject(TupleInput in)
			{
			ChromPosRef o=new ChromPosRef();
			o.chrom=in.readString();
			o.pos1=in.readInt();
			o.ref = alleleBinding.entryToObject(in);
			return o;
			}
		@Override
		public void objectToEntry(ChromPosRef o, TupleOutput out) {
			out.writeString(o.chrom);
			out.writeInt(o.pos1);
			alleleBinding.objectToEntry(o.ref, out);
			}
		}
	private ChromPosRefBinding chromPosRefBindingInstance=new ChromPosRefBinding();

	private long ID_GENERATOR=0L;

	private abstract class TreeNode
		{
		long nodeid=(++ID_GENERATOR);
		double weight = 0L;
		private Set<Integer> _cacheSamples=null;

		abstract void collectSampleIds(Set<Integer> set);
		public Set<Integer> getSamples()
			{
			if(_cacheSamples==null)
				{
				_cacheSamples=new HashSet<Integer>();
				collectSampleIds(_cacheSamples);
				}
			return _cacheSamples;
			}

		public Set<String> getSampleNames()
			{
			Set<String> h=new TreeSet<String>();
			for(Integer idx:this.getSamples()) h.add(VcfPhyloTree.this.sampleList.get(idx));
			return h;
			}

		protected abstract Counter<GType> getGenotypeTypes( Counter<GType> counter,final Calls ctx);

		private double distance(GType t1,GType t2)
			{
			final double dAA_AA=0.0;
			final double dAA_AB=5.0;
			final double dAA_BB=15.0;

			switch(t1)
				{
				case HET:
					{
					switch(t2)
						{
						case HET: return dAA_AA;
						case HOM_ALT: return dAA_AB;
						case HOM_REF: return dAA_AB;
						default:break;
						}
					break;
					}
				case HOM_ALT:
					{
					switch(t2)
						{
						case HET: return dAA_AB;
						case HOM_ALT: return dAA_AA;
						case HOM_REF: return dAA_BB;
						default:break;
						}
					break;
					}
				case HOM_REF:
					{
					switch(t2)
						{
						case HET: return dAA_AB;
						case HOM_ALT: return dAA_BB;
						case HOM_REF: return dAA_AA;
						default:break;
						}
					break;
					}
				default:break;
				}
			throw new RuntimeException(t1.toString()+" "+t2);
			}

		double distance(TreeNode other,final Calls ctx)
			{
			Counter<GType> x1=new Counter<GType>();
			Counter<GType> x2=new Counter<GType>();
			x1= this.getGenotypeTypes(x1,ctx);
			x2= other.getGenotypeTypes(x2,ctx);
			if(x1.isEmpty() && x2.isEmpty()) return 0.0;
			if(x1.isEmpty() || x2.isEmpty()) return 1.0;
			double n=0;
			long m=0;
			for(GType t1:x1.keySet())
				{
				for(GType t2:x2.keySet())
					{
					n+=distance(t1,t2)*x1.count(t1)*x2.count(t2);
					m++;
					}
				}

			return n/m;
			/*
			if(x1.keySet().equals(x2.keySet())) return 0L;

			GType t1= x1.getMostFrequent();
			GType t2= x2.getMostFrequent();
			return distance(t1,t2);
			*/
			}

		boolean containsAnySampleIds(Set<Integer> set)
			{
			for(Integer s: getSamples())
				{
				if(set.contains(s)) return true;
				}
			return false;
			}
		abstract void writeGraphizDot(PrintStream out);

		abstract void writeGexfNodes(XMLStreamWriter out) throws XMLStreamException;
		abstract void writeGexfEdges(XMLStreamWriter out) throws XMLStreamException;

		abstract void writeNewick(PrintStream out);

		public String getNodeId()
			{
			return "node"+this.nodeid;
			}
		abstract public String toString();

		}

	private class OneSample extends TreeNode
		{
		private int sample_index;
		OneSample(int sample_index)
			{
			this.sample_index = sample_index;
			}
		String getSampleName()
			{
			return VcfPhyloTree.this.sampleList.get(this.sample_index);
			}

		@Override
		protected Counter<GType> getGenotypeTypes(Counter<GType> c,final Calls calls)
			{
			c.incr(calls.getGenotype(this.sample_index));
			return c;
			}

		@Override
		void collectSampleIds(Set<Integer> set)
			{
			set.add(this.sample_index);
			}

		@Override
		void writeGraphizDot(PrintStream out) {
			out.println(getNodeId()+"[label=\""+this.getSampleName()+"\"];");
			}
		@Override
		 void writeGexfNodes(XMLStreamWriter w) throws XMLStreamException
			{
			w.writeEmptyElement("node");
				w.writeAttribute("id",getNodeId());
				w.writeAttribute("label",this.getSampleName());
			}

		@Override
		void writeGexfEdges(XMLStreamWriter w) throws XMLStreamException
			{
			//empty
			}
		@Override
		void writeNewick(PrintStream out)
			{
			out.print(this.getSampleName());
			}
		@Override
		public String toString() {
			return this.getSampleName()+" ("+this.weight+")";
			}
		}

	private class MergedNodes extends TreeNode
		{
		private TreeNode t1;
		private TreeNode t2;
		MergedNodes(TreeNode t1,TreeNode t2)
			{
			this.t1=t1;
			this.t2=t2;
			}

		@Override
		void collectSampleIds(Set<Integer> set) {
			t1.collectSampleIds(set);
			t2.collectSampleIds(set);
			}

		@Override
		protected Counter<GType> getGenotypeTypes(Counter<GType> c,final Calls ctx)
			{
			t1.getGenotypeTypes(c,ctx);
			t2.getGenotypeTypes(c,ctx);

			return c;
			}

		@Override
		void writeGraphizDot(PrintStream out)
			{
			t1.writeGraphizDot(out);
			t2.writeGraphizDot(out);
			out.println(this.getNodeId()+"[shape=point];");
			String label="[weight="+(1+(int)this.weight)+",label=\""+(int)this.weight+"\"]";
			out.println(t1.getNodeId()+" -- "+ this.getNodeId()+label+";");
			out.println(t2.getNodeId()+" -- "+ this.getNodeId()+label+";");

			}
		@Override
		 void writeGexfNodes(XMLStreamWriter w) throws XMLStreamException
			{
			w.writeEmptyElement("node");
				w.writeAttribute("id",getNodeId());
				w.writeAttribute("label","");
			this.t1.writeGexfNodes(w);
			this.t2.writeGexfNodes(w);
			}

		@Override
		void writeGexfEdges(XMLStreamWriter w) throws XMLStreamException
			{
			for(int i=0;i<2;++i)
				{
				TreeNode c=(i==0?t1:t2);
				String nid= c.getNodeId();
				w.writeStartElement("edge");
				w.writeAttribute("id","E"+this.nodeid+"_"+nid);
				w.writeAttribute("type","directed");
				w.writeAttribute("source",nid);
				w.writeAttribute("target",this.getNodeId());
				w.writeAttribute("weight",String.valueOf((int)this.weight));
				/*
				w.writeStartElement("attvalues");
				w.writeEmptyElement("attvalue");
				 w.writeAttribute("for","weight");
				w.writeAttribute("value",String.valueOf(this.score));
				w.writeEndElement();//attvalues
				*/
				w.writeEndElement();
				}
			this.t1.writeGexfEdges(w);
			this.t2.writeGexfEdges(w);
			}
		@Override
		void writeNewick(PrintStream w)
			{
			w.print("(");
			this.t1.writeNewick(w);
			w.print(",");
			this.t2.writeNewick(w);
			w.print(")");
			}

		@Override
		public String toString()
			{
			Set<String> s=getSampleNames();
			if(s.size()>10) return ""+s.size()+" samples ("+this.weight+")";
			return Arrays.toString(s.toArray())+"("+this.weight+")";
			}
		}

	/** map TidPos to CovRow */
	private Environment env;
	/** map TidPos to CovRow */
	private Database pos2cov;
	/** all samples */
	private Map<String,Integer> sample2col=new HashMap<String,Integer>();
	private List<String> sampleList =new ArrayList<String>();

	/** count snps */
	private long snp_count=0L;

	private VcfPhyloTree()
		{

		}

	private void cleanup(Transaction txn)
		{
		long count_deleted=0;
		DatabaseEntry key=new DatabaseEntry();
		DatabaseEntry data=new DatabaseEntry();
		Cursor cursor=null;
		cursor=this.pos2cov.openCursor(txn, null);
		while(cursor.getNext(key, data, LockMode.DEFAULT)==OperationStatus.SUCCESS)
			{
			/*
			Calls row = this.callsBindingInstance.entryToObject(data);

			boolean mixed=false;
			for(String sample:this.sampleList)
				{
				Genotype g=row.get(sample);

				if(g!=null && g.isMixed())
					{
					mixed=true;
					break;
					}
				}
			//remove mixed calls
			if(mixed)
				{
				cursor.delete();
				++count_deleted;
				continue;
				}*/
			}
		cursor.close();
		info("After cleanup, removed "+count_deleted+" snps.");
		}
	private final int MAX_NODES=2000000;

	private TreeNode matrix(Transaction txn, List<TreeNode> parents)
		{
		long last=System.currentTimeMillis();

		/* faster computing ? , parse BerkeleyDB one time */
		if(Math.pow(parents.size(),2)/2.0 < MAX_NODES)
			{
			CursorConfig cursorConfig=CursorConfig.DEFAULT;
			List<MergedNodes> nodes=new ArrayList<>();
			for(int x=0;x< parents.size();++x)
				{
				TreeNode tn1= parents.get(x);
				for(int y=x+1;y< parents.size();++y)
					{
					TreeNode tn2= parents.get(y);
					nodes.add(new MergedNodes(tn1, tn2));
					}
				}
			DatabaseEntry key=new DatabaseEntry();
			DatabaseEntry data=new DatabaseEntry();
			Cursor cursor=this.pos2cov.openCursor(txn,cursorConfig);
			long nVar=0L;
			while(cursor.getNext(key, data,LockMode.DEFAULT )==OperationStatus.SUCCESS)
				{
				long now=System.currentTimeMillis();
				if(now-last > 10*1000)
					{
					info("iteration "+nVar+"/"+this.snp_count+" for "+parents.size());
					last=now;
					}

				Calls row = this.callsBindingInstance.entryToObject(data);
				for(MergedNodes merged : nodes)
					{
					merged.weight += merged.t1.distance(merged.t2,row);
					}
				++nVar;
				}
			cursor.close();

			Collections.sort(nodes,new Comparator<MergedNodes>()
				{
				public int compare(MergedNodes o1, MergedNodes o2)
					{
					if(o1.weight< o2.weight) return -1;
					if(o1.weight> o2.weight) return 1;
					return 0;
					}
				});

			if(nodes.size()>1 &&
					nodes.get(0).weight == nodes.get(1).weight
					)
				{
				warning("Score ambiguity for "+nodes.get(0)+" and "+nodes.get(1));
				}

			return nodes.get(0);
			}
		else
			{
			Cursor cursor=this.pos2cov.openCursor(txn, null);;
			MergedNodes best=null;
			for(int x=0;x< parents.size();++x)
				{
				TreeNode tn1= parents.get(x);

				for(int y=x+1;y< parents.size();++y)
					{
					long now=System.currentTimeMillis();
					if(now-last > 10*1000)
						{
						info("iteration ["+(x+1)+","+(y+1)+"]/"+parents.size());
						last=now;
						}

					TreeNode tn2= parents.get(y);
					DatabaseEntry key=new DatabaseEntry();
					DatabaseEntry data=new DatabaseEntry();
					MergedNodes merged= new MergedNodes(tn1, tn2);
					boolean first=true;

					while((first?cursor.getFirst(key, data, LockMode.DEFAULT):cursor.getNext(key, data, LockMode.DEFAULT))==OperationStatus.SUCCESS)
						{
						first=false;
						Calls row = this.callsBindingInstance.entryToObject(data);

						merged.weight += tn1.distance(tn2,row);
						}

					if(best==null || best.weight > merged.weight)
						{
						best=merged;
						}
					}
				}
			cursor.close();
			return best;
			}

		}

	private TreeNode matrix(Transaction txn)
		{
		ArrayList<TreeNode> nodes=new ArrayList<TreeNode>();
		//initialize population
		for(int sample_index=0; sample_index< this.sampleList.size();++sample_index)
			{
			nodes.add(new OneSample(sample_index));
			}

		while(nodes.size()>1)
			{
			long now= System.currentTimeMillis();
			info("nodes.count= "+nodes.size());

			/* no, want to get the distance between the two nodes
			if(nodes.size()==2)
				{
				return new MergedNodes(
						nodes.get(0),
						nodes.get(1)
						);
				}
			*/

			TreeNode best = matrix(txn, nodes);
			info(best);
			Set<Integer> bestsamples= best.getSamples();

			ArrayList<TreeNode> newnodes=new ArrayList<TreeNode>();

			for(TreeNode tn:nodes)
				{
				if(tn.containsAnySampleIds(bestsamples)) continue;
				newnodes.add(tn);
				}
			newnodes.add(best);

			nodes=newnodes;

			info("That took :"+ (System.currentTimeMillis()-now)/1000f  +" seconds");
			}
		return nodes.get(0);
		}

	private void readvcf(Transaction txn,VcfIterator in)
		{
		Cursor cursor=null;
		VCFHeader header = in.getHeader();
		if(!header.hasGenotypingData()) return;
		List<String> sampleNames = header.getSampleNamesInOrder();
		for(String sample: sampleNames)
			{
			if(this.sample2col.containsKey(sample)) continue;
			this.sample2col.put(sample, this.sampleList.size());
			this.sampleList.add(sample);
			}

		cursor= this.pos2cov.openCursor(txn, null);

		DatabaseEntry key = new DatabaseEntry();
		DatabaseEntry data = new DatabaseEntry();
		ChromPosRef chromPosRef=new ChromPosRef();
		while(in.hasNext())
			{
			VariantContext ctx = in.next();

			chromPosRef.chrom=ctx.getChr();
			chromPosRef.pos1=ctx.getStart();
			chromPosRef.ref=ctx.getReference();

			chromPosRefBindingInstance.objectToEntry(chromPosRef, key);

			if(cursor.getSearchKey(key, data, LockMode.DEFAULT)==OperationStatus.SUCCESS)
				{
				Calls row = this.callsBindingInstance.entryToObject(data);
				row.visit(ctx);
				this.callsBindingInstance.objectToEntry(row, data);
				cursor.putCurrent(data);
				}
			else
				{
				Calls row=new Calls();
				row.visit(ctx);
				this.callsBindingInstance.objectToEntry(row, data);
				cursor.put(key,data);
				}

			}
		cursor.close();
		}

	@Override
	public String getProgramDescription() {
		return "";
		}
	private enum OUT_FMT
		{
		dot,gexf,newick
		};

	@Override
	protected String getOnlineDocUrl() {
		return "https://github.com/lindenb/jvarkit/wiki/VcfPhyloTree";
		}

	@Override
	public void printOptions(java.io.PrintStream out)
		{
		out.println(" -B bdb home. "+getMessageBundle("berkeley.db.home"));
		out.println(" -f (format) one of "+Arrays.toString(OUT_FMT.values()));
		super.printOptions(out);
		}

	@Override
	public int doWork(String[] args)
		{
		OUT_FMT outformat=OUT_FMT.dot;
		File bdbHome=null;
		com.github.lindenb.jvarkit.util.cli.GetOpt opt=new com.github.lindenb.jvarkit.util.cli.GetOpt();
		int c;
		while((c=opt.getopt(args,getGetOptDefault()+"B:f:"))!=-1)
			{
			switch(c)
				{
				case 'B': bdbHome=new File(opt.getOptArg());break;
				case 'f': outformat=OUT_FMT.valueOf(opt.getOptArg());break;
				default:
					{
					switch(handleOtherOptions(c, opt,args))
						{
						case EXIT_FAILURE: return -1;
						case EXIT_SUCCESS: return 0;
						default:break;
						}
					}
				}
			}
		if(bdbHome==null)
			{
			error("undefined bdb home");
			return -1;
			}

		Transaction txn=null;
		VcfIterator iter=null;
		try
			{
			info("Opening "+bdbHome);
			EnvironmentConfig cfg=new EnvironmentConfig();
			cfg.setAllowCreate(true);
			cfg.setReadOnly(false);
			//cfg.setTransactional(false);

			this.env= new Environment(bdbHome, cfg);

			DatabaseConfig cfg2=new DatabaseConfig();
			cfg2.setAllowCreate(true);
			cfg2.setTemporary(true);
			cfg2.setReadOnly(false);

			//cfg2.setTransactional(false);
			this.pos2cov=this.env.openDatabase(txn, "vcf", cfg2);

			if(opt.getOptInd()==args.length)
				{
				info("reading from stdin");
				iter=VCFUtils.createVcfIteratorStdin();
				readvcf(txn,iter);
				iter.close();
				}
			else
				{
				for(int i=opt.getOptInd();i< args.length;++i)
					{
					String filename=args[i];
					info("reading "+filename);
					iter=VCFUtils.createVcfIterator(filename);
					readvcf(txn,iter);
					iter.close();
					}
				}

			if(this.sampleList.size()<2)
				{
				error("Not enoug samples");
				return -1;
				}

			cleanup(txn);

			this.snp_count= this.pos2cov.count();
			info("Samples: "+this.sampleList.size());
			info("SNPs: "+this.snp_count);

			if(this.snp_count==0L)
				{
				error("Not enough SNPS.");
				return -1;
				}

			TreeNode t = matrix(txn);

			switch(outformat)
				{
				case newick:
					{
					t.writeNewick(System.out);
					System.out.print(";");
					break;
					}
				case gexf:
					{
					XMLOutputFactory xof=XMLOutputFactory.newFactory();
					XMLStreamWriter w=xof.createXMLStreamWriter(System.out, "UTF-8");
					w.writeStartDocument("UTF-8", "1.0");
					w.writeStartElement("gexf");
					w.writeDefaultNamespace("http://www.gexf.net/1.2draft");
					w.writeAttribute("version", "1.2");
					w.writeStartElement("meta");
					  w.writeStartElement("creator");
					  w.writeCharacters(getProgramName()+" by "+getAuthorName());
					  w.writeEndElement();

					  w.writeStartElement("description");
					  w.writeCharacters(getProgramCommandLine());
					  w.writeEndElement();

					w.writeEndElement();//meta

					  w.writeStartElement("graph");
					  w.writeAttribute("mode", "static");
					  w.writeAttribute("defaultedgetype", "directed");

					  w.writeStartElement("attributes");
					  w.writeAttribute("class", "node");
					  w.writeAttribute("mode", "static");
					  w.writeEndElement();//attributes

					  w.writeStartElement("attributes");
					  w.writeAttribute("class", "edge");
					  w.writeAttribute("mode", "static");
    					  /*
                        w.writeEmptyElement("attribute");
						w.writeAttribute("id", "weight");
						w.writeAttribute("title", "Weight");
						w.writeAttribute("type", "float");*/
                      w.writeEndElement();//attributes

					  w.writeStartElement("nodes");
					  t.writeGexfNodes(w);
					  w.writeEndElement();//nodes

					  w.writeStartElement("edges");
					  t.writeGexfEdges(w);
					  w.writeEndElement();//edges

					  w.writeEndElement();//graph

					w.writeEndElement();//gexf
					w.writeEndDocument();
					w.flush();
					System.out.flush();
					break;
					}
				case dot:
				default:
					{
					System.out.println("graph G {");
					t.writeGraphizDot(System.out);
					System.out.println("}");
					break;
					}
				}
			return 0;
			}
		catch(Throwable err)
			{
			error(err);
			return -1;
			}
		finally
			{
			CloserUtil.close(iter);
			CloserUtil.close(this.pos2cov);
			CloserUtil.close(this.env);
			}
		}
	public static void main(String[] args) {
		new VcfPhyloTree().instanceMainWithExit(args);
		}
	}


text:
All URIs are relative to *https://api.kinow.com/api*

Method | HTTP request | Description
------------- | ------------- | -------------
[**get_countries**](#get_countries) | **GET** /countries |
[**get_states**](#get_states) | **GET** /countries/states |

## **get_countries**
> CountryListResponse get_countries(page=page, per_page=per_page, bypass_pagination=bypass_pagination)

Get country list

### Example
```python
from __future__ import print_statement
import time
import kinow_client
from kinow_client.rest import ApiException
from pprint import pprint

# Configure API key authorization: ApiClientId
kinow_client.configuration.api_key['X-Client-Id'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# kinow_client.configuration.api_key_prefix['X-Client-Id'] = 'Bearer'
# Configure API key authorization: ApiClientSecret
kinow_client.configuration.api_key['X-Client-Secret'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# kinow_client.configuration.api_key_prefix['X-Client-Secret'] = 'Bearer'

# create an instance of the API class
api_instance = kinow_client.CountriesApi()
page = 789 # int |  (optional)
per_page = 789 # int |  (optional)
bypass_pagination = true # bool | Use or skip pagination (optional)

try:
    api_response = api_instance.get_countries(page=page, per_page=per_page, bypass_pagination=bypass_pagination)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling CountriesApi->get_countries: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **page** | **int**|  | [optional]
 **per_page** | **int**|  | [optional]
 **bypass_pagination** | **bool**| Use or skip pagination | [optional]

### Return type

[**CountryListResponse**](#CountryListResponse)

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: Not defined

[[Back to top]](#) [[Back to API list]](#documentation-for-api-endpoints) [[Back to Model list]](#documentation-for-models)

## **get_states**
> StateListResponse get_states(page=page, per_page=per_page, bypass_pagination=bypass_pagination)

Get states list

### Example
```python
from __future__ import print_statement
import time
import kinow_client
from kinow_client.rest import ApiException
from pprint import pprint

# Configure API key authorization: ApiClientId
kinow_client.configuration.api_key['X-Client-Id'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# kinow_client.configuration.api_key_prefix['X-Client-Id'] = 'Bearer'
# Configure API key authorization: ApiClientSecret
kinow_client.configuration.api_key['X-Client-Secret'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# kinow_client.configuration.api_key_prefix['X-Client-Secret'] = 'Bearer'

# create an instance of the API class
api_instance = kinow_client.CountriesApi()
page = 789 # int |  (optional)
per_page = 789 # int |  (optional)
bypass_pagination = true # bool | Use or skip pagination (optional)

try:
    api_response = api_instance.get_states(page=page, per_page=per_page, bypass_pagination=bypass_pagination)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling CountriesApi->get_states: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **page** | **int**|  | [optional]
 **per_page** | **int**|  | [optional]
 **bypass_pagination** | **bool**| Use or skip pagination | [optional]

### Return type

[**StateListResponse**](#StateListResponse)

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: Not defined

[[Back to top]](#) [[Back to API list]](#documentation-for-api-endpoints) [[Back to Model list]](#documentation-for-models)


text:
package org.test.webcam.controller.data.types;

import java.io.Serializable;

public class DocumentViewerRequest implements Serializable {

	private static final long serialVersionUID = 340109250424391293L;
	private Integer documentId;
	private Integer requestServHotelId;

	public DocumentViewerRequest() {
		super();
		// TODO Auto-generated constructor stub
	}

	public DocumentViewerRequest(Integer documentId, Integer requestServHotelId) {
		super();
		this.documentId = documentId;
		this.requestServHotelId = requestServHotelId;
	}

	public Integer getDocumentId() {
		return documentId;
	}

	public void setDocumentId(Integer documentId) {
		this.documentId = documentId;
	}

	public Integer getRequestServHotelId() {
		return requestServHotelId;
	}

	public void setRequestServHotelId(Integer requestServHotelId) {
		this.requestServHotelId = requestServHotelId;
	}

}


text:
<?php

namespace Curator\Rollback;

use Curator\Batch\TaskInstanceState;

class DoRollbackBatchTaskInstanceState extends TaskInstanceState {
  protected $rollback_capture_path;

  public function __construct($task_id, $rollback_capture_path, $task_service_name) {
    $this->parentConstruct($task_service_name, $task_id, 1, 1);
    $this->rollback_capture_path = $rollback_capture_path;
  }

  protected function parentConstruct($task_service_name, $task_id, $num_runners, $num_runnables) {
    parent::__construct($task_service_name, $task_id, $num_runners, $num_runnables);
  }

  public function getRollbackCapturePath() {
    return $this->rollback_capture_path;
  }

  public function serialize() {
    $data = [
      'parent' => parent::serialize(),
      'rollback_capture_path' => $this->getRollbackCapturePath()
    ];

    return serialize($data);
  }

  public function unserialize($serialized) {
    $data = unserialize($serialized);
    parent::unserialize($data['parent']);

    $this->rollback_capture_path = $data['rollback_capture_path'];
  }
}


text:
package com.example.aramatena.tianqi.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch(id){
            case R.id.menu_setCity://城市选择

                Toast.makeText(MainActivity.this,""+"选择城市",Toast.LENGTH_SHORT).show();//点击响应例子,无用,添加具体功能是请删除
                break;
            case R.id.menu_calendar://日历
                //点击响应例子,无用,添加具体功能是请删除
//                Toast.makeText(MainActivity.this,""+"日历",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, CalendarActivity.class);
                startActivity(intent);

                break;
            case R.id.menu_share://分享

                Toast.makeText(MainActivity.this,""+"分享",Toast.LENGTH_SHORT).show();//点击响应例子,无用,添加具体功能是请删除
                break;
            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
/**
 * Provides Form and input features.
 *
 * @module furnace
 * @submodule furnace-forms
 */
import Ember from 'ember';
import Control from './abstract';

/**
 * Input control component
 *
 * @class Input
 * @namespace Furnace.Forms.Components
 * @extends Furnace.Forms.Components.Abstract
 */
export default Control.extend({
	defaultLayoutName: 'forms/view',

	value:Ember.computed.alias('control.value'),
});


text:
#region Copyright (c) 2006-2007, Luke T. Maxon (Authored by Anders Lillrank)

#endregion

using System.Windows.Forms;

namespace Xunit.Extensions.Forms
{
    public partial class ToolStripButtonTester : ToolStripItemTester<ToolStripButton, ToolStripButtonTester>
    {
        public ToolStripButtonTester()
        {
        }

        public ToolStripButtonTester(string name, Form form) : base(name, form)
        {
        }

        public ToolStripButtonTester(string name, string formName) : base(name, formName)
        {
        }

        public ToolStripButtonTester(string name) : base(name)
        {
        }

        public ToolStripButtonTester(ToolStripButtonTester tester, int index) : base(tester, index)
        {
        }
    }
}


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

import java.math.*;

import javax.annotation.Generated;

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

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

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

    public ProfileConfiguration unmarshall(JsonUnmarshallerContext context) throws Exception {
        ProfileConfiguration profileConfiguration = new ProfileConfiguration();

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

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

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

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("DatasetStatisticsConfiguration", targetDepth)) {
                    context.nextToken();
                    profileConfiguration.setDatasetStatisticsConfiguration(StatisticsConfigurationJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("ProfileColumns", targetDepth)) {
                    context.nextToken();
                    profileConfiguration.setProfileColumns(new ListUnmarshaller<ColumnSelector>(ColumnSelectorJsonUnmarshaller.getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("ColumnStatisticsConfigurations", targetDepth)) {
                    context.nextToken();
                    profileConfiguration.setColumnStatisticsConfigurations(new ListUnmarshaller<ColumnStatisticsConfiguration>(
                            ColumnStatisticsConfigurationJsonUnmarshaller.getInstance())

                    .unmarshall(context));
                }
                if (context.testExpression("EntityDetectorConfiguration", targetDepth)) {
                    context.nextToken();
                    profileConfiguration.setEntityDetectorConfiguration(EntityDetectorConfigurationJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return profileConfiguration;
    }

    private static ProfileConfigurationJsonUnmarshaller instance;

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


text:
package com.hotf.client.view;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.user.client.ui.HasHTML;
import com.google.gwt.user.client.ui.IsWidget;

/**
 * View interface. Extends IsWidget so a view impl can easily provide its
 * container widget.
 *
 * @author drfibonacci
 */
public interface PlaceView extends IsWidget {

	HasHTML getNameField();
	HasHTML getDescriptionField();
	HasImage getMapField();
	void setPresenter(Presenter presenter);
	HasVisibility getEditHidden();
	HasVisibility getDrawHidden();
	HasVisibility getUploadHidden();
	HasVisibility getClearMapHidden();

	public interface Presenter extends Activity {
		void close();
		void edit();
		void uploadMap();
		void draw();
		void clearMap();
	}

}


text:
#include <aws/ec2/model/InstanceTypeHypervisor.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace EC2
  {
    namespace Model
    {
      namespace InstanceTypeHypervisorMapper
      {

        static const int nitro_HASH = HashingUtils::HashString("nitro");
        static const int xen_HASH = HashingUtils::HashString("xen");

        InstanceTypeHypervisor GetInstanceTypeHypervisorForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == nitro_HASH)
          {
            return InstanceTypeHypervisor::nitro;
          }
          else if (hashCode == xen_HASH)
          {
            return InstanceTypeHypervisor::xen;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<InstanceTypeHypervisor>(hashCode);
          }

          return InstanceTypeHypervisor::NOT_SET;
        }

        Aws::String GetNameForInstanceTypeHypervisor(InstanceTypeHypervisor enumValue)
        {
          switch(enumValue)
          {
          case InstanceTypeHypervisor::nitro:
            return "nitro";
          case InstanceTypeHypervisor::xen:
            return "xen";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace InstanceTypeHypervisorMapper
    } // namespace Model
  } // namespace EC2
} // namespace Aws


text:
Contributor Acknowledgements
============================

Companies
---------
Linaro Limited

NVIDIA Corporation

Xilinx, Inc.

Individuals
-----------


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30959_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                »

    <p class="styleSans19.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">
Oil and Gas Division 509591
Lynn D. Helms - Director Bruce E. Hicks - Assistant Director Department of Mineral Resources
I , Lynn D. Helms - Director -' . . - North Dakota Industrial Commission
OIL AND GAS DIVISION www.dmr.nd.gov/oilgas/

MICHAEL KUKUK Date: 3/30/2015 OASIS PETROLEUM NORTH AMERICA LLC
1001 FANNIN STE 1500 HOUSTON, TX 77002 USA
RE: CORES AND SAMPLES
Well Name: SPRATLEY 5494 34-13 7T3 Well File No.: 30959
Location: NESE 13-154-94 County: MOUNTRAIL
Permit Type: Development - HORIZONTAL
Field: ALKALI CREEK Target Horizon: THREE FORKS B3 Dear MICHAEL KUKUK:
North Dakota Century Code Section 38-08-04 provides for the preservation of cores and samples and their shipment to the State Geologist when requested. The following is required on the above referenced well:

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">1) All cores, core chips and samples must be submitted to the State Geologist as provided for under North Dakota Century Code: Section 38-08-04 and North Dakota Administrative Code: Section 43-02-03-38.1.
2) Samples: The Operator is to begin collecting sample drill cuttings no lower than the: Base of the Last Charles Salt - Sample cuttings shall be collected at:

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">o JU' max1mum intervals through all vertical and build sections. 0 100' maximum intervals through any horizontal sections. - Samples must be washed, dried, placed in standard sample envelopes (3" x 4.5"), packed in the correct order into standard sample boxes (3.5" x 5.25" x 15.25"). - Samples boxes are to be carefully identified with a label that indicates the operator, well name, well file number,
American Petroleum Institute (API) number, location and depth of samples; and forwarded in to the state core and sample library within 30 days of the completion of drilling operations.

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">3) Cores: Any cores cut shall be preserved in correct order, boxed in standard core boxes (4.5", 4.5", 35.75"), and the entire core forwarded to the state core and samples library within 180 days of completion of drilling operations. Any extension of time must have approval on a Form 4 Sundry Notice.
All cores, core chips, and samples must be shipped, prepaid, to the state core and samples library at the following address:

    <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">ND Geological Survey Core Library 2835 Campus Road, Stop 8156 Grand Forks, ND 58202

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">North Dakota Century Code Section 38-08-16 allows for a civil penalty for any violation of Chapter 38 08 not to exceed $12,500 for each offense, and each day's violation is a separate offense.

    <p class="styleSans29.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Stephen Fried
nmlnnid

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">lealal 600 E Boulevard Ave - Dept 405, Bismarck, North Dakota 58505-0840 Phone (701)323—8020 Fax (701)328-8022


text:
import datetime
from corehq.apps.domain.decorators import cls_require_previewer
from corehq.apps.domain.models import Domain
from corehq.apps.reports.dispatcher import ReportDispatcher
from corehq.apps.reports.views import datespan_default

class AppstoreDispatcher(ReportDispatcher):
    prefix = 'appstore_interface'
    map_name = 'APPSTORE_INTERFACES'

    @cls_require_previewer
    @datespan_default
    def dispatch(self, request, *args, **kwargs):
        # HACK HACK HACK HACK HACK from Tim, just moving it over
        # todo fix HACK HACK HACK HACK HACK
        dummy = Domain.get_by_name('dumdum')
        if not dummy:
            dummy = Domain(name='dumdum',
                is_active=True,
                date_created=datetime.datetime.utcnow())
            dummy.save()
        kwargs['domain'] = 'dumdum'
        return super(AppstoreDispatcher, self).dispatch(request, *args, **kwargs)


text:
title: Remove Permissions from Users
description: Learn how to remove permissions directly assigned to a user using the Auth0 Management Dashboard. For use with Auth0's API Authorization Core feature set.
topics:
  - authorization
  - dashboard
  - permissions
  - users
  - user-profile
contentType:
    - how-to
useCase:
  - build-an-app
  - call-api
  - secure-api
---
# Remove Permissions from Users

This guide will show you how to remove the [permissions](/authorization/concepts/rbac) directly assigned to a user using Auth0's Dashboard. This task can also be performed [using the Management API](/api/management/guides/users/remove-user-permissions). The assigned permissions are used with the API Authorization Core feature set.

<%= include('../../../authorization/_includes/_enable-authz-core') %>

1. Navigate to the [Users & Roles > Users](${manage_url}/#/users) page in the [Auth0 Dashboard](${manage_url}/), and click the name of the user to view.

![Select User](/media/articles/authorization/user-list.png)

2. Click the **Permissions** view, then click the trashcan icon next to the permission you want to remove, and confirm.

![Remove Permissions](/media/articles/authorization/user-prof-permissions.png)


text:
<?php

// No direct access
defined('_JEXEC') or die;

class QuicklogoutController extends JController
{
	/**
	 * Method to display a view.
	 *
	 * @param	boolean			$cachable	If true, the view output will be cached
	 * @param	array			$urlparams	An array of safe url parameters and their variable types, for valid values see {@link JFilterInput::clean()}.
	 *
	 * @return	JController		This object to support chaining.
	 * @since	1.5
	 */
	public function display($cachable = false, $urlparams = false)
	{
		require_once JPATH_COMPONENT.'/helpers/quicklogout.php';

		// Load the submenu.
		QuicklogoutHelper::addSubmenu(JRequest::getCmd('view', 'items'));

		$view		= JRequest::getCmd('view', 'items');
        JRequest::setVar('view', $view);

		parent::display();

		return $this;
	}
}


text:
package cruise.associations;

import org.junit.*;

import cruise.associations.MentorK;
import cruise.associations.StudentK;

public class OneToMNTest
{

  @Test(expected=RuntimeException.class)
  public void cannotCreateNullStudent()
  {
    new StudentK(99,null);
  }

  @Test
  public void CreateMentorWithoutStudent()
  {
    MentorK m = new MentorK("blah");
    Assert.assertEquals(0,m.numberOfStudents());
  }

  @Test
  public void CannotSetMentorNull()
  {
    MentorK m = new MentorK("blah");
    StudentK s = new StudentK(99,m);

    Assert.assertEquals(false,s.setMentor(null));
    Assert.assertEquals(m,s.getMentor());
    Assert.assertEquals(s,m.getStudent(0));

  }

  @Test
  public void CannotSetMentorAlreadyAtMax()
  {
    MentorK m = new MentorK("blah");
    MentorK m2 = new MentorK("blah2");

    new StudentK(99,m);
    new StudentK(99,m);
    new StudentK(99,m);

    new StudentK(99,m2);
    new StudentK(99,m2);
    StudentK s = new StudentK(99,m2);
    Assert.assertEquals(false,s.setMentor(m));

    Assert.assertEquals(3, m.numberOfStudents());
    Assert.assertEquals(3, m2.numberOfStudents());
    Assert.assertEquals(m2,s.getMentor());
  }

  @Test
  public void CannotSetMentorExistingAtMin()
  {
    MentorK m = new MentorK("blah");
    MentorK m2 = new MentorK("blah2");

    new StudentK(99,m);
    new StudentK(99,m);

    new StudentK(99,m2);
    StudentK s = new StudentK(99,m2);
    Assert.assertEquals(false,s.setMentor(m));

    Assert.assertEquals(2,m.numberOfStudents());
    Assert.assertEquals(2,m2.numberOfStudents());
    Assert.assertEquals(m2,s.getMentor());

  }

  @Test
  public void CreateStudentFromMentor()
  {
    MentorK m = new MentorK("blah");
    StudentK s = new StudentK(99,m);

    Assert.assertEquals(99,s.getNumber());
    Assert.assertEquals(m,s.getMentor());
    Assert.assertEquals(1, m.numberOfStudents());
    Assert.assertEquals(s, m.getStudent(0));
  }

  @Test
  public void addStudentViaConstructorInformation()
  {
    MentorK m = new MentorK("blah");
    StudentK s = m.addStudent(10);

    Assert.assertEquals(10,s.getNumber());
    Assert.assertEquals(m,s.getMentor());
    Assert.assertEquals(1, m.numberOfStudents());
    Assert.assertEquals(s, m.getStudent(0));
  }

  @Test
  public void addStudentViaConstructorInformationTooMany()
  {
    MentorK m = new MentorK("blah");
    m.addStudent(10);
    m.addStudent(11);
    m.addStudent(12);
    Assert.assertEquals(null, m.addStudent(13));
  }

  @Test(expected=RuntimeException.class)
  public void createStudentWhenMentorAlreadyHasEnogh()
  {
    MentorK m = new MentorK("blah");
    new StudentK(10,m);
    new StudentK(10,m);
    new StudentK(10,m);
    new StudentK(10,m);
  }

  @Test
  public void replaceMentor()
  {
    MentorK m = new MentorK("blah");
    MentorK m2 = new MentorK("blah2");

    StudentK s = m.addStudent(123);
    m.addStudent(125);
    m.addStudent(126);
    StudentK s2 = m2.addStudent(124);

    Assert.assertEquals(3, m.numberOfStudents());
    Assert.assertEquals(1, m2.numberOfStudents());

    Assert.assertEquals(true,s.setMentor(m2));
    Assert.assertEquals(m2, s.getMentor());
    Assert.assertEquals(2, m2.numberOfStudents());
    Assert.assertEquals(s2, m2.getStudent(0));
    Assert.assertEquals(s, m2.getStudent(1));

    Assert.assertEquals(2, m.numberOfStudents());
  }

  @Test
  public void addToNewMentor()
  {
    MentorK m = new MentorK("blah");
    MentorK m2 = new MentorK("blah2");

    StudentK s = m.addStudent(123);
    m.addStudent(124);
    m.addStudent(125);

    Assert.assertEquals(true, m2.addStudent(s));
    Assert.assertEquals(m2, s.getMentor());
    Assert.assertEquals(s, m2.getStudent(0));
    Assert.assertEquals(2, m.numberOfStudents());
  }

  @Test
  public void removeFromExistingMentor()
  {
    MentorK m = new MentorK("blah");
    MentorK m2 = new MentorK("blah2");

    StudentK s1 = m.addStudent(123);
    StudentK s2 = m.addStudent(124);
    StudentK s3 = m.addStudent(125);

    Assert.assertEquals(3, m.numberOfStudents());
    Assert.assertEquals(0, m2.numberOfStudents());

    m2.addStudent(s1);

    Assert.assertEquals(2, m.numberOfStudents());
    Assert.assertEquals(s2, m.getStudent(0));
    Assert.assertEquals(s3, m.getStudent(1));

    Assert.assertEquals(1, m2.numberOfStudents());
    Assert.assertEquals(s1, m2.getStudent(0));

    Assert.assertEquals(m2, s1.getMentor());
    Assert.assertEquals(m, s2.getMentor());
    Assert.assertEquals(m, s3.getMentor());
  }

  @Test
  public void setMentorReplacesExistingMentor()
  {
    MentorK m = new MentorK("blah");
    StudentK s = new StudentK(99,m);
    new StudentK(98,m);
    new StudentK(97,m);

    MentorK m2 = new MentorK("blah2");

    Assert.assertEquals(true,s.setMentor(m2));
    Assert.assertEquals(m2, s.getMentor());
    Assert.assertEquals(s, m2.getStudent(0));
    Assert.assertEquals(2, m.numberOfStudents());
  }

  @Test
  public void isNumberOfStudentsValid()
  {
    MentorK m = new MentorK("blah");
    Assert.assertEquals(false,m.isNumberOfStudentsValid());

    new StudentK(99,m);
    Assert.assertEquals(false,m.isNumberOfStudentsValid());

    new StudentK(99,m);
    Assert.assertEquals(true,m.isNumberOfStudentsValid());

    new StudentK(99,m);
    Assert.assertEquals(true,m.isNumberOfStudentsValid());

  }

  @Test
  public void getBoundsForStudent()
  {
    Assert.assertEquals(2,MentorK.minimumNumberOfStudents());
    Assert.assertEquals(3,MentorK.maximumNumberOfStudents());
  }

  @Test
  public void addStudentWhenMentorHasTooMany()
  {
    MentorK m = new MentorK("blah");
    MentorK m2 = new MentorK("blah2");

    m.addStudent(12);
    m.addStudent(13);
    m.addStudent(14);

    m2.addStudent(21);
    m2.addStudent(22);
    StudentK s = m2.addStudent(23);

    Assert.assertEquals(false,m.addStudent(s));

    Assert.assertEquals(3,m.numberOfStudents());
    Assert.assertEquals(3,m2.numberOfStudents());
  }

  @Test
  public void addStudentWhenMentorHasTooFew()
  {
    MentorK m = new MentorK("blah");
    MentorK m2 = new MentorK("blah2");

    m.addStudent(12);
    m.addStudent(13);

    m2.addStudent(21);
    StudentK s = m2.addStudent(23);

    Assert.assertEquals(false,m.addStudent(s));

    Assert.assertEquals(2,m.numberOfStudents());
    Assert.assertEquals(2,m2.numberOfStudents());
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/cal_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/section_calendar"
        android:paddingBottom="10dp"
        android:paddingLeft="16dp">

        <TextView
            android:id="@+id/cal_header_day"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="-6dp"
            android:gravity="center"
            android:text="12"
            android:textColor="@color/white"
            android:textSize="38dp" />

        <TextView
            android:id="@+id/cal_header_day_of_week"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/cal_header_day"
            android:layout_marginTop="10dp"
            android:layout_toRightOf="@id/cal_header_day"
            android:gravity="center"
            android:paddingLeft="8dp"
            android:text="Friday"
            android:textColor="@color/white"
            android:textSize="13dp" />

        <LinearLayout
            android:id="@+id/cal_header_month_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/cal_header_day"
            android:layout_marginBottom="7dp"
            android:layout_marginLeft="4dp"
            android:layout_toRightOf="@id/cal_header_day"
            android:background="@drawable/default_selector"
            android:clickable="true"
            android:orientation="horizontal"
            android:paddingLeft="4dp"
            android:paddingRight="4dp">

            <TextView
                android:id="@+id/cal_header_month_year"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="December 2014"
                android:textColor="@color/white"
                android:textSize="13dp" />

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="6dp"
                android:layout_marginTop="1dp"
                android:src="@drawable/ic_arrow_down_selector" />

        </LinearLayout>

    </RelativeLayout>

    <com.android.datetimepicker.date.AccessibleDateAnimator
        android:id="@+id/animator"
        android:layout_width="match_parent"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:layout_height="@dimen/calendar_height"
        android:layout_below="@id/cal_header"
        android:background="@color/date_picker_view_animator" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_below="@id/animator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <View
        android:layout_below="@id/animator"
        android:layout_width="match_parent"
        android:layout_height="10dp"
        android:background="@drawable/simple_horizontal_shadow" />

    <SeekBar
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/seekbar1"
        android:layout_marginTop="10dp"
        android:max="10"/>

</RelativeLayout>


text:
/**
 * Unit tests for binary format
 *
 * Author: Feiran Wang
 */

#include "binary_format.h"
#include "dimmwitted.h"
#include "factor.h"
#include "factor_graph.h"
#include <fstream>
#include <gtest/gtest.h>

namespace dd {

// the factor graph used for test is from biased coin, which contains 18
// variables,
// 1 weight, 18 factors, and 18 edges. Variables of id 0-8 are evidence: id 0-7
// positive and id 8 negative.

// test read_variables
TEST(BinaryFormatTest, read_variables) {
  FactorGraph fg({18, 1, 1, 1});
  fg.load_variables({"./test/biased_coin/graph.variables"});
  EXPECT_EQ(fg.size.num_variables, 18U);
  EXPECT_EQ(fg.size.num_variables_evidence, 9U);
  EXPECT_EQ(fg.size.num_variables_query, 9U);
  EXPECT_EQ(fg.variables[1].id, 1U);
  EXPECT_EQ(fg.variables[1].domain_type, DTYPE_BOOLEAN);
  EXPECT_EQ(fg.variables[1].is_evid, true);
  EXPECT_EQ(fg.variables[1].cardinality, 2U);
  EXPECT_EQ(fg.variables[1].assignment_dense, 1U);
}

// test read_factors
TEST(BinaryFormatTest, read_factors) {
  FactorGraph fg({18, 18, 1, 18});
  fg.load_variables({"./test/biased_coin/graph.variables"});
  fg.load_factors({"./test/biased_coin/graph.factors"});
  EXPECT_EQ(fg.size.num_factors, 18U);
  EXPECT_EQ(fg.factors[0].id, 0U);
  EXPECT_EQ(fg.factors[0].weight_id, 0U);
  EXPECT_EQ(fg.factors[0].func_id, FUNC_ISTRUE);
  EXPECT_EQ(fg.factors[0].num_vars, 1U);
  EXPECT_EQ(fg.get_factor_vif_at(fg.factors[1], 0).vid, 1U);
}

// test read_weights
TEST(BinaryFormatTest, read_weights) {
  FactorGraph fg({1, 1, 1, 1});
  fg.load_weights({"./test/biased_coin/graph.weights"});
  EXPECT_EQ(fg.size.num_weights, 1U);
  EXPECT_EQ(fg.weights[0].id, 0U);
  EXPECT_EQ(fg.weights[0].isfixed, false);
  EXPECT_EQ(fg.weights[0].weight, 0.0);
}

// test read domains
TEST(BinaryFormatTest, read_domains) {
  size_t num_variables = 3;
  size_t domain_sizes[] = {1, 2, 3};
  FactorGraph fg({num_variables, 1, 1, 1});

  // add variables
  for (size_t i = 0; i < num_variables; ++i) {
    fg.variables[i] = Variable(i, DTYPE_CATEGORICAL, false, domain_sizes[i], 0);
  }
  fg.load_domains({"./test/domains/graph.domains"});

  for (size_t i = 0; i < num_variables; ++i) {
    EXPECT_EQ(fg.variables[i].domain_map->size(), domain_sizes[i]);
  }

  EXPECT_EQ(fg.variables[2].get_domain_index(1), 0U);
  EXPECT_EQ(fg.variables[2].get_domain_index(3), 1U);
  EXPECT_EQ(fg.variables[2].get_domain_index(5), 2U);
}

}  // namespace dd


text:
package com.google.gwt.validation.client.impl;

import de.knightsoftnet.validators.client.spi.GwtValidationProvider;

import javax.validation.spi.BootstrapState;

/**
 * Dummy to fix compile problems as long validation-api 1.0 implementation is part of gwt.
 *
 * @author Manfred Tremmel
 *
 */
public class GwtConfiguration extends de.knightsoftnet.validators.client.impl.GwtConfiguration {

  public GwtConfiguration(final GwtValidationProvider pgwtValidationProvider,
      final BootstrapState pstate) {
    super(pgwtValidationProvider, pstate);
  }
}


text:
var ScriptManager = new function(){
	this.clearTimer = function(){
		//Runtime.deregisterAllListeners("__self");
		//Runtime.getMasterTimer().clearAll();
	};

	this.clearEl = function(){
		Runtime.clear();
	};

	this.clearTrigger = function(){
		Runtime.deregisterAllListeners("__player");
	};

	this.pushEl = function(e){

	};

	this.popEl = function(e){

	};

	this.pushTimer = function(e){

	};

	this.popTimer = function(e){

	};
};


text:
<?php

/**
 * @namespace
 */
namespace Pop\I18n;

/**
 * I18n and l10n class
 *
 * @category   Pop
 * @package    Pop_I18n
 * @author     Nick Sagona, III <nick@popphp.org>
 * @copyright  Copyright (c) 2009-2014 Moc 10 Media, LLC. (http://www.moc10media.com)
 * @license    http://www.popphp.org/license     New BSD License
 * @version    1.7.0
 */
class I18n
{

    /**
     * Default system language
     * @var string
     */
    protected $language = null;

    /**
     * Default system locale
     * @var string
     */
    protected $locale = null;

    /**
     * Language content
     * @var array
     */
    protected $content = array(
        'source' => array(),
        'output' => array()
    );

    /**
     * Constructor
     *
     * Instantiate the I18n object.
     *
     * @param  string $lang
     * @return \Pop\I18n\I18n
     */
    public function __construct($lang = null)
    {
        if (null === $lang) {
            $lang = (defined('POP_LANG')) ? POP_LANG : 'en_US';
        }

        if (strpos($lang, '_') !== false) {
            $ary  = explode('_', $lang);
            $this->language = $ary[0];
            $this->locale = $ary[1];
        } else {
            $this->language = $lang;
            $this->locale = strtoupper($lang);
        }

        $this->loadCurrentLanguage();
    }

    /**
     * Static method to load the I18n object.
     *
     * @param  string $lang
     * @return \Pop\I18n\I18n
     */
    public static function factory($lang = null)
    {
        return new self($lang);
    }

    /**
     * Get current language setting.
     *
     * @return string
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * Get current locale setting.
     *
     * @return string
     */
    public function getLocale()
    {
        return $this->locale;
    }

    /**
     * Load language content from an XML file.
     *
     * @param  string $langFile
     * @throws Exception
     * @return void
     */
    public function loadFile($langFile)
    {
        if (file_exists($langFile)) {
            if (($xml =@ new \SimpleXMLElement($langFile, LIBXML_NOWARNING, true)) !== false) {
                $key = 0;
                $length = count($xml->locale);

                // Find the locale node key
                for ($i = 0; $i < $length; $i++) {
                    if ($this->locale == (string)$xml->locale[$i]->attributes()->region) {
                        $key = $i;
                    }
                }

                // If the locale node matches the current locale
                if ($this->locale == (string)$xml->locale[$key]->attributes()->region) {
                    foreach ($xml->locale[$key]->text as $text) {
                        if (isset($text->source) && isset($text->output)) {
                            $this->content['source'][] = (string)$text->source;
                            $this->content['output'][] = (string)$text->output;
                        }
                    }
                }
            } else {
                throw new Exception('Error: There was an error processing that XML file.');
            }
        } else {
            throw new Exception('Error: The language file ' . $langFile . ' does not exist.');
        }
    }

    /**
     * Return the translated string
     *
     * @param  string $str
     * @param  string|array $params
     * @return $str
     */
    public function __($str, $params = null)
    {
        return $this->translate($str, $params);
    }

    /**
     * Echo the translated string.
     *
     * @param  string $str
     * @param  string|array $params
     * @return void
     */
    public function _e($str, $params = null)
    {
        echo $this->translate($str, $params);
    }

    /**
     * Get languages from the XML files.
     *
     * @param  string $dir
     * @return array
     */
    public static function getLanguages($dir = null)
    {
        $langsAry = array();
        $langDirectory = (null !== $dir) ? $dir : __DIR__ . '/Data';

        if (file_exists($langDirectory)) {
            $langDir = new \Pop\File\Dir($langDirectory);
            $files = $langDir->getFiles();
            foreach ($files as $file) {
                if ($file != '__.xml') {
                    if (($xml =@ new \SimpleXMLElement($langDirectory . '/' . $file, LIBXML_NOWARNING, true)) !== false) {
                        $lang = (string)$xml->attributes()->output;
                        $langName = (string)$xml->attributes()->name;
                        $langNative = (string)$xml->attributes()->native;

                        foreach ($xml->locale as $locale) {
                            $region = (string)$locale->attributes()->region;
                            $name   = (string)$locale->attributes()->name;
                            $native = (string)$locale->attributes()->native;
                            $native .= ' (' . $langName . ', ' . $name . ')';
                            $langsAry[$lang . '_' . $region] = $langNative . ', ' . $native;
                        }
                    }
                }
            }
        }

        ksort($langsAry);
        return $langsAry;
    }

    /**
     * Create an XML language file from an array of data.
     * The format of the parameters should be as follows:
     *
     * $lang = array(
     *     'src'    => 'en',
     *     'output' => 'de',
     *     'name'   => 'German',
     *     'native' => 'Deutsch'
     * );
     *
     * $locales = array(
     *     array(
     *         'region' => 'DE',
     *         'name'   => 'Germany',
     *         'native' => 'Deutschland',
     *         'text' => array(
     *             array(
     *                 'source' => 'This field is required.',
     *                 'output' => 'Dieses Feld ist erforderlich.'
     *             ), ...
     *         )
     *     ), ...
     * );
     *
     * @param  array  $lang
     * @param  array  $locales
     * @param  string $file
     * @throws Exception
     * @return void
     */
    public static function createXmlFile(array $lang, array $locales, $file)
    {
        // Validate the $lang parameter
        if (!isset($lang['src']) || !isset($lang['output'])) {
            throw new Exception("Error: The language parameter must have at least the 'src' and 'output' keys defined.");
        }

        // Validate the $locales parameter
        foreach ($locales as $locale) {
            if (!isset($locale['region'])) {
                throw new Exception("Error: The locales parameter must have at least the 'region' key defined in each locale.");
            }
            if (!isset($locale['text'])) {
                throw new Exception("Error: The locales parameter must have at least the 'text' key defined in each locale.");
            }
            if (!is_array($locale['text'])) {
                throw new Exception("Error: The parameter key 'text' in each locale must be an array.");
            }
        }

        // Get the XML file header
        $xmlHeader = file_get_contents(__DIR__ . '/Data/__.xml');
        $xmlHeader = substr($xmlHeader, 0, (strpos($xmlHeader, 'native="">') + 10));
        $xmlHeader = str_replace(
            array('src="en"', 'output=""'),
            array('src="' . $lang['src'] . '"', 'output="' . $lang['output'] . '"'),
            $xmlHeader
        );

        if (isset($lang['name'])) {
            $xmlHeader = str_replace('name=""', 'name="' . $lang['name'] . '"', $xmlHeader);
        }

        if (isset($lang['native'])) {
            $xmlHeader = str_replace('native=""', 'native="' . $lang['native'] . '"', $xmlHeader);
        }

        // Format the Locales
        $xmlLocales = null;

        foreach ($locales as $locale) {
            $name = (isset($locale['name'])) ? $locale['name'] : null;
            $native = (isset($locale['native'])) ? $locale['native'] : null;
            $xmlLocales .= '    <locale region="' . $locale['region'] . '" name="' . $name . '" native="' . $native . '">' . PHP_EOL;
            foreach ($locale['text'] as $text) {
                if (!isset($text['source']) || !isset($text['output'])) {
                    throw new Exception("Error: The 'source' and 'output' keys must be defined in each 'text' array.");
                }
                $xmlLocales .= '        <text>' . PHP_EOL;
                $xmlLocales .= '            <source>' . $text['source'] . '</source>' . PHP_EOL;
                $xmlLocales .= '            <output>' . $text['output'] . '</output>' . PHP_EOL;
                $xmlLocales .= '        </text>' . PHP_EOL;
            }
            $xmlLocales .= '    </locale>' . PHP_EOL;
        }

        // Save XML file
        file_put_contents($file, $xmlHeader . PHP_EOL . $xmlLocales . '</language>');
    }

    /**
     * Create an XML document fragment from a source file and an output file,
     * each entry separated by a new line
     *
     * @param  string $source
     * @param  string $output
     * @param  string $target
     * @throws Exception
     * @return void
     */
    public static function createXmlFromText($source, $output, $target = null)
    {
        if (!file_exists($source)) {
            throw new Exception('Error: The source file does not exist.');
        }
        if (!file_exists($output)) {
            throw new Exception('Error: The output file does not exist.');
        }

        $sourceLines = explode(PHP_EOL, file_get_contents($source));
        $outputLines = explode(PHP_EOL, file_get_contents($output));

        $targetDir = (null !== $target) ? $target : dirname($output);

        if (!file_exists($targetDir)) {
            throw new Exception('Error: The target directory does not exist.');
        }

        if (strpos($output, '/') !== false) {
            $lang = substr($output, (strrpos($output, '/') + 1));
            $lang = substr($lang, 0, strpos($lang, '.'));
        } else if (strpos($output, "\\") !== false) {
            $lang = substr($output, (strrpos($output, "\\") + 1));
            $lang = substr($lang, 0, strpos($lang, '.'));
        } else {
            $lang = substr($output, 0, strpos($output, '.'));
        }

        $xml = null;

        foreach ($outputLines as $key => $value) {
            if (!empty($value) && !empty($sourceLines[$key])) {
                $xml .= '        <text>' . PHP_EOL . '            <source>' . $sourceLines[$key] . '</source>' . PHP_EOL .
                    '            <output>' . $value . '</output>' . PHP_EOL .
                    '        </text>' . PHP_EOL;
            }
        }

        file_put_contents($targetDir . DIRECTORY_SEPARATOR . $lang . '.xml', $xml);
    }

    /**
     * Translate and return the string.
     *
     * @param  string $str
     * @param  string|array $params
     * @return mixed
     */
    protected function translate($str, $params = null)
    {
        $key = array_search($str, $this->content['source']);
        $trans = ($key !== false) ? $this->content['output'][$key] : $str;

        if (null !== $params) {
            if (is_array($params)) {
                foreach ($params as $key => $value) {
                    $trans = str_replace('%' . ($key + 1), $value, $trans);
                }
            } else {
                $trans = str_replace('%1', $params, $trans);
            }
        }

        return $trans;
    }

    /**
     * Get language content from the XML file.
     *
     * @return void
     */
    protected function loadCurrentLanguage()
    {
        $this->loadFile(__DIR__ . '/Data/' . $this->language . '.xml');
    }

}