text:
package still.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import still.data.DimensionDescriptor;
import still.data.Operator;
import still.data.Table;
import still.data.TableEvent;
import still.data.TableFactory;
import still.data.TableListener;
import still.expression.Expression;
import still.expression.ExpressionEvent;
import still.expression.ExpressionListener;
//import still.operators.CutoffOp;
//import still.operators.PCAOp;
//import still.operators.PearsonCollectOp;

public class ExpressionTreeView extends JPanel implements 	ActionListener,
															ExpressionListener,
															TreeSelectionListener,
															TreeModelListener,
															TableListener {

	/**
	 *
	 */
	private static final long serialVersionUID = 8513944058034774182L;
	public JTree tree = null;

	public Expression selExpr  	= null;
	public Table selTable 		= null;
	public int selDim 			= -1;
	JButton removeOpButton 		= null;
	JButton stepOpButton 		= null;
	ArrayList<ActionListener> actionListeners = null;
	NumberFormat nf = NumberFormat.getInstance();

	public void addActionListener( ActionListener al ) {

		actionListeners.add( al );
	}

	public ExpressionTreeView( ArrayList<Expression> es ) {

		super( new BorderLayout() );

		nf.setMaximumFractionDigits(2);
		nf.setMinimumFractionDigits(0);

		actionListeners = new ArrayList<ActionListener>();

		DefaultMutableTreeNode top = new DefaultMutableTreeNode( "Expressions" );
		DefaultMutableTreeNode first_exp = null;

		if( es != null ) {

			for( int i = 0; i < es.size(); i++ ) {

				es.get(i).addExpressionListener(this);

				DefaultMutableTreeNode expr_node = new DefaultMutableTreeNode( new StillNode(es.get(i),i+1));
				DefaultMutableTreeNode input_node = new DefaultMutableTreeNode( new StillNode(es.get(i).table));
				if( input_node != null && first_exp == null ) {

					first_exp = input_node;
				}

				es.get(i).table.addActionListener(this);

				expr_node.add(input_node);
				int opnum = 0;
				for( Operator op :  es.get(i).operators ) {

					opnum++;

					op.setExpressionNumber(i+1);
					op.setTermNumber(opnum);

					DefaultMutableTreeNode op_node = new DefaultMutableTreeNode(new StillNode(op,opnum));
					expr_node.add(op_node);
					op.addActionListener(this);
					op.addTableListener(this);
					ArrayList<DimensionDescriptor> descriptors = op.getConstructedDimensions();
					if( descriptors != null ) {
						for( DimensionDescriptor dd : descriptors ) {

							DefaultMutableTreeNode dd_node = new DefaultMutableTreeNode( dd );
							op_node.add( dd_node );
							if( dd.sub_values != null ) {

								for( String s : dd.sub_values ) {

									DefaultMutableTreeNode sv_node = new DefaultMutableTreeNode( s );
									dd_node.add( sv_node );
								}
							}
						}
					}
				}
				top.add( expr_node );
			}
		}

		tree = new JTree( top );
		tree.setCellRenderer( new ExpressionTreeCellRenderer() );
		tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

		tree.addTreeSelectionListener(this);
		JScrollPane scrollPane = new JScrollPane(tree);
		this.add(scrollPane, BorderLayout.CENTER);

		// add buttons

		JPanel buttonPanel = new JPanel();
		buttonPanel.setLayout( new GridLayout(0,3,5,5));
		removeOpButton = new JButton("Remove Operator");
		stepOpButton = new JButton("Step Operator");
		buttonPanel.add( removeOpButton );
		buttonPanel.add( stepOpButton );
		removeOpButton.addActionListener( this );
		stepOpButton.addActionListener(this);
		this.add(buttonPanel,BorderLayout.SOUTH);
		tree.getModel().addTreeModelListener(this);

		// if there is an expression to load, then set the first to be selected

		if( first_exp == null)  {

			tree.setSelectionPath( new TreePath(top.getPath()) );
		}
		else {

			tree.setSelectionPath( new TreePath(first_exp.getPath()) );
		}
	}

	/**
	 *
	 * Re-fires a selection event for the selected nodes.
	 */
	public void reSelect() {

		TreePath path = tree.getSelectionPath();
		tree.setSelectionPath( null );
		tree.setSelectionPath( path );
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		if( e.getSource() == stepOpButton ) {

			if( selExpr != null ) {

				this.setCursor( new Cursor( Cursor.WAIT_CURSOR ) );
				selExpr.activateNextOperator();
				this.setCursor( new Cursor( Cursor.DEFAULT_CURSOR ) );
			}
		}
		if( e.getSource() == removeOpButton ) {

			if( selTable != null && selTable instanceof Operator ) {

				selExpr.delOperator((Operator)selTable);
			}
		}

		if( e.getSource() instanceof Operator || e.getSource() instanceof Table ) {

			DefaultTreeModel model = ((DefaultTreeModel)tree.getModel());
			model.nodeChanged(findOpNodes((Table)e.getSource()));
		}
	}

	/**
	 * Find a node in a tree given that it is an operator or table
	 *
	 * @param t
	 * @return
	 */
	public DefaultMutableTreeNode findOpNodes( Table t ) {

		DefaultMutableTreeNode node = null;

		// get the appropriate expression node
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot();
		int expression_count = tree.getModel().getChildCount(root);
		if( expression_count < 1) {
			return null;
		}
		for( int i = 0; i < expression_count; i++ ) {

			DefaultMutableTreeNode child = (DefaultMutableTreeNode) tree.getModel().getChild(root, i);
			for( int j = 0; j < child.getChildCount(); j++ ) {

				DefaultMutableTreeNode gchild = (DefaultMutableTreeNode) child.getChildAt(j);
				if( ( (StillNode) gchild.getUserObject()).table == t  ||
				    ( (StillNode) gchild.getUserObject()).op == t  ) {

			    	return gchild;
				}
			}
		}

		return node;
	}

	/**
	 * Find a node in a tree given that it is an expression
	 *
	 * @param e
	 * @return
	 */
	public DefaultMutableTreeNode findExNode( Expression e ) {

		DefaultMutableTreeNode node = null;

		// get the appropriate expression node
		DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot();
		int expression_count = tree.getModel().getChildCount(root);
		if( expression_count < 1) {

			return null;
		}

		for( int i = 0; i < expression_count; i++ ) {

			DefaultMutableTreeNode child = (DefaultMutableTreeNode) tree.getModel().getChild(root, i);
			if( ( (StillNode) child.getUserObject()).ex == e ) {

				return child;
			}
		}

		return node;
	}

	/**
	 * Renumber the expressions and update the tree strings
	 */
	public void renumberExpressions( ) {

		DefaultMutableTreeNode root = (DefaultMutableTreeNode)((DefaultTreeModel)tree.getModel()).getRoot();
		Enumeration enumeration = root.children();
		int opnum = 0;
		while( enumeration.hasMoreElements() ) {

			DefaultMutableTreeNode node = (DefaultMutableTreeNode)enumeration.nextElement();
			if(((StillNode)node.getUserObject()).ex != null) {

				opnum++;
				((StillNode)node.getUserObject()).opnum = opnum;
			}
		}
		((DefaultTreeModel)tree.getModel()).nodeStructureChanged(root);
	}

	/**
	 * Renumber the operators and update the tree strings
	 *
	 * @param e
	 */
	public void renumberOps( Expression e ) {

		DefaultMutableTreeNode child = findExNode( e );
		Enumeration enumeration = child.children();
		int opnum = 0;
		while( enumeration.hasMoreElements() ) {

			DefaultMutableTreeNode node = (DefaultMutableTreeNode)enumeration.nextElement();
			if(((StillNode)node.getUserObject()).op != null) {

				opnum++;
				((StillNode)node.getUserObject()).opnum = opnum;
			}
		}
		((DefaultTreeModel)tree.getModel()).nodeStructureChanged(child);
	}

	@Override
	public void expressionChanged(ExpressionEvent e) {

		if( e.command == ExpressionEvent.ExpressionEventType.TERM_ADDED ) {

			DefaultMutableTreeNode child = findExNode( (Expression) e.getSource() );
			if( child != null ) {

				int opnum = 0;
				DefaultMutableTreeNode op_node = null;
				for( Operator op :  ((Expression) e.getSource()).operators ) {

					opnum++;
					if( op == e.getTerm() ) {

						op.addActionListener(this);
						op.addTableListener(this);
						op.setTermNumber(opnum);
						op.setExpressionNumber( ((StillNode)child.getUserObject()).exnum );
						op_node = new DefaultMutableTreeNode(new StillNode(op, opnum));
						if( op.isActive() ) {

							ArrayList<DimensionDescriptor> descriptors = op.getConstructedDimensions();
							if( descriptors != null ) {
								for( DimensionDescriptor dd : descriptors ) {

									DefaultMutableTreeNode dd_node = new DefaultMutableTreeNode( dd );
									op_node.add( dd_node );
									if( dd.sub_values != null ) {

										for( String s : dd.sub_values ) {

											DefaultMutableTreeNode sv_node = new DefaultMutableTreeNode( s );
											dd_node.add( sv_node );
										}
									}
								}
							}
						}
						break;
					}
				}
				if( op_node != null ) {

					((DefaultTreeModel)tree.getModel()).insertNodeInto(op_node, child, opnum);
					renumberOps( (Expression) e.getSource() );
					tree.setSelectionPath( new TreePath( new Object[] { tree.getModel().getRoot(), child, op_node } ) );

				}
			}
		}
		else if( e.command == ExpressionEvent.ExpressionEventType.TERM_ACTIVATED ||
				e.command == ExpressionEvent.ExpressionEventType.TERM_CHANGED ) {
			// repaint everything
			DefaultTreeModel model = ((DefaultTreeModel)tree.getModel());
			model.nodeChanged(findOpNodes( e.term ));
		}
		else if( e.command == ExpressionEvent.ExpressionEventType.NEW_INPUT ) {

			// repaint everything
			DefaultTreeModel model = ((DefaultTreeModel)tree.getModel());
			DefaultMutableTreeNode treeNode = findOpNodes( e.additionalTerm );
			StillNode stillNode = ((StillNode)treeNode.getUserObject());
			stillNode.table = e.term;
			model.nodeChanged( findOpNodes( e.term ));
			if( selTable == e.additionalTerm ) {

				selTable = e.term;
			}
		}
		else if( e.command == ExpressionEvent.ExpressionEventType.TERM_REMOVED ) {

			DefaultMutableTreeNode child = findOpNodes( e.getTerm() );
			if( child != null ) {

				((DefaultTreeModel)tree.getModel()).removeNodeFromParent(child);
				renumberOps( (Expression) e.getSource() );
			}
		}
		else if( e.command == ExpressionEvent.ExpressionEventType.EXPRESSION_DELETED ) {

			DefaultMutableTreeNode child = findExNode( (Expression) e.getSource() );
			if( child != null ) {

				((DefaultTreeModel)tree.getModel()).removeNodeFromParent(child);
				renumberExpressions( );
			}
		}
		else if( e.command == ExpressionEvent.ExpressionEventType.NEW_EXPRESSION ) {

			Expression es = (Expression)e.getSource();
			//es.addExpressionListener(this);

			DefaultMutableTreeNode expr_node  = new DefaultMutableTreeNode( new StillNode(es,((DefaultMutableTreeNode)((DefaultTreeModel)tree.getModel()).getRoot()).getChildCount()+1));
			DefaultMutableTreeNode input_node = new DefaultMutableTreeNode( new StillNode(es.table));
			DefaultMutableTreeNode last_node = input_node;

			((DefaultTreeModel)tree.getModel()).insertNodeInto( expr_node,
																((DefaultMutableTreeNode)((DefaultTreeModel)tree.getModel()).getRoot()),
																((DefaultMutableTreeNode)((DefaultTreeModel)tree.getModel()).getRoot()).getChildCount());
			((DefaultTreeModel)tree.getModel()).insertNodeInto( input_node, expr_node, 0);

			es.table.addActionListener(this);

			expr_node.add(input_node);
			int opnum = 0;
			for( Operator op :  es.operators ) {

				opnum++;
				op.setTermNumber(opnum);
				op.setExpressionNumber(((DefaultMutableTreeNode)((DefaultTreeModel)tree.getModel()).getRoot()).getChildCount()+1);
				DefaultMutableTreeNode op_node = new DefaultMutableTreeNode(new StillNode(op,opnum));
				last_node = op_node;
				op.addActionListener(this);
				op.addTableListener(this);
				ArrayList<DimensionDescriptor> descriptors = op.getConstructedDimensions();
				if( descriptors != null ) {
					for( DimensionDescriptor dd : descriptors ) {

						DefaultMutableTreeNode dd_node = new DefaultMutableTreeNode( dd );
						op_node.add( dd_node );
						if( dd.sub_values != null ) {

							for( String s : dd.sub_values ) {

								DefaultMutableTreeNode sv_node = new DefaultMutableTreeNode( s );
								dd_node.add( sv_node );
							}
						}
					}
				}
				((DefaultTreeModel)tree.getModel()).insertNodeInto( op_node, expr_node, opnum);
			}
			renumberExpressions( );
			tree.setSelectionPath( new TreePath(last_node.getPath()) );
		}
	}

	public static Expression getTreeExpression( TreeSelectionEvent e ) {

	    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();

		if (node == null || node.isRoot()) {

			return null;
		}

		if( node.getUserObject() instanceof DimensionDescriptor ) {

			node  = (DefaultMutableTreeNode) node.getParent();
		}

		if( node.isLeaf() && node.getUserObject() instanceof String ) {

			node  = (DefaultMutableTreeNode) ( node.getParent()).getParent();
		}

		if (node == null || node.isRoot()) {

			return null;
		}

		// determine the expression, the
		if( node.getUserObject() instanceof StillNode ) {

			StillNode myNode = (StillNode) node.getUserObject();
			if( myNode.ex != null ) {

				return myNode.ex;
			}
			if( (myNode.op != null || myNode.table != null ) && myNode.ncol < 0 ) {

				return ( (StillNode) ( (DefaultMutableTreeNode) node.getParent() ).getUserObject() ).ex;
			}

			if (node.isLeaf()) {

				DefaultMutableTreeNode parent  = (DefaultMutableTreeNode) node.getParent();

				return ( (StillNode) ( parent ).getUserObject() ).ex;
			}
		}

		return null;
	}

	public static Table getTreeOperator( TreeSelectionEvent e ) {

	    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();

	    if (node == null || node.isRoot()) {

			return null;
		}

		if( node.getUserObject() instanceof DimensionDescriptor ) {

			node  = (DefaultMutableTreeNode) node.getParent();
		}

		if( node.isLeaf() && node.getUserObject() instanceof String ) {

			node  = (DefaultMutableTreeNode) ( node.getParent()).getParent();
		}

		if (node == null || node.isRoot()) {

			return null;
		}

		// determine the expression, the

		if( node.getUserObject() instanceof StillNode ) {

			StillNode myNode = (StillNode) node.getUserObject();
			if( myNode.ex != null ) {

				return null;
			}
			if( (myNode.op != null || myNode.table != null ) && myNode.ncol < 0 ) {

				if( myNode.op != null ) {
					return myNode.op;
				}
				if( myNode.table != null ) {
					return myNode.table;
				}
				return null;
			}
		}

		return null;
	}

	public void signalActionListeners( ) {

		for( ActionListener al : actionListeners ) {

			al.actionPerformed( new ActionEvent( selExpr, ActionEvent.ACTION_PERFORMED, "" ) );
		}
	}

	@Override
	public void valueChanged(TreeSelectionEvent e) {

	    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();

		if (node == null || node.isRoot()) {

			selExpr  	= null;
			selTable 	= null;
			selDim 		= -1;
			signalActionListeners( );
			return;
		}

		// determine the expression, the
		if( node.isLeaf() == false ) {

			if( node.getUserObject() instanceof StillNode ) {

				StillNode myNode = (StillNode) node.getUserObject();
				if( myNode.ex != null ) {

					selExpr  	= myNode.ex;
					selTable 	= null;
					selDim 		= -1;
					signalActionListeners( );
					return;
				}

				if( (myNode.op != null || myNode.table != null ) && myNode.ncol < 0 ) {

					selExpr  	= ( (StillNode) ( (DefaultMutableTreeNode) node.getParent() ).getUserObject() ).ex;
					if( myNode.op == null ) {
						selTable 	= myNode.table;
					}
					else {
						selTable 	= myNode.op;
					}
					selDim 		= -1;
					signalActionListeners( );
					return;
				}
			}
		}

		if (node.isLeaf()) {

			DefaultMutableTreeNode parent  = (DefaultMutableTreeNode) node.getParent();

			if( ( parent ).getUserObject() instanceof StillNode ) {

				StillNode myNode  =  (StillNode) ( parent ).getUserObject();
				selExpr  	= ( (StillNode) ( parent ).getUserObject() ).ex;
				if( selExpr != null ) {
					myNode = (StillNode) node.getUserObject();
				}

				if( myNode.op == null ) {
					selTable 	= myNode.table;
				}
				else {
					selTable 	= myNode.op;
				}
				selDim 		= myNode.ncol;
				signalActionListeners( );
			}
		}
	}

	public static void main( final String[] args ) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {

            	JFrame frame = new JFrame("TreeDemo");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());

                // load up a sample file
                Table table = TableFactory.fromCSV( args[0] );

                // set up a really simple expression list
                ArrayList<Expression> e = new ArrayList<Expression>();
                for( int i = 0; i < 1; i++ ) {

//                	e.add( 	new Expression(
//							new PCAOp(
//							new PearsonCollectOp(
//							new CutoffOp( table, true, 0 ), true, 0.8 ), true, 1 ) ) );
                }

                //Add content to the window.
                frame.add(new ExpressionTreeView(e), BorderLayout.CENTER);

                //Display the window.
                frame.pack();
                frame.setVisible(true);
            }
        } );
	}

	public class StillNode  {

		public Operator op 	= null;
		public Expression ex 	= null;
		public Table table		= null;
		public int ncol = -1;
		public int opnum = -1;
		public int exnum = -1;

		public StillNode( Operator op, int opnum ) {

			this.opnum = opnum;
			this.op = op;
		}

		public StillNode( Expression ex, int exnum ) {

			this.exnum = exnum;
			this.ex = ex;
		}

		public StillNode( Table table ) {

			this.table = table;
		}

		public StillNode( Table table, int col ) {

			this.table = table;
			this.ncol = col;
		}

		public String toString() {

			String str = "";

			if( op != null ) {

				if( op.isActive() ) {

					String foo = "";
					if( op.getParamString().length() > 0 ) {

						foo = " (" + op.getParamString() +")";
					}
					String rows_str = "" + op.rows();
					if( op.rows() > 100 ) {

						rows_str = nf.format( 100 * op.rows() / op.input.rows() ) + "%";
					}
					str = "S" + opnum + ":" + op + " p=" + rows_str + " d=" + Operator.getNonAttributeDims(op) + foo;
				}
				else {
					str = "S" + opnum + ":" + op ;
				}
			}
			if( ex != null ) {

				str = "E" + exnum + ": " + ex ;
			}
			if( table != null ) {

				str = "[Input:File]" + " p=" + table.rows() + " d=" + Operator.getNonAttributeDims(table) + " (" + table + ")" ;
			}
			if( table != null && ncol >= 0 ) {

				str = "" + ncol + " : " + table.getColType(ncol);
			}

			return str;
		}

	}

	@Override
	public void treeNodesChanged(TreeModelEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void treeNodesInserted(TreeModelEvent e) {

	}

	@Override
	public void treeNodesRemoved(TreeModelEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void treeStructureChanged(TreeModelEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void tableChanged(TableEvent te) {

		// find the appropriate operator
		DefaultMutableTreeNode node = findOpNodes( (Table) te.src );

		// adjust selection to the table instead of any of its subnodes

		if( tree.getSelectionPath() != null) {

			boolean is_in_selection_path = false;
			int path_count = 0;

			Object[] path = tree.getSelectionPath().getPath();
			for( Object o : path ) {

				path_count++;

				if( o == node ) {

					is_in_selection_path = true;
					break;
				}
			}
			if( is_in_selection_path ) {

				Object[] new_path = new Object[path_count];
				int i = 0;
				for( Object o : path ) {

					new_path[i] = o;
					i++;

					if( o == node ) {

						break;
					}
				}

				tree.setSelectionPath( new TreePath(new_path) );
			}
		}

		ArrayList<DefaultMutableTreeNode> old_nodes = new ArrayList<DefaultMutableTreeNode>();

		// remove the existing nodes
		for( int j = 0; j < node.getChildCount(); j++ ) {

			DefaultMutableTreeNode gchild = (DefaultMutableTreeNode) node.getChildAt(j);
			old_nodes.add( gchild );
		}
		for( DefaultMutableTreeNode dmtn : old_nodes ) {
			((DefaultTreeModel)tree.getModel()).removeNodeFromParent(dmtn);
		}

		// update its dimension descriptors
		if( node != null ) {

			ArrayList<DimensionDescriptor> descriptors = ((Table)te.src).getConstructedDimensions();
			if( descriptors != null ) {
				int k = 0;
				for( DimensionDescriptor dd : descriptors ) {

					DefaultMutableTreeNode dd_node = new DefaultMutableTreeNode( dd );
					if( dd.sub_values != null ) {

						for( String s : dd.sub_values ) {

							DefaultMutableTreeNode sv_node = new DefaultMutableTreeNode( s );
							dd_node.add( sv_node );
						}
					}

					((DefaultTreeModel)tree.getModel()).insertNodeInto(dd_node, node, k);
					k++;
				}
			}
		}
	}

	class ExpressionTreeCellRenderer extends DefaultTreeCellRenderer {

		/**
		 *
		 */
		private static final long serialVersionUID = -2147342463298722375L;

		public Component getTreeCellRendererComponent(	JTree tree,
														Object value,
														boolean sel,
														boolean expanded,
														boolean leaf,
														int row,
														boolean hasFocus) {

				super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
				DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
				if( node.getUserObject() instanceof StillNode ) {

					StillNode snode = (StillNode) node.getUserObject();
					if( snode.op != null && !snode.op.isActive() ) {

						this.setEnabled(false);
						this.setDisabledIcon( this.getClosedIcon() );
					}
				}
				if( node.getUserObject() instanceof DimensionDescriptor ) {

					DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
					if( parent.getUserObject() instanceof StillNode ) {

						StillNode snode = (StillNode) parent.getUserObject();
						if( snode.op != null && !snode.op.isActive() ) {

							this.setEnabled(false);
							this.setDisabledIcon( this.getClosedIcon() );
						}
					}
				}
				if( node.getUserObject() instanceof String && !node.isRoot()) {

					DefaultMutableTreeNode parent = (DefaultMutableTreeNode)(node.getParent().getParent());
					if( parent.getUserObject() instanceof StillNode ) {

						StillNode snode = (StillNode) parent.getUserObject();
						if( snode.op != null && !snode.op.isActive() ) {

							this.setEnabled(false);
							this.setDisabledIcon( this.getClosedIcon() );
						}
					}
				}

				return this;
		}
	}
}


text:
#include <convert.hpp>

#include <cmdline.hpp>
#include <kdb.hpp>
#include <modules.hpp>
#include <toolexcept.hpp>

#include <iostream>

using namespace std;
using namespace kdb;
using namespace kdb::tools;

ConvertCommand::ConvertCommand ()
{
}

int ConvertCommand::execute (Cmdline const & cl)
{
	size_t argc = cl.arguments.size ();
	if (argc != 0 && argc != 1 && argc != 2 && argc != 3 && argc != 4)
	{
		throw invalid_argument ("need 0 to 4 arguments");
	}

	string import_format = cl.format;
	if (argc > 0) import_format = cl.arguments[0];

	string export_format = cl.format;
	if (argc > 1) export_format = cl.arguments[1];

	string import_file = "/dev/stdin";
	if (argc > 2 && cl.arguments[2] != "-") import_file = cl.arguments[2];

	string export_file = "/dev/stdout";
	if (argc > 3 && cl.arguments[3] != "-") export_file = cl.arguments[3];

	if (cl.verbose)
	{
		cout << "converting from " << import_format << " to " << export_format << endl;
	}

	Modules modules;
	PluginPtr import_plugin = modules.load (import_format);

	// TODO: reuse import/export
	// to namespace dir
	PluginPtr export_plugin = modules.load (export_format);

	Key errorKey;
	KeySet keys;

	errorKey.setString (import_file);
	import_plugin->get (keys, errorKey);

	errorKey.setString (export_file);
	export_plugin->set (keys, errorKey);

	printWarnings (cerr, errorKey);
	printError (cerr, errorKey);

	return 0;
}

ConvertCommand::~ConvertCommand ()
{
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace umi\orm\toolbox\factory;

use umi\orm\collection\ICollectionFactory;
use umi\orm\collection\ICollectionManagerAware;
use umi\orm\collection\ICommonHierarchy;
use umi\orm\collection\IHierarchicCollection;
use umi\orm\collection\ILinkedHierarchicCollection;
use umi\orm\collection\ISimpleCollection;
use umi\orm\collection\TCollectionManagerAware;
use umi\orm\exception\RuntimeException;
use umi\orm\metadata\IMetadata;
use umi\orm\selector\ISelectorFactory;
use umi\toolkit\factory\IFactory;
use umi\toolkit\factory\TFactory;

/**
 * Фабрика коллекий объектов.
 */
class CollectionFactory implements ICollectionFactory, IFactory, ICollectionManagerAware
{

    use TFactory;
    use TCollectionManagerAware;

    /**
     * @var  $selectorFactory
     */
    protected $selectorFactory;
    /**
     * @var string $defaultSimpleCollectionClass имя класса простой коллекции по умолчанию
     */
    public $defaultSimpleCollectionClass = 'umi\orm\collection\SimpleCollection';
    /**
     * @var string $defaultHierarchicCollectionClass имя класса иерархической коллекции по умолчанию
     */
    public $defaultHierarchicCollectionClass = 'umi\orm\collection\SimpleHierarchicCollection';
    /**
     * @var string $defaultLinkedHierarchicCollectionClass имя класса связанной иерархической коллекции по умолчанию
     */
    public $defaultLinkedHierarchicCollectionClass = 'umi\orm\collection\LinkedHierarchicCollection';
    /**
     * @var string $defaultCommonHierarchyClass имя класса общей иерархии по умолчанию
     */
    public $defaultCommonHierarchyClass = 'umi\orm\collection\CommonHierarchy';

    /**
     * Конструктор
     * @param ISelectorFactory $selectorFactory фабрика селекторов
     */
    public function __construct(ISelectorFactory $selectorFactory)
    {
        $this->selectorFactory = $selectorFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function create($collectionName, IMetadata $metadata, array $config)
    {
        if (!isset($config['type'])) {
            throw new RuntimeException($this->translate(
                'Collection configuration should contain type info.'
            ));
        }
        switch ($config['type']) {
            case self::TYPE_SIMPLE:
                return $this->createSimpleCollection($collectionName, $metadata, $config);
            case self::TYPE_SIMPLE_HIERARCHIC:
                return $this->createSimpleHierarchicCollection($collectionName, $metadata, $config);
            case self::TYPE_LINKED_HIERARCHIC:
                return $this->createLinkedHierarchicCollection($collectionName, $metadata, $config);
            case self::TYPE_COMMON_HIERARCHY:
                return $this->createCommonHierarchy($collectionName, $metadata, $config);
            default:
                throw new RuntimeException($this->translate(
                    'Cannot create collection. Unknown collection type "{type}".',
                    ['type' => $config['type']]
                ));
        }
    }

    /**
     * Создает экземпляр простой коллекции объектов
     * @param string $collectionName имя коллекции
     * @param IMetadata $metadata метаданные коллекции
     * @param array $config конфигурация коллекции
     * @return ISimpleCollection
     */
    protected function createSimpleCollection($collectionName, IMetadata $metadata, array $config)
    {
        if (!isset($config['class'])) {
            $config['class'] = $this->defaultSimpleCollectionClass;
        }

        return $this->getPrototype(
            $config['class'],
            ['umi\orm\collection\ISimpleCollection']
        )
        ->createInstance([$collectionName, $metadata, $this->selectorFactory]);
    }

    /**
     * Создает экземпляр иерархической коллекции объектов
     * @param string $collectionName имя коллекции
     * @param IMetadata $metadata метаданные коллекции
     * @param array $config конфигурация коллекции
     * @return IHierarchicCollection
     */
    protected function createSimpleHierarchicCollection($collectionName, IMetadata $metadata, array $config)
    {
        if (!isset($config['class'])) {
            $config['class'] = $this->defaultHierarchicCollectionClass;
        }

        return $this->getPrototype(
            $config['class'],
            ['umi\orm\collection\ISimpleHierarchicCollection']
        )
        ->createInstance([$collectionName, $metadata, $this->selectorFactory]);
    }

    /**
     * Создает экземпляр связанной иерархической коллекции объектов
     * @param string $collectionName имя коллекции
     * @param IMetadata $metadata метаданные коллекции
     * @param array $config конфигурация коллекции
     * @throws RuntimeException если не удалось создать коллекцию
     * @return ILinkedHierarchicCollection
     */
    protected function createLinkedHierarchicCollection($collectionName, IMetadata $metadata, array $config)
    {
        if (!isset($config['hierarchy'])) {
            throw new RuntimeException($this->translate(
                'Cannot create linked collection. Configuration should contain "hierarchy" option.'
            ));
        }
        if (!isset($config['class'])) {
            $config['class'] = $this->defaultLinkedHierarchicCollectionClass;
        }

        /**
         * @var ILinkedHierarchicCollection $linkedCollection
         */
        $linkedCollection = $this->getPrototype(
            $config['class'],
            ['umi\orm\collection\ILinkedHierarchicCollection']
        )
        ->createInstance([$collectionName, $metadata, $this->selectorFactory]);

        $commonHierarchy = $this->getCollectionManager()
            ->getCollection($config['hierarchy']);
        if (!$commonHierarchy instanceof ICommonHierarchy) {
            throw new RuntimeException($this->translate(
                'Cannot create linked collection. Relation collection should be instance of ICommonHierarchy.'
            ));
        }

        $linkedCollection->setCommonHierarchy($commonHierarchy);

        return $linkedCollection;
    }

    /**
     * Создает экземпляр общей иерархии
     * @param string $collectionName имя коллекции
     * @param IMetadata $metadata метаданные коллекции
     * @param array $config конфигурация коллекции
     * @return ICommonHierarchy
     */
    protected function createCommonHierarchy($collectionName, IMetadata $metadata, array $config)
    {
        if (!isset($config['class'])) {
            $config['class'] = $this->defaultCommonHierarchyClass;
        }

        return $this->getPrototype(
            $config['class'],
            ['umi\orm\collection\ICommonHierarchy']
        )
        ->createInstance([$collectionName, $metadata, $this->selectorFactory]);
    }
}


text: find /mnt -type f -print


text:
package org.apache.logging.log4j.core.async;

import com.lmax.disruptor.WaitStrategy;
import com.lmax.disruptor.YieldingWaitStrategy;

import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.test.appender.ListAppender;
import org.apache.logging.log4j.core.test.categories.AsyncLoggers;
import org.apache.logging.log4j.core.test.junit.LoggerContextSource;
import org.apache.logging.log4j.core.test.junit.Named;
import org.junit.experimental.categories.Category;
import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertEquals;

@Category(AsyncLoggers.class)
public class AsyncWaitStrategyFactoryConfigTest {

    @Test
    @LoggerContextSource("AsyncWaitStrategyFactoryConfigTest.xml")
    public void testConfigWaitStrategyFactory(final LoggerContext context) throws Exception {
        AsyncWaitStrategyFactory asyncWaitStrategyFactory = context.getConfiguration().getAsyncWaitStrategyFactory();
        assertEquals(YieldingWaitStrategyFactory.class, asyncWaitStrategyFactory.getClass());
        assertThat("factory is YieldingWaitStrategyFactory", asyncWaitStrategyFactory instanceof YieldingWaitStrategyFactory);
    }

    @Test
    @LoggerContextSource("AsyncWaitStrategyFactoryConfigTest.xml")
    public void testWaitStrategy(final LoggerContext context) throws Exception {

        org.apache.logging.log4j.Logger logger = context.getRootLogger();

        AsyncLoggerConfig loggerConfig = (AsyncLoggerConfig) ((org.apache.logging.log4j.core.Logger) logger).get();
        AsyncLoggerConfigDisruptor delegate = (AsyncLoggerConfigDisruptor) loggerConfig.getAsyncLoggerConfigDelegate();
        assertEquals(YieldingWaitStrategy.class, delegate.getWaitStrategy().getClass());
        assertThat("waitstrategy is YieldingWaitStrategy", delegate.getWaitStrategy() instanceof com.lmax.disruptor.YieldingWaitStrategy);
    }

    @Test
    @LoggerContextSource("AsyncWaitStrategyIncorrectFactoryConfigTest.xml")
    public void testIncorrectConfigWaitStrategyFactory(final LoggerContext context) throws Exception {
        AsyncWaitStrategyFactory asyncWaitStrategyFactory = context.getConfiguration().getAsyncWaitStrategyFactory();
        assertNull(asyncWaitStrategyFactory);
    }

    @Test
    @LoggerContextSource("AsyncWaitStrategyIncorrectFactoryConfigTest.xml")
    public void testIncorrectWaitStrategyFallsBackToDefault(
            @Named("WaitStrategyAppenderList") final ListAppender list1,
            final LoggerContext context) throws Exception {
        org.apache.logging.log4j.Logger logger = context.getRootLogger();

        AsyncLoggerConfig loggerConfig = (AsyncLoggerConfig) ((org.apache.logging.log4j.core.Logger) logger).get();
        AsyncLoggerConfigDisruptor delegate = (AsyncLoggerConfigDisruptor) loggerConfig.getAsyncLoggerConfigDelegate();
        assertEquals(TimeoutBlockingWaitStrategy.class, delegate.getWaitStrategy().getClass());
        assertThat("waitstrategy is TimeoutBlockingWaitStrategy", delegate.getWaitStrategy() instanceof TimeoutBlockingWaitStrategy);
    }

    public static class YieldingWaitStrategyFactory implements AsyncWaitStrategyFactory {
        @Override
        public WaitStrategy createWaitStrategy() {
            return new YieldingWaitStrategy();
        }
    }
}


text:
ARG OS_VERSION
ARG OS_NAME

# Image with gcsfuse installed and its package (.deb)
FROM golang:1.18.4 as gcsfuse-package

RUN apt-get update -qq && apt-get install -y ruby ruby-dev rubygems build-essential rpm fuse && gem install --no-document fpm

ENV CGO_ENABLED=0
ENV GOOS=linux
ENV GO111MODULE=auto

ARG GCSFUSE_VERSION
ARG GCSFUSE_REPO="github.com/googlecloudplatform/gcsfuse/"
ENV GCSFUSE_PATH "$GOPATH/src/$GCSFUSE_REPO"
RUN go get ${GCSFUSE_REPO}

WORKDIR ${GCSFUSE_PATH}
# Branch name for building through a particular branch.
ARG BRANCH_NAME="v${GCSFUSE_VERSION}"
RUN git checkout "${BRANCH_NAME}"

ARG GCSFUSE_BIN="/gcsfuse"
WORKDIR ${GOPATH}
RUN go install ${GCSFUSE_REPO}/tools/build_gcsfuse
RUN mkdir -p ${GCSFUSE_BIN}
RUN build_gcsfuse ${GCSFUSE_PATH} ${GCSFUSE_BIN} ${GCSFUSE_VERSION}
RUN mkdir -p ${GCSFUSE_BIN}/usr && mv ${GCSFUSE_BIN}/bin ${GCSFUSE_BIN}/usr/bin

ARG GCSFUSE_PKG="/packages"
RUN mkdir -p ${GCSFUSE_PKG}
WORKDIR ${GCSFUSE_PKG}
RUN fpm \
    -s dir \
    -t deb \
    -n gcsfuse \
    -C ${GCSFUSE_BIN} \
    -v ${GCSFUSE_VERSION} \
    -d fuse \
    --vendor "" \
    --url "https://$GCSFUSE_REPO" \
    --description "A user-space file system for Google Cloud Storage."

# distroless image with gcsfuse installed.
FROM gcr.io/gke-release/gke-distroless/libc as distroless

# Copy gcsfuse and fuse binaries
ARG GCSFUSE_BIN="/gcsfuse"
COPY --from=gcsfuse-package ${GCSFUSE_BIN}/usr/bin/gcsfuse /bin/
COPY --from=gcsfuse-package ${GCSFUSE_BIN}/sbin/mount.gcsfuse /sbin/
COPY --from=gcsfuse-package /bin/fusermount /bin/
COPY --from=gcsfuse-package /bin/sh /bin/

ENV PATH "/bin:$PATH"
ENV BUCKET_NAME ""

# Labels:https://github.com/opencontainers/image-spec/blob/master/annotations.md
ARG BUILD_DATE
ARG GCSFUSE_VERSION
LABEL "org.opencontainers.artifact.created"=$BUILD_DATE
LABEL "org.opencontainers.image.title"="GoogleCloudPlatform/gcsfuse-distroless"
LABEL "org.opencontainers.image.version"="v${GCSFUSE_VERSION}"
LABEL "org.opencontainers.image.description"="A user-space file system for Google Cloud Storage."
LABEL "org.opencontainers.image.url"="https://cloud.google.com/storage/docs/gcs-fuse"
LABEL "org.opencontainers.image.source"="https://github.com/GoogleCloudPlatform/gcsfuse"

CMD gcsfuse --key-file /key.json -o allow_other --file-mode 777 --dir-mode 777 --foreground --implicit-dirs $BUCKET_NAME /gcs

# Ubuntu/debian image with gcsfuse installed
FROM ${OS_NAME}:${OS_VERSION}

# Copy gcsfuse .deb package from gcsfuse-package image
ARG GCSFUSE_PKG="/packages"
COPY --from=gcsfuse-package ${GCSFUSE_PKG}/*amd64.deb gcsfuse.deb

# Install gcsfuse and dependencies
RUN apt-get update && \
    apt-get install -y ca-certificates fuse && \
    rm -rf /var/lib/apt/lists/* && \
    apt-get clean
RUN dpkg -i gcsfuse.deb && rm gcsfuse.deb

# Allow non-root users to specify the allow_other or allow_root mount options
RUN echo "user_allow_other" > /etc/fuse.conf

ENV BUCKET_NAME ""

# Labels:https://github.com/opencontainers/image-spec/blob/master/annotations.md
ARG BUILD_DATE
ARG GCSFUSE_VERSION
ARG OS_NAME
LABEL "org.opencontainers.artifact.created"=$BUILD_DATE
LABEL "org.opencontainers.image.title"="GoogleCloudPlatform/gcsfuse-${OS_NAME}"
LABEL "org.opencontainers.image.version"="v${GCSFUSE_VERSION}"
LABEL "org.opencontainers.image.description"="A user-space file system for Google Cloud Storage."
LABEL "org.opencontainers.image.url"="https://cloud.google.com/storage/docs/gcs-fuse"
LABEL "org.opencontainers.image.source"="https://github.com/GoogleCloudPlatform/gcsfuse"

CMD gcsfuse --key-file /key.json -o allow_other --file-mode 777 --dir-mode 777 --foreground --implicit-dirs $BUCKET_NAME /gcs


text:
namespace ash {

namespace {

// The border radius on the text field.
constexpr int kDesksTextfieldBorderRadius = 4;

constexpr int kDesksTextfieldMinHeight = 16;

#if DCHECK_IS_ON()
bool IsDesksBarOrSavedDeskLibraryWidget(const views::Widget* widget) {
  if (!widget)
    return false;

  auto* overview_controller = Shell::Get()->overview_controller();
  if (!overview_controller->InOverviewSession())
    return false;

  auto* session = overview_controller->overview_session();
  for (const auto& grid : session->grid_list()) {
    if (widget == grid->saved_desk_library_widget() ||
        widget == grid->desks_widget()) {
      return true;
    }
  }

  return false;
}
#endif  // DCHECK_IS_ON()

}  // namespace

DesksTextfield::DesksTextfield() {
  views::Builder<DesksTextfield>(this)
      .SetBorder(nullptr)
      .SetCursorEnabled(true)
      .BuildChildren();

  views::FocusRing* focus_ring =
      StyleUtil::SetUpFocusRingForView(this, kFocusRingHaloInset);
  focus_ring->SetHasFocusPredicate([](views::View* view) {
    return static_cast<DesksTextfield*>(view)->IsViewHighlighted() ||
           view->HasFocus();
  });
  focus_ring->SetColorId(ui::kColorAshFocusRing);

  GetRenderText()->SetElideBehavior(gfx::ELIDE_TAIL);
}

DesksTextfield::~DesksTextfield() = default;

// static
constexpr size_t DesksTextfield::kMaxLength;

// static
void DesksTextfield::CommitChanges(views::Widget* widget) {
#if DCHECK_IS_ON()
  DCHECK(IsDesksBarOrSavedDeskLibraryWidget(widget));
#endif  // DCHECK_IS_ON()

  auto* focus_manager = widget->GetFocusManager();
  focus_manager->ClearFocus();
  // Avoid having the focus restored to the same view when the parent view is
  // refocused.
  focus_manager->SetStoredFocusView(nullptr);
}

gfx::Size DesksTextfield::CalculatePreferredSize() const {
  const std::u16string& text = GetText();
  int width = 0;
  int height = 0;
  gfx::Canvas::SizeStringInt(text, GetFontList(), &width, &height, 0,
                             gfx::Canvas::NO_ELLIPSIS);
  gfx::Size size{width + GetCaretBounds().width(), height};
  const auto insets = GetInsets();
  size.Enlarge(insets.width(), insets.height());
  size.SetToMax(gfx::Size(0, kDesksTextfieldMinHeight));
  return size;
}

void DesksTextfield::SetBorder(std::unique_ptr<views::Border> b) {
  // `views::Textfield` override of `SetBorder()` removes an installed focus
  // ring, which we want to keep.
  views::View::SetBorder(std::move(b));
}

bool DesksTextfield::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) {
  // The default behavior of the tab key is that it moves the focus to the next
  // available view.
  // We want that to be handled by OverviewHighlightController as part of moving
  // the highlight forward or backward when tab or shift+tab are pressed.
  return event.key_code() == ui::VKEY_TAB;
}

std::u16string DesksTextfield::GetTooltipText(const gfx::Point& p) const {
  return GetPreferredSize().width() > width() ? GetText() : std::u16string();
}

void DesksTextfield::GetAccessibleNodeData(ui::AXNodeData* node_data) {
  Textfield::GetAccessibleNodeData(node_data);
  node_data->SetNameChecked(GetAccessibleName());
}

void DesksTextfield::OnMouseEntered(const ui::MouseEvent& event) {
  UpdateViewAppearance();
}

void DesksTextfield::OnMouseExited(const ui::MouseEvent& event) {
  UpdateViewAppearance();
}

void DesksTextfield::OnThemeChanged() {
  Textfield::OnThemeChanged();
  SetBackground(views::CreateRoundedRectBackground(
      GetBackgroundColor(), kDesksTextfieldBorderRadius));
  AshColorProvider* color_provider = AshColorProvider::Get();
  const SkColor text_color = color_provider->GetContentLayerColor(
      AshColorProvider::ContentLayerType::kTextColorPrimary);
  SetTextColor(text_color);
  SetSelectionTextColor(text_color);

  const SkColor selection_color = color_provider->GetControlsLayerColor(
      AshColorProvider::ControlsLayerType::kFocusAuraColor);
  SetSelectionBackgroundColor(selection_color);

  UpdateFocusRingState();
}

ui::Cursor DesksTextfield::GetCursor(const ui::MouseEvent& event) {
  return ui::mojom::CursorType::kIBeam;
}

void DesksTextfield::OnFocus() {
  GetRenderText()->SetElideBehavior(gfx::NO_ELIDE);
  views::Textfield::OnFocus();
  UpdateViewAppearance();
}

void DesksTextfield::OnBlur() {
  GetRenderText()->SetElideBehavior(gfx::ELIDE_TAIL);
  views::Textfield::OnBlur();
  UpdateViewAppearance();

  // Avoid having the focus restored to the same DeskNameView when the desk bar
  // widget is refocused. Use a post task to avoid calling
  // `FocusManager::SetStoredFocusView()` while `FocusManager::ClearFocus()` is
  // still being activated. In this case, we want to set the stored focus view
  // to nullptr after the stack of the call to `FocusManager::ClearFocus()`
  // returns completely.
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
      FROM_HERE, base::BindOnce(
                     [](base::WeakPtr<views::Widget> w) {
                       if (w)
                         w->GetFocusManager()->SetStoredFocusView(nullptr);
                     },
                     GetWidget()->GetWeakPtr()));
}

void DesksTextfield::OnDragEntered(const ui::DropTargetEvent& event) {
  GetRenderText()->SetElideBehavior(gfx::NO_ELIDE);
  views::Textfield::OnDragEntered(event);
}

void DesksTextfield::OnDragExited() {
  GetRenderText()->SetElideBehavior(gfx::ELIDE_TAIL);
  views::Textfield::OnDragExited();
}

views::View* DesksTextfield::GetView() {
  return this;
}

void DesksTextfield::MaybeActivateHighlightedView() {
  RequestFocus();
}

void DesksTextfield::MaybeCloseHighlightedView(bool primary_action) {}

void DesksTextfield::MaybeSwapHighlightedView(bool right) {}

void DesksTextfield::OnViewHighlighted() {
  UpdateFocusRingState();
}

void DesksTextfield::OnViewUnhighlighted() {
  UpdateFocusRingState();
}

void DesksTextfield::UpdateFocusRingState() {
  views::FocusRing* focus_ring = views::FocusRing::Get(this);
  DCHECK(focus_ring);
  focus_ring->SchedulePaint();
}

void DesksTextfield::UpdateViewAppearance() {
  background()->SetNativeControlColor(GetBackgroundColor());
  // Paint the whole view to update the background. The `SchedulePaint` in
  // `UpdateFocusRingState` will only repaint the focus ring.
  SchedulePaint();
  UpdateFocusRingState();
}

SkColor DesksTextfield::GetBackgroundColor() const {
  // Admin desk templates may be read only.
  if (GetReadOnly())
    return SK_ColorTRANSPARENT;

  return HasFocus() || IsMouseHovered()
             ? AshColorProvider::Get()->GetControlsLayerColor(
                   AshColorProvider::ControlsLayerType::
                       kControlBackgroundColorInactive)
             : SK_ColorTRANSPARENT;
}

BEGIN_METADATA(DesksTextfield, views::Textfield)
END_METADATA

}  // namespace ash


text:
package com.microsoft.azure.management.mysql.v2017_12_01.implementation;

import com.microsoft.azure.management.mysql.v2017_12_01.LogFile;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import rx.Observable;
import org.joda.time.DateTime;

class LogFileImpl extends WrapperImpl<LogFileInner> implements LogFile {
    private final MySQLManager manager;

    LogFileImpl(LogFileInner inner,  MySQLManager manager) {
        super(inner);
        this.manager = manager;
    }

    @Override
    public MySQLManager manager() {
        return this.manager;
    }

    @Override
    public DateTime createdTime() {
        return this.inner().createdTime();
    }

    @Override
    public String id() {
        return this.inner().id();
    }

    @Override
    public DateTime lastModifiedTime() {
        return this.inner().lastModifiedTime();
    }

    @Override
    public String logFileType() {
        return this.inner().logFileType();
    }

    @Override
    public String name() {
        return this.inner().name();
    }

    @Override
    public Long sizeInKB() {
        return this.inner().sizeInKB();
    }

    @Override
    public String type() {
        return this.inner().type();
    }

    @Override
    public String url() {
        return this.inner().url();
    }

}


text:
package invtweaks;

import java.io.File;
import java.util.logging.Level;

import net.minecraft.client.Minecraft;

public class InvTweaksConst {

    // Mod version
    public static final String MOD_VERSION = "1.50 (1.4.7)";

    // Mod tree version
    // Change only when the tree evolves significantly enough to need to override all configs
    public static final String TREE_VERSION = "1.4.0";

    // Timing constants
    public static final int RULESET_SWAP_DELAY = 1000;
    public static final int AUTO_REFILL_DELAY = 200;
    public static final int AUTO_REFILL_DAMAGE_TRESHOLD = 5;
    public static final int POLLING_DELAY = 3;
    public static final int POLLING_TIMEOUT = 1500;
    public static final int CHEST_ALGORITHM_SWAP_MAX_INTERVAL = 2000;
    public static final int TOOLTIP_DELAY = 800;
    public static final int INTERRUPT_DELAY = 300;

    // File constants
    public static final String MINECRAFT_DIR = getMinecraftDir();
    public static final String MINECRAFT_CONFIG_DIR = MINECRAFT_DIR + "config" + File.separatorChar;
    public static final String CONFIG_PROPS_FILE = MINECRAFT_CONFIG_DIR + "InvTweaks.cfg";
    public static final String CONFIG_RULES_FILE = MINECRAFT_CONFIG_DIR + "InvTweaksRules.txt";
    public static final String CONFIG_TREE_FILE = MINECRAFT_CONFIG_DIR + "InvTweaksTree.txt";
    public static final String OLD_CONFIG_TREE_FILE = MINECRAFT_CONFIG_DIR + "InvTweaksTree.xml";
    public static final String OLDER_CONFIG_RULES_FILE = MINECRAFT_DIR + "InvTweaksRules.txt";
    public static final String OLDER_CONFIG_TREE_FILE = MINECRAFT_DIR + "InvTweaksTree.txt";
    public static final String DEFAULT_CONFIG_FILE = "DefaultConfig.dat";
    public static final String DEFAULT_CONFIG_TREE_FILE = "DefaultTree.dat";
    public static final String HELP_URL = "http://modding.kalam-alami.net/invtweaks";

    // Global mod constants
    public static final String INGAME_LOG_PREFIX = "InvTweaks: ";
    public static final Level DEFAULT_LOG_LEVEL = Level.WARNING;
    public static final Level DEBUG = Level.INFO;
    public static final int JIMEOWAN_ID = 54696386; // Used in GUIs

    // Minecraft constants
    public static final int INVENTORY_SIZE = 36;
    public static final int INVENTORY_ROW_SIZE = 9;
    public static final int CHEST_ROW_SIZE = INVENTORY_ROW_SIZE;
    public static final int DISPENSER_ROW_SIZE = 3;
    public static final int INVENTORY_HOTBAR_SIZE = INVENTORY_ROW_SIZE;
    public static final int PLAYER_INVENTORY_WINDOW_ID = 0;
	public static final int SLOW_SORTING_DELAY = 30;

    /**
     * Returns the Minecraft folder ensuring:
     * - It is an absolute path
     * - It ends with a folder separator
     */
    public static String getMinecraftDir() {
        String absolutePath = Minecraft.getMinecraftDir().getAbsolutePath();
        if (absolutePath.endsWith(".")) {
            return absolutePath.substring(0, absolutePath.length() - 1);
        }
        if (absolutePath.endsWith(File.separator)) {
            return absolutePath;
        } else {
            return absolutePath + File.separatorChar;
        }
    }

}


text:
module Rusql
  class Operand
    def initialize(op)
      raise TypeException.new(String, op.class) unless op.is_a?(String)
      @op = op
    end

    %i(greater_than greater_than_or_equals less_than less_than_or_equals equals not_equals).each do |type|
      define_method type, Proc.new { |v|
        c = BasicCondition.new
        c.type = type
        c.left = self
        c.right = v

        c
      }
    end

    %i(in not_in).each do |type|
      define_method type, Proc.new { |v|
        raise TypeException.new(Array, v.class) unless v.is_a?(Array) || v.is_a?(Range)

        c = BasicCondition.new
        c.type = type
        c.left = self
        c.right = v.to_a

        c
      }
    end

    def like(v)
      raise TypeException.new(String, v.class) unless v.is_a?(String)

      c = BasicCondition.new
      c.type = :like
      c.left = self
      c.right = v

      c
    end

    def to_s
      @op
    end
  end
end


text:
package org.rcsb.mmtf.codec;
/**
 * Interface all String codecs must implement.
 * @author Anthony Bradley
 *
 */
public interface StringCodecsInterface {

	/**
	 * Encode a String array to a byte array.
	 * @param inputData the input String array
	 * @param param the input param
	 * @return the encoded byte array
	 */
	public byte[] encode(String[] inputData, int param);

	/**
	 * Decode a byte array to a String array.
	 * @param inputData the input byte array
	 * @param param the input param
	 * @return the decoded String array
	 */
	public String[] decode(byte[] inputData, int param);
}


text:
import {AbstractIterator} from '../commons/AbstractIterator'
import {ContainersAPI} from './api'

import Queue = ContainersAPI.Queue

export class HeapIterator<E> extends AbstractIterator<E> {
    constructor(pq: E[], n: number, private copy: Queue<E>) {
        super()
        for (let i = 1; i <= n; i++) {
            copy.enqueue(pq[i])
        }
    }

    hasNext(): boolean {
        return !this.copy.isEmpty()
    }

    next(): E {
        if (!this.hasNext()) {
            throw new Error('No such element')
        }
        return this.copy.dequeue()
    }

}


text:
package com.github.lihongjie.userlogin.register;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

@Service
public class RegisterService {

    @Autowired
    private ApplicationContext applicationContext;

    public void register(String username, String password) {
        System.out.println(username + "注册成功!");
        publishRegisterEvent(new User(username, password));
    }

    private void publishRegisterEvent(User user) {
        applicationContext.publishEvent(new RegisterEvent(user));
    }

}


text:
package com.abstractfactory;

public class ComputerFactory {
    public static Computer getComputer(String type, String ram, String hdd, String cpu) {
        if ("PC".equalsIgnoreCase(type)) return new PC(ram, hdd, cpu);
        else if ("Server".equalsIgnoreCase(type)) return new Server(ram, hdd, cpu);

        return null;
    }
}


text:
<resources>

    <style name="Meter">
        <item name="android:layout_width">180px</item>
        <item name="android:layout_height">130px</item>
        <item name="android:layout_gravity">center</item>
        <item name="android:layout_marginTop">-20px</item>
        <item name="android:gravity">left</item>
        <item name="android:textSize">120px</item>
    </style>

    <style name="Label">
        <item name="android:layout_width">180px</item>
        <item name="android:layout_height">50px</item>
        <item name="android:layout_gravity">left</item>
        <item name="android:layout_marginTop">0px</item>
        <item name="android:gravity">left</item>
        <item name="android:textSize">40px</item>
    </style>

    <style name="MenuTheme" parent="@android:style/Theme.DeviceDefault">
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:colorBackgroundCacheHint">@null</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowAnimationStyle">@null</item>
    </style>

</resources>


text:
const expect = require('chai').expect
const insertReductionReason = require('../../../../app/services/data/insert-reduction-reason')
const ReductionReason = require('../../../../app/services/domain/reduction-reason')
const dataHelper = require('../../../helpers/data/aggregated-data-helper')

const getReductionReasonById = require('../../../../app/services/data/get-reduction-reason-by-id')

const ids = []

describe('/services/data/insert-reduction-reason', function () {
  it('should insert a reduction reason with blank optional fields', function () {
    const testReductionReason = new ReductionReason('Test Reduction Reason', 'TRR1', '1', '', '', '', 'true')
    return insertReductionReason(testReductionReason)
      .then(function (id) {
        ids.push(id)
        return getReductionReasonById(id)
          .then(function (reductionReason) {
            expect(reductionReason.category).to.equal('Personal Circumstances')
            expect(reductionReason.reason).to.equal('Test Reduction Reason')
            expect(reductionReason.reasonShortName).to.equal('TRR1')
            expect(reductionReason.allowancePercentage).to.equal(null)
            expect(reductionReason.maxAllowancePercentage).to.equal(null)
            expect(reductionReason.monthsToExpiry).to.equal(null)
            expect(reductionReason.isEnabled).to.equal(true)
          })
      })
  })

  it('should insert a reduction reason with optional fields filled in', function () {
    const testReductionReason = new ReductionReason('Test Reduction Reason', 'TRR1', '1', '20', '20', '6', 'true')
    return insertReductionReason(testReductionReason)
      .then(function (id) {
        ids.push(id)
        return getReductionReasonById(id)
          .then(function (reductionReason) {
            expect(reductionReason.category).to.equal('Personal Circumstances')
            expect(reductionReason.reason).to.equal('Test Reduction Reason')
            expect(reductionReason.reasonShortName).to.equal('TRR1')
            expect(reductionReason.allowancePercentage).to.equal(20)
            expect(reductionReason.maxAllowancePercentage).to.equal(20)
            expect(reductionReason.monthsToExpiry).to.equal(6)
            expect(reductionReason.isEnabled).to.equal(true)
          })
      })
  })

  after(function () {
    return dataHelper.deleteRecordsFromTableForIds('reduction_reason', ids)
  })
})


text:
namespace blink {

DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(RectBase)

void RectBase::trace(Visitor* visitor)
{
    visitor->trace(m_top);
    visitor->trace(m_right);
    visitor->trace(m_bottom);
    visitor->trace(m_left);
}

}


text:
Run Locally with CMake and [vcpkg] installed:
```
cmake -S . -B .build -DCMAKE_TOOLCHAIN_FILE=${VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake
cmake --build .build
.build/hello
```

Run Locally with pack & Docker:
```
pack build --builder=gcr.io/buildpacks/builder sample-functions-framework-cpp
docker run -p8080:8080 sample-functions-framework-cpp
```

Check it out: [http://localhost:8080](http://localhost:8080)

Run on Cloud Run:

[![Run on Google Cloud](https://deploy.cloud.run/button.svg)](https://deploy.cloud.run)


text:
<?php

Admin::model(\App\Content::class)
	->form(function ()
{
	// Describing elements in create and editing forms
	// Describing elements in create and editing forms
	FormItem::select('page_id', 'Page')
		->list(\App\Page::class)
		->required();
	FormItem::text('name', 'Name')->required();
	FormItem::textarea('content', 'Content')->required();
	FormItem::text('order', 'Order')->required();
})
	->columns(function ()
{
	// Describing columns for table view
	Column::string('page_id', 'Page Id');
	Column::string('name', 'Name');
	//Column::lists('sites.domain', 'Domain');
	Column::string('order', 'Order');
		//Column::yesNo()->myCustomMethod();
});


text:
{% set title = "Press" %}
{% set cssName = "press" %}
{% extends "includes/main.html" %}

{#
 # This is auto generated from press.json.
 # press.json is an array. Each item is another array, which represents one row.
 # Each item in a row is an object, which represents one article. The widths for
 # the article are auto-calculated.
 #
 # The properties of a story are:
 # color: The color for the strip at the top. Any valid CSS color is OK.
 # link: The link to the article.
 # name: a unique name for the *news outlet* all one word, letters and numbers
         only. Must be all lowercase, and correspont to a .png file in
         assets/images. (ex. 'verge' => 'assets/images/verge.png', 'motherboard'.)
 # title: The title of the article.
 # textCSS: any valid css, will be applied to the title. Usually this includes
 #          `color` and `font-family`, but also sometimes `font-size` and
 #          `font-weight` are used.
 #}

{% block main %}

  {% for row in stories %}
    {% set width = 90 / row.length %}
    {% for story in row %}

{{ story.title }}

    {% endfor %}
  {% endfor %}

{% endblock %}


text:
<?php
use AgileGeeks\RegistrarFacade\Rotld as Api;
require_once(__DIR__.'../../../BaseTestCase.php');
require_once(__DIR__.'../../DomainHandler.php');

class TestDomainRenew extends BaseTestCase {

    function __construct() {
        $this->contact_registrant = null;
    }

    protected function setUp($configfile = null) {
        include('config.php');
        $this->handler = new Api\DomainHandler($config);

        $this->contact_registrant = (object) array(
            'person_type' => 'p',
            'cnp_fiscal_code' => '1876972634324',
            'registration_number' => '',
            'first_name' => 'John',
            'last_name' => 'Doe',
            'address1' => 'Agile Geeks Street',
            'address2' => 'Line 2',
            'address3' => 'Line 3',
            'city' => 'Bucuresti',
            'state_province' => 'Bucuresti',
            'postal_code' => '',
            'country' => 'RO',
            'email' => 'johndoe@gmail.com',
            'phone' => '+40.1222227',
            'fax' => ''
        );

        $this->test_apex_domain = $this->randomstring(60).'.ro';
        $result = $this->handler->register($this->test_apex_domain,
                                $registration_period=1,
                                $nameservers=array('ns1.x.com','ns2.x.com'),
                                $domain_password='G0odPasswd21$',
                                $contact_registrant=$this->contact_registrant,
                                $contact_tech=null,
                                $contact_admin=null,
                                $contact_billing=null,
                                $extra_params=array()
                            );
    }

    protected function tearDown() {

    }

    public function test_domain_renew() {

        $period = 1;
        $response = $this->handler->renew($this->test_apex_domain, $period);
        $this->assertFalse($response);
        //var_dump( $this->handler->getError());
        //
        // $response = $this->handler->info(
        //     $this->test_apex_domain, $include_contacts=False, $include_namservers=False
        // );
        // $this->assertTrue($response);
        // $result = $this->handler->getResult();
        // var_dump($result);
    }

}


text:
1、FetchFailedException

```
org.apache.spark.shuffle.FetchFailedException
这种情况通常是executor的内存不够。
```

2、ExecutorLostFailure

```
内存超过yarn的限制,executor被kill掉了
16/12/07 22:06:49 WARN TaskSetManager: Lost task 232.0 in stage 28.0 (TID 12561, [rz-data-hdp-dn0037.rz.***.com](http://rz-data-hdp-dn0037.rz.***.com/)):     ExecutorLostFailure (executor 11 exited caused by one of the running tasks) Reason: Container killed by YARN fora exceeding memory limits. 16.1 GB of 16 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead.
```

3、bad symbolic reference

```
[ERROR] uncaught exception during compilation: scala.reflect.internal.Types$TypeError,error: scala.reflect.internal.Types$TypeError: bad symbolic reference. A signature in PipelineStage.class refers to term internal,the classpath might be incompatible with the version used when compiling PipelineStage.class.

出现关于类路径或者签名不对等类型的错误多半是版本之间的不兼容造成的,在使用xgboost4j-spark的过程中遇到的问题,发现xgboost4j-spark依赖了spark-mllib2.0.0,将所有的spark组件升级到2.0.2之后,编译通过
```

4、spark.yarn.executor.memoryOverhead是executor的非堆内存,spark有些数据是放在这里的,excutor内存:核数:overhead = 2:1:1

5、spark作业失败的时候不会写入Hive表,成功的时候会写入Hive表

6、join过后需要在map中的case的相关情况写全,否则会出现错误,就像java语言里的default一样。

7、Spark运行过程中,倘若抛出文件存在异常的话,要么是路径下真的存在文件,第二种情况就是程序中有Bug,导致第一次运行时创建了文件路径,在第二次尝试执行的时候则会抛出文件路径存在的异常

8、RDD中的文件一般都是以key-value对的形式出现,所以最好是用key来作为分组,剩下的包装成一个元组Tuple

```scala
val browseUserRDD = browseDealRDD.union(browsePoiRDD).join(uuidMapUserIdRDD).map{
      case ((uuid, (browseTime, userId))) =>
        (userId, Set(browseTime))
    }.reduceByKey{
      case (a, b) => a ++ b
    }.flatMap{
      case (a, b) => b.map((a, _))
    }
```

9、通常情况下union后面要跟着distinct函数,因为union会增加重复数据,因此有必要通过使用distinct函数来去重。


text:
#define EIGEN_USE_THREADS

#include <vector>
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/util/sparse/sparse_tensor.h"

namespace tensorflow {

template <typename T>
class SparseSliceOp : public OpKernel {
 public:
  explicit SparseSliceOp(OpKernelConstruction* context) : OpKernel(context) {}

  void Compute(OpKernelContext* context) override {
    const Tensor& input_indices = context->input(0);
    const Tensor& input_values = context->input(1);
    const Tensor& input_shape = context->input(2);
    const Tensor& input_start = context->input(3);
    const Tensor& input_size = context->input(4);

    OP_REQUIRES(context, TensorShapeUtils::IsMatrix(input_indices.shape()),
                errors::InvalidArgument(
                    "Input indices should be a matrix but received shape ",
                    input_indices.shape().DebugString()));
    OP_REQUIRES(context, TensorShapeUtils::IsVector(input_values.shape()),
                errors::InvalidArgument(
                    "Input values should be a vector but received shape ",
                    input_indices.shape().DebugString()));
    OP_REQUIRES(context, TensorShapeUtils::IsVector(input_shape.shape()),
                errors::InvalidArgument(
                    "Input shape should be a vector but received shape ",
                    input_shape.shape().DebugString()));
    OP_REQUIRES(context, TensorShapeUtils::IsVector(input_start.shape()),
                errors::InvalidArgument(
                    "Input start should be a vector but received shape ",
                    input_start.shape().DebugString()));
    OP_REQUIRES(context, TensorShapeUtils::IsVector(input_size.shape()),
                errors::InvalidArgument(
                    "Input size should be a vector but received shape ",
                    input_size.shape().DebugString()));

    const int input_dims = input_shape.NumElements();
    OP_REQUIRES(context, input_dims == input_start.NumElements(),
                errors::InvalidArgument(
                    "Expected start to be a vector of length ", input_dims,
                    " but got length ", input_start.NumElements()));

    OP_REQUIRES(context, input_dims == input_size.NumElements(),
                errors::InvalidArgument(
                    "Expected size to be a vector of length ", input_dims,
                    " but got length ", input_size.NumElements()));

    sparse::SparseTensor sparse_tensor;
    OP_REQUIRES_OK(
        context, sparse::SparseTensor::Create(
                     input_indices, input_values,
                     TensorShape(input_shape.vec<int64_t>()), &sparse_tensor));

    const gtl::ArraySlice<int64_t> start(input_start.flat<int64_t>().data(),
                                         input_dims);
    const gtl::ArraySlice<int64_t> size(input_size.flat<int64_t>().data(),
                                        input_dims);

    const sparse::SparseTensor output =
        sparse::SparseTensor::Slice<T>(sparse_tensor, start, size);

    context->set_output(0, output.indices());
    context->set_output(1, output.values());

    const TensorShape output_shape(output.shape());

    Tensor* shape = nullptr;
    OP_REQUIRES_OK(context,
                   context->allocate_output(2, {output_shape.dims()}, &shape));
    for (int dim = 0; dim < output_shape.dims(); ++dim) {
      shape->vec<int64_t>()(dim) = output_shape.dim_size(dim);
    }
  }

 private:
};

#define REGISTER_KERNELS(type)                                          \
  REGISTER_KERNEL_BUILDER(                                              \
      Name("SparseSlice").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
      SparseSliceOp<type>)

TF_CALL_ALL_TYPES(REGISTER_KERNELS);
#undef REGISTER_KERNELS

}  // namespace tensorflow


text:
// Copyright (C) 2017 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server.git.receive;

import com.google.gerrit.common.UsedAt;

/**
 * Interface used by {@link ReceiveCommits} for send messages over the wire during {@code
 * receive-pack}.
 */
@UsedAt(UsedAt.Project.GOOGLE)
public interface MessageSender {
  void sendMessage(String what);

  void sendError(String what);

  void sendBytes(byte[] what);

  void sendBytes(byte[] what, int off, int len);

  void flush();
}


text:
test -e /home/csgrads/sgoka001/CS100/rshell/src/tests            #returns true because there exists a directory called tests
test -e /home/csgrads/sgoka001/CS100/rshell/src/Command.h        #returns true because there exists a regular file called Command.h
test -e /home/csgrads/sgoka001/CS100/rshell/src/unreal.cpp       #returns false because there is no file or directory called unreal.cpp

test -d /home/csgrads/sgoka001/CS100/rshell/src/tests            #returns true because there exists a directory called tests
test -d /home/csgrads/sgoka001/CS100/rshell/src/Command.h        #returns false because although Command.h exists, it is a regular file NOT a directory
test -d /home/csgrads/sgoka001/CS100/rshell/src/unreal.cpp       #returns false because unreal.cpp doesn't exist

test -f /home/csgrads/sgoka001/CS100/rshell/src/tests            #returns false because tests is a directory and not a regular file
test -f /home/csgrads/sgoka001/CS100/rshell/src/Command.h        #returns true because there exists a regular file called Command.h
test -f /home/csgrads/sgoka001/CS100/rshell/src/unreal.cpp       #returns false because unreal.cpp doesn't exist

test -e /home/csgrads/sgoka001/CS100/rshell/src/DIRECTORY_OR_REGULAR_FILE #works the same as the above tests for -e
test -d /home/csgrads/sgoka001/CS100/rshell/src/DIRECTORY                 #works the same as the above tests for -d
test -f /home/csgrads/sgoka001/CS100/rshell/src/REGULAR_FILE              #works the same as the above tests for -f

test -e /home/csgrads/sgoka001/CS100/rshell/src/tests && echo "path exists"        #returns true and "path exists" on the next line
test -d /home/csgrads/sgoka001/CS100/rshell/src/tests && echo "path exists"        #returns true and "path exists" on the next line
test -f /home/csgrads/sgoka001/CS100/rshell/src/Command.h && echo "path exists"    #returns true and "path exists" on the next line

test -e /home/csgrads/sgoka001/CS100/rshell/src/unreal.cpp && echo "path exists"   #returns false ONLY
test -d /home/csgrads/sgoka001/CS100/rshell/src/Command.h && echo "path exists"    #returns false ONLY
test -f /home/csgrads/sgoka001/CS100/rshell/src/tests && echo "path exists"        #returns false ONLY

[ -e /home/csgrads/sgoka001/CS100/rshell/src/tests ]            #returns true because there exists a directory called tests
[ -e /home/csgrads/sgoka001/CS100/rshell/src/Command.h ]        #returns true because there exists a regular file called Command.h
[ -e /home/csgrads/sgoka001/CS100/rshell/src/unreal.cpp ]       #returns false because there is no file or directory called unreal.cpp

[ -d /home/csgrads/sgoka001/CS100/rshell/src/tests ]            #returns true because there exists a directory called tests
[ -d /home/csgrads/sgoka001/CS100/rshell/src/Command.h ]        #returns false because although Command.h exists, it is a regular file NOT a directory
[ -d /home/csgrads/sgoka001/CS100/rshell/src/unreal.cpp ]       #returns false because unreal.cpp doesn't exist

[ -f /home/csgrads/sgoka001/CS100/rshell/src/tests ]            #returns false because tests is a directory and not a regular file
[ -f /home/csgrads/sgoka001/CS100/rshell/src/Command.h ]        #returns true because there exists a regular file called Command.h
[ -f /home/csgrads/sgoka001/CS100/rshell/src/unreal.cpp ]       #returns false because unreal.cpp doesn't exist

[ -e /home/csgrads/sgoka001/CS100/rshell/src/DIRECTORY_OR_REGULAR_FILE ] #works the same as the above tests for -e
[ -d /home/csgrads/sgoka001/CS100/rshell/src/DIRECTORY ]                 #works the same as the above tests for -d
[ -f /home/csgrads/sgoka001/CS100/rshell/src/REGULAR_FILE ]              #works the same as the above tests for -f

[ -e /home/csgrads/sgoka001/CS100/rshell/src/tests && echo "path exists" ]        #returns true and "path exists" on the next line
[ -d /home/csgrads/sgoka001/CS100/rshell/src/tests && echo "path exists" ]        #returns true and "path exists" on the next line
[ -f /home/csgrads/sgoka001/CS100/rshell/src/Command.h && echo "path exists" ]    #returns true and "path exists" on the next line

[ -e /home/csgrads/sgoka001/CS100/rshell/src/unreal.cpp && echo "path exists" ]   #returns false ONLY
[ -d /home/csgrads/sgoka001/CS100/rshell/src/Command.h && echo "path exists" ]    #returns false ONLY
[ -f /home/csgrads/sgoka001/CS100/rshell/src/tests && echo "path exists" ]        #returns false ONLY


text:
         Peserta Didik
         Nilai

<ui-view></ui-view>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NikTiles.Engine;

namespace NikTiles.Editor.Forms.FloorMenu {
    public partial class MaterialEditPreview : UserControl {

        private Texture bottom , top;
        private Bitmap bottomBitmap, topBitmap;

        public MaterialEditPreview() {
            InitializeComponent();
            topBitmap    = new Bitmap(Tile.Width, Tile.Height);
            bottomBitmap = new Bitmap(Tile.Width, Tile.Height);
        }

        public void Initialize() {
            bottom       = Texture.floor["Empty"].Copy();
            top          = Texture.floor["Empty"].Copy();
            topBitmap    = top.GetBitmap();
            bottomBitmap = bottom.GetBitmap();
        }

        private new void Update() {
            topBitmap = top.GetBitmap();
            bottomBitmap = bottom.GetBitmap();
            BackgroundImage = Texture.BlendImages(bottomBitmap, topBitmap);
        }

        public Texture TopTexture {
            set {
                if (value != null) {
                    top.DiffuseMap = value.DiffuseMap;
                    Update();
                }
            } get { return top; }
        }

        public Texture BottomTexture {
            set {
                if (value != null) {
                    bottom = value;
                    Update();
                }
            } get { return bottom; }
        }

        public Color TopColor {
            set {
                top.Color = value;
                Update();
            } get { return top.Color; }
        }

        public Color BottomColor {
            set {
                bottom.Color = value;
                Update();
            } get { return bottom.Color; }
        }

        public byte TopAlpha {
            set{
                top.Alpha = value;
                Update();
            } get { return top.Alpha; }
        }

        public byte BottomAlpha {
            set{
                bottom.Alpha = value;
                Update();
            } get { return bottom.Alpha; }
        }

        public void FlipTextures() {

            Texture temp = bottom.Copy();
            bottom = top.Copy();
            top = temp.Copy();

            Update();
        }

        public FloorMaterial CreateMaterial(string name) {
            FloorMaterial material = new FloorMaterial(name, top, bottom);
            return material;
        }

    }
}


text: module.exports = /RegExpString/g;