text:
package javax.naming.directory;

import java.util.Vector;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.lang.reflect.Array;

import javax.naming.NamingException;
import javax.naming.NamingEnumeration;
import javax.naming.OperationNotSupportedException;

/**
  * This class provides a basic implementation of the <tt>Attribute</tt> interface.
  *

  * This implementation does not support the schema methods
  * <tt>getAttributeDefinition()</tt> and <tt>getAttributeSyntaxDefinition()</tt>.
  * They simply throw <tt>OperationNotSupportedException</tt>.
  * Subclasses of <tt>BasicAttribute</tt> should override these methods if they
  * support them.
  *

  * The <tt>BasicAttribute</tt> class by default uses <tt>Object.equals()</tt> to
  * determine equality of attribute values when testing for equality or
  * when searching for values, except when the value is an array.
  * For an array, each element of the array is checked using <tt>Object.equals()</tt>.
  * Subclasses of <tt>BasicAttribute</tt> can make use of schema information
  * when doing similar equality checks by overriding methods
  * in which such use of schema is meaningful.
  * Similarly, the <tt>BasicAttribute</tt> class by default returns the values passed to its
  * constructor and/or manipulated using the add/remove methods.
  * Subclasses of <tt>BasicAttribute</tt> can override <tt>get()</tt> and <tt>getAll()</tt>
  * to get the values dynamically from the directory (or implement
  * the <tt>Attribute</tt> interface directly instead of subclassing <tt>BasicAttribute</tt>).
  *

  * Note that updates to <tt>BasicAttribute</tt> (such as adding or removing a value)
  * does not affect the corresponding representation of the attribute
  * in the directory.  Updates to the directory can only be effected
  * using operations in the <tt>DirContext</tt> interface.
  *

  * A <tt>BasicAttribute</tt> instance is not synchronized against concurrent
  * multithreaded access. Multiple threads trying to access and modify a
  * <tt>BasicAttribute</tt> should lock the object.
  *
  * @author Rosanna Lee
  * @author Scott Seligman
  * @since 1.3
  */
public class BasicAttribute implements Attribute {
    /**
     * Holds the attribute's id. It is initialized by the public constructor and
     * cannot be null unless methods in BasicAttribute that use attrID
     * have been overridden.
     * @serial
     */
    protected String attrID;

    /**
     * Holds the attribute's values. Initialized by public constructors.
     * Cannot be null unless methods in BasicAttribute that use
     * values have been overridden.
     */
    protected transient Vector<Object> values;

    /**
     * A flag for recording whether this attribute's values are ordered.
     * @serial
     */
    protected boolean ordered = false;

    public Object clone() {
        BasicAttribute attr;
        try {
            attr = (BasicAttribute)super.clone();
        } catch (CloneNotSupportedException e) {
            attr = new BasicAttribute(attrID, ordered);
        }
        attr.values = (Vector)values.clone();
        return attr;
    }

    /**
      * Determines whether obj is equal to this attribute.
      * Two attributes are equal if their attribute-ids, syntaxes
      * and values are equal.
      * If the attribute values are unordered, the order that the values were added
      * are irrelevant. If the attribute values are ordered, then the
      * order the values must match.
      * If obj is null or not an Attribute, false is returned.
      *

      * By default <tt>Object.equals()</tt> is used when comparing the attribute
      * id and its values except when a value is an array. For an array,
      * each element of the array is checked using <tt>Object.equals()</tt>.
      * A subclass may override this to make
      * use of schema syntax information and matching rules,
      * which define what it means for two attributes to be equal.
      * How and whether a subclass makes
      * use of the schema information is determined by the subclass.
      * If a subclass overrides <tt>equals()</tt>, it should also override
      * <tt>hashCode()</tt>
      * such that two attributes that are equal have the same hash code.
      *
      * @param obj      The possibly null object to check.
      * @return true if obj is equal to this attribute; false otherwise.
      * @see #hashCode
      * @see #contains
      */
    public boolean equals(Object obj) {
        if ((obj != null) && (obj instanceof Attribute)) {
            Attribute target = (Attribute)obj;

            // Check order first
            if (isOrdered() != target.isOrdered()) {
                return false;
            }
            int len;
            if (attrID.equals(target.getID()) &&
                (len=size()) == target.size()) {
                try {
                    if (isOrdered()) {
                        // Go through both list of values
                        for (int i = 0; i < len; i++) {
                            if (!valueEquals(get(i), target.get(i))) {
                                return false;
                            }
                        }
                    } else {
                        // order is not relevant; check for existence
                        Enumeration theirs = target.getAll();
                        while (theirs.hasMoreElements()) {
                            if (find(theirs.nextElement()) < 0)
                                return false;
                        }
                    }
                } catch (NamingException e) {
                    return false;
                }
                return true;
            }
        }
        return false;
    }

    /**
      * Calculates the hash code of this attribute.
      *

      * The hash code is computed by adding the hash code of
      * the attribute's id and that of all of its values except for
      * values that are arrays.
      * For an array, the hash code of each element of the array is summed.
      * If a subclass overrides <tt>hashCode()</tt>, it should override
      * <tt>equals()</tt>
      * as well so that two attributes that are equal have the same hash code.
      *
      * @return an int representing the hash code of this attribute.
      * @see #equals
      */
    public int hashCode() {
        int hash = attrID.hashCode();
        int num = values.size();
        Object val;
        for (int i = 0; i < num; i ++) {
            val = values.elementAt(i);
            if (val != null) {
                if (val.getClass().isArray()) {
                    Object it;
                    int len = Array.getLength(val);
                    for (int j = 0 ; j < len ; j++) {
                        it = Array.get(val, j);
                        if (it != null) {
                            hash += it.hashCode();
                        }
                    }
                } else {
                    hash += val.hashCode();
                }
            }
        }
        return hash;
    }

    /**
      * Generates the string representation of this attribute.
      * The string consists of the attribute's id and its values.
      * This string is meant for debugging and not meant to be
      * interpreted programmatically.
      * @return The non-null string representation of this attribute.
      */
    public String toString() {
        StringBuffer answer = new StringBuffer(attrID + ": ");
        if (values.size() == 0) {
            answer.append("No values");
        } else {
            boolean start = true;
            for (Enumeration e = values.elements(); e.hasMoreElements(); ) {
                if (!start)
                    answer.append(", ");
                answer.append(e.nextElement());
                start = false;
            }
        }
        return answer.toString();
    }

    /**
      * Constructs a new instance of an unordered attribute with no value.
      *
      * @param id The attribute's id. It cannot be null.
      */
    public BasicAttribute(String id) {
        this(id, false);
    }

    /**
      * Constructs a new instance of an unordered attribute with a single value.
      *
      * @param id The attribute's id. It cannot be null.
      * @param value The attribute's value. If null, a null
      *        value is added to the attribute.
      */
    public BasicAttribute(String id, Object value) {
        this(id, value, false);
    }

    /**
      * Constructs a new instance of a possibly ordered attribute with no value.
      *
      * @param id The attribute's id. It cannot be null.
      * @param ordered true means the attribute's values will be ordered;
      * false otherwise.
      */
    public BasicAttribute(String id, boolean ordered) {
        attrID = id;
        values = new Vector();
        this.ordered = ordered;
    }

    /**
      * Constructs a new instance of a possibly ordered attribute with a
      * single value.
      *
      * @param id The attribute's id. It cannot be null.
      * @param value The attribute's value. If null, a null
      *        value is added to the attribute.
      * @param ordered true means the attribute's values will be ordered;
      * false otherwise.
      */
    public BasicAttribute(String id, Object value, boolean ordered) {
        this(id, ordered);
        values.addElement(value);
    }

    /**
      * Retrieves an enumeration of this attribute's values.
      *

      * By default, the values returned are those passed to the
      * constructor and/or manipulated using the add/replace/remove methods.
      * A subclass may override this to retrieve the values dynamically
      * from the directory.
      */
    public NamingEnumeration<?> getAll() throws NamingException {
      return new ValuesEnumImpl();
    }

    /**
      * Retrieves one of this attribute's values.
      *

      * By default, the value returned is one of those passed to the
      * constructor and/or manipulated using the add/replace/remove methods.
      * A subclass may override this to retrieve the value dynamically
      * from the directory.
      */
    public Object get() throws NamingException {
        if (values.size() == 0) {
            throw new
        NoSuchElementException("Attribute " + getID() + " has no value");
        } else {
            return values.elementAt(0);
        }
    }

    public int size() {
      return values.size();
    }

    public String getID() {
        return attrID;
    }

    /**
      * Determines whether a value is in this attribute.
      *

      * By default,
      * <tt>Object.equals()</tt> is used when comparing <tt>attrVal</tt>
      * with this attribute's values except when <tt>attrVal</tt> is an array.
      * For an array, each element of the array is checked using
      * <tt>Object.equals()</tt>.
      * A subclass may use schema information to determine equality.
      */
    public boolean contains(Object attrVal) {
        return (find(attrVal) >= 0);
    }

    // For finding first element that has a null in JDK1.1 Vector.
    // In the Java 2 platform, can just replace this with Vector.indexOf(target);
    private int find(Object target) {
        Class cl;
        if (target == null) {
            int ct = values.size();
            for (int i = 0 ; i < ct ; i++) {
                if (values.elementAt(i) == null)
                    return i;
            }
        } else if ((cl=target.getClass()).isArray()) {
            int ct = values.size();
            Object it;
            for (int i = 0 ; i < ct ; i++) {
                it = values.elementAt(i);
                if (it != null && cl == it.getClass()
                    && arrayEquals(target, it))
                    return i;
            }
        } else {
            return values.indexOf(target, 0);
        }
        return -1;  // not found
    }

    /**
     * Determines whether two attribute values are equal.
     * Use arrayEquals for arrays and <tt>Object.equals()</tt> otherwise.
     */
    private static boolean valueEquals(Object obj1, Object obj2) {
        if (obj1 == obj2) {
            return true; // object references are equal
        }
        if (obj1 == null) {
            return false; // obj2 was not false
        }
        if (obj1.getClass().isArray() &&
            obj2.getClass().isArray()) {
            return arrayEquals(obj1, obj2);
        }
        return (obj1.equals(obj2));
    }

    /**
     * Determines whether two arrays are equal by comparing each of their
     * elements using <tt>Object.equals()</tt>.
     */
    private static boolean arrayEquals(Object a1, Object a2) {
        int len;
        if ((len = Array.getLength(a1)) != Array.getLength(a2))
            return false;

        for (int j = 0; j < len; j++) {
            Object i1 = Array.get(a1, j);
            Object i2 = Array.get(a2, j);
            if (i1 == null || i2 == null) {
                if (i1 != i2)
                    return false;
            } else if (!i1.equals(i2)) {
                return false;
            }
        }
        return true;
    }

    /**
      * Adds a new value to this attribute.
      *

      * By default, <tt>Object.equals()</tt> is used when comparing <tt>attrVal</tt>
      * with this attribute's values except when <tt>attrVal</tt> is an array.
      * For an array, each element of the array is checked using
      * <tt>Object.equals()</tt>.
      * A subclass may use schema information to determine equality.
      */
    public boolean add(Object attrVal) {
        if (isOrdered() || (find(attrVal) < 0)) {
            values.addElement(attrVal);
            return true;
        } else {
            return false;
        }
    }

    /**
      * Removes a specified value from this attribute.
      *

      * By default, <tt>Object.equals()</tt> is used when comparing <tt>attrVal</tt>
      * with this attribute's values except when <tt>attrVal</tt> is an array.
      * For an array, each element of the array is checked using
      * <tt>Object.equals()</tt>.
      * A subclass may use schema information to determine equality.
      */
    public boolean remove(Object attrval) {
        // For the Java 2 platform, can just use "return removeElement(attrval);"
        // Need to do the following to handle null case

        int i = find(attrval);
        if (i >= 0) {
            values.removeElementAt(i);
            return true;
        }
        return false;
    }

    public void clear() {
        values.setSize(0);
    }

//  ---- ordering methods

    public boolean isOrdered() {
        return ordered;
    }

    public Object get(int ix) throws NamingException {
        return values.elementAt(ix);
    }

    public Object remove(int ix) {
        Object answer = values.elementAt(ix);
        values.removeElementAt(ix);
        return answer;
    }

    public void add(int ix, Object attrVal) {
        if (!isOrdered() && contains(attrVal)) {
            throw new IllegalStateException(
                "Cannot add duplicate to unordered attribute");
        }
        values.insertElementAt(attrVal, ix);
    }

    public Object set(int ix, Object attrVal) {
        if (!isOrdered() && contains(attrVal)) {
            throw new IllegalStateException(
                "Cannot add duplicate to unordered attribute");
        }

        Object answer = values.elementAt(ix);
        values.setElementAt(attrVal, ix);
        return answer;
    }

// ----------------- Schema methods

    /**
      * Retrieves the syntax definition associated with this attribute.
      *

      * This method by default throws OperationNotSupportedException. A subclass
      * should override this method if it supports schema.
      */
    public DirContext getAttributeSyntaxDefinition() throws NamingException {
            throw new OperationNotSupportedException("attribute syntax");
    }

    /**
      * Retrieves this attribute's schema definition.
      *

      * This method by default throws OperationNotSupportedException. A subclass
      * should override this method if it supports schema.
      */
    public DirContext getAttributeDefinition() throws NamingException {
        throw new OperationNotSupportedException("attribute definition");
    }

//  ---- serialization methods

    /**
     * Overridden to avoid exposing implementation details
     * @serialData Default field (the attribute ID -- a String),
     * followed by the number of values (an int), and the
     * individual values.
     */
    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        s.defaultWriteObject(); // write out the attrID
        s.writeInt(values.size());
        for (int i = 0; i < values.size(); i++) {
            s.writeObject(values.elementAt(i));
        }
    }

    /**
     * Overridden to avoid exposing implementation details.
     */
    private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();  // read in the attrID
        int n = s.readInt();    // number of values
        values = new Vector(n);
        while (--n >= 0) {
            values.addElement(s.readObject());
        }
    }

    class ValuesEnumImpl implements NamingEnumeration<Object> {
    Enumeration list;

    ValuesEnumImpl() {
        list = values.elements();
    }

    public boolean hasMoreElements() {
        return list.hasMoreElements();
    }

    public Object nextElement() {
        return(list.nextElement());
    }

    public Object next() throws NamingException {
        return list.nextElement();
    }

    public boolean hasMore() throws NamingException {
        return list.hasMoreElements();
    }

    public void close() throws NamingException {
        list = null;
    }
    }

    /**
     * Use serialVersionUID from JNDI 1.1.1 for interoperability.
     */
    private static final long serialVersionUID = 6743528196119291326L;
}


text:
static void wmf_plot_region_frame (wmfAPI* API,wmfPolyRectangle_t* poly_rect)
{	wmf_plot_t* ddata = WMF_PLOT_GetData (API);

	plot_t* plot = (plot_t*) ddata->plot_data;

	WMF_DEBUG (API,"wmf_[plot_]region_frame");

}

static void wmf_plot_region_paint (wmfAPI* API,wmfPolyRectangle_t* poly_rect)
{	wmf_plot_t* ddata = WMF_PLOT_GetData (API);

	plot_t* plot = (plot_t*) ddata->plot_data;

	WMF_DEBUG (API,"wmf_[plot_]region_paint");

}

static void wmf_plot_region_clip (wmfAPI* API,wmfPolyRectangle_t* poly_rect)
{	wmf_plot_t* ddata = WMF_PLOT_GetData (API);

	plot_t* plot = (plot_t*) ddata->plot_data;

	WMF_DEBUG (API,"wmf_[plot_]region_clip");

}

redpajama_set_name: RedPajamaGithub


text:
/* graph.h */
/*
	This software library implements the maxflow algorithm
	described in

		An Experimental Comparison of Min-Cut/Max-Flow Algorithms
		for Energy Minimization in Vision.
		Yuri Boykov and Vladimir Kolmogorov.
		In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI),
		September 2004

	This algorithm was developed by Yuri Boykov and Vladimir Kolmogorov
	at Siemens Corporate Research. To make it available for public use,
	it was later reimplemented by Vladimir Kolmogorov based on open publications.

	If you use this software for research purposes, you should cite
	the aforementioned paper in any resulting publication.
*/

/*
	Copyright 2001 Vladimir Kolmogorov (vnk@cs.cornell.edu), Yuri Boykov (yuri@csd.uwo.ca).

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/*
	For description, example usage, discussion of graph representation
	and memory usage see README.TXT.
*/

#ifndef __GRAPH_H__
#define __GRAPH_H__

#include <tmwtypes.h>
#include "block.h"

/*
	Nodes, arcs and pointers to nodes are
	added in blocks for memory and time efficiency.
	Below are numbers of items in blocks
*/
#define NODE_BLOCK_SIZE 512
#define ARC_BLOCK_SIZE 1024
#define NODEPTR_BLOCK_SIZE 128

class Graph
{
public:
	typedef enum
	{
		SOURCE	= 0,
		SINK	= 1
	} termtype; /* terminals */

	/* Type of edge weights.
	   Can be changed to char, int, float, double, ... */
	typedef float captype; /* bagon changed  from int to float */

    /* Type of total flow */
	typedef float flowtype; /* bagon changed  from int to float */
	typedef void * node_id;

	/* interface functions */

	/* Constructor. Optional argument is the pointer to the
	   function which will be called if an error occurs;
	   an error message is passed to this function. If this
	   argument is omitted, exit(1) will be called. */
	Graph(void (*err_function)(const char *) = NULL);

	/* Destructor */
	~Graph();

	/* Adds a node to the graph */
	node_id add_node();

	/* Adds a bidirectional edge between 'from' and 'to'
	   with the weights 'cap' and 'rev_cap' */
	void add_edge(node_id from, node_id to, captype cap, captype rev_cap);

	/* Sets the weights of the edges 'SOURCE->i' and 'i->SINK'
	   Can be called at most once for each node before any call to 'add_tweights'.
	   Weights can be negative */
	void set_tweights(node_id i, captype cap_source, captype cap_sink);

	/* Adds new edges 'SOURCE->i' and 'i->SINK' with corresponding weights
	   Can be called multiple times for each node.
	   Weights can be negative */
	void add_tweights(node_id i, captype cap_source, captype cap_sink);

	/* After the maxflow is computed, this function returns to which
	   segment the node 'i' belongs (Graph::SOURCE or Graph::SINK) */
	termtype what_segment(node_id i);

	/* Computes the maxflow. Can be called only once. */
	flowtype maxflow();

/***********************************************************************/
/***********************************************************************/
/***********************************************************************/

private:
	/* internal variables and functions */

	struct arc_forward_st;
	struct arc_reverse_st;

#ifdef A64BITS
#define POINTER_CAST    int64_T
#else
#define POINTER_CAST    int
#endif

#define IS_ODD(a) ((POINTER_CAST)(a) & 1)
#define MAKE_ODD(a)  ((arc_forward *) ((POINTER_CAST)(a) | 1))
#define MAKE_EVEN(a) ((arc_forward *) ((POINTER_CAST)(a) & (~1)))
#define MAKE_ODD_REV(a)  ((arc_reverse *) ((POINTER_CAST)(a) | 1))
#define MAKE_EVEN_REV(a) ((arc_reverse *) ((POINTER_CAST)(a) & (~1)))

	/* node structure */
	typedef struct node_st
	{
		/*
			Usually i->first_out is the first outgoing
			arc, and (i+1)->first_out-1 is the last outgoing arc.
			However, it is not always possible, since
			arcs are allocated in blocks, so arcs corresponding
			to two consecutive nodes may be in different blocks.

			If outgoing arcs for i are last in the arc block,
			then a different mechanism is used. i->first_out
			is odd in this case; the first outgoing arc
			is (a+1), and the last outgoing arc is
			((arc_forward *)(a->shift))-1, where
			a = (arc_forward *) (((char *)(i->first_out)) + 1);

			Similar mechanism is used for incoming arcs.
		*/
		arc_forward_st	*first_out;	/* first outcoming arc */
		arc_reverse_st	*first_in;	/* first incoming arc */

		arc_forward_st	*parent;	/* describes node's parent
									   if IS_ODD(parent) then MAKE_EVEN(parent) points to 'arc_reverse',
									   otherwise parent points to 'arc_forward' */

		node_st			*next;		/* pointer to the next active node
									   (or to itself if it is the last node in the list) */

		int				TS;			/* timestamp showing when DIST was computed */
		int				DIST;		/* distance to the terminal */
		short			is_sink;	/* flag showing whether the node is in the source or in the sink tree */

		captype			tr_cap;		/* if tr_cap > 0 then tr_cap is residual capacity of the arc SOURCE->node
									   otherwise         -tr_cap is residual capacity of the arc node->SINK */
	} node;

	/* arc structures */
#define NEIGHBOR_NODE(i, shift) ((node *) ((char *)(i) + (shift)))
#define NEIGHBOR_NODE_REV(i, shift) ((node *) ((char *)(i) - (shift)))
	typedef struct arc_forward_st
	{
		POINTER_CAST	shift;		/* node_to = NEIGHBOR_NODE(node_from, shift) */
		captype			r_cap;		/* residual capacity */
		captype			r_rev_cap;	/* residual capacity of the reverse arc*/
	} arc_forward;

	typedef struct arc_reverse_st
	{
		arc_forward		*sister;	/* reverse arc */
	} arc_reverse;

	/* 'pointer to node' structure */
	typedef struct nodeptr_st
	{
		node_st			*ptr;
		nodeptr_st		*next;
	} nodeptr;

	typedef struct node_block_st
	{
		node					*current;
		struct node_block_st	*next;
		node					nodes[NODE_BLOCK_SIZE];
	} node_block;

#define last_node LAST_NODE.LAST_NODE

	typedef struct arc_for_block_st
	{
		char					*start;		/* the actual start address of this block.
											   May be different from 'this' since 'this'
											   must be at an even address. */
		arc_forward				*current;
		struct arc_for_block_st	*next;
		arc_forward				arcs_for[ARC_BLOCK_SIZE]; /* all arcs must be at even addresses */
		union
		{
			arc_forward			dummy;
			node				*LAST_NODE;	/* used in graph consruction */
		}						LAST_NODE;
	} arc_for_block;

	typedef struct arc_rev_block_st
	{
		char					*start;		/* the actual start address of this block.
											   May be different from 'this' since 'this'
											   must be at an even address. */
		arc_reverse				*current;
		struct arc_rev_block_st	*next;
		arc_reverse				arcs_rev[ARC_BLOCK_SIZE]; /* all arcs must be at even addresses */
		union
		{
			arc_reverse			dummy;
			node				*LAST_NODE;	/* used in graph consruction */
		}						LAST_NODE;
	} arc_rev_block;

	node_block			*node_block_first;
	arc_for_block		*arc_for_block_first;
	arc_rev_block		*arc_rev_block_first;
	DBlock<nodeptr>		*nodeptr_block;

	void	(*error_function)(const char *);	/* this function is called if a error occurs,
										   with a corresponding error message
										   (or exit(1) is called if it's NULL) */

	flowtype			flow;		/* total flow */

/***********************************************************************/

	node				*queue_first[2], *queue_last[2];	/* list of active nodes */
	nodeptr				*orphan_first, *orphan_last;		/* list of pointers to orphans */
	int					TIME;								/* monotonically increasing global counter */

/***********************************************************************/

	/* functions for processing active list */
	void set_active(node *i);
	node *next_active();

	void prepare_graph();
	void maxflow_init();
	void augment(node *s_start, node *t_start, captype *cap_middle, captype *rev_cap_middle);
	void process_source_orphan(node *i);
	void process_sink_orphan(node *i);
};

#endif


text:
package com.facebook.buck.cli;

import com.facebook.buck.apple.AppleBuildRules;
import com.facebook.buck.apple.AppleBundleDescription;
import com.facebook.buck.apple.AppleLibraryDescription;
import com.facebook.buck.apple.AppleTestDescription;
import com.facebook.buck.apple.ProjectGenerator;
import com.facebook.buck.apple.SchemeActionType;
import com.facebook.buck.apple.WorkspaceAndProjectGenerator;
import com.facebook.buck.apple.XcodeWorkspaceConfigDescription;
import com.facebook.buck.io.ExecutableFinder;
import com.facebook.buck.java.JavaBuckConfig;
import com.facebook.buck.java.JavaFileParser;
import com.facebook.buck.java.JavaLibraryDescription;
import com.facebook.buck.java.JavaPackageFinder;
import com.facebook.buck.java.JavacOptions;
import com.facebook.buck.java.intellij.IjProject;
import com.facebook.buck.java.intellij.IntellijConfig;
import com.facebook.buck.java.intellij.Project;
import com.facebook.buck.js.ReactNativeBuckConfig;
import com.facebook.buck.json.BuildFileParseException;
import com.facebook.buck.log.Logger;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetException;
import com.facebook.buck.model.FilesystemBackedBuildFileTree;
import com.facebook.buck.model.HasBuildTarget;
import com.facebook.buck.parser.BuildFileSpec;
import com.facebook.buck.parser.BuildTargetSpec;
import com.facebook.buck.parser.ParserConfig;
import com.facebook.buck.parser.TargetNodePredicateSpec;
import com.facebook.buck.parser.TargetNodeSpec;
import com.facebook.buck.python.PythonBuckConfig;
import com.facebook.buck.rules.ActionGraph;
import com.facebook.buck.rules.AssociatedTargetNodePredicate;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.ProjectConfig;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.TargetGraphAndTargets;
import com.facebook.buck.rules.TargetGraphToActionGraph;
import com.facebook.buck.rules.TargetNode;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.ProcessExecutor;
import com.facebook.buck.util.ProcessManager;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ascii;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.io.Files;

import org.kohsuke.args4j.Option;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Nullable;

public class ProjectCommand extends BuildCommand {

  private static final Logger LOG = Logger.get(ProjectCommand.class);

  /**
   * Include java library targets (and android library targets) that use annotation
   * processing.  The sources generated by these annotation processors is needed by
   * IntelliJ.
   */
  private static final Predicate<TargetNode<?>> ANNOTATION_PREDICATE =
      new Predicate<TargetNode<?>>() {
        @Override
        public boolean apply(TargetNode<?> input) {
          if (input.getType() != JavaLibraryDescription.TYPE) {
            return false;
          }
          JavaLibraryDescription.Arg arg = ((JavaLibraryDescription.Arg) input.getConstructorArg());
          return !arg.annotationProcessors.get().isEmpty();
        }
      };

  private static final String XCODE_PROCESS_NAME = "Xcode";

  public enum Ide {
    INTELLIJ,
    XCODE;

    public static Ide fromString(String string) {
      switch (Ascii.toLowerCase(string)) {
        case "intellij":
          return Ide.INTELLIJ;
        case "xcode":
          return Ide.XCODE;
        default:
          throw new HumanReadableException("Invalid ide value %s.", string);
      }
    }

  }

  private static final Ide DEFAULT_IDE_VALUE = Ide.INTELLIJ;
  private static final boolean DEFAULT_READ_ONLY_VALUE = false;
  private static final boolean DEFAULT_DISABLE_R_JAVA_IDEA_GENERATOR = false;

  @Option(
      name = "--combined-project",
      usage = "Generate an xcode project of a target and its dependencies.")
  private boolean combinedProject;

  @Option(
      name = "--build-with-buck",
      usage = "Use Buck to build the generated project instead of delegating the build to the IDE.")
  private boolean buildWithBuck;

  @Option(name = "--process-annotations", usage = "Enable annotation processing")
  private boolean processAnnotations;

  @Option(
      name = "--without-tests",
      usage = "When generating a project slice, exclude tests that test the code in that slice")
  private boolean withoutTests = false;

  @Option(
      name = "--combine-test-bundles",
      usage = "Combine multiple ios/osx test targets into the same bundle if they have identical " +
          "settings")
  private boolean combineTestBundles = false;

  @Option(
      name = "--ide",
      usage = "The type of IDE for which to generate a project. Defaults to 'intellij' if not " +
          "specified in .buckconfig.")
  @Nullable
  private Ide ide = null;

  @Option(
      name = "--read-only",
      usage = "If true, generate project files read-only. Defaults to '" +
          DEFAULT_READ_ONLY_VALUE + "' if not specified in .buckconfig. (Only " +
          "applies to generated Xcode projects.)")
  private boolean readOnly = DEFAULT_READ_ONLY_VALUE;

  @Option(
      name = "--dry-run",
      usage = "Instead of actually generating the project, only print out the targets that " +
          "would be included.")
  private boolean dryRun = false;

  @Option(
      name = "--disable-r-java-idea-generator",
      usage = "Turn off auto generation of R.java by Android IDEA plugin." +
          " You can specify disable_r_java_idea_generator = true" +
          " in .buckconfig/project section")
  private boolean androidAutoGenerateDisabled = DEFAULT_DISABLE_R_JAVA_IDEA_GENERATOR;

  @Option(
      name = "--experimental-ij-generation",
      usage = "Enables the experimental IntelliJ project generator.")
  private boolean experimentalIntelliJProjectGenerationEnabled = false;

  public boolean getCombinedProject() {
    return combinedProject;
  }

  public boolean getDryRun() {
    return dryRun;
  }

  public boolean getCombineTestBundles() {
    return combineTestBundles;
  }

  public boolean shouldProcessAnnotations() {
    return processAnnotations;
  }

  public ImmutableMap<Path, String> getBasePathToAliasMap(BuckConfig buckConfig) {
    return buckConfig.getBasePathToAliasMap();
  }

  public JavaPackageFinder getJavaPackageFinder(BuckConfig buckConfig) {
    return buckConfig.createDefaultJavaPackageFinder();
  }

  public Optional<String> getPathToDefaultAndroidManifest(BuckConfig buckConfig) {
    return buckConfig.getValue("project", "default_android_manifest");
  }

  public Optional<String> getPathToPostProcessScript(BuckConfig buckConfig) {
    return buckConfig.getValue("project", "post_process");
  }

  public boolean getReadOnly(BuckConfig buckConfig) {
    if (readOnly) {
      return readOnly;
    }
    return buckConfig.getBooleanValue("project", "read_only", DEFAULT_READ_ONLY_VALUE);
  }

  public boolean isAndroidAutoGenerateDisabled(BuckConfig buckConfig) {
    if (androidAutoGenerateDisabled) {
      return androidAutoGenerateDisabled;
    }
    return buckConfig.getBooleanValue(
        "project",
        "disable_r_java_idea_generator",
        DEFAULT_DISABLE_R_JAVA_IDEA_GENERATOR);
  }

  /**
   * Returns true if Buck should prompt to kill a running IDE before changing its files,
   * false otherwise.
   */
  public boolean getIdePrompt(BuckConfig buckConfig) {
    return buckConfig.getBooleanValue("project", "ide_prompt", true);
  }

  public Ide getIde(BuckConfig buckConfig) {
    if (ide != null) {
      return ide;
    } else {
      Optional<Ide> ide = buckConfig.getValue("project", "ide").transform(
          new Function<String, Ide>() {
            @Override
            public Ide apply(String input) {
              return Ide.fromString(input);
            }
          });
      return ide.or(DEFAULT_IDE_VALUE);
    }
  }

  public boolean isWithTests() {
    return !withoutTests;
  }

  private List<String> getInitialTargets(BuckConfig buckConfig) {
    Optional<String> initialTargets = buckConfig.getValue("project", "initial_targets");
    return initialTargets.isPresent()
        ? Lists.newArrayList(Splitter.on(' ').trimResults().split(initialTargets.get()))
        : ImmutableList.<String>of();
  }

  public boolean hasInitialTargets(BuckConfig buckConfig) {
    return !getInitialTargets(buckConfig).isEmpty();
  }

  public BuildCommand createBuildCommandOptionsWithInitialTargets(
      BuckConfig buckConfig,
      List<String> additionalInitialTargets) {
    List<String> initialTargets;
    if (additionalInitialTargets.isEmpty()) {
      initialTargets = getInitialTargets(buckConfig);
    } else {
      initialTargets = Lists.newArrayList();
      initialTargets.addAll(getInitialTargets(buckConfig));
      initialTargets.addAll(additionalInitialTargets);
    }

    BuildCommand buildCommand = new BuildCommand();
    buildCommand.setArguments(initialTargets);
    return buildCommand;
  }

  public boolean isExperimentalIntelliJProjectGenerationEnabled() {
    return experimentalIntelliJProjectGenerationEnabled;
  }

  public List<String> getArgumentsFormattedAsBuildTargets(BuckConfig buckConfig) {
    return getCommandLineBuildTargetNormalizer(buckConfig).normalizeAll(getArguments());
  }

  @Override
  public int runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException {
    if (getIde(params.getBuckConfig()) == ProjectCommand.Ide.XCODE) {
      checkForAndKillXcodeIfRunning(params, getIdePrompt(params.getBuckConfig()));
    }

    ImmutableSet<BuildTarget> passedInTargetsSet = getBuildTargets(
        getArgumentsFormattedAsBuildTargets(params.getBuckConfig()));
    ProjectGraphParser projectGraphParser = ProjectGraphParsers.createProjectGraphParser(
        params.getParser(),
        new ParserConfig(params.getBuckConfig()),
        params.getBuckEventBus(),
        params.getConsole(),
        params.getEnvironment(),
        getEnableProfiling());

    TargetGraph projectGraph = projectGraphParser.buildTargetGraphForTargetNodeSpecs(
        getTargetNodeSpecsForIde(
            getIde(params.getBuckConfig()),
            passedInTargetsSet,
            params.getRepository().getFilesystem().getIgnorePaths(),
            isExperimentalIntelliJProjectGenerationEnabled()));

    ProjectPredicates projectPredicates = ProjectPredicates.forIde(getIde(params.getBuckConfig()));

    ImmutableSet<BuildTarget> graphRoots;
    if (!passedInTargetsSet.isEmpty()) {
      ImmutableSet<BuildTarget> supplementalGraphRoots = ImmutableSet.of();
      if (getIde(params.getBuckConfig()) == Ide.INTELLIJ &&
          !isExperimentalIntelliJProjectGenerationEnabled()) {
        supplementalGraphRoots = getRootBuildTargetsForIntelliJ(
            getIde(params.getBuckConfig()),
            projectGraph,
            projectPredicates);
      }
      graphRoots = Sets.union(passedInTargetsSet, supplementalGraphRoots).immutableCopy();
    } else {
      graphRoots = getRootsFromPredicate(
          projectGraph,
          projectPredicates.getProjectRootsPredicate());
    }

    TargetGraphAndTargets targetGraphAndTargets = createTargetGraph(
        projectGraph,
        graphRoots,
        projectGraphParser,
        projectPredicates.getAssociatedProjectPredicate(),
        isWithTests(),
        getIde(params.getBuckConfig()),
        params.getRepository().getFilesystem().getIgnorePaths(),
        isExperimentalIntelliJProjectGenerationEnabled());

    if (getDryRun()) {
      for (TargetNode<?> targetNode : targetGraphAndTargets.getTargetGraph().getNodes()) {
        params.getConsole().getStdOut().println(targetNode.toString());
      }

      return 0;
    }

    switch (getIde(params.getBuckConfig())) {
      case INTELLIJ:
        return runIntellijProjectGenerator(
            params,
            projectGraph,
            targetGraphAndTargets,
            passedInTargetsSet);
      case XCODE:
        return runXcodeProjectGenerator(
            params,
            targetGraphAndTargets,
            passedInTargetsSet);
      default:
        // unreachable
        throw new IllegalStateException("'ide' should always be of type 'INTELLIJ' or 'XCODE'");
    }
  }

  @Override
  public boolean isReadOnly() {
    return false;
  }

  public static ImmutableSet<BuildTarget> getRootBuildTargetsForIntelliJ(
      ProjectCommand.Ide ide,
      TargetGraph projectGraph,
      ProjectPredicates projectPredicates) {
    if (ide != ProjectCommand.Ide.INTELLIJ) {
      return ImmutableSet.of();
    }
    return getRootsFromPredicate(
        projectGraph,
        Predicates.and(
            new Predicate<TargetNode<?>>() {

              @Override
              public boolean apply(TargetNode<?> input) {
                return input.getBuildTarget() != null &&
                    input.getBuildTarget().getBasePathWithSlash().isEmpty();
              }
            },
            projectPredicates.getProjectRootsPredicate()
        )
    );
  }

  /**
   * Run intellij specific project generation actions.
   */
  int runExperimentalIntellijProjectGenerator(
      CommandRunnerParams params,
      final TargetGraphAndTargets targetGraphAndTargets) throws IOException, InterruptedException {
    ActionGraph actionGraph = new TargetGraphToActionGraph(
        params.getBuckEventBus(),
        new BuildTargetNodeToBuildRuleTransformer(),
        params.getFileHashCache()).apply(targetGraphAndTargets.getTargetGraph());
    BuildRuleResolver buildRuleResolver =
        new BuildRuleResolver(ImmutableSet.copyOf(actionGraph.getNodes()));
    SourcePathResolver sourcePathResolver = new SourcePathResolver(buildRuleResolver);

    JavacOptions javacOptions = new JavaBuckConfig(params.getBuckConfig())
        .getDefaultJavacOptions(new ProcessExecutor(params.getConsole()));

    IjProject project = new IjProject(
        targetGraphAndTargets,
        getJavaPackageFinder(params.getBuckConfig()),
        JavaFileParser.createJavaFileParser(javacOptions),
        buildRuleResolver,
        sourcePathResolver,
        params.getRepository().getFilesystem());

    ImmutableSet<BuildTarget> requiredBuildTargets = project.write();

    if (!requiredBuildTargets.isEmpty()) {
      BuildCommand buildCommand = new BuildCommand();
      buildCommand.setArguments(
          FluentIterable.from(requiredBuildTargets)
              .transform(Functions.toStringFunction())
              .toList());
      return buildCommand.run(params);
    }

    return 0;
  }

  /**
   * Run intellij specific project generation actions.
   */
  int runIntellijProjectGenerator(
      CommandRunnerParams params,
      TargetGraph projectGraph,
      TargetGraphAndTargets targetGraphAndTargets,
      ImmutableSet<BuildTarget> passedInTargetsSet)
      throws IOException, InterruptedException {
    if (isExperimentalIntelliJProjectGenerationEnabled()) {
      return runExperimentalIntellijProjectGenerator(params, targetGraphAndTargets);
    }
    // Create an ActionGraph that only contains targets that can be represented as IDE
    // configuration files.
    ActionGraph actionGraph = new TargetGraphToActionGraph(
        params.getBuckEventBus(),
        new BuildTargetNodeToBuildRuleTransformer(),
        params.getFileHashCache()).apply(targetGraphAndTargets.getTargetGraph());

    try (ExecutionContext executionContext = createExecutionContext(params)) {
      Project project = new Project(
          new SourcePathResolver(
              new BuildRuleResolver(ImmutableSet.copyOf(actionGraph.getNodes()))),
          FluentIterable
              .from(actionGraph.getNodes())
              .filter(ProjectConfig.class)
              .toSortedSet(Ordering.natural()),
          actionGraph,
          getBasePathToAliasMap(params.getBuckConfig()),
          getJavaPackageFinder(params.getBuckConfig()),
          executionContext,
          new FilesystemBackedBuildFileTree(
              params.getRepository().getFilesystem(),
              new ParserConfig(params.getBuckConfig()).getBuildFileName()),
          params.getRepository().getFilesystem(),
          getPathToDefaultAndroidManifest(params.getBuckConfig()),
          new IntellijConfig(params.getBuckConfig()),
          getPathToPostProcessScript(params.getBuckConfig()),
          new PythonBuckConfig(
              params.getBuckConfig(),
              new ExecutableFinder()).getPythonInterpreter(),
          params.getObjectMapper(),
          isAndroidAutoGenerateDisabled(params.getBuckConfig()));

      File tempDir = Files.createTempDir();
      File tempFile = new File(tempDir, "project.json");
      int exitCode;
      try {
        exitCode = project.createIntellijProject(
            tempFile,
            executionContext.getProcessExecutor(),
            !passedInTargetsSet.isEmpty(),
            params.getConsole().getStdOut(),
            params.getConsole().getStdErr());
        if (exitCode != 0) {
          return exitCode;
        }

        List<String> additionalInitialTargets = ImmutableList.of();
        if (shouldProcessAnnotations()) {
          try {
            additionalInitialTargets = getAnnotationProcessingTargets(
                projectGraph,
                passedInTargetsSet);
          } catch (BuildTargetException | BuildFileParseException e) {
            throw new HumanReadableException(e);
          }
        }

        // Build initial targets.
        if (hasInitialTargets(params.getBuckConfig()) ||
            !additionalInitialTargets.isEmpty()) {
          BuildCommand buildCommand = createBuildCommandOptionsWithInitialTargets(
              params.getBuckConfig(),
              additionalInitialTargets);

          exitCode = buildCommand.runWithoutHelp(params);
          if (exitCode != 0) {
            return exitCode;
          }
        }
      } finally {
        // Either leave project.json around for debugging or delete it on exit.
        if (params.getConsole().getVerbosity().shouldPrintOutput()) {
          params.getConsole().getStdErr().printf(
              "project.json was written to %s",
              tempFile.getAbsolutePath());
        } else {
          tempFile.delete();
          tempDir.delete();
        }
      }

      if (passedInTargetsSet.isEmpty()) {
        String greenStar = params.getConsole().getAnsi().asHighlightedSuccessText(" * ");
        params.getConsole().getStdErr().printf(
            params.getConsole().getAnsi().asHighlightedSuccessText("=== Did you know ===") + "\n" +
                greenStar + "You can run `buck project <target>` to generate a minimal project " +
                "just for that target.\n" +
                greenStar + "This will make your IDE faster when working on large projects.\n" +
                greenStar + "See buck project --help for more info.\n" +
                params.getConsole().getAnsi().asHighlightedSuccessText(
                    "--=* Knowing is half the battle!") + "\n");
      }

      return 0;
    }
  }

  ImmutableList<String> getAnnotationProcessingTargets(
      TargetGraph projectGraph,
      ImmutableSet<BuildTarget> passedInTargetsSet)
      throws BuildTargetException, BuildFileParseException, IOException, InterruptedException {
    ImmutableSet<BuildTarget> buildTargets;
    if (!passedInTargetsSet.isEmpty()) {
      buildTargets = passedInTargetsSet;
    } else {
      buildTargets = getRootsFromPredicate(
          projectGraph,
          ANNOTATION_PREDICATE);
    }
    return FluentIterable
        .from(buildTargets)
        .transform(Functions.toStringFunction())
        .toList();
  }

  /**
   * Run xcode specific project generation actions.
   */
  int runXcodeProjectGenerator(
      final CommandRunnerParams params,
      final TargetGraphAndTargets targetGraphAndTargets,
      ImmutableSet<BuildTarget> passedInTargetsSet)
      throws IOException, InterruptedException {
    ImmutableSet.Builder<ProjectGenerator.Option> optionsBuilder = ImmutableSet.builder();
    if (getReadOnly(params.getBuckConfig())) {
      optionsBuilder.add(ProjectGenerator.Option.GENERATE_READ_ONLY_FILES);
    }
    if (isWithTests()) {
      optionsBuilder.add(ProjectGenerator.Option.INCLUDE_TESTS);
    }

    boolean combinedProject = getCombinedProject();
    ImmutableSet<BuildTarget> targets;
    if (passedInTargetsSet.isEmpty()) {
      targets = FluentIterable
          .from(targetGraphAndTargets.getProjectRoots())
          .transform(HasBuildTarget.TO_TARGET)
          .toSet();
    } else {
      targets = passedInTargetsSet;
    }
    if (combinedProject) {
      optionsBuilder.addAll(ProjectGenerator.COMBINED_PROJECT_OPTIONS);
    } else {
      optionsBuilder.addAll(ProjectGenerator.SEPARATED_PROJECT_OPTIONS);
    }
    LOG.debug("Generating workspace for config targets %s", targets);
    Map<Path, ProjectGenerator> projectGenerators = new HashMap<>();
    ImmutableSet<TargetNode<?>> testTargetNodes = targetGraphAndTargets.getAssociatedTests();
    ImmutableSet<TargetNode<AppleTestDescription.Arg>> groupableTests = getCombineTestBundles()
        ? AppleBuildRules.filterGroupableTests(testTargetNodes)
        : ImmutableSet.<TargetNode<AppleTestDescription.Arg>>of();
    ImmutableSet.Builder<BuildTarget> requiredBuildTargetsBuilder = ImmutableSet.builder();
    for (final BuildTarget inputTarget : targets) {
      TargetNode<?> inputNode = Preconditions.checkNotNull(
          targetGraphAndTargets.getTargetGraph().get(inputTarget));
      XcodeWorkspaceConfigDescription.Arg workspaceArgs;
      BuildRuleType type = inputNode.getType();
      if (type == XcodeWorkspaceConfigDescription.TYPE) {
        TargetNode<XcodeWorkspaceConfigDescription.Arg> castedWorkspaceNode =
            castToXcodeWorkspaceTargetNode(inputNode);
        workspaceArgs = castedWorkspaceNode.getConstructorArg();
      } else if (canGenerateImplicitWorkspaceForType(type)) {
        workspaceArgs = createImplicitWorkspaceArgs(inputNode);
      } else {
        throw new HumanReadableException(
            "%s must be a xcode_workspace_config, apple_bundle, or apple_library",
            inputNode);
      }
      WorkspaceAndProjectGenerator generator = new WorkspaceAndProjectGenerator(
          params.getRepository().getFilesystem(),
          new ReactNativeBuckConfig(params.getBuckConfig()),
          targetGraphAndTargets.getTargetGraph(),
          workspaceArgs,
          inputTarget,
          optionsBuilder.build(),
          combinedProject,
          buildWithBuck,
          super.getOptions(),
          new ParserConfig(params.getBuckConfig()).getBuildFileName(),
          new Function<TargetNode<?>, Path>() {
            @Nullable
            @Override
            public Path apply(TargetNode<?> input) {
              TargetGraphToActionGraph targetGraphToActionGraph = new TargetGraphToActionGraph(
                  params.getBuckEventBus(),
                  new BuildTargetNodeToBuildRuleTransformer(),
                  params.getFileHashCache());
              TargetGraph subgraph = targetGraphAndTargets.getTargetGraph().getSubgraph(
                  ImmutableSet.of(
                      input));
              ActionGraph actionGraph = Preconditions.checkNotNull(
                  targetGraphToActionGraph.apply(subgraph));
              BuildRule rule = Preconditions.checkNotNull(
                  actionGraph.findBuildRuleByTarget(input.getBuildTarget()));
              return rule.getPathToOutput();
            }
          });
      generator.setGroupableTests(groupableTests);
      generator.generateWorkspaceAndDependentProjects(projectGenerators);
      ImmutableSet<BuildTarget> requiredBuildTargetsForWorkspace =
          generator.getRequiredBuildTargets();
      LOG.debug(
          "Required build targets for workspace %s: %s",
          inputTarget,
          requiredBuildTargetsForWorkspace);
      requiredBuildTargetsBuilder.addAll(requiredBuildTargetsForWorkspace);
    }

    int exitCode = 0;
    ImmutableSet<BuildTarget> requiredBuildTargets = requiredBuildTargetsBuilder.build();
    if (!requiredBuildTargets.isEmpty()) {
      BuildCommand buildCommand = new BuildCommand();
      buildCommand.setArguments(
          FluentIterable.from(requiredBuildTargets)
              .transform(Functions.toStringFunction())
              .toList());
      exitCode = buildCommand.runWithoutHelp(params);
    }
    return exitCode;
  }

  @SuppressWarnings(value = "unchecked")
  private static TargetNode<XcodeWorkspaceConfigDescription.Arg> castToXcodeWorkspaceTargetNode(
      TargetNode<?> targetNode) {
    Preconditions.checkArgument(targetNode.getType() == XcodeWorkspaceConfigDescription.TYPE);
    return (TargetNode<XcodeWorkspaceConfigDescription.Arg>) targetNode;
  }

  private void checkForAndKillXcodeIfRunning(CommandRunnerParams params, boolean enablePrompt)
      throws InterruptedException, IOException {
    Optional<ProcessManager> processManager = params.getProcessManager();
    if (!processManager.isPresent()) {
      LOG.warn("Could not check if Xcode is running (no process manager)");
      return;
    }

    if (!processManager.get().isProcessRunning(XCODE_PROCESS_NAME)) {
      LOG.debug("Xcode is not running.");
      return;
    }

    if (enablePrompt && canPrompt()) {
      if (
          prompt(
              params,
              "Xcode is currently running. Buck will modify files Xcode currently has " +
                  "open, which can cause it to become unstable.\n\n" +
                  "Kill Xcode and continue?")) {
        processManager.get().killProcess(XCODE_PROCESS_NAME);
      } else {
        params.getConsole().getStdOut().println(
            params.getConsole().getAnsi().asWarningText(
                "Xcode is running. Generated projects might be lost or corrupted if Xcode " +
                    "currently has them open."));
      }
      params.getConsole().getStdOut().format(
          "To disable this prompt in the future, add the following to %s: \n\n" +
              "[project]\n" +
              "  ide_prompt = false\n\n",
          params.getRepository().getFilesystem()
              .getRootPath()
              .resolve(BuckConfig.DEFAULT_BUCK_CONFIG_OVERRIDE_FILE_NAME)
              .toAbsolutePath());
    } else {
      LOG.debug(
          "Xcode is running, but cannot prompt to kill it (enabled %s, can prompt %s)",
          enablePrompt, canPrompt());
    }
  }

  private boolean canPrompt() {
    return System.console() != null;
  }

  private boolean prompt(CommandRunnerParams params, String prompt) throws IOException {
    Preconditions.checkState(canPrompt());

    LOG.debug("Displaying prompt %s..", prompt);
    params
        .getConsole()
        .getStdOut()
        .print(params.getConsole().getAnsi().asWarningText(prompt + " [Y/n] "));

    Optional<String> result;
    try (InputStreamReader stdinReader = new InputStreamReader(System.in, Charsets.UTF_8);
         BufferedReader bufferedStdinReader = new BufferedReader(stdinReader)) {
      result = Optional.fromNullable(bufferedStdinReader.readLine());
    }
    LOG.debug("Result of prompt: [%s]", result);
    return result.isPresent() &&
        (result.get().isEmpty() || result.get().toLowerCase(Locale.US).startsWith("y"));
  }

  @VisibleForTesting
  static ImmutableSet<BuildTarget> getRootsFromPredicate(
      TargetGraph projectGraph,
      Predicate<TargetNode<?>> rootsPredicate) {
    return FluentIterable
        .from(projectGraph.getNodes())
        .filter(rootsPredicate)
        .transform(HasBuildTarget.TO_TARGET)
        .toSet();
  }

  private static Iterable<? extends TargetNodeSpec> getTargetNodeSpecsForIde(
      ProjectCommand.Ide ide,
      Collection<BuildTarget> passedInBuildTargets,
      ImmutableSet<Path> ignoreDirs,
      boolean experimentalProjectGenerationEnabled
  ) {
    if ((ide == ProjectCommand.Ide.XCODE || experimentalProjectGenerationEnabled) &&
        !passedInBuildTargets.isEmpty()) {
      return Iterables.transform(
          passedInBuildTargets,
          BuildTargetSpec.TO_BUILD_TARGET_SPEC);
    } else {
      return ImmutableList.of(
          TargetNodePredicateSpec.of(
              Predicates.<TargetNode<?>>alwaysTrue(),
              BuildFileSpec.fromRecursivePath(Paths.get(""), ignoreDirs)));
    }
  }

  private static TargetGraphAndTargets createTargetGraph(
      TargetGraph projectGraph,
      ImmutableSet<BuildTarget> graphRoots,
      ProjectGraphParser projectGraphParser,
      AssociatedTargetNodePredicate associatedProjectPredicate,
      boolean isWithTests,
      ProjectCommand.Ide ide,
      ImmutableSet<Path> ignoreDirs,
      boolean experimentalProjectGenerationEnabled
  )
      throws IOException, InterruptedException {

    TargetGraph resultProjectGraph;
    ImmutableSet<BuildTarget> explicitTestTargets;

    if (isWithTests) {
      explicitTestTargets = TargetGraphAndTargets.getExplicitTestTargets(
          graphRoots,
          projectGraph);
      resultProjectGraph =
          projectGraphParser.buildTargetGraphForTargetNodeSpecs(
              getTargetNodeSpecsForIde(
                  ide,
                  Sets.union(graphRoots, explicitTestTargets),
                  ignoreDirs,
                  experimentalProjectGenerationEnabled));
    } else {
      resultProjectGraph = projectGraph;
      explicitTestTargets = ImmutableSet.of();
    }

    return TargetGraphAndTargets.create(
        graphRoots,
        resultProjectGraph,
        associatedProjectPredicate,
        isWithTests,
        explicitTestTargets);
  }

  private boolean canGenerateImplicitWorkspaceForType(BuildRuleType type) {
    // We weren't given a workspace target, but we may have been given something that could
    // still turn into a workspace (for example, a library or an actual app rule). If that's the
    // case we still want to generate a workspace.
    return type == AppleBundleDescription.TYPE ||
        type == AppleLibraryDescription.TYPE;
  }

  /**
   * @param sourceTargetNode - The TargetNode which will act as our fake workspaces `src_target`
   * @return Workspace Args that describe a generic Xcode workspace containing `src_target` and its
   * tests
   */
  private XcodeWorkspaceConfigDescription.Arg createImplicitWorkspaceArgs(
      TargetNode<?> sourceTargetNode) {
    XcodeWorkspaceConfigDescription.Arg workspaceArgs = new XcodeWorkspaceConfigDescription.Arg();
    workspaceArgs.srcTarget = Optional.of(sourceTargetNode.getBuildTarget());
    workspaceArgs.actionConfigNames = Optional.of(ImmutableMap.<SchemeActionType, String>of());
    workspaceArgs.extraTests = Optional.of(ImmutableSortedSet.<BuildTarget>of());
    workspaceArgs.extraTargets = Optional.of(ImmutableSortedSet.<BuildTarget>of());
    workspaceArgs.workspaceName = Optional.absent();
    workspaceArgs.extraSchemes = Optional.of(ImmutableSortedMap.<String, BuildTarget>of());
    workspaceArgs.isRemoteRunnable = Optional.absent();
    return workspaceArgs;
  }

  @Override
  public String getShortDescription() {
    return "generates project configuration files for an IDE";
  }

}


text:
package org.scalameter

import language.higherKinds

import collection._
import reporting._
import Key._
import collections._
import parallel.ParIterable

class JSChartTest extends Bench.Regression with Collections {

  def persistor = new persistence.SerializationPersistor()

  override def reporter = org.scalameter.Reporter.Composite(
    new RegressionReporter(
      RegressionReporter.Tester.OverlapIntervals(),
      RegressionReporter.Historian.ExponentialBackoff() ),
    HtmlReporter(true)
  )

  def withPar[A <% CustomParallelizable[B, C[B]], B, C[B] <: ParIterable[B]](collections: Gen[A]) = {
    for {
      collection <- collections
      par <- Gen.exponential("par")(1, 8, 2)
    } yield {
      val parCollection = collection.par
      parCollection.tasksupport = new parallel.ForkJoinTaskSupport(
        new scala.concurrent.forkjoin.ForkJoinPool(par))
      parCollection
    }
  }

  performance of "Traversable" in {

    measure method "reduce" config (
      exec.minWarmupRuns -> 120,
      exec.maxWarmupRuns -> 240,
      exec.benchRuns -> 36,
      exec.independentSamples -> 3,
      reports.regression.significance -> 1e-13,
      reports.regression.noiseMagnitude -> 0.2
    ) in {
      val from = 100000
      val to = 600000
      val by = 150000

      using(withPar(arrays(from, to, by))) curve("Array") config (
        exec.minWarmupRuns -> 150,
        exec.maxWarmupRuns -> 320
      ) in {
        _.reduce(_ + _)
      }

      using(withPar(arraybuffers(from, to, by))) curve("ArrayBuffer") in {
        _.reduce(_ + _)
      }

      using(withPar(vectors(from, to, by))) curve("Vector") in {
        _.reduce(_ + _)
      }

      using(withPar(ranges(from, to, by))) curve("Range") in {
        _.reduce(_ + _)
      }
    }

    measure method "filter" config (
      exec.minWarmupRuns -> 100,
      exec.maxWarmupRuns -> 200,
      exec.benchRuns -> 36,
      exec.independentSamples -> 4,
      reports.regression.significance -> 1e-13,
      reports.regression.noiseMagnitude -> 0.2
    ) in {
      val from = 100000
      val to = 400000
      val by = 100000

      using(withPar(arrays(from, to, by))) curve("Array") in {
        _.filter(_ % 2 == 0)
      }

      using(withPar(arraybuffers(from, to, by))) curve("ArrayBuffer") config (
        exec.minWarmupRuns -> 120,
        exec.maxWarmupRuns -> 240,
        exec.reinstantiation.frequency -> 4
      ) in {
        _.filter(_ % 2 == 0)
      }

      using(withPar(vectors(from, to, by))) curve("Vector") in {
        _.filter(_ % 2 == 0)
      }

      using(withPar(ranges(from, to, by))) curve("Range") in {
        _.filter(_ % 2 == 0)
      }
    }

    measure method "groupBy" config (
      exec.minWarmupRuns -> 80,
      exec.maxWarmupRuns -> 160,
      exec.benchRuns -> 36,
      exec.independentSamples -> 4,
      reports.regression.significance -> 1e-13,
      reports.regression.noiseMagnitude -> 0.2
    ) in {
      val from = 50000
      val to = 200000
      val by = 50000

      using(withPar(arrays(from, to, by))) curve("Array") in {
        _.groupBy(_ % 10)
      }

      using(withPar(arraybuffers(from, to, by))) curve("ArrayBuffer") in {
        _.groupBy(_ % 10)
      }

      using(withPar(vectors(from, to, by))) curve("Vector") in {
        _.groupBy(_ % 10)
      }

      using(withPar(ranges(from, to, by))) curve("Range") in {
        _.groupBy(_ % 10)
      }
    }

    measure method "map" config (
      exec.minWarmupRuns -> 100,
      exec.maxWarmupRuns -> 200,
      exec.benchRuns -> 36,
      reports.regression.significance -> 1e-13,
      exec.independentSamples -> 4,
      reports.regression.noiseMagnitude -> 0.2
    ) in {
      val from = 100000
      val to = 400000
      val by = 100000

      using(withPar(arrays(from, to, by))) curve("Array") in {
        _.map(_ * 2)
      }

      using(withPar(arraybuffers(from, to, by))) curve("ArrayBuffer")  in {
        _.map(_ * 2)
      }

      using(withPar(vectors(from, to, by))) curve("Vector") in {
        _.map(_ * 2)
      }

      using(withPar(ranges(from, to, by))) curve("Range") in {
        _.map(_ * 2)
      }
    }
  }
}


text:
package java.awt;

public class Container extends Component {
  public Component add(Component comp) {
    // TODO: how to synthesize other behavior in detail?
    return comp; // TODO: how can we synthesize this return statement as well?
  }

  public void add(Component comp, Object constraints);

  public LayoutManager getLayout();
  public void setLayout(LayoutManager mgr);
}


text:
#ifndef InjectedBundlePageUIClient_h
#define InjectedBundlePageUIClient_h

#include "APIClient.h"
#include "WKBundlePage.h"
#include "WebEvent.h"
#include <wtf/Forward.h>

namespace WebCore {
    class GraphicsContext;
    class HitTestResult;
    class IntRect;
}

namespace WebKit {

class APIObject;
class WebFrame;
class WebPage;

class InjectedBundlePageUIClient : public APIClient<WKBundlePageUIClient> {
public:
    void willAddMessageToConsole(WebPage*, const String& message, int32_t lineNumber);
    void willSetStatusbarText(WebPage*, const String&);
    void willRunJavaScriptAlert(WebPage*, const String&, WebFrame*);
    void willRunJavaScriptConfirm(WebPage*, const String&, WebFrame*);
    void willRunJavaScriptPrompt(WebPage*, const String&, const String&, WebFrame*);
    void mouseDidMoveOverElement(WebPage*, const WebCore::HitTestResult&, WebEvent::Modifiers, RefPtr<APIObject>& userData);
    void pageDidScroll(WebPage*);

    bool shouldPaintCustomOverhangArea();
    void paintCustomOverhangArea(WebPage*, WebCore::GraphicsContext*, const WebCore::IntRect&, const WebCore::IntRect&, const WebCore::IntRect&);

    String shouldGenerateFileForUpload(WebPage*, const String& originalFilePath);
    String generateFileForUpload(WebPage*, const String& originalFilePath);
};

} // namespace WebKit

#endif // InjectedBundlePageUIClient_h


text:
package com.netflix.astyanax.thrift;

import com.netflix.astyanax.cql.CqlStatement;
import com.netflix.astyanax.query.CqlQuery;

public class ThriftCql3Factory implements ThriftCqlFactory {
    @Override
    public CqlStatement createCqlStatement(ThriftKeyspaceImpl keyspace) {
        return new ThriftCql3Statement(keyspace);
    }

    @Override
    public <K, C> CqlQuery<K, C> createCqlQuery(ThriftColumnFamilyQueryImpl<K, C> cfQuery, String cql) {
        return new ThriftCql3Query<K,C>(cfQuery, cql);
    }
}


text:
'use strict'

const chai = require('chai')
const expect = chai.expect

const engine = require('../../../engine.mock')
const Domain = require('../../../../src-v3/lib/Domain')
let domain = false

before(function (done) {
  engine.initialize()
    .then(() => {
      domain = new Domain(engine)
      return domain.initialize().then(() => {
        done()
      })
    })
    .catch(done)
})

describe('[unit] domain: IndividualRegisterCommand', function () {
  it('should not create individual because password1 != password2', function (done) {
    const payload = {
      email: 'gperreymond@gmail.com',
      password1: 'test1234',
      password2: '1234test',
      entity: 'urn:abibao:database:entity:ffd7dd87c544f29f0d9fbf70ceebb8d1a6949bd6ce3b4c65',
      survey: 'urn:abibao:database:survey:ffd7dd87c544f29f0d9fbf70ceebb8d1a6949bd6ce3b4c65',
      source: 'test unit'
    }
    domain.execute('Command', 'IndividualRegisterCommand', payload)
      .catch((error) => {
        expect(error).to.have.property('eraro')
        expect(error).to.have.property('gateway-domain')
        expect(error).to.have.property('details')
        expect(error).to.have.property('code')
        expect(error.eraro).to.be.equal(true)
        expect(error.code).to.be.equal('service_error')
        expect(error['gateway-domain']).to.be.equal(true)
        expect(error.details).to.be.an('object')
        expect(error.details).to.have.property('type')
        expect(error.details).to.have.property('name')
        expect(error.details.type).to.eq('Command.Error')
        expect(error.details.name).to.eq('IndividualRegisterCommand')
        expect(error.details.error.toString()).to.eq('Error: Passwords verication failed')
        done()
      })
  })
  it('should success create a complex individual', function (done) {
    const payload = {
      email: 'gperreymond@gmail.com',
      password1: 'test1234',
      password2: 'test1234',
      entity: 'urn:abibao:database:entity:ffd7dd87c544f29f0d9fbf70ceebb8d1a6949bd6ce3b4c65',
      survey: 'urn:abibao:database:survey:ffd7dd87c544f29f0d9fbf70ceebb8d1a6949bd6ce3b4c65',
      source: 'test unit'
    }
    domain.execute('Command', 'IndividualRegisterCommand', payload)
      .then((result) => {
        expect(result).to.be.an('object')
        done()
      })
      .catch((error) => {
        console.log(error)
        done(error)
      })
  })
  it('should success create a simple individual', function (done) {
    const payload = {
      email: 'gilles@abibao.com',
      password1: 'test1234',
      password2: 'test1234'
    }
    domain.execute('Command', 'IndividualRegisterCommand', payload)
      .then((result) => {
        expect(result).to.be.an('object')
        expect(result.result).to.be.an('object')
        expect(result.result.urn).to.be.a('string')
        expect(result.result.email).to.be.eq('gilles@abibao.com')
        done()
      })
      .catch(done)
  })
  it('should not create individual because email already in database', function (done) {
    const payload = {
      email: 'gperreymond@gmail.com',
      password1: 'test1234',
      password2: 'test1234',
      entity: 'urn:abibao:database:entity:ffd7dd87c544f29f0d9fbf70ceebb8d1a6949bd6ce3b4c65',
      survey: 'urn:abibao:database:survey:ffd7dd87c544f29f0d9fbf70ceebb8d1a6949bd6ce3b4c65',
      source: 'test unit'
    }
    domain.execute('Command', 'IndividualRegisterCommand', payload)
      .catch((error) => {
        expect(error).to.have.property('eraro')
        expect(error).to.have.property('gateway-domain')
        expect(error).to.have.property('details')
        expect(error).to.have.property('code')
        expect(error.eraro).to.be.equal(true)
        expect(error.code).to.be.equal('service_error')
        expect(error['gateway-domain']).to.be.equal(true)
        expect(error.details).to.be.an('object')
        expect(error.details).to.have.property('type')
        expect(error.details).to.have.property('name')
        expect(error.details.type).to.eq('Command.Error')
        expect(error.details.name).to.eq('IndividualRegisterCommand')
        expect(error.details.error.toString()).to.eq('Error: Email already exists in database')
        done()
      })
  })
})


text:
var assert = require('assert');
var Circle = require('../src/Circle.js');
var Shape = require('../src/Shape.js');

describe('Circle constructor', function() {

  it('should set type to "Circle"', function() {
    assert.equal((new Circle()).type, "Circle");
  });

  it('should throw when not using the "new" keyword', function() {
    assert.throws(function() { Circle(); }, /Circle constructor must be called with the "new" keyword/);
  });

  it('should set the radius to 0', function() {
    var c = new Circle();
    assert.equal(c.radius, 0);
  });

  it('should be an instance of Shape', function() {
    assert((new Circle()) instanceof Shape);
  });

});


text:
/**
 * styles.css
 *
 * App container styles
 */

.container {
  display: block;
  font-family: 'Open Sans';
  font-size: 14px;
}


text:
package jetbrains.buildServer.nuget.feed.server.odata4j.functions;

import jetbrains.buildServer.nuget.feed.server.index.NuGetFeed;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.odata4j.edm.EdmFunctionImport;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Evgeniy.Koshkin
 */
public class NuGetFeedFunctions {
  private final Map<String, NuGetFeedFunction> myAPIv2Functions = new HashMap<>();

  public NuGetFeedFunctions(@NotNull final NuGetFeed feed) {
    addFunction(new FindPackagesByIdFunction(feed));
    addFunction(new GetUpdatesFunction(feed));
    addFunction(new SearchFunction(feed));
  }

  private void addFunction(NuGetFeedFunction feedFunction) {
    myAPIv2Functions.put(feedFunction.getName(), feedFunction);
  }

  @Nullable
  public NuGetFeedFunction find(@NotNull final EdmFunctionImport name) {
    return myAPIv2Functions.get(name.getName());
  }

  public Iterable<? extends NuGetFeedFunction> getAll() {
    return Collections.unmodifiableCollection(myAPIv2Functions.values());
  }
}


text:
import React from 'react';
import renderer from 'react/lib/ReactTestRenderer';

import Button from '../../src/js/components/Button';

import FakeIcon from '../mocks/FakeIcon';

describe('Button', () => {
  it('has correct default options', () => {
    const component = renderer.create(
      <Button label='Test me' />
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
  it('has correct primary={true} rendering', () => {
    const component = renderer.create(
      <Button label='Test me' primary={true} />
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
  it('has correct plain={true} rendering', () => {
    const component = renderer.create(
      <Button label='Test me' plain={true} />
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
  it('has correct icon rendering', () => {
    const component = renderer.create(
      <Button icon={<FakeIcon />} />
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
  it('has correct icon as children rendering', () => {
    const component = renderer.create(
      <Button><FakeIcon /></Button>
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
  it('has text as children rendering', () => {
    const component = renderer.create(
      <Button>test</Button>
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
  it('has className property rendering', () => {
    const component = renderer.create(
      <Button className="test">test</Button>
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
  it('has microdata properties rendering', () => {
    const component = renderer.create(
      <Button itemScope={true} itemType="http://schema.org/Article"
        itemProp="test">test</Button>
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
});


text:
layout:     post
title:      Tutorial: Creating models in 3dsMAX and Render via jPCT-Bones
date:       2017-02-20 13:52:19
summary:    See the tutorial for creating a bone model which jPCT-Bones could read
categories: opengl android jPCT-Bones
---

**jPCT-Bones** can be used for rendering Skeleton Model and the workflow can be described as follow:

* step_1 : Create a Skeleton Model;
* step_2 : Export the model;
* step_3 : Rendering;

In this tutorial, I will teach you step by step:

* Create a Skeleton Model via 3ds Max;
* Export the model via OgreMax(Plugin) and script of Bones;
* Render via jPCT-Bones;

Ok , here we go ~

#Platform you need

* Engine: Bones.
* Model Creation: 3ds Max 2013.
* Plugin: [OgreMax](http://www.ogremax.com/downloads).

#Create Model and Bones

1. Create a new file;
2. Select the ¡°Create¡± tab > ¡°Geometry¡± > ¡°Cylinder¡±;
3. Draw a cylinder, let's say with 6 height segments and check the ¡°Generate Mapping Coords¡±;
4. Click ¡°Create¡± tab > ¡°Systems¡± > ¡°Bones¡±;
5. Add some bones in the center of the cylinder;
6. Select the cylinder, right click it and click ¡°Convert To:¡± > ¡°Convert to Editable Mesh¡±;
7. Click the ¡°Modify¡± tab > ¡°Modifier List¡± and add the ¡°Skin¡± modifier;
8. Beneath ¡°Bones:¡± click ¡°Add¡± and select all of your bones;

#Create the Animation

1. Select the cylinder, and click ¡°Display¡± tab > ¡°Freeze Selected¡± so it is easier to select the bones during animation;
2. enable the ¡°Auto Key¡± mode;
3. The first key frame will be created automatically. Move the animation track slider to frame 5;
4. Move the selected bones a bit. The cylinder mesh will be deformed;
5. Create some additional key frames. You may also select more bones and move or rotate them. (for example, I¡¯ve created 25 frames);
6. After creating the animation, disable the ¡°Auto Key¡± mode;

#OgreMax Settings and Export

1. Open the ¡°OgreMax¡± > ¡°Scene Settings¡± dialog from the menu;
2. In the ¡°Meshes¡± tab, enable ¡°Export XML Files¡± and disable ¡°Export Binary Files¡± and ¡°Export Vertex Colors¡±;
3. Click the ¡°Environment¡± tab and uncheck ¡°Export Environment Settings¡±;
4. While having the cylinder selected, open the ¡°OgreMax¡±> ¡°Object Settings¡± dialog from the menu;
5. Open the ¡°Mesh Animations¡± tab and select type ¡°Skeleton¡±, ¡°Export Skeleton¡± : ¡°Yes¡±;
6. Below ¡°Mesh Animations¡± click the ¡°Add¡¡± button;
7. Assign a name to the track, maybe ¡°Cylinder¡±. The track type must be ¡°Skin. Set the right ¡°Start/End Frames¡± for your animation;
8. Hit ok and you will see the animation in the table;
9. While having the cylinder selected, open the ¡°OgreMax¡±> ¡°Global Settings¡± dialog from the menu;
10. Check the Up Axis to Z , (if you select Up Axis to Y, something weird will happen);
11. Finishing all setting above, click ¡°OgreMax¡± > ¡°Export¡± >¡±Export Scene¡± to export xxxxxx.scene;
12. And then, you'll get xxxxxx.mesh.xml and xxxxxx.skelten.xml files;

#*.bones exporting

###jPCT-Bones can only render format with .bones, so we need to transfer again from .xml to .bones via the script from jPCT-Bones ;

1. Copy xxxxxx.mesh.xml and xxxxxx.skelten.xml into ¡°./Bones/script/¡±
2. Transfer this two files to .bones file(xxxxxx.bones) via Command Line Interface;

###Example:

**jmeOgreImporter** **-out** xxxxxx.bones **-in** xxxxxx.mesh.xml

#Render
You can test your model( xxxxxx.bones ) with the [Android demo application](http://www.aptalkarga.com/bones/bones_android_demo.zip)

***Congratulation ~ Make it !***


text:
package org.lasalle.javaweb.av2.model;

import java.util.Date;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
import org.lasalle.javaweb.av2.model.Tema;

@Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2014-11-11T11:51:43")
@StaticMetamodel(Miniatura.class)
public class Miniatura_ {

    public static volatile SingularAttribute<Miniatura, Float> preco;
    public static volatile SingularAttribute<Miniatura, Date> dta;
    public static volatile SingularAttribute<Miniatura, Tema> tema;
    public static volatile SingularAttribute<Miniatura, String> nome;
    public static volatile SingularAttribute<Miniatura, Long> id;
    public static volatile SingularAttribute<Miniatura, Integer> quantidade;
    public static volatile SingularAttribute<Miniatura, String> descricao;

}


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
     <alpha
        android:fromAlpha="1.0"
        android:toAlpha="0.0"
        android:duration="300"
    />
    <translate
	    android:fromXDelta="0.0"
	    android:toXDelta="0.0"
	    android:fromYDelta="0"
	    android:toYDelta="80"
	    android:duration="300"
	    />

</set>


text:
package com.mikepenz.meteocons_typeface_library;

import android.content.Context;
import android.graphics.Typeface;

import com.mikepenz.iconics.typeface.IIcon;
import com.mikepenz.iconics.typeface.ITypeface;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;

public class Meteoconcs implements ITypeface {
    private static final String TTF_FILE = "meteocons.ttf";

    private static Typeface typeface = null;

    private static HashMap<String, Character> mChars;

    @Override
    public IIcon getIcon(String key) {
        return Icon.valueOf(key);
    }

    @Override
    public HashMap<String, Character> getCharacters() {
        if (mChars == null) {
            HashMap<String, Character> aChars = new HashMap<String, Character>();
            for (Icon v : Icon.values()) {
                aChars.put(v.name(), v.character);
            }
            mChars = aChars;
        }

        return mChars;
    }

    @Override
    public String getMappingPrefix() {
        return "met";
    }

    @Override
    public String getFontName() {
        return "Meteocons";
    }

    @Override
    public String getVersion() {
        return "1.0.0";
    }

    @Override
    public int getIconCount() {
        return mChars.size();
    }

    @Override
    public Collection<String> getIcons() {
        Collection<String> icons = new LinkedList<String>();

        for (Icon value : Icon.values()) {
            icons.add(value.name());
        }

        return icons;
    }

    @Override
    public String getAuthor() {
        return "Alessio Atzeni";
    }

    @Override
    public String getUrl() {
        return "http://www.alessioatzeni.com/meteocons/";
    }

    @Override
    public String getDescription() {
        return "Meteocons is a set of weather icons, it containing 40+ icons available in PSD, CSH, EPS, SVG, Desktop font and Web font. All icon and updates are free and always will be.";
    }

    @Override
    public String getLicense() {
        return "";
    }

    @Override
    public String getLicenseUrl() {
        return "";
    }

    @Override
    public Typeface getTypeface(Context context) {
        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(), "fonts/" + TTF_FILE);
            } catch (Exception e) {
                return null;
            }
        }
        return typeface;
    }

    public static enum Icon implements IIcon {
        met_windy_rain_inv('\ue800'),
        met_snow_inv('\ue801'),
        met_snow_heavy_inv('\ue802'),
        met_hail_inv('\ue803'),
        met_clouds_inv('\ue804'),
        met_clouds_flash_inv('\ue805'),
        met_temperature('\ue806'),
        met_compass('\ue807'),
        met_na('\ue808'),
        met_celcius('\ue809'),
        met_fahrenheit('\ue80a'),
        met_clouds_flash_alt('\ue80b'),
        met_sun_inv('\ue80c'),
        met_moon_inv('\ue80d'),
        met_cloud_sun_inv('\ue80e'),
        met_cloud_moon_inv('\ue80f'),
        met_cloud_inv('\ue810'),
        met_cloud_flash_inv('\ue811'),
        met_drizzle_inv('\ue812'),
        met_rain_inv('\ue813'),
        met_windy_inv('\ue814'),
        met_sunrise('\ue815'),
        met_sun('\ue816'),
        met_moon('\ue817'),
        met_eclipse('\ue818'),
        met_mist('\ue819'),
        met_wind('\ue81a'),
        met_snowflake('\ue81b'),
        met_cloud_sun('\ue81c'),
        met_cloud_moon('\ue81d'),
        met_fog_sun('\ue81e'),
        met_fog_moon('\ue81f'),
        met_fog_cloud('\ue820'),
        met_fog('\ue821'),
        met_cloud('\ue822'),
        met_cloud_flash('\ue823'),
        met_cloud_flash_alt('\ue824'),
        met_drizzle('\ue825'),
        met_rain('\ue826'),
        met_windy('\ue827'),
        met_windy_rain('\ue828'),
        met_snow('\ue829'),
        met_snow_alt('\ue82a'),
        met_snow_heavy('\ue82b'),
        met_hail('\ue82c'),
        met_clouds('\ue82d'),
        met_clouds_flash('\ue82e');

        char character;

        Icon(char character) {
            this.character = character;
        }

        public String getFormattedName() {
            return "{" + name() + "}";
        }

        public char getCharacter() {
            return character;
        }

        public String getName() {
            return name();
        }
    }
}


text:
A JavaScript library playground.

# build

`npm run server` for developing

`npm run compiler` to build to `./bin`

`npm run linter` to lint code

`npm test` host tests at `localhost:8080/test.bundle`


text:
layout: page
title: Flex Corporation Award Ceremony
date: 2016-05-24
author: Bruce Cooper
tags: weekly links, java
status: published
summary: Proin viverra nisl semper mauris iaculis.
banner: images/banner/wedding.jpg
booking:
  startDate: 03/07/2019
  endDate: 03/08/2019
  ctyhocn: BTVMVHX
  groupCode: FCAC
published: true
---
Pellentesque quis sem massa. Suspendisse facilisis tellus in interdum lobortis. Praesent tellus nunc, eleifend nec sapien sit amet, rhoncus sodales risus. Integer sed erat turpis. Donec malesuada orci eu urna mollis pharetra. Proin tempus dolor vitae lectus euismod molestie. Vivamus nec ultricies ligula. Nam congue dolor et volutpat finibus. Donec neque enim, venenatis ac posuere aliquet, mollis a dui. Pellentesque ut urna massa. Proin a augue sed nisl volutpat vehicula.
Integer elementum, augue non auctor posuere, arcu arcu luctus lorem, id molestie tellus tellus ac eros. Pellentesque non commodo arcu. In scelerisque augue id metus gravida, sed mollis justo aliquet. Suspendisse posuere feugiat est ut feugiat. Fusce id faucibus mi, non bibendum urna. Fusce hendrerit elit vitae felis scelerisque, eu blandit velit bibendum. Ut suscipit, magna id tristique facilisis, nisl nisl laoreet ante, nec feugiat augue nisi vel tortor. Mauris est sem, bibendum a diam id, convallis imperdiet tortor. In hac habitasse platea dictumst.

* Ut vel neque sed nisl sodales cursus
* Nam vestibulum nulla vitae blandit sodales
* Vivamus accumsan enim eget orci commodo iaculis.

Phasellus semper mauris non risus ultrices venenatis. Curabitur sed hendrerit massa. Nullam ut lobortis velit. In scelerisque volutpat orci, id iaculis magna dapibus non. Donec non neque at turpis blandit mollis nec eget odio. Etiam quis sagittis nisl, vitae egestas orci. Suspendisse hendrerit condimentum interdum. Etiam convallis condimentum diam. Nulla facilisi. Nulla facilisi.


text:
"""Drop MySQL user and database."""

import sys
import sqlalchemy as sa
import coils

# Load configuration file.
CONFIG = sys.argv[1] if len(sys.argv)>=2 else 'wabbit.conf'
config = coils.Config(CONFIG)

# Connect to database engine.
root_u = coils.user_input('Admin username', default=config['admin'])
root_p = coils.user_input('Admin password', password=True, empty_ok=True)
engine = sa.create_engine(
        'mysql://{}:{}@{}'.format(root_u, root_p, config['host']))
try:
    conn = engine.connect()
except sa.exc.OperationalError:
    print('Failed to connect.')
    sys.exit(1)

# Drop the user and database.
try:
    conn.execute('REVOKE ALL PRIVILEGES, GRANT OPTION FROM "{}"@"{}"'.format(
            config['username'], config['host']))
    conn.execute('DROP USER "{}"@"{}"'.format(
            config['username'], config['host']))
except:
    print('Failed to drop user.')
try:
    conn.execute('DROP DATABASE {}'.format(config['db_name']))
except:
    print('Failed to drop database.')

# Disconnect from database engine.
conn.close()


text:
<?php
namespace Tests\Database;

class PgsqlTest extends Write
{
    public $connection = 'pqsql';

    public function __construct()
    {
        new \Tests\Bootstrap;

        $this->db = new \Resources\Database($this->connection);

        $this->db->query('DROP TABLE IF EXISTS users');

        $this->db->query('CREATE TABLE users (
            id SERIAL NOT NULL,
            name varchar(50) NOT NULL,
            email varchar(50) NOT NULL,
            password varchar(32) NOT NULL,
            PRIMARY KEY (id)
        )');
    }
}


text:
reset-table-cell opaque mixin

## Usage

```stylus
@require 'shoelace-ui-reset-table-cell'
```

## License

MIT


text:
<ng-form name="_form" ng-cloak>
        <div layout-padding layout-margin layout="row" md-whiteframe="2" layout-align=" center">
            <md-input-container md-no-float class="" md-is-error="$component.invalid && ($component.touched || $component.dirty)" flex="95">
                <input type="{{ $component.type }}"
                       placeholder="{{$component.label}}"

                       name="{{ $component.name }}"
                       id="{{ $component.name }}"

                       ng-model="$component.value"
                       ng-change="$component.onChange()"
                       ng-model-options="$component.modelOptions"

                       ng-required="$component.isRequired"
                       ng-disabled="$component.isDisabled"

                       ng-minlength="$component.minLength"
                       ng-maxlength="$component.maxLength"

                       md-maxlength="$component.maxLength"

                       maxlength="{{$component.maxLength }}"
                       ng-focus="$component.isDisabled || $component.setTouched()"
                       ng-click="$component.isDisabled || $component.setTouched()">

                <div ng-messages="$component.errors" ng-show="$component.dirty || $component.touched" >
                    <ng-transclude></ng-transclude>
                </div>
            </md-input-container>

                <md-button ng-show="($component.value == '' || $component.value == null)" ng-click="$component.focus($component.name);" class="md-icon-button search-btn" aria-label="search" ng-disabled="$component.isDisabled">
                    <md-icon  class="material-icons" >search</md-icon>
                </md-button>
                <md-button ng-show="!($component.value == '' || $component.value == null)" ng-click="$component.clean()" class="md-icon-button search-btn" aria-label="close" ng-disabled="$component.isDisabled">
                    <md-icon  class="material-icons" >close</md-icon>
                </md-button>
        </div>
</ng-form>


text:
import types from './actionTypes'
import postTypes from '../post/actionTypes'
import { CategoryAPI } from "../shared/api"

export const getAllCategories = () => dispatch => {
  dispatch({ type: types.REQUEST_ALL_CATEGORIES })

  CategoryAPI.getAll(categories => {
    dispatch({
      type: types.RECEIVE_ALL_CATEGORIES,
      categories
    })
  })
}

const requestPostsByCategory = category => ({
  type: postTypes.REQUEST_POSTS_BY_CATEGORY,
  category
})

const receivePostsByCategory = (category, posts) => ({
  type: postTypes.RECEIVE_POSTS_BY_CATEGORY,
  category,
  posts
})

export const getPostsByCategory = category => dispatch => {
  dispatch(requestPostsByCategory(category))

  CategoryAPI.getPosts(category, posts => {
    dispatch(receivePostsByCategory(category, posts))
  })
}