text:
/*
 * Terminal2.java
 *
 * Created on April 27, 2005, 10:17 AM
 */

package net.giantsystem.sf;

import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.regex.*;

/**
 * Provides GUI and I/O services to the KASH shell
 * @author karve
 */
public class KASHTerm extends javax.swing.JInternalFrame {
    //private String KASH_DIR;// = "/Users/karve/Desktop/PROJECTS/KASH/KASH_2.5";
    //public final static String KASH_DIR = "/net/kant/V4/bin/";
    //public final static String[] START_KASH = new String[]{KASH_DIR + "/kash", "giant.kash"};
    /**
     * The prompt that KASH returns after evaluating an expression
     * (something like "kash> ")
     */
    public final static String KASH_PROMPT = "kash> ";
    /**
     * Somtimes KASH will only return "> "
     * @deprecated not used
     */
    public final static String KASH_PROMPT_B = "> ";
    /**
     * Append this text to GUI error messages
     */
    public final static String DETAILS = " (View/KASH for details.) ";

    //sometimes we want to find the kash prompt
        //turn on DOTALL with (?s)
    /**
     * Regex pattern to match KASH_PROMPT
     */
    public final static Pattern KASH_P = Pattern.compile("(?s)(.*)" + KASH_PROMPT);
    /**
     * regex pattern to match "error"
     */
    public final static Pattern ERROR = Pattern.compile("(?i)error");
    /**
     * regex pattern to match "true"
     */
    public final static Pattern TRUE = Pattern.compile("(?i)true");
    /**
     * regex pattern to match "false"
     */
    public final static Pattern FALSE = Pattern.compile("(?i)false");
    /**
     * regex pattern to match text returned by KASH 2.5 on creating an order:
     * "Generating Polynomial: " so that we can parse for this text
     */
    public final static Pattern GEN_POLY = Pattern.compile("Generating polynomial:");
    /**
     * regex pattern to match text "syntax error"
     */
    public static final Pattern SYNTAX_ERR = Pattern.compile("Syntax error.*");//to find error messages
    /**
     * regex pattern to match "quit"
     */
    public static final Pattern QUIT = Pattern.compile("\\s*quit\\s*;\\s*");

    /**
     * key code for up arrow
     */
    public final static int UP_ARROW = java.awt.event.KeyEvent.VK_UP;
    /**
     * key code for down arrow
     */
    public final static int DOWN_ARROW = java.awt.event.KeyEvent.VK_DOWN;
	/**
	 * keeps track of position in the commandHistory list to support command
	 * history in the java accessible KASH shell (i.e. the GUI face of the KASHTerm class)
	 * @see #commandHistory
	 */
	private int histCursor = 0;
    /**
     * number field degree at which we stop auto-computing the Galois group (for performance
     * reasons)
     */
    public final static int GALOIS_LIMIT = 2;
    /**
     * KASH assignment operator
     */
    public final static String EQ = " := ";
    /**
     * KASH statement terminator
     */
    public final static String END  = ";";
    /**
     * ,
     */
    public final static String COMMA = ", ";
    /**
     * If no character is given to join(), use this one
     * @see #join(String[], String)
     */
    public final static String JOIN = ", ";
    /**
     * Used to signal a KASH error
     * @see #funExecToString
     */
    public final static String HUH = "?" + DETAILS;

    //Function names
    /**
     * KASH function name used to create number fields
     */
    public final static String NEW_NF = "Order";
    /**
     * KASH function name to determine a polynomial's degree
     */
    public final static String POLY_DEG = "PolyDeg";
    /**
     * KASH function for determining order degree
     */
    public final static String ORDER_DEG = "OrderDegAbs";
    /**
     * KASH function for power basis
     */
    public final static String BASIS = "Basis";
    /**
     * KASH function for discriminant
     */
    public final static String DISC = "OrderDisc";
    /**
     * KASH function for order signature
     */
    public final static String SIG = "OrderSig";
    /**
     * KASH subfield test for orders
     */
    public final static String SUBFLD = "GiantIsSubfield";//KASH OrderIsSubfield() is slow (bug?)
    /**
     * KASH function for galois group of an order
     */
    public final static String GALOIS_GROUP = "Galois";
    /**
     * KASH function to create a polynomial algebra
     */
    public static final String POLY_ALG = "PolyAlg";
    /**
     * KASH function to define polynomials
     */
    public static final String POLY = "Poly";
    /**
     * KASH trace function
     */
    public static final String TRACE = "Trace";
    /**
     * KASH norm function
     */
    public static final String NORM = "Norm";
    /**
     * KASH function to fetch ideal's (2) generators
     */
    public static final String IDEAL_GENERATORS = "GiantIdealGenerators";
    /**
     * KASH function for minimal polynomial
     */
    public static final String MIN_POLY = "MinPoly";
    /**
     * KASH function for polynomial disc.
     */
    public static final String POLY_DISC = "PolyDisc";
	/**
	 * KASH function to move polynomials
	 */
	public static final String POLY_MOVE = "PolyMove";
    /**
     * KASH test for polynomial reducibility
     */
    public static final String REDUCIBLE_P = "PolyIsIrreducible";
    /**
     * KASH ideal primality test
     */
    public static final String PRIME_P = "IdealIsPrime";
    /**
     * KASH ideal principality test
     */
    public static final String PRINCIPAL = "GiantIdealIsPrincipal";
	/**
	 * KASH ideal principality test using the class group (iff available)
	 */
	public static final String PRINCIPAL_CL = "GiantIdealIsPrincipalCl";
    /**
     * KASH test for integrality of an ideal
     */
    public static final String INTEGRAL_P = "IdealIsIntegral";
	/**
	 * KASH function to fetch ideal class representative of a given ideal
	 */
	public static final String CLASS_REP = "IdealClassRep";
    /**
     * KASH test for polynomial-hood
     */
    public static final String POLY_P = "IsPoly";
    /**
     * KASH test for element-hood
     */
    public static final String ELT_P = "IsElt";
	/**
	 * KASH function to move elements between orders
	 */
	public static final String ELT_MOVE = "EltMove";
    /**
     * KASH ideal predicate
     */
    public static final String IDEAL_P = "IsIdeal";
	/**
	 * KASH ideal factorization
	 */
	public static final String IDEAL_FACTOR = "IdealFactor";
    /**
     * KASH ideal constructor
     */
    public static final String IDEAL_CONSTRUCTOR = "Ideal";
	/**
	 * KASH fxn to move ideals between orders
	 */
	public static final String IDEAL_MOVE = "IdealMove";
    /**
     * KASH fxn to fetch torsion unit
     */
    public static final String TORSION = "OrderTorsionUnit";
    /**
     * KASH fxn to fetch torsion rank
     */
    public static final String TORSION_RANK = "OrderTorsionUnitRank";
    /**
     * KASH fxn to calculate fundamental units
     */
    public static final String FUND_UNITS = "GiantOrderUnitsFund";
	/**
	 * KASH fxn to calculate class group
	 */
	public static final String CLASS_GROUP = "OrderClassGroup";
	/**
	 * GiANT KASH fxn to get the cyclic factors of the given class group
	 * (GiANT fxns usually just change the format of the data from KASH)
	 */
	public static final String CLASS_FACTORS2 = "GiantClassGroupFactors";//WIHTOUT orders
	/**
	 * Standard KASH fxn to get the cyclic factors of the given class group
	 */
	public static final String CLASS_FACTORS = "OrderClassGroupCyclicFactors";//WITH orders
    /**
     * KASH test for integrality of an element
     */
    public static final String INTEGRAL_P_ELT = "EltIsIntegral";
    /**
     * KASH Maximal Order constructor
     */
    public final static String MAX_ORDER = "OrderMaximal";
    /**
     * KASH regulator function
     */
    public final static String REG = "OrderReg";
	/**
	 * KASH fxn to define absolute orders (used to place relative orders on the desktop)
	 */
	public final static String ABS_ORDER = "OrderAbs";
	/**
	 * KASH fxn for torsion X fundamental unit decomposition of a unit
	 */
	public final static String UNIT_REP = "EltUnitDecompose";
        //operators
    /**
     * + operator
     */
    public final static String PLUS = " + ";
    /**
     * - operator
     */
    public final static String MINUS = " - ";
    /**
     * x operator
     */
    public final static String TIMES = " * ";
    /**
     * / operator
     */
    public final static String DIVIDE = " / ";

    /**
     * The object that handles I/O to GiANT's KASH session
     */
    private IO io;//= new IO();
    /**
     * A list of commands sent to KASH by the user via the GUI command-line for the shell
     */
    private ArrayList commandHistory = new ArrayList();

    /**
     * constructor
     * @param args The command-line argument string given to GiANT.jar at startup
     */
    public KASHTerm(String[] args) {
		String kashDir = args[0];//the user tells us where kash lives
		io = new IO(kashDir);
        initComponents();
    }

    /**
     * Wrap the arguemnt in parenthesis
     * @param s The string to enclose
     * @return ( + s + )
     */
    public static String enclose(String s){
        return "(" + s + ")";
    }

    /**
     * WRITE a function call to give to KASH (but don't perform the call)
     * @param fname function name
     * @param args arguments to fname
     * @return KASH's response
     * @see #funExec
     */
    public static String funCall(String fname, String[] args){
        if(fname == null)
            return join(args);
        return fname + enclose(join(args));
    }

    /**
     * Make the specified KASH function call
     * @param fname function name
     * @param args arguments to fname
     * @return KASH's response
     * @see #funCall
     */
    public Response funExec(String fname, String[]args){
        return tell(funCall(fname, args) + END);
    }

    /**
     * Like funExec except returns a String
     * @param fname KASH function to call
     * @param args fname's arguments
     * @return HUH iff there was an error; the KASH output string otherwise
     * @see #HUH
     * @see #funExec
     */
    public String funExecToString(String fname, String[]args){
        Response r = tell(funCall(fname, args) + END);
        if(!r.error())
            return r.getOutput();
        else
            return HUH;
    }

    /**
     * Assign a variable to the power basis of the given number field
     * @param nm the variable name for the basis of nm
     * @param n a number field
     * @return the KASH power basis of n OR HUH if there is an error
     */
    public String basis(String nm, NumberField n){
        return assignToFunCall(nm, BASIS, new String[]{n.getName()});
    }

    /**
     * Capture the integral basis of the given nubmer field with the given name
     * @param nm name of the integral basis (in KASH)
     * @param n number field
     * @return the integral basis
     */
    public String integralBasis(String nm, NumberField n){
        return assignToFunCall(nm, BASIS, new String[]{n.getMaxOrderName()});
    }

    /**
     * Element predicate
     * @param e an KASH expression
     * @return true iff e is an element
     */
    public boolean integral(Element e){
        Response r = funExec(INTEGRAL_P_ELT, new String[]{e.getName()});
        return trueString(r.getOutput());
    }

    /**
     * Capture the discriminant of an order
     * @param nm name under which to capture the returned value
     * @param n number field
     * @return discriminant of n
     */
    public String disc(String nm, NumberField n){
        return assignToFunCall(nm, DISC, new String[]{n.getName()});
    }

    /**
     * Store the class respresentative of the given ideal under the given name
     * @param nm a variable name for KASH to use
     * @param i an ideal
     * @return i's ideal class representative
     */
    public String classRep(String nm, Ideal i){
        return assignToFunCall(nm, CLASS_REP, new String[]{i.getName(), "\"gen\""});
    }

	/**
	 * Discriminant of a n's maximal order
	 * @param n a number field
	 * @return discriminant of the maximal order of n
	 */
	public String maxOrderDisc(NumberField n){
        return assignToFunCall("temp", DISC, new String[]{n.getMaxOrderName()});
    }

    /**
     * Store the unit representation of an element
     * @param nm Name under which to store the representation
     * @param e element
     * @param f parent field of e
     * @return e's unit decomposition
     */
    public String unitRep(String nm, Element e, NumberField f){
		//if we don't do the move first, EltUnitDecompose may complain that the element
		// is not integral
		String move = funCall(ELT_MOVE, new String[]{e.getName(), f.getMaxOrderName()});
        return assignToFunCall(nm, UNIT_REP, new String[]{move, "\"expons\""});
    }

    /**
     * Store the regulator of a unit group
     * @param nm variable name (in KASH) under which to store the regulator
     * @param n number field in which the unit group lives
     * @return regulator
     */
    public String regulator(String nm, NumberField n){
        return assignToFunCall(nm, REG, new String[]{n.getMaxOrderName()});
    }
    //OPTIM you allocate tons of String[] arrays...use static one
    /**
     * Rank of the torsion unit in n
     * @param n number field
     * @return Rank of the torsion unit in n
     */
    public String torsionRank(NumberField n){
        return assignToFunCall("temp", TORSION_RANK, new String[]{n.getMaxOrderName()});
    }

    /**
     * Store the given polynomial's discriminant
     * @param nm name for the discriminant
     * @param p polynomial
     * @return p's discriminant
     */
    public String disc(String nm, Polynomial p){
        return assignToFunCall(nm, POLY_DISC, new String[]{p.getName()});
    }

	/**
	 * Store the fundamental units of a number field
	 * @param nm name under which to store the fundamental units in KASH
	 * @param n the number field
	 * @return fundamental units list
	 */
	public String fundUnits(String nm, NumberField n){
        return assignToFunCall(nm, FUND_UNITS, new String[]{n.getMaxOrderName(), n.getName()});
	}

	/**
	 * Store the class group of the given number field under the given name
	 * @param nm KASH name for the class group
	 * @param n number field
	 * @return class group
	 */
	public String classGroup(String nm, NumberField n){
		return assignToFunCall(nm, CLASS_GROUP, new String[] {n.getMaxOrderName()});
	}

	/**
	 * Calculate, store the cyclic factors of the class group
	 * @param nm name under which to store the return value
	 * @param n number field
	 * @return cyclic factors of the class group
	 */
	public String classGroupFactors(String nm, NumberField n){
		String[] arg = new String[] {n.getMaxOrderName()};
		assignToFunCall(nm, CLASS_FACTORS2, arg);//class group factors w/o orders
		return funExecToString(CLASS_FACTORS, arg);//WITH orders
	}
    /**
     * Calculate, Store, the torsion unit
     * @param nm name under which to store
     * @param n number field
     * @return torsion unit
     */
    public String torsion(String nm, NumberField n){
        return assignToFunCall(nm, TORSION, new String[]{n.getMaxOrderName()});
    }

    /**
     * Calculate, store, the (2) generators of an ideal
     * @param nm KASH name under which to store the return value
     * @param idl ideal
     * @return generators of idl
     */
    public String generators(String nm, Ideal idl){
        return assignToFunCall(nm, IDEAL_GENERATORS, new String[]{idl.getName()});
    }

    /**
     * Calculate & store the primitive element of a given number field
     * @param nm KASH name under which to store the return value
     * @param val value of the primitive element
     * @return the primitive element as represented by KASH
     */
    public String primElt(String nm, String val){
        return assignToFunCall(nm, null, new String[]{val});
    }

    /**
     * Capture the degree of the give number field in a KASH variable
     * @param nm variable name under which to store the degree of n
     * @param n number field
     * @return degree of n
     */
    public String degree(String nm, NumberField n){
        return assignToFunCall(nm, ORDER_DEG, new String[]{n.getName()});
    }

    /**
     * Capture the signature (real & complex embeddings) of the given number field
     * @param nm variable name for signature
     * @param n number field
     * @return signature (as KASH list of the form "[X, Y]"
     */
    public String sig(String nm, NumberField n){
        return assignToFunCall(nm, SIG, new String[]{n.getName()});
    }

    /**
     * Capture the Norm of an element
     * @param nm variable name for the return value
     * @param v variable
     * @return norm
     */
    public String norm(String nm, Variable v){
        return assignToFunCall(nm, NORM, new String[]{v.getName()});
    }

    /**
     * Capture the maximal order of n in an automatic variable name
     * @param n number field
     * @return KASH output resulting from the creation of n's maximal order
     */
    public String maximalOrder(NumberField n){
        return assignToFunCall(n.getMaxOrderName(), MAX_ORDER, new String[]{n.getName()});
    }

    /**
     * Capture the Trace of the given object
     * @param nm name under which to capture the trace
     * @param v variable
     * @return Tr(v)
     */
    public String trace(String nm, Variable v){
        return assignToFunCall(nm, TRACE, new String[]{v.getName()});
    }

    /**
     * Return the integral basis representation of e in n
     * @param nm the name to be given to the integral basis rep.
     * @param e the element whose representation we will return
     * @param n the number field whose integral basis we are
     * concerned with
     * @return integral basis integral basis representation of e
	 * in n
     */
    public String integralBasis(String nm, Element e, NumberField n){
        return assignToFunCall(nm, ELT_MOVE, new String[]{e.getName(), n.getMaxOrderName()});
    }

    /**
     * Store the minimal polynomial of the given element
     * @param nm name for the min. poly.
     * @param e element whose min. poly. we are looking for
     * @return minimal poly.
     */
    public String minPoly(String nm, Element e){
        return assignToFunCall(nm, MIN_POLY, new String[]{e.getName()});
    }

    /**
     * Find the principal generator of i whenever possible
     * @param nm shell name under which to store the return value
     * @param i an ideal
     * @return i's principal generator; false if i is not principal; (also see KASH documentation)
     */
    public String principal(String nm, Ideal i){
        return assignToFunCall(nm, PRINCIPAL, new String[]{i.getName()});
    }

	/**
	 * Like principal(), but this test is faster. Can only be called if the class group
	 * for the field in which i resides has already been computed.
	 * @param nm shell name under which to store the return value
	 * @param i ideal
	 * @return whenever possible i's principal generator; false if i is not principal; (also see KASH documentation)
	 * @see #principal
	 */
	public String principalFromClassGroup(String nm, Ideal i){
        return assignToFunCall(nm, PRINCIPAL_CL, new String[]{i.getName()});
    }

    //TO DO, pretty print string, add subscripts...?
    /**
     * Calculate, store the Galois group of a number field
     * @param nm name under which to store the return value
     * @param n a number field
     * @return String describing the structure of n's Galois group
     */
    protected String galoisGroup(String nm, NumberField n){
        return assignToFunCall(nm, GALOIS_GROUP, new String[]{n.getName()});
    }

    /**
     * Assign var to the given function call (in KASH)
     * @param var variable name
     * @param func KASH function to call
     * @param args args for func
     * @return KASH result for the assignment
     */
    public String assignToFunCall(String var, String func, String[] args){
        String f = funCall(func, args);
        Response r = assign(var, f);
        if(!r.error())
            return r.getOutput();
        else
			return HUH;
    }

    /**
     * Capture the variable for the univariate polynomial ring of the given number field
     * @param nm variable name for the return value
     * @param n number field
     * @return KASH representation for X as in n[X]
     */
    public String polyRingVar(String nm, NumberField n){
        String[] args = {n.getName()};
        String alg = funCall(POLY_ALG, args);   //univariate ring over  n

        String[] args2 = {alg, "[1,0]"};        //polynomial of deg=1, no constant term
        return assignToFunCall(nm, POLY, args2);
    }

    /**
     * Polynomial predicate
     * @param exp KASH expression
     * @return true iff exp defines a polynomial in KASH (note that 0 is NOT
     * a polynomia in KASH)
     */
    public boolean isPoly(String exp){
        Response r = funExec(POLY_P, new String[]{exp});
        if(!r.error())
            return trueString(r.getOutput());
        else return false;
    }

    /**
     * Element predicate
     * @param exp KASH expression
     * @return true iff exp is an element
     */
    public boolean isElement(String exp){
        Response r = funExec(ELT_P, new String[]{exp});
        if(!r.error())
            return trueString(r.getOutput());
        else return false;
    }

    /**
     * Ideal predicate
     * @param exp KASH expression
     * @return true iff exp is an ideal
     */
    public boolean isIdeal(String exp){
        Response r = funExec(IDEAL_P, new String[]{exp});
        if(!r.error())
            return trueString(r.getOutput());
        else return false;
    }

    /**
     * Call KASH eval on the given string, return the results
     * @param varName a KASH expression or variable name
     * @return result of eval(varName) in KASH
     */
    public Response eval(String varName){
        return tell(varName + END);
    }

	/**
     * Similar to eval(), except a string, and not a Response object is
	 * returned
     * @param eval a KASH expression
     * @return result of eval(eval) in KASH
	 * @see #eval
     */
	public String evalToString(String eval){
		Response r = eval(eval);
		if(r.error())
			return HUH;
		else
			return r.getOutput();
	}

    /**
     * Join the array using the default character
     * @see #JOIN
     * @param arr Array to join
     * @return A string of the array elements joined by the JOIN character
     */
    public static String join(String[] arr){
        return join(arr, JOIN);
    }

    /**
     * Join the given array with the given character
     * @param arr The array of strings to join
     * @param j The character to join with
     * @return The contents of arr joined by j
     */
    public static String join(String[] arr, String j){
        StringBuffer buff = new StringBuffer();

        int i = 0;
        for(i = 0; i < arr.length-1; i++)
            buff.append(arr[i] + j);
        //add the last element WITHOUT JOIN
        buff.append(arr[i]);

        return buff.toString();
    }

    //we write to the terminal
    /**
     * Add text to the end of the text display area (where KASH output goes)
     * @param msg text to append
     * @see #textDisplayArea
     */
    protected void appendText(String msg){
        textDisplayArea.append(msg);
        textDisplayArea.setCaretPosition(textDisplayArea.getDocument().getLength());
    }

    /**
     * Disable/Enable user input for this object
     * @param flag iff flag == true enable input; otherwise disable it
     */
    protected void setInputEnabled(boolean flag){
        textInputField.setEnabled(flag);
    }
    /*@deprecated
	 */
    /**
     * Check if a given string contains a KASH return prompt (used in determining when
     * the shell has finished the most recent request)
     * @param s string to search for the prompt
     * @return true iff s contains a kash prompt
     * @deprecated this is now done, differently, with regex
     * @see #KASH_P
     * @see #KASH_PROMPT
     */
    public static boolean hasKASHPrompt(String s){
        if(s != null){
        //TO DO...there can be problems with this...e.g. with answers containing >
            return (s.endsWith(KASH_PROMPT) || s.endsWith(KASH_PROMPT_B));
        }else{
        // null string is not a KASH Prompt
            return false;
        }
    }

    /**
     * Does the argument contain the word "true"?
     * @see #TRUE
     * @see #FALSE
     * @param s string to search
     * @return true iff s matches the pattern TRUE and does
     * NOT match the pattern FALSE; exception thrown if neither or both patterns
     * are matched
     */
    public static boolean trueString(String s){
        s = s.trim();
        Matcher m = TRUE.matcher(s);
        boolean t = m.find();

        m = FALSE.matcher(s);
        boolean f = m.find();

        if(t && f)  //this should be done with execptions!!!
            throw new AssertionError("String contains 'true' and 'false'");
        else if(!t && !f)
            throw new AssertionError("String contains neither 'true' nor 'false'");
        else
            return t;
    }

    /**
     * Wait until KASH responds until the last query; post response
     * @return KASH's response
     * @see KASHTerm.Response
     */
    protected Response listen(){
        return io.listen();

    }

    /**
     * Shut down all I/O streams to the KASH process
     */
    public void close(){
        tell("quit;");

        try{
            io.kashIn.write(("exit\n").toCharArray());
            io.kashIn.flush();
        }catch(Exception e){
            System.err.println("Problem closing shell:  " + e);
        }

        try{
            io.kashOut.close();
            io.kashErr.close();
        }catch(Exception e){
            System.err.println("Error closing streams:  " + e);
        }

    }

    /**
     * Create, store a new number field
     * @param name name for the number field
     * @param poly generating polynomial
     * @return resulting KASH output
     */
    protected Response newNumberField(String name, String poly){
        String[] args = {poly};
        Response r = tell(name + EQ + funCall(NEW_NF, args) + END);
        Matcher m = GEN_POLY.matcher(r.getOutput());
        String parse = m.replaceAll(""); //get rid of beginning part; e.g. >>>Generating polynomial:<<< x^3 + 2*x^2 - 2*x - 19
        r.parsed = Graphic.removeSpace(parse);

        return r;
    }

	/**
	 * Form a relative extension
	 * @param name name for the extension
	 * @param poly generating polynomial (from the polynomial ring of another number field)
	 * @return resulting KASH output
	 */
	protected Response relativeExtension(String name, String poly){
		String order = funCall(NEW_NF, new String[]{poly});
		//conver the relative order into an absolute one
		String absOrder = funCall(ABS_ORDER,  new String[]{order});
		Response r = tell(name + EQ + absOrder + END);
        Matcher m = GEN_POLY.matcher(r.getOutput());
        String parse = m.replaceAll(""); //get rid of beginning part; e.g. >>>Generating polynomial:<<< x^3 + 2*x^2 - 2*x - 19
        r.parsed = Graphic.removeSpace(parse);

        return r;
    }

    /**
     * Determine degree of the given polynomial
     * @param poly polynomial
     * @return degree of poly
     */
    protected int getDegree(String poly){
        String[] args = {poly};
        Response r = tell(funCall(POLY_DEG, args) + END);
        if(!r.error()){
            String answer = r.getOutput();
            return Integer.parseInt(answer);
            //do nothing
        }else{
            return -1;
        }
    }

    /**
     * Assign one quantity to another in KASH
     * @param var the left-hand side of the assignment
     * @param value the right-hand side of the assignment
     * @return result given by KASH
     */
    public Response assign(String var, String value){
        return tell(var + EQ + value + END);
    }
    /*
    public String assignReturnsString(String var, String value){
        Response r = assign(var, value);
        if(!r.error())
            return r.getOutput();
        else
            return HUH;
    }*/

    /**
     * Reducibility predicate for polynomials
     * @param p polynomial
     * @return true iff p is irreducible
     */
    public boolean irreducible(Polynomial p){
        String[] args = {p.getName()};
        Response r = tell(funCall(REDUCIBLE_P, args) + END);
        return  trueString(r.getOutput());
    }

    /**
     * Test if an ideal is prime
     * @param i ideal
     * @return true iff i is a prime ideal
     */
    public boolean prime(Ideal i){
        String[] args = {i.getName()};
        Response r = tell(funCall(PRIME_P, args) + END);
        return  trueString(r.getOutput());
    }

	/**
	 * Factor an ideal
	 * @param nm name under which to store the list of factors returned by KASH
	 * @param i ideal
	 * @return factors of i
	 */
	public String factor(String nm, Ideal i){
		return assignToFunCall(nm, IDEAL_FACTOR, new String[]{i.getName()});
	}
	/*
    public BooleanPlus prime(Ideal i){
        String[] args = {i.getName()};
        Response r = tell(funCall(PRIME_P, args) + END);
        BooleanPlus answer = BooleanPlus.UNKNOWN;
        try{
            boolean ans = trueString(r.getOutput());
            if(ans)
                answer = BooleanPlus.TRUE;
            else
                answer = BooleanPlus.FALSE;
        }catch(AssertionError e){

        }finally{
            return answer;
        }
    }*/

    /**
     * Test if an ideal is integral
     * @param i an ideal
     * @return true iff i is integral
     */
    public boolean integral(Ideal i){
        String[] args = {i.getName()};
        Response r = funExec(INTEGRAL_P, args);
        return  trueString(r.getOutput());
    }
    /*
    private void renderText(Graphics g){
        //mac os x, why doesn't this work?
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
        //textDisplayArea.super.paintComponent(g);
    }*/

    //@return is n1 a subfield of n2?
    /**
     * Subfield test
     * @param n1 number field
     * @param n2 number field
     * @return true iff n1 <= n2
     */
    protected boolean isSubfield(NumberField n1, NumberField n2){
        String[] args = {n1.getName(), n2.getName()};
        Response r = tell(funCall(SUBFLD, args) + END);
        if(!r.error()){
            return trueString(r.getOutput());
        }else{
            throw new AssertionError("Error testing subfields");
        }
    }
    //split a KASH-style list of the form [x,y,z...], where all entries
    //are either lists or rational numbers!
    /**
     * Split KASH lists into their constituent elements
     * @param list KASH list
     * @return list split into it's elements
     */
    public static String[] splitList(String list){

        String[] split = new String[0];
        String elts = Graphic.removeSpace(list);//make life easier
        if(elts.length() <= 2)//handle empty lists
            if(elts.length() < 2)//should have at least two chars:  [ and ]
                throw new AssertionError("malformed list:  " + list);
            else
                return split;//list is empty, nothing to split
        elts = elts.substring(1, elts.length());//strip opening '['
        ArrayList temp = new ArrayList();

        doSplit:
        while(!elts.equals("]")){//the closing brace of the list we are splitting
            int border, start=0;
            if(elts.startsWith("["))//starts with a list
                start = elts.indexOf("]");//find end of list
            border = elts.indexOf(",", start);//find the end of current element
            if(border == -1){//end of list
                temp.add(elts.substring(0, elts.length()-1));//-1 = forget the last ] in there
                break doSplit;
            }else{
                temp.add(elts.substring(0, border));
                elts = elts.substring(border+1, elts.length());//+1 to step over ','
            }
        }
        return (String[])temp.toArray(split);
    }

    //@return is n1 a superfield of n2?
    /**
     * Superfield test for a pair of number fields
     * @param n1 number field
     * @param n2 number field
     * @return true iff n1 >= n2
     */
    protected boolean isSuperfield(NumberField n1, NumberField n2){
        return isSubfield(n2,n1);
    }
    /*
    protected boolean isomorphic(NumberField n1, NumberField n2){
        return isSuperfield(n1, n2) && isSubfield(n1,n2);
    }*/

    /**
     * Send cmd to the current KASH environment
     * @param cmd the command string to send to KASH; same as if using KASH from a normal shell
     * @return void
     */
    protected Response tell(String cmd){

        if(!cmd.endsWith(END)){
            cmd += END;
            System.err.println(cmd + "\n^Received KASH command without terminator ';'");
        }
        Matcher m = QUIT.matcher(cmd);
        if(m.matches()){
            GiANT.gui.appendConsoleText("\nPlease quit GiANT using the main menu.", true);
            //GiANT.gui.setInputEnabled(true);
            return null;
        }else{
            //echo user's own input
            appendText(cmd + "\n");
            try{
                io.kashIn.write((cmd + "\n").toCharArray());
                io.kashIn.flush();
            }catch(Exception e){
                System.err.println("Problem sending text to KASH:  " + e);
            }
            // start listening for a response from KASH
            return io.listen();
        }
    }

    /**
     * class IO
     * Provides a java interface to UNIX shell process (e.g. KASH) I/O.
     */
    class IO{
        /**
         * The System-level object for the kash process itself
         */
        private Process kash;
        /**
         * Output stream FROM KASH
         */
        private Reader kashOut;
        /**
         * Error stream FROM KASH
         */
        private BufferedReader kashErr;
        /**
         * Stream for sending information TO (into) KASH
         */
        private OutputStreamWriter kashIn;

        /**
         * constructor
         * @see KASHTerm.IO
         * @param kashDir local path to the kash executable
         */
        private IO(String kashDir){
			    String[] startKASH = new String[]{kashDir + "/kash", "giant.kash"};
            try {
                // ask the Runtime to start KASH
                kash = Runtime.getRuntime().exec(startKASH, null, new File(kashDir));
                //kash = Runtime.getRuntime().exec(SSH_MACH, null, new File(KASH_DIR));
            }catch (Exception e){
                System.err.println("Unable to start KASH via Runtime:  " + e);
                //System.exit(-1);
            }

            try{
                //KASH OUTPUT Streams
                //buffering kashOut causes problems; the KASH prompt, e.g., never shows up
                kashOut = new InputStreamReader(kash.getInputStream());
                kashErr = new BufferedReader(new InputStreamReader(kash.getErrorStream()));
            }catch(Exception e){
                System.err.println("Unable to get Input/Error stream from KASH:  " + e);
                System.exit(-1);
            }

            try{
                kashIn = new OutputStreamWriter(kash.getOutputStream());
            }catch(Exception e){
                System.err.println("Unable to open OStream to KASH:  " + e);
                System.exit(-1);
            }
        }

        /**
         * Collect characters in the pipe FROM KASH until it returns a prompt (e.g. "kash> ")
         * @return A Response containing the information returned by KASH in response
         * to the command that preceded this call to listen()
         * @see KASHTerm.Response
         */
        private Response listen(){
            GiANT.gui.setInputEnabled(false);
            GiANT.gui.appendConsoleText("\n", false);//clear any previous error msgs
            //TO DO (minor), this puts extra blank lines into the conslole...
            String output = null;
            String finalError = null;
            StringBuffer error = new StringBuffer();
            Matcher m = KASH_P.matcher("");
            try{
                StringBuffer b = new StringBuffer();
                //listen until KASH returns a prompt
                while(!m.matches()){
                    //read char by char (buffering not possible...see above instantiation of kashOut
                    // -1 = end of stream
                    char c;
                    while(kashOut.ready()){
                        c = (char)kashOut.read();
                        b.append(c);
                    }
                    m.reset(b.toString());
                }
                output = b.toString();
            }catch(IOException e){
                System.err.println("kashOut stream:  " + e);
            }try{
                //now read out of the error stream
                //this is a bit of a hack in that it assumes all errors terminated with "\n"
                String s = null;
                while(kashErr.ready()){
                    //echo the error to our java KASH and to the GUI
                    s = kashErr.readLine();
                    appendText(s + "\n");
                    error.append(s);
                    //DEBUG
                    //System.err.println(s);
                    //TO DO...the Error text displayed by KASH is not always germane (e.g. it gives the
                    // wrong signatures for functions...so you may want to say something about that
                }
                finalError = error.toString();
                if(finalError.length() > 0)
                    GiANT.gui.appendConsoleText("\n" + finalError + DETAILS, true);
            }catch(IOException io){
                System.err.println("kashErr stream:  " + io);
            }
            //show the KASH prompt AFTER the error (if any)
            appendText(output);
            //DEBUG
                                //DEBUG
            //System.err.println(output);
            //System.err.println("group="+m.group(1).trim()+"***\n\n");
            Matcher m2 = ERROR.matcher(output);    //syntax errors don't go to stderr!
            if(m2.find()){
                error.append(output);
                GiANT.gui.appendConsoleText("\n"+Graphic.removeBackslash(m2.group()) + DETAILS, true);
            }
            GiANT.gui.setInputEnabled(true);
            //DEBUG
            //System.err.println("ERROR=" + error.toString());
            //System.err.println("OUTPUT=" + output);
            //m.group(1).trim() is minus kash prompt
            return new Response(m.group(1), finalError);
        }
    }

    /**
     * For each listen() call KASH issues a response
     * @see #listen()
     */
    protected class Response{

        /**
         * Error string from KASH
         */
        private String error;
        /**
         * Raw output string from KASH
         */
        private String output;
        /**
         * Occasionally we wish to parse the output a bit; it goes here. This value is returned
         * by getOutput()
         * @see #getOutput
         */
        private String parsed; //sometimes we want to parse the output...it goes here!

        /**
         * Constructor
         * @param output output information from KASH
         * @param error error information from KASH
         */
        private Response(String output, String error){
            this.error = error;
            this.output = output;
            parsed = Graphic.removeBackslash(output).trim();
        }

        /**
         * Was there an error?
         * @return true iff there was an error
         */
        protected boolean error(){
            return error.length() != 0;
        }

        /**
         * Get the error string associated with this repsonse
         * @return the error information returned by KASH
         */
        protected String getError(){
            return error;
        }

        /**
         * Get the output string associated with this repsonse
         * @return the output information returned by KASH
         */
        protected String getOutput(){
            return parsed;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        mainPanel = new javax.swing.JPanel();
        textDisplayScrollPane = new javax.swing.JScrollPane();
        textDisplayArea = new javax.swing.JTextArea();
        textInputPanel = new javax.swing.JPanel();
        textInputField = new javax.swing.JTextField();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
        setIconifiable(true);
        setResizable(true);
        setTitle("KASH");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
            public void componentHidden(java.awt.event.ComponentEvent evt) {
                formComponentHidden(evt);
            }
        });

        mainPanel.setLayout(new java.awt.BorderLayout());

        textDisplayScrollPane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        textDisplayScrollPane.setAutoscrolls(true);
        textDisplayArea.setBackground(new java.awt.Color(0, 0, 0));
        textDisplayArea.setColumns(80);
        textDisplayArea.setEditable(false);
        textDisplayArea.setFont(new java.awt.Font("Courier", 0, 11));
        textDisplayArea.setForeground(new java.awt.Color(51, 255, 0));
        textDisplayArea.setLineWrap(true);
        textDisplayArea.setRows(24);
        textDisplayArea.setTabSize(4);
        textDisplayArea.setDragEnabled(false);
        textDisplayArea.setMargin(new java.awt.Insets(2, 2, 2, 2));
        textDisplayScrollPane.setViewportView(textDisplayArea);

        mainPanel.add(textDisplayScrollPane, java.awt.BorderLayout.CENTER);

        getContentPane().add(mainPanel, java.awt.BorderLayout.CENTER);

        textInputPanel.setLayout(new java.awt.GridBagLayout());

        textInputPanel.setFocusable(false);
        textInputField.setFont(new java.awt.Font("Monaco", 0, 12));
        textInputField.setFocusCycleRoot(true);
        textInputField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textInputFieldActionPerformed(evt);
            }
        });
        textInputField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textInputFieldKeyPressed(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE;
        gridBagConstraints.gridheight = java.awt.GridBagConstraints.RELATIVE;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        textInputPanel.add(textInputField, gridBagConstraints);

        getContentPane().add(textInputPanel, java.awt.BorderLayout.SOUTH);

        pack();
    }
    // </editor-fold>//GEN-END:initComponents

    /**
     * Code to execute when the KASH window is shown
     * @param evt show event
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        textInputField.grabFocus();
    }//GEN-LAST:event_formComponentShown

    /**
     * Execute special code when this window is hidden
     * @param evt hide event
     */
    private void formComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentHidden
        GiANT.gui.requestDesktopFocus(true);
    }//GEN-LAST:event_formComponentHidden

    /**
     * Handle key presses (like up/down arrows) for textInputField
     * @param evt incoming key event
     */
    private void textInputFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textInputFieldKeyPressed
        final int code = evt.getKeyCode();
        boolean up = false;
        boolean down = false;

        up = code == UP_ARROW;
        down = code == DOWN_ARROW;

        if((up || down) && !commandHistory.isEmpty()){ //see if user pressed one of the up or down arrows
            //make sure there is a command history
           if(up)
               histCursor--;
           else
               histCursor++;

           int i = java.lang.Math.abs(histCursor % commandHistory.size());
           String hist = (String)commandHistory.get(i);
           textInputField.setText(hist);
           textInputField.setCaretPosition(hist.length());
        }

        if(code == java.awt.event.KeyEvent.VK_ESCAPE)
            setVisible(false);
    }//GEN-LAST:event_textInputFieldKeyPressed

    /**
     * Called when the user hits return in the input field
     * @see #textInputField
     * @param evt The event that started it all
     */
    private void textInputFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textInputFieldActionPerformed
        //prevent other user input
        //GiANT.gui.setInputEnabled(false);
        //fetch input string
        String cmd = textInputField.getText();
        //clear field
        textInputField.setText("");
        //handle command history
        commandHistory.add(cmd);
        histCursor = commandHistory.size(); //reset the history cursor
        //send command to shell
        tell(cmd);
        //keep focus
        textInputField.grabFocus();//focus model needs attention? TODO
        textInputField.setCaretPosition(0);
    }//GEN-LAST:event_textInputFieldActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    /**
     * The base Panel for the KASH window shown in GiANT
     */
    private javax.swing.JPanel mainPanel;
    /**
     * KASH output is displayed here
     */
    protected javax.swing.JTextArea textDisplayArea;
    /**
     * Scroll the KASH session output
     */
    private javax.swing.JScrollPane textDisplayScrollPane;
    /**
     * User input to KASH comes in here
     */
    private javax.swing.JTextField textInputField;
    /**
     * Lower Panel for KASH window in GiANT
     */
    private javax.swing.JPanel textInputPanel;
    // End of variables declaration//GEN-END:variables

}


text:
package com.github.riccardove.easyjasub.rendersnake;

import static org.rendersnake.HtmlAttributesFactory.charset;
import static org.rendersnake.HtmlAttributesFactory.class_;
import static org.rendersnake.HtmlAttributesFactory.lang;

import java.io.IOException;

import org.rendersnake.HtmlCanvas;

public class RendersnakeHtmlCanvas {

	private final String newLineStr;

	public RendersnakeHtmlCanvas(String newLine) {
		newLineStr = newLine;
		html = new HtmlCanvas();
	}

	private final HtmlCanvas html;

	public void header(String cssFileRef, String charsetStr) throws IOException {
		html.write("<!DOCTYPE html>", false)
				.write(newLineStr, false)
				.html(lang("ja"))
				.write(newLineStr, false)
				.head()
				.write(newLineStr, false)
				.meta(charset(charsetStr))
				.write(newLineStr, false)
				.write("<link href=\"" + cssFileRef
						+ "\" rel=\"stylesheet\" type=\"text/css\" />", false)
				.write(newLineStr, false)._head().write(newLineStr, false)
				.body().write(newLineStr, false);
	}

	public void footer() throws IOException {
		html._body()._html();
	}

	@Override
	public String toString() {
		return html.toHtml();
	}

	public RendersnakeHtmlCanvas h1() throws IOException {
		html.h1();
		return this;
	}

	public RendersnakeHtmlCanvas _h1() throws IOException {
		html._h1();
		return this;
	}

	public RendersnakeHtmlCanvas h2() throws IOException {
		html.h2();
		return this;
	}

	public RendersnakeHtmlCanvas _h2() throws IOException {
		html._h2();
		return this;
	}

	public RendersnakeHtmlCanvas _ul() throws IOException {
		html._ul();
		return this;
	}

	public RendersnakeHtmlCanvas ul() throws IOException {
		html.ul();
		return this;
	}

	public RendersnakeHtmlCanvas li() throws IOException {
		html.li();
		return this;
	}

	public RendersnakeHtmlCanvas _li() throws IOException {
		html._li();
		return this;
	}

	public RendersnakeHtmlCanvas newline() throws IOException {
		html.write(newLineStr, false);
		return this;
	}

	public void table() throws IOException {
		html.table();
	}

	public void tr(String string) throws IOException {
		html.tr(class_(string)).write(newLineStr, false);
	}

	public void _tr() throws IOException {
		html._tr();
	}

	public void space() throws IOException {
		html.write("  ");
	}

	public void tdEmpty() throws IOException {
		html.td()._td();
	}

	public void td(String grammarElement, String furigana) throws IOException {
		html.td(class_(grammarElement)).content(furigana, false);
	}

	public void td(String dict) throws IOException {
		html.td().content(dict);
	}

	public RendersnakeHtmlCanvas write(String trimmedText) throws IOException {
		html.write(trimmedText, true);
		return this;
	}

	public void writeUnescaped(String trimmedText) throws IOException {
		html.write(trimmedText, false);
	}

	public void tdOpen(String styleClass) throws IOException {
		html.td(class_(styleClass));
	}

	public void td() throws IOException {
		html.td();
	}

	public void _td() throws IOException {
		html._td();
	}

	public void spanKanji(String kanji) throws IOException {
		html.span(class_("kk")).content(kanji, false);
	}

	public void span(String styleClass) throws IOException {
		html.span(class_(styleClass));
	}

	public void _span() throws IOException {
		html._span();
	}

	public void _table() throws IOException {
		html._table();
	}

	public void p(String translation) throws IOException {
		html.p(class_("translation")).write(translation, false)._p();
	}

	public void table(String string, String subText) throws IOException {
		html.table().tr(class_(string)).td().content(subText, false)._tr()
				._table();
	}

	public void comment() throws IOException {
		html.write("<!--", false);
		newline();
	}

	public void _comment() throws IOException {
		html.write("-->", false);
		newline();
	}

	public RendersnakeHtmlCanvas p() throws IOException {
		html.p(class_("ja"));
		return this;
	}

	public RendersnakeHtmlCanvas _p() throws IOException {
		html._p();
		return this;
	}

	public void ruby() throws IOException {
		html.ruby();
	}

	public void ruby(String grammarElement) throws IOException {
		html.ruby(class_(grammarElement));
	}

	public void rt(String furigana) throws IOException {
		html.rt().write(furigana, false)._rt();
	}

	public void _ruby() throws IOException {
		html._ruby();
	}

	public void div() throws IOException {
		html.div();
	}

	public void _div() throws IOException {
		html._div();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package ecs

// ComponentType is used to describe a specific type of
// component that can be added to an Entity
type ComponentType string


text:
{% extends "layout.html" %}
{% block pageTitle %}
  File full accounts
{% endblock %}
{% block main %}

    {% include "includes/phase_banner_beta.html" %}
    {% include "includes/chs-user-menu-logged-in.html" %}

    {{ govukBackLink({
    text: "Back",
    href: "javascript:history.back()"
  }) }}

    {% include 'includes/error.html' %}

          <form action="/small-full/profit-loss-yes-no" method="get" class="form">

            {{ govukRadios({
                classes: "govuk-radios--inline",
                idPrefix: "smallfulldirectorsreport",
                name: "smallfulldirectorsreport",
                fieldset: {
                  legend: {
                    text: "Do your prepared accounts include a directors' report?",
                    isPageHeading: true,
                    classes: "govuk-fieldset__legend--l",
                    id: "main-content"
                  }
                },
                items: [
                  {
                    value: "yes",
                    text: "Yes"
                  },
                  {
                    value: "no",
                    text: "No"
                  }
                ]
              }) }}

            {{ govukButton({
                text: "Save and continue"
              }) }}

          </form>

{% endblock %}


text:
package ems_test;

import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import ems.Branch;
import ems.Customer;
import ems.Dijkstra;
import ems.Edge;
import ems.Graph;
import ems.Position;
import ems.Company;
import ems.CmdAddBranch;
import ems.CmdAddLinkage;
import ems.CmdCreateOrder;
import ems.CmdAddCustomer;
import ems.Manager;

public class CmdCreateOrderTest {
	Position pos1 = null;
    Position pos2 = null;
    Position pos3 = null;
    Position pos4 = null;
    Manager manager = null;
    Edge edge1 = null;
	CmdAddBranch cmdAddBranch;
	CmdAddLinkage cmdAddLinkage;
	CmdCreateOrder cmd;
	CmdAddCustomer cmdC;
	String[] paraB1 = new String[]{"addBranch","Sheila","2","1"};
	String[] paraB2 = new String[] {"addBranch","Sherlock","5","4"};
	Customer sender,receiver;
	@Before
	public void setUp() throws Exception {
		pos1 = new Position(1,1);
		pos2 = new Position(2,1);
		pos3 = new Position(5,4);
		pos4 = new Position(5,3);
        manager = new Manager(1, "test", "password","male", 1);
		cmdAddBranch = new CmdAddBranch(paraB1,manager);
		cmdAddBranch.execute();
		cmdAddBranch = new CmdAddBranch(paraB2,manager);
		cmdAddBranch.execute();
		cmdAddLinkage = new CmdAddLinkage(manager,new String[]{"addLinkage","1","2"}) ;
		cmdAddLinkage.execute();
		cmdC = new CmdAddCustomer(new String[]{"addCustomer","Sheila","password","8","1","1"},manager);
		cmdC.execute();
		cmdC = new CmdAddCustomer(new String[]{"addCustomer","Yolanda","password","8","5","3"},manager);
		cmdC.execute();
		sender = Company.getInstance().getCustomer(0);
		cmd = new CmdCreateOrder(Company.getInstance(),new String[] {"addCreateOrder","iphone","1"},sender);
	}
	@Test
	public void testConstructor() {
		//cmd = new CmdCreateOrder(Company.getInstance(),new String[] {"addCreateOrder","iphone","1"},sender);
	}
	@Test
	public void testExecute() {
		 ByteArrayOutputStream outContent = new ByteArrayOutputStream();
	     System.setOut(new PrintStream(outContent));
	     cmd.execute();
	     assertEquals("[#1 iphone] is created.\n",outContent.toString());
	}

}


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      ShowMeYourGraph Contest Participation · tehAnswer

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

          tehAnswer
           also known as
          Sergio Gijón

ShowMeYourGraph Contest Participation

  29 Jul 2014

This is my participation. The graph express the relation between brands and players, conferences, teams... of the NBA.

Click to download it

  Please enable JavaScript to view the comments powered by Disqus.
  comments powered by Disqus

           The journey of a thousand miles begins with a single step.


text:
const chai = require('chai')
const expect = chai.expect
const should = chai.should()
const checkStatusCode = require('../lib/helpers.js')
const format = require('../lib/format')
const STATUS_CODES = require('../lib/internals')

describe("checkStatusCode()", ()=> {
		it('should be a function', (done)=> {
		   	expect(checkStatusCode).to.be.a('function')
		   	done()
		})

		it('if status code not passed returns null', (done)=> {
			expect(checkStatusCode(null,"dummy msg")).to.be.null
			done()
		})

		it('returns default msg if msg is not specified', (done)=> {
			expect(checkStatusCode('200',null)).to.equal('OK')
			done()
		})

		it('returns custom msg if msg is specified', (done)=> {
			expect(checkStatusCode('200','response is ok')).to.equal('response is ok')
			done()
		})

})


text: <!DOCTYPE html>


text:
import {ModuleWithProviders, NgModule} from '@angular/core';

import {MdOptionModule, OverlayModule, OVERLAY_PROVIDERS, CompatibilityModule} from '../core';
import {CommonModule} from '@angular/common';
import {MdAutocomplete} from './autocomplete';
import {MdAutocompleteTrigger} from './autocomplete-trigger';

@NgModule({
  imports: [MdOptionModule, OverlayModule, CompatibilityModule, CommonModule],
  exports: [MdAutocomplete, MdOptionModule, MdAutocompleteTrigger, CompatibilityModule],
  declarations: [MdAutocomplete, MdAutocompleteTrigger],
})
export class MdAutocompleteModule {
  /** @deprecated */
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: MdAutocompleteModule,
      providers: [OVERLAY_PROVIDERS]
    };
  }
}

export * from './autocomplete';
export * from './autocomplete-trigger';


text:
package org.apache.geode.internal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;

import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.DataSerializer;
import org.apache.geode.internal.cache.UnitTestValueHolder;
import org.apache.geode.internal.serialization.BufferDataOutputStream;
import org.apache.geode.internal.serialization.KnownVersion;
import org.apache.geode.pdx.internal.TypeRegistry;
import org.apache.geode.test.junit.categories.SerializationTest;

/**
 * Test of methods on HeapDataOutputStream
 *
 * TODO right now this just tests the new write(ByteBuffer) method. We might want to add some unit
 * tests for the existing methods.
 */
@Category({SerializationTest.class})
public class HeapDataOutputStreamJUnitTest {

  @Before
  public void setup() {
    // ensure no bleedthrough from other tests
    TypeRegistry.init();
  }

  @Test
  public void testWriteByteBuffer() {
    HeapDataOutputStream out = new HeapDataOutputStream(64, KnownVersion.CURRENT);

    byte[] bytes = "1234567890qwertyuiopasdfghjklzxcvbnm,./;'".getBytes();
    out.write(ByteBuffer.wrap(bytes, 0, 2));
    out.write(ByteBuffer.wrap(bytes, 2, bytes.length - 2));

    ByteBuffer unused = out.finishWritingAndReturnUnusedBuffer();
    assertEquals(64 - bytes.length, unused.capacity());
    assertEquals(0, unused.position());
    assertEquals(unused.capacity(), unused.limit());

    byte[] actual = out.toByteArray();

    assertEquals(new String(bytes), new String(actual));
  }

  @Test
  public void testWriteByteBufferCopyUseBuffer() {
    ByteBuffer buf = ByteBuffer.allocate(32);
    HeapDataOutputStream out = new HeapDataOutputStream(buf, KnownVersion.CURRENT, true);

    out.write(0);

    byte[] bytes = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
        20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33};
    out.write(ByteBuffer.wrap(bytes));

    out.write(34);

    ByteBuffer unused = out.finishWritingAndReturnUnusedBuffer();
    assertEquals(buf.capacity() - 3, unused.capacity());
    assertEquals(0, unused.position());
    assertEquals(unused.capacity(), unused.limit());

    int bbCount = out.getByteBufferCount();
    assertEquals(2, bbCount);
    ByteBuffer[] bbs = new ByteBuffer[bbCount];
    out.fillByteBufferArray(bbs, 0);

    byte[] bbsBytes = new byte[out.size()];
    ByteBuffer tmp = ByteBuffer.wrap(bbsBytes);
    for (int i = 0; i < bbCount; i++) {
      tmp.put(bbs[i]);
    }
    tmp.flip();
    byte[] expectedBytes = new byte[bytes.length + 2];
    ByteBuffer expected = ByteBuffer.wrap(expectedBytes);
    expected.put((byte) 0);
    expected.put(bytes);
    expected.put((byte) 34);
    expected.flip();
    assertEquals(expected, tmp);
  }

  @Test
  public void testWriteByteBufferNoCopyUseBuffer() {
    ByteBuffer buf = ByteBuffer.allocate(32);
    HeapDataOutputStream out = new HeapDataOutputStream(buf, KnownVersion.CURRENT, true);

    out.write(0);

    byte[] bytes = new byte[BufferDataOutputStream.MIN_TO_COPY + 1];
    for (int i = 0; i < bytes.length; i++) {
      bytes[i] = (byte) ((i + 1) % 128);
    }
    ByteBuffer bytesBB = ByteBuffer.wrap(bytes);
    out.write(bytesBB);

    out.write((byte) ((bytes.length + 1) % 128));

    ByteBuffer unused = out.finishWritingAndReturnUnusedBuffer();
    assertEquals(buf.capacity() - 2, unused.capacity());
    assertEquals(0, unused.position());
    assertEquals(unused.capacity(), unused.limit());

    int bbCount = out.getByteBufferCount();
    assertEquals(3, bbCount);
    ByteBuffer[] bbs = new ByteBuffer[bbCount];
    out.fillByteBufferArray(bbs, 0);

    assertEquals(true, bbs[1] == bytesBB);

    byte[] bbsBytes = new byte[out.size()];
    ByteBuffer tmp = ByteBuffer.wrap(bbsBytes);
    for (int i = 0; i < bbCount; i++) {
      tmp.put(bbs[i]);
    }
    tmp.flip();
    byte[] expectedBytes = new byte[bytes.length + 2];
    for (int i = 0; i < expectedBytes.length; i++) {
      expectedBytes[i] = (byte) (i % 128);
    }
    ByteBuffer expected = ByteBuffer.wrap(expectedBytes);
    assertEquals(expected, tmp);
  }

  @Test
  public void testWriteJavaSerializeNoCopy() throws IOException, ClassNotFoundException {
    byte[] bytes = new byte[2000];
    for (int i = 0; i < bytes.length; i++) {
      bytes[i] = (byte) i;
    }
    UnitTestValueHolder vh = new UnitTestValueHolder(bytes);
    ByteBuffer buf = ByteBuffer.allocate(32);
    HeapDataOutputStream out = new HeapDataOutputStream(buf, KnownVersion.CURRENT, true);
    DataSerializer.writeObject(vh, out);
    UnitTestValueHolder vh2 = DataSerializer.readObject(new DataInputStream(out.getInputStream()));
    if (!Arrays.equals(bytes, (byte[]) vh2.getValue())) {
      fail("expected " + Arrays.toString(bytes) + " but found "
          + Arrays.toString((byte[]) vh2.getValue()));
    }
  }

}


text:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { reduxForCreateStore } from 'koot';
import reducers from './reducers';

/**
 * 项目自创建 store 的方法函数
 * - 提供创建 store 的方法
 * - 使用自定函数
 */
export default () => {
    const {
        reducers: defaultReducers,
        initialState,
        middlewares
    } = reduxForCreateStore;

    return createStore(
        combineReducers({
            ...defaultReducers,
            ...reducers
        }),
        initialState,
        applyMiddleware(...middlewares)
    );
};


text:
package com.bluedot.efactura;

import com.sun.xml.bind.marshaller.NamespacePrefixMapper;

public class MyNamespacePrefixMapper extends NamespacePrefixMapper
{

	@Override
	public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix)
	{
		System.out.println("String namespaceUri:"+namespaceUri+", String suggestion:"+suggestion+", boolean requirePrefix:"+requirePrefix);// TODO Auto-generated method stub
		if ("http://cfe.dgi.gub.uy".equals(namespaceUri))
			return "cfe";
		return "";
	}

}


text:
layout: post
title: "Markup: Title *with* **Markdown**"
categories:
  - Markdown
tags:
  - css
  - html
  - title
---

Verify that:

* The post title renders the word "with" in *italics* and the word "Markdown" in **bold**.
* The post title markup should be removed from the browser window / tab.


text:
sudo apt-get update
sudo apt-get install -y wget
wget https://apt.puppetlabs.com/puppetlabs-release-trusty.deb
sudo dpkg -i puppetlabs-release-trusty.deb
rm -f puppetlabs-release-trusty.deb
sudo apt-get update
sudo apt-get install -y puppet


text:
package org.spdx.compare;

import org.apache.poi.ss.usermodel.Workbook;
import org.spdx.rdfparser.model.SpdxFile;

/**
 * Sheet for file notice comparison results
 * @author Gary O'Neall
 *
 */
public class FileNoticeSheet extends AbstractFileCompareSheet {

	private static final int FILE_NOTICE_COL_WIDTH = 60;

	/**
	 * @param workbook
	 * @param sheetName
	 */
	public FileNoticeSheet(Workbook workbook, String sheetName) {
		super(workbook, sheetName);
	}

	static void create(Workbook wb, String sheetName) {
		AbstractFileCompareSheet.create(wb, sheetName, FILE_NOTICE_COL_WIDTH);
	}

	/* (non-Javadoc)
	 * @see org.spdx.compare.AbstractFileCompareSheet#valuesMatch(org.spdx.compare.SpdxComparer, org.spdx.rdfparser.SpdxFile, int, org.spdx.rdfparser.SpdxFile, int)
	 */
	@Override
	boolean valuesMatch(SpdxComparer comparer, SpdxFile fileA, int docIndexA,
			SpdxFile fileB, int docIndexB) throws SpdxCompareException {
		return SpdxComparer.stringsEqual(fileA.getNoticeText(), fileB.getNoticeText());
	}

	/* (non-Javadoc)
	 * @see org.spdx.compare.AbstractFileCompareSheet#getFileValue(org.spdx.rdfparser.SpdxFile)
	 */
	@Override
	String getFileValue(SpdxFile spdxFile) {
		String retval = spdxFile.getNoticeText();
		if (retval == null) {
			return "";
		} else {
			return retval;
		}
	}

}


text:
require File.join(File.dirname(__FILE__), '../../spec_helper')

describe Astute::GenerateKeys do
  include SpecHelpers

  before(:each) do
    Astute.config.puppet_keys = ['mongodb']
  end

  let(:ctx) do
    tctx = mock_ctx
    tctx.stubs(:status).returns({})
    tctx
  end

  let(:deploy_data) { [{'uid' => 1, 'deployment_id' => 1}, {'uid' => 2}] }
  let(:generate_keys) { Astute::GenerateKeys.new }

  around(:each) do |example|
    old_keys_dir = Astute.config.keys_src_dir
    old_puppet_keys = Astute.config.puppet_keys
    example.run
    Astute.config.keys_src_dir = old_keys_dir
    Astute.config.puppet_keys = old_puppet_keys
  end

  it 'should raise error if deployment_id is not set' do
    nodes = [{'uid' => 1}, {'uid' => 2}]
    expect { generate_keys.process(nodes, ctx) }.to raise_error('Deployment_id is missing')
  end

  it 'should save files in correct place: KEY_DIR/<name of key>/' do
    generate_keys.stubs(:run_system_command).returns([0, "", ""])

    Dir.mktmpdir do |temp_dir|
      Astute.config.keys_src_dir = temp_dir
      generate_keys.process(deploy_data, ctx)

      expect { File.directory? File.join(temp_dir, 'mongodb.key') }.to be_true
    end
  end

  it 'should raise error if directory for key was not created' do
    FileUtils.stubs(:mkdir_p).returns(false)
    File.stubs(:directory?).returns(false)

    expect { generate_keys.process(deploy_data, ctx) }.to raise_error(Astute::DeploymentEngineError,
                                                     /Could not create directory/)
  end

  it 'should raise error if key generation fail' do
    FileUtils.stubs(:mkdir_p).returns(true)
    File.stubs(:directory?).returns(true)
    generate_keys.stubs(:run_system_command).returns([1, "", ""])

    expect { generate_keys.process(deploy_data, ctx) }.to raise_error(Astute::DeploymentEngineError,
                                                     /Could not generate key! Command:/)
  end

  it 'should raise error if key generation command not found' do
    FileUtils.stubs(:mkdir_p).returns(true)
    File.stubs(:directory?).returns(true)
    generate_keys.stubs(:run_system_command).returns([127, "Command not found", ""])

    expect { generate_keys.process(deploy_data, ctx) }.to raise_error(Astute::DeploymentEngineError,
                                                     /Command not found/)
  end

  it 'should run key generation with correct command' do
    FileUtils.stubs(:mkdir_p).returns(true)
    File.stubs(:directory?).returns(true)

    key_path = File.join(
      Astute.config.keys_src_dir,
      deploy_data.first['deployment_id'].to_s,
      'mongodb',
      'mongodb.key'
    )
    cmd = "openssl rand -base64 741 > #{key_path} 2>&1"
    generate_keys.expects(:run_system_command).with(cmd).returns([0, "", ""])

    generate_keys.process(deploy_data, ctx)
  end

  it 'should not overwrite files' do
    Dir.mktmpdir do |temp_dir|
      Astute.config.keys_src_dir = temp_dir
      key_path = File.join(temp_dir,'mongodb', 'mongodb.key')
      FileUtils.mkdir_p File.join(temp_dir, 'mongodb')
      File.open(key_path, 'w') { |file| file.write("say no overwrite") }
      generate_keys.process(deploy_data, ctx)

      expect { File.exist? File.join(key_path, 'mongodb', 'mongodb.key') }.to be_true
      expect { File.read File.join(key_path, 'mongodb', 'mongodb.key') == "say no overwrite" }.to be_true
    end
  end

  it 'should check next key if find existing' do
    Astute.config.puppet_keys = ['mongodb', 'test']
    mongodb_key_path = File.join(
      Astute.config.keys_src_dir,
      deploy_data.first['deployment_id'].to_s,
      'mongodb',
      'mongodb.key'
    )
    test_key_path = File.join(
      Astute.config.keys_src_dir,
      deploy_data.first['deployment_id'].to_s,
      'test',
      'test.key'
    )

    FileUtils.stubs(:mkdir_p).returns(true).twice
    File.stubs(:directory?).returns(true).twice

    File.stubs(:exist?).with(mongodb_key_path).returns(true)
    File.stubs(:exist?).with(test_key_path).returns(false)

    generate_keys.expects(:run_system_command).returns([0, "", ""])

    generate_keys.process(deploy_data, ctx)
  end

end


text:
import a1 = require("garbage");
export declare var a: {
    test1: a1.connectModule;
    (): a1.connectExport;
};

//// [badExternalModuleReference.js]
define(["require", "exports"], function (require, exports) {
});


text:
Tessereact config should be named as `tessereact.config.json` and located in root directory of your app
(or on the path specified by `TESSEREACT_CONFIG` environment variable).

## Configuration options

`port` — a port of your Tessereact server, 5001 by default

`snapshotsPath` — a path to directory where Tessereact is going to store snapshots

`appURL` — Tessereact webpack-dev-server URL

`screenshotSizes` (optional) — a list of sizes for screenshot diff.
  Example:
  ```json
  "screenshotSizes": [
    {"width": 320, "height": 568, "alias": "iPhone SE"},
    {"width": 640, "height": 480},
    {"width": 800, "height": 600},
    {"width": 1024, "height": 768}
  ]
  ```

`screenshotDiff` (optional) — options for visual diffs:

- `screenshotDiff.command` — a command used to create a visual diff.
    Default: "convert -delay 50 $BEFORE $AFTER -loop 0 $RESULT".
    Use $BEFORE, $AFTER and $RESULT variables instead of the respective file names.
    Example:
    ```json
    "screenshotDiff": {
      "command": "convert '(' $BEFORE -flatten -grayscale Rec709Luminance ')' '(' $AFTER -flatten -grayscale Rec709Luminance ')' '(' -clone 0-1 -compose darken -composite ')' -channel RGB -combine $RESULT"
    }
    ```

- `screenshotDiff.resultExtension` - file name extension of the result file. Default: "gif"


text:
'use strict';

var colors = require('./colors');
var fs = require('graceful-fs');
var path = require('path');
var Q = require('q');

var DEFAULT_CONFIG_VALUES = {
  cacheDirectory: path.resolve(__dirname, '..', '..', '.haste_cache'),
  globals: {},
  moduleLoader: require.resolve('../HasteModuleLoader/HasteModuleLoader'),
  modulePathIgnorePatterns: [],
  testDirectoryName: '__tests__',
  testEnvironment: require.resolve('../JSDomEnvironment'),
  testFileExtensions: ['js'],
  moduleFileExtensions: ['js', 'json'],
  testPathDirs: ['<rootDir>'],
  testPathIgnorePatterns: ['/node_modules/'],
  testRunner: require.resolve('../jasmineTestRunner/jasmineTestRunner'),
};

function _replaceRootDirTags(rootDir, config) {
  switch (typeof config) {
    case 'object':
      if (config instanceof RegExp) {
        return config;
      }

      if (Array.isArray(config)) {
        return config.map(function(item) {
          return _replaceRootDirTags(rootDir, item);
        });
      }

      if (config !== null) {
        var newConfig = {};
        for (var configKey in config) {
          newConfig[configKey] =
            configKey === 'rootDir'
            ? config[configKey]
            : _replaceRootDirTags(rootDir, config[configKey]);
        }
        return newConfig;
      }
      break;
    case 'string':
      if (!/^<rootDir>/.test(config)) {
        return config;
      }

      return pathNormalize(path.resolve(
        rootDir,
        './' + path.normalize(config.substr('<rootDir>'.length))
      ));
  }
  return config;
}

function escapeStrForRegex(str) {
  return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

/**
 * Given the coverage info for a single file (as output by
 * CoverageCollector.js), return an array whose entries are bools indicating
 * whether anything on the line could have been covered and was, or null if the
 * line wasn't measurable (like empty lines, declaration keywords, etc).
 *
 * For example, for the following coverage info:
 *
 * COVERED:     var a = [];
 * NO CODE:
 * COVERED:     for (var i = 0; i < a.length; i++)
 * NOT COVERED:   console.log('hai!');
 *
 * You'd get an array that looks like this:
 *
 * [true, null, true, false]
 */
function getLineCoverageFromCoverageInfo(coverageInfo) {
  var coveredLines = {};
  coverageInfo.coveredSpans.forEach(function(coveredSpan) {
    var startLine = coveredSpan.start.line;
    var endLine = coveredSpan.end.line;
    for (var i = startLine - 1; i < endLine; i++) {
      coveredLines[i] = true;
    }
  });

  var uncoveredLines = {};
  coverageInfo.uncoveredSpans.forEach(function(uncoveredSpan) {
    var startLine = uncoveredSpan.start.line;
    var endLine = uncoveredSpan.end.line;
    for (var i = startLine - 1; i < endLine; i++) {
      uncoveredLines[i] = true;
    }
  });

  var sourceLines = coverageInfo.sourceText.trim().split('\n');

  return sourceLines.map(function(line, lineIndex) {
    if (uncoveredLines[lineIndex] === true) {
      return false;
    } else if (coveredLines[lineIndex] === true) {
      return true;
    } else {
      return null;
    }
  });
}

/**
 * Given the coverage info for a single file (as output by
 * CoverageCollector.js), return the decimal percentage of lines in the file
 * that had any coverage info.
 *
 * For example, for the following coverage info:
 *
 * COVERED:     var a = [];
 * NO CODE:
 * COVERED:     for (var i = 0; i < a.length; i++)
 * NOT COVERED:   console.log('hai');
 *
 * You'd get: 2/3 = 0.666666
 */
function getLinePercentCoverageFromCoverageInfo(coverageInfo) {
  var lineCoverage = getLineCoverageFromCoverageInfo(coverageInfo);
  var numMeasuredLines = 0;
  var numCoveredLines = lineCoverage.reduce(function(counter, lineIsCovered) {
    if (lineIsCovered !== null) {
      numMeasuredLines++;
      if (lineIsCovered === true) {
        counter++;
      }
    }
    return counter;
  }, 0);

  return numCoveredLines / numMeasuredLines;
}

function normalizeConfig(config) {
  var newConfig = {};

  // Assert that there *is* a rootDir
  if (!config.hasOwnProperty('rootDir')) {
    throw new Error('No rootDir config value found!');
  }

  config.rootDir = pathNormalize(config.rootDir);

  // Normalize user-supplied config options
  Object.keys(config).reduce(function(newConfig, key) {
    var value;
    switch (key) {
      case 'collectCoverageOnlyFrom':
        value = Object.keys(config[key]).reduce(function(normObj, filePath) {
          filePath = pathNormalize(path.resolve(
            config.rootDir,
            _replaceRootDirTags(config.rootDir, filePath)
          ));
          normObj[filePath] = true;
          return normObj;
        }, {});
        break;

      case 'testPathDirs':
        value = config[key].map(function(scanDir) {
          return pathNormalize(path.resolve(
            config.rootDir,
            _replaceRootDirTags(config.rootDir, scanDir)
          ));
        });
        break;

      case 'cacheDirectory':
      case 'scriptPreprocessor':
      case 'setupEnvScriptFile':
      case 'setupTestFrameworkScriptFile':
        value = pathNormalize(path.resolve(
          config.rootDir,
          _replaceRootDirTags(config.rootDir, config[key])
        ));
        break;

      case 'testPathIgnorePatterns':
      case 'modulePathIgnorePatterns':
      case 'unmockedModulePathPatterns':
        // _replaceRootDirTags is specifically well-suited for substituting
        // <rootDir> in paths (it deals with properly interpreting relative path
        // separators, etc).
        //
        // For patterns, direct global substitution is far more ideal, so we
        // special case substitutions for patterns here.
        value = config[key].map(function(pattern) {
          return pattern.replace(/<rootDir>/g, config.rootDir);
        });
        break;

      case 'collectCoverage':
      case 'globals':
      case 'moduleLoader':
      case 'name':
      case 'persistModuleRegistryBetweenSpecs':
      case 'rootDir':
      case 'setupJSLoaderOptions':
      case 'setupJSTestLoaderOptions':
      case 'setupJSMockLoaderOptions':
      case 'testDirectoryName':
      case 'testFileExtensions':
      case 'moduleFileExtensions':
        value = config[key];
        break;

      default:
        throw new Error('Unknown config option: ' + key);
    }
    newConfig[key] = value;
    return newConfig;
  }, newConfig);

  // If any config entries weren't specified but have default values, apply the
  // default values
  Object.keys(DEFAULT_CONFIG_VALUES).reduce(function(newConfig, key) {
    if (!newConfig[key]) {
      newConfig[key] = DEFAULT_CONFIG_VALUES[key];
    }
    return newConfig;
  }, newConfig);

  // Fill in some default values for node-haste config
  newConfig.setupJSLoaderOptions = newConfig.setupJSLoaderOptions || {};
  newConfig.setupJSTestLoaderOptions = newConfig.setupJSTestLoaderOptions || {};
  newConfig.setupJSMockLoaderOptions = newConfig.setupJSMockLoaderOptions || {};

  if (!newConfig.setupJSTestLoaderOptions.extensions) {
    newConfig.setupJSTestLoaderOptions.extensions =
      newConfig.testFileExtensions.map(_addDot);
  }

  if (!newConfig.setupJSLoaderOptions.extensions) {
    newConfig.setupJSLoaderOptions.extensions = uniqueStrings(
      newConfig.moduleFileExtensions.map(_addDot).concat(
        newConfig.setupJSTestLoaderOptions.extensions
      )
    );
  }

  if (!newConfig.setupJSMockLoaderOptions.extensions) {
    newConfig.setupJSMockLoaderOptions.extensions =
      newConfig.setupJSLoaderOptions.extensions;
  }

  return _replaceRootDirTags(newConfig.rootDir, newConfig);
}

function _addDot(ext) {
  return '.' + ext;
}

function uniqueStrings(set) {
  var newSet = [];
  var has = {};
  set.forEach(function (item) {
    if (!has[item]) {
      has[item] = true;
      newSet.push(item);
    }
  });
  return newSet;
}

function pathNormalize(dir) {
  return path.normalize(dir.replace(/\\/g, '/')).replace(/\\/g, '/');
}

function loadConfigFromFile(filePath) {
  var fileDir = path.dirname(filePath);
  return Q.nfcall(fs.readFile, filePath, 'utf8').then(function(fileData) {
    var config = JSON.parse(fileData);
    if (!config.hasOwnProperty('rootDir')) {
      config.rootDir = fileDir;
    } else {
      config.rootDir = path.resolve(fileDir, config.rootDir);
    }
    return normalizeConfig(config);
  });
}

function loadConfigFromPackageJson(filePath) {
  var pkgJsonDir = path.dirname(filePath);
  return Q.nfcall(fs.readFile, filePath, 'utf8').then(function(fileData) {
    var packageJsonData = JSON.parse(fileData);
    var config = packageJsonData.jest;
    config.name = packageJsonData.name;
    if (!config.hasOwnProperty('rootDir')) {
      config.rootDir = pkgJsonDir;
    } else {
      config.rootDir = path.resolve(pkgJsonDir, config.rootDir);
    }
    return normalizeConfig(config);
  });
}

var _contentCache = {};
function readAndPreprocessFileContent(filePath, config) {
  var cacheRec;
  var mtime = fs.statSync(filePath).mtime;
  if (_contentCache.hasOwnProperty(filePath)) {
    cacheRec = _contentCache[filePath];
    if (cacheRec.mtime === mtime) {
      return cacheRec.content;
    }
  }

  var fileData = fs.readFileSync(filePath, 'utf8');

  // If the file data starts with a shebang remove it (but leave the line empty
  // to keep stack trace line numbers correct)
  if (fileData.substr(0, 2) === '#!') {
    fileData = fileData.replace(/^#!.*/, '');
  }

  if (config.scriptPreprocessor) {
    try {
      fileData = require(config.scriptPreprocessor).process(fileData, filePath);
    } catch (e) {
      e.message = config.scriptPreprocessor + ': ' + e.message;
      throw e;
    }
  }
  _contentCache[filePath] = cacheRec = {mtime: mtime, content: fileData};
  return cacheRec.content;
}

function runContentWithLocalBindings(contextRunner, scriptContent, scriptPath,
                                     bindings) {
  var boundIdents = Object.keys(bindings);
  try {
    var wrapperFunc = contextRunner(
      '(function(' + boundIdents.join(',') + '){' +
      scriptContent +
      '\n})',
      scriptPath
    );
  } catch (e) {
    e.message = scriptPath + ': ' + e.message;
    throw e;
  }

  var bindingValues = boundIdents.map(function(ident) {
    return bindings[ident];
  });

  try {
    wrapperFunc.apply(null, bindingValues);
  } catch (e) {
    e.message = scriptPath + ': ' + e.message;
    throw e;
  }
}

/**
 * Given a test result, return a human readable string representing the
 * failures.
 *
 * @param {Object} testResult
 * @param {boolean} color true if message should include color flags
 * @return {String}
 */
function formatFailureMessage(testResult, color) {
  var colorize = color ? colors.colorize : function (str) { return str; };
  var ancestrySeparator = ' \u203A ';
  var descBullet = colorize('\u25cf ', colors.BOLD);
  var msgBullet = '  - ';
  var msgIndent = msgBullet.replace(/./g, ' ');

  return testResult.testResults.filter(function (result) {
    return result.failureMessages.length !== 0;
  }).map(function(result) {
    var failureMessages = result.failureMessages.map(function (errorMsg) {
      // Filter out q and jasmine entries from the stack trace.
      // They're super noisy and unhelpful
      errorMsg = errorMsg.split('\n').filter(function(line) {
        if (/^\s+at .*?/.test(line)) {
          // Extract the file path from the trace line
          var filePath = line.match(/(?:\(|at (?=\/))(.*):[0-9]+:[0-9]+\)?$/);
          if (filePath
              && STACK_TRACE_LINE_IGNORE_RE.test(filePath[1])) {
            return false;
          }
        }
        return true;
      }).join('\n');

      return msgBullet + errorMsg.replace(/\n/g, '\n' + msgIndent);
    }).join('\n');

    var testTitleAncestry = result.ancestorTitles.map(function(title) {
      return colorize(title, colors.BOLD);
    }).join(ancestrySeparator) + ancestrySeparator;

    return descBullet + testTitleAncestry + result.title + '\n' +
      failureMessages;
  }).join('\n');
}

// A RegExp that matches paths that should not be included in error stack traces
// (mostly because these paths represent noisy/unhelpful libs)
var STACK_TRACE_LINE_IGNORE_RE = new RegExp('^(?:' + [
    path.resolve(__dirname, '..', 'node_modules', 'q'),
    path.resolve(__dirname, '..', 'vendor', 'jasmine')
].join('|') + ')');

exports.escapeStrForRegex = escapeStrForRegex;
exports.getLineCoverageFromCoverageInfo = getLineCoverageFromCoverageInfo;
exports.getLinePercentCoverageFromCoverageInfo =
  getLinePercentCoverageFromCoverageInfo;
exports.loadConfigFromFile = loadConfigFromFile;
exports.loadConfigFromPackageJson = loadConfigFromPackageJson;
exports.normalizeConfig = normalizeConfig;
exports.pathNormalize = pathNormalize;
exports.readAndPreprocessFileContent = readAndPreprocessFileContent;
exports.runContentWithLocalBindings = runContentWithLocalBindings;
exports.formatFailureMessage = formatFailureMessage;


text:
package com.streamsets.pipeline.stage.processor.statsaggregation;

import java.util.Iterator;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * A bounded deque that also de-dupes values between consecutive offers.
 *
 * This is required to make sure we store only the last n alert texts and do not store 2 consecutive alert texts that
 * happen to be the same.
 *
 * @param <E>
 */
class BoundedDeque<E> implements Iterable<E> {

  private final LinkedBlockingDeque<E> linkedBlockingDeque;

  public BoundedDeque(int capacity) {
    linkedBlockingDeque = new LinkedBlockingDeque<>(capacity);
  }

  public boolean offerLast(E e) {
    if (null != e && (null == linkedBlockingDeque.peekLast() || !e.equals(linkedBlockingDeque.peekLast()))) {
      if (linkedBlockingDeque.remainingCapacity() == 0) {
        linkedBlockingDeque.removeFirst();
      }
      linkedBlockingDeque.offerLast(e);
      return true;
    }
    return false;
  }

  public Iterator<E> iterator() {
    return linkedBlockingDeque.iterator();
  }
}


text:
PROPERTY INFO

Amenities

Furnished office space

2 conference rooms

All utilities included

Wireless internet

Mailing address

Weekly Cleaning

Flexible lease

Kitchen

$0
                            /month

BASIC

Open desk space

Come to the Dojo anytime to work in a relaxed enviroment
                            with entrepreneurs like you.

<input type="button" class="btn btn-primary-custom" value="INQUIRE"/>

$75
                            /month

INTERMEDIATE

Reserved desk space

Take your business to the next level with your
                            own desk set aside for you at the Dojo. Flexible lease available

<input type="button" class="btn btn-primary-custom" value="INQUIRE"/>

$250
                            /month

DA BEST

1 room reserved space

Ideal for 3-5 people, this set up will give you an entire
                            room to take your startup from zero to hero. Flexible lease.

<input type="button" class="btn btn-primary-custom" value="INQUIRE"/>

Contact us

            <form action="" class="form-group">
                <input type="text" name="contact_name" class="form-control form-custom" id="input1"
                       placeholder="Name">

                <input type="email" name="contact_email" class="form-control form-custom" id="input2"
                       placeholder="Email Address">

                <input type="phone" name="contact_phone" class="form-control form-custom" id="input3"
                       placeholder="Phone Number">

                <textarea name="contact_message" class="form-control form-custom" rows="6" id="input4"
                          placeholder="Message"></textarea>

                    <button type="submit" class="btn btn-primary btn-primary-custom">SEND</button>

            </form>


text:
#ifndef FRAMEPROCESSOR_FRAME_H
#define FRAMEPROCESSOR_FRAME_H

#include <string>
#include <stdint.h>

#include <log4cxx/logger.h>
#include "FrameMetaData.h"

namespace FrameProcessor {

/** Interface class for a Frame; all Frames must sub-class this.
 *
 */
class Frame {

 public:

  /** Base constructor */
  Frame(const FrameMetaData &meta_data, const size_t &data_size, const int &image_offset = 0);
  /** Shallow-copy copy */
  Frame(const Frame &frame);

  /** Deep-copy assignment */
  Frame &operator=(const Frame& frame);

  /** Return if frame is valid */
  bool is_valid() const;

  /** Return a void pointer to the raw data */
  virtual void *get_data_ptr() const = 0;

  /** Return a void pointer to the image data */
  virtual void *get_image_ptr() const;

  /** Return if this frame object is an "end of acquisition" frame*/
  virtual bool get_end_of_acquisition() const;

  /** Return the data size */
  size_t get_data_size() const;

  /** Update the data size */
  void set_data_size(size_t size);

  /** Return the frame number */
  long long get_frame_number() const;

  /** Set the frame number */
  void set_frame_number(long long frame_number);

  /** Return a reference to the MetaData */
  FrameMetaData &meta_data();

  /** Return the MetaData */
  const FrameMetaData &get_meta_data() const;

  /** Return deep copy of the MetaData */
  FrameMetaData get_meta_data_copy() const;

  /** Set MetaData */
  void set_meta_data(const FrameMetaData &meta_data);

  /** Return the image size */
  int get_image_size() const;

  /** Set the image size */
  void set_image_size(const int &size);

  /** Set the image offset */
  void set_image_offset(const int &offset);

  /** Set the outer chunk size */
  void set_outer_chunk_size(const int &size);

  /** Set the outer chunk size */
  int get_outer_chunk_size() const;

 protected:

  /** Pointer to logger */
  log4cxx::LoggerPtr logger_;

  /** Frame MetaData */
  FrameMetaData meta_data_;

  /** Shared memory size **/
  size_t data_size_;

  /** Size of the image **/
  int image_size_;

  /** Offset from frame memory start to image data */
  int image_offset_;

  /** Outer chunk size of this frame (number of images in this chunk) */
  int outer_chunk_size_;

};

}

#endif


text:
<?php while (have_posts()) : the_post(); ?>
  <?php get_template_part('partials/page-header'); ?>
  <?php get_template_part('partials/content-page'); ?>
<?php endwhile; ?>


text:
"""Config flow to configure Met component."""
from typing import Any, Dict, Optional

import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv

from .const import CONF_TRACK_HOME, DOMAIN, HOME_LOCATION_NAME

@callback
def configured_instances(hass):
    """Return a set of configured SimpliSafe instances."""
    entries = []
    for entry in hass.config_entries.async_entries(DOMAIN):
        if entry.data.get("track_home"):
            entries.append("home")
            continue
        entries.append(
            f"{entry.data.get(CONF_LATITUDE)}-{entry.data.get(CONF_LONGITUDE)}"
        )
    return set(entries)

class MetFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
    """Config flow for Met component."""

    VERSION = 1
    CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL

    def __init__(self):
        """Init MetFlowHandler."""
        self._errors = {}

    async def async_step_user(self, user_input=None):
        """Handle a flow initialized by the user."""
        self._errors = {}

        if user_input is not None:
            if (
                f"{user_input.get(CONF_LATITUDE)}-{user_input.get(CONF_LONGITUDE)}"
                not in configured_instances(self.hass)
            ):
                return self.async_create_entry(
                    title=user_input[CONF_NAME], data=user_input
                )
            self._errors[CONF_NAME] = "name_exists"

        return await self._show_config_form(
            name=HOME_LOCATION_NAME,
            latitude=self.hass.config.latitude,
            longitude=self.hass.config.longitude,
            elevation=self.hass.config.elevation,
        )

    async def _show_config_form(
        self, name=None, latitude=None, longitude=None, elevation=None
    ):
        """Show the configuration form to edit location data."""
        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(
                {
                    vol.Required(CONF_NAME, default=name): str,
                    vol.Required(CONF_LATITUDE, default=latitude): cv.latitude,
                    vol.Required(CONF_LONGITUDE, default=longitude): cv.longitude,
                    vol.Required(CONF_ELEVATION, default=elevation): int,
                }
            ),
            errors=self._errors,
        )

    async def async_step_import(
        self, user_input: Optional[Dict] = None
    ) -> Dict[str, Any]:
        """Handle configuration by yaml file."""
        return await self.async_step_user(user_input)

    async def async_step_onboarding(self, data=None):
        """Handle a flow initialized by onboarding."""
        return self.async_create_entry(
            title=HOME_LOCATION_NAME, data={CONF_TRACK_HOME: True}
        )


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

namespace Pregunta.Me.Core.Base
{
    public abstract class DomainService<T>
    {
    }
}


text:
@interface TJPRefreshGifHeader()

@property (nonatomic, strong) NSMutableArray *refreshingArr;
@property (nonatomic, strong) NSMutableArray *pullingArr;
@property (nonatomic, strong) NSMutableArray *idleArr;

@end

@implementation TJPRefreshGifHeader

- (NSMutableArray *)refreshingArr {
    if (!_refreshingArr) {
        _refreshingArr = [NSMutableArray array];
    }
    return _refreshingArr;
}

- (NSMutableArray *)pullingArr {
    if (!_pullingArr) {
        _pullingArr = [NSMutableArray array];
    }
    return _pullingArr;
}

- (NSMutableArray *)idleArr {
    if (!_idleArr) {
        _idleArr = [NSMutableArray array];
    }
    return _idleArr;
}

- (instancetype)init {

    if (self = [super init]) {
        self.lastUpdatedTimeLabel.hidden = YES;
        self.stateLabel.hidden = YES;
        for (int i = 1; i < 30; i++) {
            [self.refreshingArr addObject:[UIImage imageNamed:[NSString stringWithFormat:@"refresh_fly_%i", i]]];
        }
        [self setImages:_refreshingArr  duration:1.5 forState:MJRefreshStateRefreshing];

//        for (int i = 1; i < 8; i++) {
//            [self.pullingArr addObject:[UIImage imageNamed:[NSString stringWithFormat:@"refresh_fly_%i", i]]];
//
//        }

        for (int i = 22; i < 29; i++) {
            [self.idleArr addObject:[UIImage imageNamed:[NSString stringWithFormat:@"refresh_fly_%i", i]]];
        }
        [self setImages:_idleArr forState:MJRefreshStateIdle];
        [self setImages:_idleArr forState:MJRefreshStatePulling];

    }
    return self;
}

@end


text:
import { MyAngularAppPage } from './app.po';

describe('my-angular-app App', () => {
  let page: MyAngularAppPage;

  beforeEach(() => {
    page = new MyAngularAppPage();
  });

  it('should display message saying app works', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('koios works!');
  });
});


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

namespace dir_size
{
    class Program
    {
        static void Main(string[] args)
        {
            var dirSize = Directory.GetFiles("TestFolder").Select(f => new FileInfo(f)).Sum(f => f.Length / 1024.0 / 1024.0).ToString();
            File.AppendAllText("result.txt", dirSize);
        }
    }
}